Compare commits
19 Commits
v1.3.0
...
537d78e71b
| Author | SHA1 | Date | |
|---|---|---|---|
| 537d78e71b | |||
| 47e9c4faf7 | |||
| 31a5090f4f | |||
| ecdac6fe23 | |||
| 1a84edc064 | |||
| bfb2c26821 | |||
| a985268987 | |||
| 218cdb08c5 | |||
| 2855cc7f81 | |||
| 07d2e215e4 | |||
| 8ef839d6d0 | |||
| 7af88328c8 | |||
| 096e2afb3d | |||
| 668e7c34bb | |||
| e796b4f400 | |||
| a4b5c20993 | |||
| d17f364fc5 | |||
| 5f79eec3dd | |||
| ed98bb57c0 |
@@ -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" \
|
||||
|
||||
52
css/app.css
52
css/app.css
@@ -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; }
|
||||
}
|
||||
|
||||
26
index.html
26
index.html
@@ -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>
|
||||
|
||||
64
js/ui.js
64
js/ui.js
@@ -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';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
const VERSION = "1.3.0";
|
||||
const VERSION = "1.4.0";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "catalyst",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node server/server.js",
|
||||
|
||||
33
server/db.js
33
server/db.js
@@ -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
63
server/jobs.js
Normal 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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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}`));
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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('');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user