19 Commits

Author SHA1 Message Date
537d78e71b Merge pull request 'feat: Tailscale sync jobs' (#46) from feat/tailscale-sync-jobs into dev
All checks were successful
CI / test (push) Successful in 13s
CI / build-dev (push) Successful in 25s
Reviewed-on: #46
2026-03-28 17:12:35 -04:00
47e9c4faf7 feat: Tailscale sync jobs
All checks were successful
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
Adds a background job system that polls the Tailscale API on a configurable
interval and syncs tailscale status and IPs to instances by hostname match.

- New config table (key/value) in SQLite for persistent server-side settings
- New server/jobs.js: runTailscaleSync + restartJobs scheduler
- GET/PUT /api/config — read and write Tailscale settings; API key masked as **REDACTED** on GET
- POST /api/jobs/tailscale/run — immediate manual sync
- Settings modal: new Tailscale Sync section with enable toggle, tailnet, API key, poll interval, Save + Run Now buttons, last-run status

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 17:11:40 -04:00
31a5090f4f Merge pull request 'fix: remove internal database ID from frontend' (#45) from fix/hide-internal-id into dev
All checks were successful
CI / test (push) Successful in 13s
CI / build-dev (push) Successful in 20s
Reviewed-on: #45
2026-03-28 16:48:19 -04:00
ecdac6fe23 fix: remove internal database ID from frontend
All checks were successful
CI / test (pull_request) Successful in 13s
CI / build-dev (pull_request) Has been skipped
Removed from the instance subtitle and the overview kv grid. The auto-
increment ID is an implementation detail with no user-facing meaning.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 16:47:20 -04:00
1a84edc064 Merge pull request 'chore: bump version to 1.4.0' (#43) from chore/bump-v1.4.0 into dev
All checks were successful
CI / test (push) Successful in 13s
CI / build-dev (push) Successful in 24s
CI / test (pull_request) Successful in 13s
CI / build-dev (pull_request) Has been skipped
Reviewed-on: #43
2026-03-28 16:15:32 -04:00
bfb2c26821 chore: bump version to 1.4.0
All checks were successful
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 16:09:08 -04:00
a985268987 Merge pull request 'feat: include history in export/import backup' (#42) from feat/export-import-history into dev
All checks were successful
CI / test (push) Successful in 12s
CI / build-dev (push) Successful in 21s
Reviewed-on: #42
2026-03-28 16:06:21 -04:00
218cdb08c5 feat: include history in export/import backup
All checks were successful
CI / test (pull_request) Successful in 15s
CI / build-dev (pull_request) Has been skipped
Export now returns version 2 with a history array alongside instances.
Import accepts the history array and restores all audit events. v1 backups
without a history key still import cleanly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 16:04:53 -04:00
2855cc7f81 Merge pull request 'feat: mobile-responsive layout under 640px' (#41) from feat/mobile-responsive into dev
All checks were successful
CI / test (push) Successful in 13s
CI / build-dev (push) Successful in 23s
Reviewed-on: #41
2026-03-28 15:57:07 -04:00
07d2e215e4 Merge branch 'dev' into feat/mobile-responsive
All checks were successful
CI / test (pull_request) Successful in 13s
CI / build-dev (pull_request) Has been skipped
2026-03-28 15:56:38 -04:00
8ef839d6d0 Merge pull request 'fix: wrap image reference in backticks in release notes' (#40) from fix/release-image-codeblock into dev
All checks were successful
CI / test (push) Successful in 12s
CI / build-dev (push) Successful in 21s
Reviewed-on: #40
2026-03-28 15:55:05 -04:00
7af88328c8 feat: mobile-responsive layout under 640px
All checks were successful
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
Single breakpoint, no desktop changes. Key adjustments:
- Reset zoom: 1 (mobile browsers handle scaling)
- Padding drops from 32px to 16px throughout
- Toolbar wraps: search full-width, filters below
- Instance grid and detail grid collapse to single column
- Detail header stacks title above action buttons
- History timeline stacks timestamp above event
- Toggle grid drops from 3 to 2 columns
- Confirm box gets max-width: calc(100vw - 32px) to prevent overflow
- Toast stretches across bottom of screen

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 15:54:12 -04:00
096e2afb3d fix: wrap image reference in backticks in release notes
All checks were successful
CI / test (pull_request) Successful in 13s
CI / build-dev (pull_request) Has been skipped
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 15:44:15 -04:00
668e7c34bb Merge pull request 'chore: release v1.3.1' (#38) from chore/bump-v1.3.1 into dev
All checks were successful
CI / test (push) Successful in 15s
CI / build-dev (push) Successful in 25s
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
Reviewed-on: #38
2026-03-28 15:40:46 -04:00
e796b4f400 chore: release v1.3.1
All checks were successful
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 15:40:16 -04:00
a4b5c20993 Merge pull request 'fix: clear instance history on delete and import' (#37) from fix/delete-clears-history into dev
All checks were successful
CI / test (push) Successful in 13s
CI / build-dev (push) Successful in 20s
Reviewed-on: #37
2026-03-28 15:38:15 -04:00
d17f364fc5 fix: clear instance history on delete and import
All checks were successful
CI / test (pull_request) Successful in 14s
CI / build-dev (pull_request) Has been skipped
deleteInstance now removes history rows for that vmid before removing
the instance. importInstances clears all history before replacing
instances. Prevents stale history appearing when a vmid is reused.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 15:37:45 -04:00
5f79eec3dd Merge pull request 'fix: categorize release notes into New Features / Bug Fixes, drop chores' (#36) from fix/release-notes-format into dev
All checks were successful
CI / test (push) Successful in 12s
CI / build-dev (push) Successful in 20s
Reviewed-on: #36
2026-03-28 15:36:27 -04:00
ed98bb57c0 fix: categorize release notes into New Features / Bug Fixes, drop chores
All checks were successful
CI / test (pull_request) Successful in 13s
CI / build-dev (pull_request) Has been skipped
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 15:35:53 -04:00
12 changed files with 466 additions and 14 deletions

View File

@@ -79,7 +79,29 @@ jobs:
- name: Create Gitea release
run: |
python3 -c "import json,os; v=os.environ['VERSION']; img=os.environ['IMAGE']; notes=open('/tmp/release_notes.txt').read(); open('/tmp/release_body.json','w').write(json.dumps({'tag_name':'v'+v,'name':'Catalyst v'+v,'body':'### Changes\n\n'+notes+'\n\n### Image\n\n'+img+':'+v,'draft':False,'prerelease':False}))"
cat > /tmp/make_release.py << 'PYEOF'
import json, os
v = os.environ['VERSION']
img = os.environ['IMAGE']
raw = open('/tmp/release_notes.txt').read().strip()
feats, fixes = [], []
for line in raw.splitlines():
msg = line.lstrip('- ').strip()
if msg.startswith('feat:'):
feats.append('- ' + msg[5:].strip())
elif msg.startswith('fix:'):
fixes.append('- ' + msg[4:].strip())
sections = []
if feats:
sections.append('### New Features\n\n' + '\n'.join(feats))
if fixes:
sections.append('### Bug Fixes\n\n' + '\n'.join(fixes))
notes = '\n\n'.join(sections) or '_No changes_'
body = notes + '\n\n### Image\n\n`' + img + ':' + v + '`'
payload = {'tag_name': 'v'+v, 'name': 'Catalyst v'+v, 'body': body, 'draft': False, 'prerelease': False}
open('/tmp/release_body.json', 'w').write(json.dumps(payload))
PYEOF
python3 /tmp/make_release.py
curl -sf -X POST \
-H "Authorization: token ${{ secrets.TOKEN }}" \
-H "Content-Type: application/json" \

View File

@@ -712,3 +712,55 @@ select:focus { border-color: var(--accent); }
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* ── MOBILE ── */
@media (max-width: 640px) {
/* Reset desktop zoom — mobile browsers handle scaling themselves */
html { zoom: 1; }
/* Nav */
nav { padding: 0 16px; }
/* Dashboard header */
.dash-header { padding: 18px 16px 14px; }
/* Stats bar */
.stat-cell { padding: 10px 16px; }
/* Toolbar — search full-width on first row, filters + button below */
.toolbar { flex-wrap: wrap; padding: 10px 16px; gap: 8px; }
.search-wrap { max-width: 100%; }
.toolbar-right { margin-left: 0; width: 100%; justify-content: flex-end; }
/* Instance grid — single column */
.instance-grid {
grid-template-columns: 1fr;
padding: 12px 16px;
gap: 8px;
}
/* Detail page */
.detail-page { padding: 16px; }
/* Detail header — stack title block above actions */
.detail-header { flex-direction: column; align-items: flex-start; gap: 14px; }
/* Detail sub — wrap items when they don't fit */
.detail-sub { flex-wrap: wrap; row-gap: 4px; }
/* Detail grid — single column */
.detail-grid { grid-template-columns: 1fr; }
/* Toggle grid — 2 columns instead of 3 */
.toggle-grid { grid-template-columns: 1fr 1fr; }
/* Confirm box — no fixed width on mobile */
.confirm-box { width: auto; max-width: calc(100vw - 32px); padding: 18px; }
/* History timeline — stack timestamp above event */
.tl-item { flex-direction: column; align-items: flex-start; gap: 3px; }
.tl-time { order: -1; }
/* Toast — stretch across bottom */
.toast { right: 16px; left: 16px; bottom: 16px; }
}

View File

@@ -69,7 +69,6 @@
<div class="detail-name" id="detail-name"></div>
<div class="detail-sub">
<span><span class="lbl">vmid</span> <span class="val" id="detail-vmid-sub"></span></span>
<span><span class="lbl">id</span> <span class="val" id="detail-id-sub"></span></span>
<span><span class="lbl">created</span> <span class="val" id="detail-created-sub"></span></span>
</div>
</div>
@@ -200,6 +199,31 @@
<button class="btn btn-danger" onclick="importDB()">Import</button>
</div>
</div>
<div class="settings-section">
<div class="settings-section-title">Tailscale Sync</div>
<p class="settings-desc">Sync Tailscale status and IPs by matching device hostnames to instance names.</p>
<div class="settings-row" style="margin-bottom:12px">
<label class="settings-label" for="ts-enabled">Enable</label>
<input type="checkbox" id="ts-enabled" style="accent-color:var(--accent);width:14px;height:14px">
</div>
<div class="form-group">
<label class="form-label" for="ts-tailnet">Tailnet</label>
<input class="form-input" id="ts-tailnet" type="text" placeholder="e.g. Tt3Btpm6D921CNTRL">
</div>
<div class="form-group">
<label class="form-label" for="ts-api-key">API Key</label>
<input class="form-input" id="ts-api-key" type="password" placeholder="tskey-api-…">
</div>
<div class="form-group">
<label class="form-label" for="ts-poll">Poll Interval (minutes)</label>
<input class="form-input" id="ts-poll" type="number" min="1" placeholder="15">
</div>
<div class="settings-row" style="gap:8px;margin-bottom:8px">
<button class="btn btn-secondary" onclick="saveTailscaleSettings()">Save</button>
<button class="btn btn-secondary" id="ts-run-btn" onclick="runTailscaleNow()">Run Now</button>
</div>
<div id="ts-status" class="settings-desc" style="margin:4px 0 0;color:var(--text3)"></div>
</div>
</div>
</div>
</div>

View File

@@ -172,7 +172,6 @@ async function renderDetailPage(vmid) {
document.getElementById('detail-vmid-crumb').textContent = vmid;
document.getElementById('detail-name').textContent = inst.name;
document.getElementById('detail-vmid-sub').textContent = inst.vmid;
document.getElementById('detail-id-sub').textContent = inst.id;
document.getElementById('detail-created-sub').textContent = fmtDate(inst.created_at);
document.getElementById('detail-identity').innerHTML = `
@@ -180,7 +179,6 @@ async function renderDetailPage(vmid) {
<div class="kv-row"><span class="kv-key">state</span><span class="kv-val"><span class="badge ${esc(inst.state)}">${esc(inst.state)}</span></span></div>
<div class="kv-row"><span class="kv-key">stack</span><span class="kv-val"><span class="badge ${esc(inst.stack)}">${esc(inst.stack) || '—'}</span></span></div>
<div class="kv-row"><span class="kv-key">vmid</span><span class="kv-val highlight">${inst.vmid}</span></div>
<div class="kv-row"><span class="kv-key">internal id</span><span class="kv-val">${inst.id}</span></div>
`;
document.getElementById('detail-network').innerHTML = `
@@ -355,6 +353,7 @@ function openSettingsModal() {
}
}
sel.value = getTimezone();
loadTailscaleSettings();
document.getElementById('settings-modal').classList.add('open');
}
@@ -384,11 +383,11 @@ async function importDB() {
document.getElementById('confirm-ok').onclick = async () => {
closeConfirm();
try {
const { instances } = JSON.parse(await file.text());
const { instances, history = [] } = JSON.parse(await file.text());
const res = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ instances }),
body: JSON.stringify({ instances, history }),
});
const data = await res.json();
if (!res.ok) { showToast(data.error ?? 'Import failed', 'error'); return; }
@@ -426,3 +425,60 @@ document.getElementById('tz-select').addEventListener('change', e => {
if (m) renderDetailPage(parseInt(m[1], 10));
else renderDashboard();
});
// ── Tailscale Settings ────────────────────────────────────────────────────────
async function loadTailscaleSettings() {
try {
const res = await fetch('/api/config');
if (!res.ok) return;
const cfg = await res.json();
document.getElementById('ts-enabled').checked = cfg.tailscale_enabled === '1';
document.getElementById('ts-tailnet').value = cfg.tailscale_tailnet ?? '';
document.getElementById('ts-api-key').value = cfg.tailscale_api_key ?? '';
document.getElementById('ts-poll').value = cfg.tailscale_poll_minutes || '15';
_updateTsStatus(cfg.tailscale_last_run_at, cfg.tailscale_last_result);
} catch { /* silent */ }
}
function _updateTsStatus(lastRun, lastResult) {
const el = document.getElementById('ts-status');
if (!lastRun) { el.textContent = 'Never run'; return; }
el.textContent = `Last run: ${fmtDateFull(lastRun)}${lastResult || '—'}`;
}
async function saveTailscaleSettings() {
const body = {
tailscale_enabled: document.getElementById('ts-enabled').checked ? '1' : '0',
tailscale_tailnet: document.getElementById('ts-tailnet').value.trim(),
tailscale_api_key: document.getElementById('ts-api-key').value,
tailscale_poll_minutes: document.getElementById('ts-poll').value || '15',
};
const res = await fetch('/api/config', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
showToast(res.ok ? 'Tailscale settings saved' : 'Failed to save settings', res.ok ? 'success' : 'error');
}
async function runTailscaleNow() {
const btn = document.getElementById('ts-run-btn');
btn.disabled = true;
btn.textContent = 'Running…';
try {
const res = await fetch('/api/jobs/tailscale/run', { method: 'POST' });
const data = await res.json();
if (res.ok) {
showToast(`Sync complete — ${data.updated} updated`, 'success');
_updateTsStatus(new Date().toISOString(), `ok: ${data.updated} updated of ${data.total}`);
} else {
showToast(data.error ?? 'Sync failed', 'error');
}
} catch {
showToast('Sync failed', 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Run Now';
}
}

View File

@@ -1 +1 @@
const VERSION = "1.3.0";
const VERSION = "1.4.0";

View File

@@ -1,6 +1,6 @@
{
"name": "catalyst",
"version": "1.3.0",
"version": "1.4.0",
"type": "module",
"scripts": {
"start": "node server/server.js",

View File

@@ -53,6 +53,11 @@ function createSchema() {
changed_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_history_vmid ON instance_history(vmid);
CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL DEFAULT ''
);
`);
}
@@ -151,11 +156,13 @@ export function updateInstance(vmid, data) {
}
export function deleteInstance(vmid) {
return db.prepare('DELETE FROM instances WHERE vmid = ?').run(vmid);
db.prepare('DELETE FROM instance_history WHERE vmid = ?').run(vmid);
db.prepare('DELETE FROM instances WHERE vmid = ?').run(vmid);
}
export function importInstances(rows) {
export function importInstances(rows, historyRows = []) {
db.exec('BEGIN');
db.exec('DELETE FROM instance_history');
db.exec('DELETE FROM instances');
const insert = db.prepare(`
INSERT INTO instances
@@ -166,6 +173,12 @@ export function importInstances(rows) {
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
`);
for (const row of rows) insert.run(row);
if (historyRows.length) {
const insertHist = db.prepare(
`INSERT INTO instance_history (vmid, field, old_value, new_value, changed_at) VALUES (?, ?, ?, ?, ?)`
);
for (const h of historyRows) insertHist.run(h.vmid, h.field, h.old_value ?? null, h.new_value ?? null, h.changed_at);
}
db.exec('COMMIT');
}
@@ -175,6 +188,22 @@ export function getInstanceHistory(vmid) {
).all(vmid);
}
export function getAllHistory() {
return db.prepare('SELECT * FROM instance_history ORDER BY vmid, changed_at').all();
}
export function getConfig(key, defaultVal = '') {
const row = db.prepare('SELECT value FROM config WHERE key = ?').get(key);
return row ? row.value : defaultVal;
}
export function setConfig(key, value) {
db.prepare(
`INSERT INTO config (key, value) VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
).run(key, String(value));
}
// ── Test helpers ──────────────────────────────────────────────────────────────
export function _resetForTest() {

63
server/jobs.js Normal file
View File

@@ -0,0 +1,63 @@
import { getInstances, updateInstance, getConfig, setConfig } from './db.js';
const TAILSCALE_API = 'https://api.tailscale.com/api/v2';
let _interval = null;
export async function runTailscaleSync() {
const apiKey = getConfig('tailscale_api_key');
const tailnet = getConfig('tailscale_tailnet');
if (!apiKey || !tailnet) throw new Error('Tailscale not configured');
const res = await fetch(
`${TAILSCALE_API}/tailnet/${encodeURIComponent(tailnet)}/devices`,
{ headers: { Authorization: `Bearer ${apiKey}` } }
);
if (!res.ok) throw new Error(`Tailscale API ${res.status}`);
const { devices } = await res.json();
// hostname -> first 100.x.x.x address
const tsMap = new Map(
devices.map(d => [d.hostname, (d.addresses ?? []).find(a => a.startsWith('100.')) ?? ''])
);
const instances = getInstances();
let updated = 0;
for (const inst of instances) {
const tsIp = tsMap.get(inst.name); // undefined = not in Tailscale
const matched = tsIp !== undefined;
const newTailscale = matched ? 1 : (inst.tailscale === 1 ? 0 : inst.tailscale);
const newIp = matched ? tsIp : (inst.tailscale === 1 ? '' : inst.tailscale_ip);
if (newTailscale !== inst.tailscale || newIp !== inst.tailscale_ip) {
// Strip db-generated columns — node:sqlite rejects unknown named parameters
const { id: _id, created_at: _ca, updated_at: _ua, ...instData } = inst;
updateInstance(inst.vmid, { ...instData, tailscale: newTailscale, tailscale_ip: newIp });
updated++;
}
}
return { updated, total: instances.length };
}
export function restartJobs() {
if (_interval) { clearInterval(_interval); _interval = null; }
if (getConfig('tailscale_enabled') !== '1') return;
const mins = parseInt(getConfig('tailscale_poll_minutes', '15'), 10);
const ms = Math.max(1, Number.isFinite(mins) ? mins : 15) * 60_000;
_interval = setInterval(async () => {
try {
const r = await runTailscaleSync();
setConfig('tailscale_last_run_at', new Date().toISOString());
setConfig('tailscale_last_result', `ok: ${r.updated} updated of ${r.total}`);
} catch (e) {
setConfig('tailscale_last_run_at', new Date().toISOString());
setConfig('tailscale_last_result', `error: ${e.message}`);
}
}, ms);
}

View File

@@ -1,8 +1,10 @@
import { Router } from 'express';
import {
getInstances, getInstance, getDistinctStacks,
createInstance, updateInstance, deleteInstance, importInstances, getInstanceHistory,
createInstance, updateInstance, deleteInstance, importInstances, getInstanceHistory, getAllHistory,
getConfig, setConfig,
} from './db.js';
import { runTailscaleSync, restartJobs } from './jobs.js';
export const router = Router();
@@ -12,6 +14,12 @@ const VALID_STATES = ['deployed', 'testing', 'degraded'];
const VALID_STACKS = ['production', 'development'];
const SERVICE_KEYS = ['atlas', 'argus', 'semaphore', 'patchmon', 'tailscale', 'andromeda'];
const CONFIG_KEYS = [
'tailscale_api_key', 'tailscale_tailnet', 'tailscale_poll_minutes',
'tailscale_enabled', 'tailscale_last_run_at', 'tailscale_last_result',
];
const REDACTED = '**REDACTED**';
function validate(body) {
const errors = [];
if (!body.name || typeof body.name !== 'string' || !body.name.trim())
@@ -116,14 +124,15 @@ router.put('/instances/:vmid', (req, res) => {
// GET /api/export
router.get('/export', (_req, res) => {
const instances = getInstances();
const history = getAllHistory();
const date = new Date().toISOString().slice(0, 10);
res.setHeader('Content-Disposition', `attachment; filename="catalyst-backup-${date}.json"`);
res.json({ version: 1, exported_at: new Date().toISOString(), instances });
res.json({ version: 2, exported_at: new Date().toISOString(), instances, history });
});
// POST /api/import
router.post('/import', (req, res) => {
const { instances } = req.body ?? {};
const { instances, history = [] } = req.body ?? {};
if (!Array.isArray(instances)) {
return res.status(400).json({ error: 'body must contain an instances array' });
}
@@ -134,7 +143,7 @@ router.post('/import', (req, res) => {
}
if (errors.length) return res.status(400).json({ errors });
try {
importInstances(instances.map(normalise));
importInstances(instances.map(normalise), Array.isArray(history) ? history : []);
res.json({ imported: instances.length });
} catch (e) {
console.error('POST /api/import', e);
@@ -159,3 +168,38 @@ router.delete('/instances/:vmid', (req, res) => {
handleDbError('DELETE /api/instances/:vmid', e, res);
}
});
// GET /api/config
router.get('/config', (_req, res) => {
const cfg = {};
for (const key of CONFIG_KEYS) {
const val = getConfig(key);
cfg[key] = (key === 'tailscale_api_key' && val) ? REDACTED : val;
}
res.json(cfg);
});
// PUT /api/config
router.put('/config', (req, res) => {
for (const key of CONFIG_KEYS) {
if (!(key in (req.body ?? {}))) continue;
if (key === 'tailscale_api_key' && req.body[key] === REDACTED) continue;
setConfig(key, req.body[key]);
}
try { restartJobs(); } catch (e) { console.error('PUT /api/config restartJobs', e); }
res.json({ ok: true });
});
// POST /api/jobs/tailscale/run
router.post('/jobs/tailscale/run', async (req, res) => {
if (!getConfig('tailscale_api_key') || !getConfig('tailscale_tailnet'))
return res.status(400).json({ error: 'Tailscale not configured' });
try {
const result = await runTailscaleSync();
setConfig('tailscale_last_run_at', new Date().toISOString());
setConfig('tailscale_last_result', `ok: ${result.updated} updated of ${result.total}`);
res.json(result);
} catch (e) {
handleDbError('POST /api/jobs/tailscale/run', e, res);
}
});

View File

@@ -3,6 +3,7 @@ import helmet from 'helmet';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { router } from './routes.js';
import { restartJobs } from './jobs.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PORT = process.env.PORT ?? 3000;
@@ -47,5 +48,6 @@ app.use((err, _req, res, _next) => {
// Boot — only when run directly, not when imported by tests
if (process.argv[1] === fileURLToPath(import.meta.url)) {
restartJobs();
app.listen(PORT, () => console.log(`catalyst on :${PORT}`));
}

View File

@@ -275,6 +275,18 @@ describe('GET /api/export', () => {
const res = await request(app).get('/api/export')
expect(res.body.instances).toEqual([])
})
it('returns version 2', async () => {
const res = await request(app).get('/api/export')
expect(res.body.version).toBe(2)
})
it('includes a history array', async () => {
await request(app).post('/api/instances').send(base)
const res = await request(app).get('/api/export')
expect(res.body.history).toBeInstanceOf(Array)
expect(res.body.history.some(e => e.field === 'created')).toBe(true)
})
})
// ── POST /api/import ──────────────────────────────────────────────────────────
@@ -309,6 +321,26 @@ describe('POST /api/import', () => {
.send({ instances: [{ ...base, name: undefined, vmid: 1 }] })
expect(res.status).toBe(400)
})
it('restores history when history array is provided', async () => {
await request(app).post('/api/instances').send(base)
const exp = await request(app).get('/api/export')
await request(app).post('/api/instances').send({ ...base, vmid: 999, name: 'other' })
const res = await request(app).post('/api/import').send({
instances: exp.body.instances,
history: exp.body.history,
})
expect(res.status).toBe(200)
const hist = await request(app).get('/api/instances/100/history')
expect(hist.body.some(e => e.field === 'created')).toBe(true)
})
it('succeeds with a v1 backup that has no history key', async () => {
const res = await request(app).post('/api/import')
.send({ instances: [{ ...base, vmid: 1, name: 'legacy' }] })
expect(res.status).toBe(200)
expect(res.body.imported).toBe(1)
})
})
// ── Static assets & SPA routing ───────────────────────────────────────────────
@@ -421,3 +453,73 @@ describe('error handling — unexpected DB failures', () => {
)
})
})
// ── GET /api/config ───────────────────────────────────────────────────────────
describe('GET /api/config', () => {
it('returns 200 with all config keys', async () => {
const res = await request(app).get('/api/config')
expect(res.status).toBe(200)
expect(res.body).toHaveProperty('tailscale_enabled')
expect(res.body).toHaveProperty('tailscale_api_key')
expect(res.body).toHaveProperty('tailscale_poll_minutes')
})
it('returns empty string for api key when not set', async () => {
expect((await request(app).get('/api/config')).body.tailscale_api_key).toBe('')
})
it('masks api key as **REDACTED** when set', async () => {
await request(app).put('/api/config').send({ tailscale_api_key: 'tskey-secret' })
expect((await request(app).get('/api/config')).body.tailscale_api_key).toBe('**REDACTED**')
})
})
// ── PUT /api/config ───────────────────────────────────────────────────────────
describe('PUT /api/config', () => {
it('saves config and returns ok', async () => {
const res = await request(app).put('/api/config').send({ tailscale_tailnet: 'example.com' })
expect(res.status).toBe(200)
expect(res.body.ok).toBe(true)
})
it('does not overwrite api key when **REDACTED** is sent', async () => {
await request(app).put('/api/config').send({ tailscale_api_key: 'real-key' })
await request(app).put('/api/config').send({ tailscale_api_key: '**REDACTED**' })
expect(dbModule.getConfig('tailscale_api_key')).toBe('real-key')
})
})
// ── POST /api/jobs/tailscale/run ──────────────────────────────────────────────
describe('POST /api/jobs/tailscale/run', () => {
afterEach(() => vi.unstubAllGlobals())
it('returns 400 when not configured', async () => {
const res = await request(app).post('/api/jobs/tailscale/run')
expect(res.status).toBe(400)
expect(res.body.error).toMatch(/not configured/i)
})
it('updates matching instance and returns count', async () => {
await request(app).put('/api/config').send({
tailscale_api_key: 'tskey-test',
tailscale_tailnet: 'example.com',
})
await request(app).post('/api/instances').send({ ...base, name: 'traefik', vmid: 100 })
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce({
ok: true,
json: async () => ({ devices: [{ hostname: 'traefik', addresses: ['100.64.0.2'] }] }),
}))
const res = await request(app).post('/api/jobs/tailscale/run')
expect(res.status).toBe(200)
expect(res.body.updated).toBe(1)
const inst = await request(app).get('/api/instances/100')
expect(inst.body.tailscale).toBe(1)
expect(inst.body.tailscale_ip).toBe('100.64.0.2')
})
})

View File

@@ -3,6 +3,7 @@ import {
_resetForTest,
getInstances, getInstance, getDistinctStacks,
createInstance, updateInstance, deleteInstance, importInstances, getInstanceHistory,
getConfig, setConfig,
} from '../server/db.js'
beforeEach(() => _resetForTest());
@@ -164,6 +165,19 @@ describe('deleteInstance', () => {
expect(getInstance(1)).toBeNull();
expect(getInstance(2)).not.toBeNull();
});
it('clears history for the deleted instance', () => {
createInstance({ ...base, name: 'a', vmid: 1 });
deleteInstance(1);
expect(getInstanceHistory(1)).toHaveLength(0);
});
it('does not clear history for other instances', () => {
createInstance({ ...base, name: 'a', vmid: 1 });
createInstance({ ...base, name: 'b', vmid: 2 });
deleteInstance(1);
expect(getInstanceHistory(2).length).toBeGreaterThan(0);
});
});
// ── importInstances ───────────────────────────────────────────────────────────
@@ -183,6 +197,21 @@ describe('importInstances', () => {
importInstances([]);
expect(getInstances()).toEqual([]);
});
it('clears history for all replaced instances', () => {
createInstance({ ...base, name: 'old', vmid: 1 });
importInstances([{ ...base, name: 'new', vmid: 2 }]);
expect(getInstanceHistory(1)).toHaveLength(0);
});
it('restores history rows when provided', () => {
importInstances(
[{ ...base, name: 'a', vmid: 1 }],
[{ vmid: 1, field: 'created', old_value: null, new_value: null, changed_at: '2026-01-01 00:00:00' }]
);
const h = getInstanceHistory(1);
expect(h.some(e => e.field === 'created')).toBe(true);
});
});
// ── instance history ─────────────────────────────────────────────────────────
@@ -241,3 +270,32 @@ describe('test environment boot isolation', () => {
expect(getInstances()).toEqual([]);
});
});
// ── getConfig / setConfig ─────────────────────────────────────────────────────
describe('getConfig / setConfig', () => {
it('returns defaultVal when key does not exist', () => {
expect(getConfig('missing', 'fallback')).toBe('fallback');
});
it('returns empty string by default', () => {
expect(getConfig('missing')).toBe('');
});
it('stores and retrieves a value', () => {
setConfig('tailscale_api_key', 'tskey-test');
expect(getConfig('tailscale_api_key')).toBe('tskey-test');
});
it('overwrites an existing key', () => {
setConfig('tailscale_enabled', '0');
setConfig('tailscale_enabled', '1');
expect(getConfig('tailscale_enabled')).toBe('1');
});
it('config is cleared by _resetForTest', () => {
setConfig('tailscale_api_key', 'tskey-test');
_resetForTest();
expect(getConfig('tailscale_api_key')).toBe('');
});
});