Compare commits
42 Commits
v1.1.1
...
b48d5fb836
| Author | SHA1 | Date | |
|---|---|---|---|
| b48d5fb836 | |||
| 6e124576cb | |||
| 1f328e026d | |||
| 71c2c68fbc | |||
| 8bcf8229db | |||
| 6e1e9f7153 | |||
| 1fbb74d1ef | |||
| 617a5b5800 | |||
| 0985d9d481 | |||
| 2af6c56558 | |||
| af207339a4 | |||
| 20d8a13375 | |||
| f72aaa52f8 | |||
| dd47d5006e | |||
| 10e25e1803 | |||
| 1a62e2fdd9 | |||
| 1271c061fd | |||
| 7b2a996c21 | |||
| 3233d65db0 | |||
| 3037381084 | |||
| e54c1d4848 | |||
| 3ae3f98df5 | |||
| 65d6514603 | |||
| bc44bcbde9 | |||
| cae0f2222a | |||
| 28833a7ec6 | |||
| 6ba02bf17d | |||
| bfe71b2511 | |||
| 0f2a37cb39 | |||
| 73f4eabbc7 | |||
| 515ff8ddb3 | |||
| 08c12c9394 | |||
| 4ce7df4649 | |||
| 6c04a30c3a | |||
| c6cd8098fd | |||
| 15ed329743 | |||
| 1412b2e0b7 | |||
| 30b037ff9c | |||
| 7a5b5d7afc | |||
| 3383bee968 | |||
| 0c30e4bd29 | |||
| 01f83d25f6 |
@@ -1,84 +0,0 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
IMAGE: ${{ vars.REGISTRY_HOST }}/${{ gitea.repository_owner }}/catalyst
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 'lts/*'
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.IMAGE }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix=,format=short
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Log in to Gitea registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ vars.REGISTRY_HOST }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
|
||||
steps:
|
||||
- name: Create release
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token ${{ secrets.TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/releases" \
|
||||
-d "{
|
||||
\"tag_name\": \"${{ gitea.ref_name }}\",
|
||||
\"name\": \"Catalyst ${{ gitea.ref_name }}\",
|
||||
\"body\": \"### Image\n\n\`${{ env.IMAGE }}:${{ gitea.ref_name }}\`\",
|
||||
\"draft\": false,
|
||||
\"prerelease\": false
|
||||
}"
|
||||
53
.gitea/workflows/ci.yml
Normal file
53
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,53 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [dev, main]
|
||||
pull_request:
|
||||
branches: [dev, main]
|
||||
|
||||
env:
|
||||
IMAGE: ${{ vars.REGISTRY_HOST }}/${{ gitea.repository_owner }}/catalyst
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 'lts/*'
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- run: npm test
|
||||
|
||||
build-dev:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/dev'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ vars.REGISTRY_HOST }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.TOKEN }}
|
||||
|
||||
- name: Compute short SHA
|
||||
run: echo "SHORT_SHA=$(git rev-parse --short HEAD)" >> $GITEA_ENV
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
build-args: BUILD_VERSION=dev-${{ env.SHORT_SHA }}
|
||||
tags: |
|
||||
${{ env.IMAGE }}:dev
|
||||
${{ env.IMAGE }}:dev-${{ gitea.sha }}
|
||||
87
.gitea/workflows/release.yml
Normal file
87
.gitea/workflows/release.yml
Normal file
@@ -0,0 +1,87 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
IMAGE: ${{ vars.REGISTRY_HOST }}/${{ gitea.repository_owner }}/catalyst
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 'lts/*'
|
||||
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
|
||||
- name: Read version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "VERSION=${VERSION}" >> $GITEA_ENV
|
||||
|
||||
- name: Assert tag does not exist
|
||||
run: |
|
||||
if git ls-remote --tags origin "refs/tags/v${{ env.VERSION }}" | grep -q .; then
|
||||
echo "ERROR: tag v${{ env.VERSION }} already exists — bump version in package.json before merging to main."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create and push tag
|
||||
run: |
|
||||
git config user.name "gitea-actions"
|
||||
git config user.email "actions@gitea"
|
||||
git tag "v${{ env.VERSION }}"
|
||||
git push origin "v${{ env.VERSION }}"
|
||||
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
LAST_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
|
||||
if [ -n "$LAST_TAG" ]; then
|
||||
git log "${LAST_TAG}..HEAD" --pretty=format:"- %s" --no-merges > /tmp/release_notes.txt
|
||||
else
|
||||
git log --pretty=format:"- %s" --no-merges > /tmp/release_notes.txt
|
||||
fi
|
||||
|
||||
- name: Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.IMAGE }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}},value=v${{ env.VERSION }}
|
||||
type=semver,pattern={{major}}.{{minor}},value=v${{ env.VERSION }}
|
||||
type=sha,prefix=,format=short
|
||||
type=raw,value=latest
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ vars.REGISTRY_HOST }}
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
|
||||
- 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}))"
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token ${{ secrets.TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/releases" \
|
||||
--data @/tmp/release_body.json
|
||||
11
Dockerfile
11
Dockerfile
@@ -7,10 +7,15 @@ COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
COPY . .
|
||||
RUN awk -F'"' '/"version"/{printf "const VERSION = \"%s\";\n", $4; exit}' \
|
||||
package.json > js/version.js
|
||||
ARG BUILD_VERSION=""
|
||||
RUN if [ -n "$BUILD_VERSION" ]; then \
|
||||
printf 'const VERSION = "%s";\n' "$BUILD_VERSION" > js/version.js; \
|
||||
else \
|
||||
awk -F'"' '/"version"/{printf "const VERSION = \"%s\";\n", $4; exit}' \
|
||||
package.json > js/version.js; \
|
||||
fi
|
||||
|
||||
RUN chown -R app:app /app
|
||||
RUN mkdir -p /app/data && chown -R app:app /app
|
||||
USER app
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
40
css/app.css
40
css/app.css
@@ -70,6 +70,19 @@ nav {
|
||||
|
||||
.nav-sep { flex: 1; }
|
||||
|
||||
.nav-btn {
|
||||
background: none;
|
||||
border: 1px solid var(--border2);
|
||||
color: var(--text2);
|
||||
border-radius: 6px;
|
||||
padding: 4px 8px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
margin-left: 10px;
|
||||
line-height: 1;
|
||||
}
|
||||
.nav-btn:hover { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
.nav-divider { color: var(--border2); }
|
||||
|
||||
.nav-status {
|
||||
@@ -289,6 +302,7 @@ select:focus { border-color: var(--accent); }
|
||||
border-radius: 3px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.badge.deployed { background: var(--accent2); color: var(--accent); }
|
||||
@@ -614,6 +628,32 @@ select:focus { border-color: var(--accent); }
|
||||
|
||||
.confirm-actions { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
|
||||
/* ── SETTINGS MODAL ── */
|
||||
#settings-modal .modal-body { padding-top: 0; }
|
||||
.settings-section { padding: 16px 0; border-bottom: 1px solid var(--border); }
|
||||
.settings-section:last-child { border-bottom: none; padding-bottom: 0; }
|
||||
.settings-section-title {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
color: var(--text3);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.settings-desc { font-size: 12px; color: var(--text2); margin: 0 0 14px; line-height: 1.6; }
|
||||
.import-row { display: flex; gap: 10px; align-items: center; }
|
||||
.import-file-input { flex: 1; }
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg3);
|
||||
border-color: var(--border2);
|
||||
color: var(--text);
|
||||
}
|
||||
.btn-secondary:hover { border-color: var(--accent); color: var(--accent); }
|
||||
|
||||
.btn-danger { background: var(--red2); border-color: var(--red); color: var(--text); }
|
||||
.btn-danger:hover { background: var(--red); }
|
||||
|
||||
/* ── SCROLLBAR ── */
|
||||
::-webkit-scrollbar { width: 6px; }
|
||||
::-webkit-scrollbar-track { background: var(--bg); }
|
||||
|
||||
27
index.html
27
index.html
@@ -3,6 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<base href="/">
|
||||
<title>Catalyst</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
@@ -21,6 +22,7 @@
|
||||
<span class="nav-divider">·</span>
|
||||
<span id="nav-version"></span>
|
||||
</div>
|
||||
<button class="nav-btn" onclick="openSettingsModal()" title="Settings">⚙</button>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
@@ -170,6 +172,31 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SETTINGS MODAL -->
|
||||
<div id="settings-modal" class="modal-overlay">
|
||||
<div class="modal">
|
||||
<div class="modal-header">
|
||||
<span class="modal-title">Settings</span>
|
||||
<button class="modal-close" onclick="closeSettingsModal()">✕</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="settings-section">
|
||||
<div class="settings-section-title">Export</div>
|
||||
<p class="settings-desc">Download all instance data as a JSON backup file.</p>
|
||||
<button class="btn btn-secondary" onclick="exportDB()">Export Database</button>
|
||||
</div>
|
||||
<div class="settings-section">
|
||||
<div class="settings-section-title">Import</div>
|
||||
<p class="settings-desc">Restore from a backup file. This replaces all current instances.</p>
|
||||
<div class="import-row">
|
||||
<input type="file" id="import-file" accept=".json" class="form-input import-file-input">
|
||||
<button class="btn btn-danger" onclick="importDB()">Import</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TOAST -->
|
||||
<div class="toast" id="toast">
|
||||
<div class="toast-dot"></div>
|
||||
|
||||
@@ -38,6 +38,9 @@ window.addEventListener('popstate', e => {
|
||||
|
||||
// ── Bootstrap ─────────────────────────────────────────────────────────────────
|
||||
|
||||
if (VERSION) document.getElementById('nav-version').textContent = `v${VERSION}`;
|
||||
if (VERSION) {
|
||||
const label = /^\d/.test(VERSION) ? `v${VERSION}` : VERSION;
|
||||
document.getElementById('nav-version').textContent = label;
|
||||
}
|
||||
|
||||
handleRoute();
|
||||
|
||||
54
js/ui.js
54
js/ui.js
@@ -39,7 +39,6 @@ async function renderDashboard() {
|
||||
<div class="stat-cell"><div class="stat-label">deployed</div><div class="stat-value">${states['deployed'] || 0}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">testing</div><div class="stat-value amber">${states['testing'] || 0}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">degraded</div><div class="stat-value red">${states['degraded'] || 0}</div></div>
|
||||
<div class="stat-cell"><div class="stat-label">stacks</div><div class="stat-value">${(await getDistinctStacks()).length}</div></div>
|
||||
`;
|
||||
|
||||
await populateStackFilter();
|
||||
@@ -258,12 +257,62 @@ function showToast(msg, type = 'success') {
|
||||
toastTimer = setTimeout(() => t.classList.remove('show'), 3000);
|
||||
}
|
||||
|
||||
// ── Settings Modal ────────────────────────────────────────────────────────────
|
||||
|
||||
function openSettingsModal() {
|
||||
document.getElementById('settings-modal').classList.add('open');
|
||||
}
|
||||
|
||||
function closeSettingsModal() {
|
||||
document.getElementById('settings-modal').classList.remove('open');
|
||||
document.getElementById('import-file').value = '';
|
||||
}
|
||||
|
||||
async function exportDB() {
|
||||
const res = await fetch('/api/export');
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `catalyst-backup-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
async function importDB() {
|
||||
const file = document.getElementById('import-file').files[0];
|
||||
if (!file) { showToast('Select a backup file first', 'error'); return; }
|
||||
document.getElementById('confirm-title').textContent = 'Replace all instances?';
|
||||
document.getElementById('confirm-msg').textContent =
|
||||
`This will delete all current instances and replace them with the contents of "${file.name}". This cannot be undone.`;
|
||||
document.getElementById('confirm-overlay').classList.add('open');
|
||||
document.getElementById('confirm-ok').onclick = async () => {
|
||||
closeConfirm();
|
||||
try {
|
||||
const { instances } = JSON.parse(await file.text());
|
||||
const res = await fetch('/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ instances }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showToast(data.error ?? 'Import failed', 'error'); return; }
|
||||
showToast(`Imported ${data.imported} instance${data.imported !== 1 ? 's' : ''}`, 'success');
|
||||
closeSettingsModal();
|
||||
renderDashboard();
|
||||
} catch {
|
||||
showToast('Invalid backup file', 'error');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ── Keyboard / backdrop ───────────────────────────────────────────────────────
|
||||
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (document.getElementById('instance-modal').classList.contains('open')) { closeModal(); return; }
|
||||
if (document.getElementById('confirm-overlay').classList.contains('open')) { closeConfirm(); return; }
|
||||
if (document.getElementById('settings-modal').classList.contains('open')) { closeSettingsModal(); return; }
|
||||
});
|
||||
|
||||
document.getElementById('instance-modal').addEventListener('click', e => {
|
||||
@@ -272,3 +321,6 @@ document.getElementById('instance-modal').addEventListener('click', e => {
|
||||
document.getElementById('confirm-overlay').addEventListener('click', e => {
|
||||
if (e.target === document.getElementById('confirm-overlay')) closeConfirm();
|
||||
});
|
||||
document.getElementById('settings-modal').addEventListener('click', e => {
|
||||
if (e.target === document.getElementById('settings-modal')) closeSettingsModal();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "catalyst",
|
||||
"version": "1.1.1",
|
||||
"version": "1.2.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node server/server.js",
|
||||
|
||||
30
server/db.js
30
server/db.js
@@ -125,6 +125,21 @@ export function deleteInstance(vmid) {
|
||||
return db.prepare('DELETE FROM instances WHERE vmid = ?').run(vmid);
|
||||
}
|
||||
|
||||
export function importInstances(rows) {
|
||||
db.exec('BEGIN');
|
||||
db.exec('DELETE FROM instances');
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO instances
|
||||
(name, state, stack, vmid, atlas, argus, semaphore, patchmon,
|
||||
tailscale, andromeda, tailscale_ip, hardware_acceleration)
|
||||
VALUES
|
||||
(@name, @state, @stack, @vmid, @atlas, @argus, @semaphore, @patchmon,
|
||||
@tailscale, @andromeda, @tailscale_ip, @hardware_acceleration)
|
||||
`);
|
||||
for (const row of rows) insert.run(row);
|
||||
db.exec('COMMIT');
|
||||
}
|
||||
|
||||
// ── Test helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
export function _resetForTest() {
|
||||
@@ -133,5 +148,18 @@ export function _resetForTest() {
|
||||
}
|
||||
|
||||
// ── Boot ──────────────────────────────────────────────────────────────────────
|
||||
// Skipped in test environment — parallel Vitest workers would race to open
|
||||
// the same file, causing "database is locked". _resetForTest() in beforeEach
|
||||
// handles initialisation for every test worker using :memory: instead.
|
||||
|
||||
init(process.env.DB_PATH ?? DEFAULT_PATH);
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
const DB_PATH = process.env.DB_PATH ?? DEFAULT_PATH;
|
||||
try {
|
||||
init(DB_PATH);
|
||||
} catch (e) {
|
||||
console.error('[catalyst] fatal: could not open database at', DB_PATH);
|
||||
console.error('[catalyst] ensure the data directory exists and is writable by the server process.');
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Router } from 'express';
|
||||
import {
|
||||
getInstances, getInstance, getDistinctStacks,
|
||||
createInstance, updateInstance, deleteInstance,
|
||||
createInstance, updateInstance, deleteInstance, importInstances,
|
||||
} from './db.js';
|
||||
|
||||
export const router = Router();
|
||||
@@ -78,7 +78,8 @@ router.post('/instances', (req, res) => {
|
||||
} catch (e) {
|
||||
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
|
||||
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
|
||||
throw e;
|
||||
console.error('POST /api/instances', e);
|
||||
res.status(500).json({ error: 'internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -98,7 +99,37 @@ router.put('/instances/:vmid', (req, res) => {
|
||||
} catch (e) {
|
||||
if (e.message.includes('UNIQUE')) return res.status(409).json({ error: 'vmid already exists' });
|
||||
if (e.message.includes('CHECK')) return res.status(400).json({ error: 'invalid field value' });
|
||||
throw e;
|
||||
console.error('PUT /api/instances/:vmid', e);
|
||||
res.status(500).json({ error: 'internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/export
|
||||
router.get('/export', (_req, res) => {
|
||||
const instances = getInstances();
|
||||
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 });
|
||||
});
|
||||
|
||||
// POST /api/import
|
||||
router.post('/import', (req, res) => {
|
||||
const { instances } = req.body ?? {};
|
||||
if (!Array.isArray(instances)) {
|
||||
return res.status(400).json({ error: 'body must contain an instances array' });
|
||||
}
|
||||
const errors = [];
|
||||
for (const [i, row] of instances.entries()) {
|
||||
const errs = validate(normalise(row));
|
||||
if (errs.length) errors.push({ index: i, errors: errs });
|
||||
}
|
||||
if (errors.length) return res.status(400).json({ errors });
|
||||
try {
|
||||
importInstances(instances.map(normalise));
|
||||
res.json({ imported: instances.length });
|
||||
} catch (e) {
|
||||
console.error('POST /api/import', e);
|
||||
res.status(500).json({ error: 'internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -112,6 +143,11 @@ router.delete('/instances/:vmid', (req, res) => {
|
||||
if (instance.stack !== 'development')
|
||||
return res.status(422).json({ error: 'only development instances can be deleted' });
|
||||
|
||||
try {
|
||||
deleteInstance(vmid);
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
console.error('DELETE /api/instances/:vmid', e);
|
||||
res.status(500).json({ error: 'internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -11,10 +11,18 @@ export const app = express();
|
||||
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
useDefaults: false, // explicit — upgrade-insecure-requests breaks HTTP deployments
|
||||
directives: {
|
||||
...helmet.contentSecurityPolicy.getDefaultDirectives(),
|
||||
'style-src': ["'self'", 'https://fonts.googleapis.com'],
|
||||
'default-src': ["'self'"],
|
||||
'base-uri': ["'self'"],
|
||||
'font-src': ["'self'", 'https://fonts.gstatic.com'],
|
||||
'form-action': ["'self'"],
|
||||
'frame-ancestors': ["'self'"],
|
||||
'img-src': ["'self'", 'data:'],
|
||||
'object-src': ["'none'"],
|
||||
'script-src': ["'self'"],
|
||||
'script-src-attr': ["'unsafe-inline'"], // allow onclick handlers
|
||||
'style-src': ["'self'", 'https://fonts.googleapis.com'],
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import request from 'supertest'
|
||||
import { app } from '../server/server.js'
|
||||
import { _resetForTest } from '../server/db.js'
|
||||
import * as dbModule from '../server/db.js'
|
||||
|
||||
beforeEach(() => _resetForTest())
|
||||
|
||||
@@ -237,3 +238,160 @@ describe('DELETE /api/instances/:vmid', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
// ── GET /api/export ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('GET /api/export', () => {
|
||||
it('returns 200 with instances array and attachment header', async () => {
|
||||
await request(app).post('/api/instances').send(base)
|
||||
const res = await request(app).get('/api/export')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers['content-disposition']).toMatch(/attachment/)
|
||||
expect(res.body.instances).toHaveLength(1)
|
||||
expect(res.body.instances[0].name).toBe('traefik')
|
||||
})
|
||||
|
||||
it('returns empty instances array when no data', async () => {
|
||||
const res = await request(app).get('/api/export')
|
||||
expect(res.body.instances).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
// ── POST /api/import ──────────────────────────────────────────────────────────
|
||||
|
||||
describe('POST /api/import', () => {
|
||||
it('replaces all instances and returns imported count', async () => {
|
||||
await request(app).post('/api/instances').send(base)
|
||||
const res = await request(app).post('/api/import')
|
||||
.send({ instances: [{ ...base, vmid: 999, name: 'imported' }] })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body.imported).toBe(1)
|
||||
expect((await request(app).get('/api/instances')).body[0].name).toBe('imported')
|
||||
})
|
||||
|
||||
it('returns 400 if instances is not an array', async () => {
|
||||
expect((await request(app).post('/api/import').send({ instances: 'bad' })).status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 with per-row errors for invalid rows', async () => {
|
||||
const res = await request(app).post('/api/import')
|
||||
.send({ instances: [{ ...base, name: '', vmid: 1 }] })
|
||||
expect(res.status).toBe(400)
|
||||
expect(res.body.errors[0].index).toBe(0)
|
||||
})
|
||||
|
||||
it('returns 400 if body has no instances key', async () => {
|
||||
expect((await request(app).post('/api/import').send({})).status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
// ── Static assets & SPA routing ───────────────────────────────────────────────
|
||||
|
||||
describe('static assets and SPA routing', () => {
|
||||
it('serves index.html at root', async () => {
|
||||
const res = await request(app).get('/')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers['content-type']).toMatch(/html/)
|
||||
})
|
||||
|
||||
it('serves index.html for deep SPA routes (e.g. /instance/117)', async () => {
|
||||
const res = await request(app).get('/instance/117')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers['content-type']).toMatch(/html/)
|
||||
})
|
||||
|
||||
it('serves CSS with correct content-type (not sniffed as HTML)', async () => {
|
||||
const res = await request(app).get('/css/app.css')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers['content-type']).toMatch(/text\/css/)
|
||||
})
|
||||
|
||||
it('does not set upgrade-insecure-requests in CSP (HTTP deployments must work)', async () => {
|
||||
const res = await request(app).get('/')
|
||||
const csp = res.headers['content-security-policy'] ?? ''
|
||||
expect(csp).not.toContain('upgrade-insecure-requests')
|
||||
})
|
||||
|
||||
it('allows inline event handlers in CSP (onclick attributes)', async () => {
|
||||
const res = await request(app).get('/')
|
||||
const csp = res.headers['content-security-policy'] ?? ''
|
||||
// script-src-attr must not be 'none' — that blocks onclick handlers
|
||||
expect(csp).not.toContain("script-src-attr 'none'")
|
||||
})
|
||||
|
||||
it('index.html contains base href / for correct asset resolution on deep routes', async () => {
|
||||
const res = await request(app).get('/')
|
||||
expect(res.text).toContain('<base href="/">')
|
||||
})
|
||||
})
|
||||
|
||||
// ── Error handling — unexpected DB failures ───────────────────────────────────
|
||||
|
||||
const dbError = () => Object.assign(
|
||||
new Error('attempt to write a readonly database'),
|
||||
{ code: 'ERR_SQLITE_ERROR', errcode: 8 }
|
||||
)
|
||||
|
||||
describe('error handling — unexpected DB failures', () => {
|
||||
let consoleSpy
|
||||
|
||||
beforeEach(() => {
|
||||
consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST returns 500 with friendly message when DB throws unexpectedly', async () => {
|
||||
vi.spyOn(dbModule, 'createInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
const res = await request(app).post('/api/instances').send(base)
|
||||
expect(res.status).toBe(500)
|
||||
expect(res.body).toEqual({ error: 'internal server error' })
|
||||
})
|
||||
|
||||
it('POST logs the error with route context when DB throws unexpectedly', async () => {
|
||||
vi.spyOn(dbModule, 'createInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
await request(app).post('/api/instances').send(base)
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('POST /api/instances'),
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
|
||||
it('PUT returns 500 with friendly message when DB throws unexpectedly', async () => {
|
||||
await request(app).post('/api/instances').send(base)
|
||||
vi.spyOn(dbModule, 'updateInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
const res = await request(app).put('/api/instances/100').send(base)
|
||||
expect(res.status).toBe(500)
|
||||
expect(res.body).toEqual({ error: 'internal server error' })
|
||||
})
|
||||
|
||||
it('PUT logs the error with route context when DB throws unexpectedly', async () => {
|
||||
await request(app).post('/api/instances').send(base)
|
||||
vi.spyOn(dbModule, 'updateInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
await request(app).put('/api/instances/100').send(base)
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('PUT /api/instances/:vmid'),
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
|
||||
it('DELETE returns 500 with friendly message when DB throws unexpectedly', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, stack: 'development', state: 'testing' })
|
||||
vi.spyOn(dbModule, 'deleteInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
const res = await request(app).delete('/api/instances/100')
|
||||
expect(res.status).toBe(500)
|
||||
expect(res.body).toEqual({ error: 'internal server error' })
|
||||
})
|
||||
|
||||
it('DELETE logs the error with route context when DB throws unexpectedly', async () => {
|
||||
await request(app).post('/api/instances').send({ ...base, stack: 'development', state: 'testing' })
|
||||
vi.spyOn(dbModule, 'deleteInstance').mockImplementationOnce(() => { throw dbError() })
|
||||
await request(app).delete('/api/instances/100')
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('DELETE /api/instances/:vmid'),
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import {
|
||||
_resetForTest,
|
||||
getInstances, getInstance, getDistinctStacks,
|
||||
createInstance, updateInstance, deleteInstance,
|
||||
createInstance, updateInstance, deleteInstance, importInstances,
|
||||
} from '../server/db.js'
|
||||
|
||||
beforeEach(() => _resetForTest());
|
||||
@@ -165,3 +165,42 @@ describe('deleteInstance', () => {
|
||||
expect(getInstance(2)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── importInstances ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('importInstances', () => {
|
||||
const base = { state: 'deployed', stack: 'production', atlas: 0, argus: 0, semaphore: 0, patchmon: 0, tailscale: 0, andromeda: 0, tailscale_ip: '', hardware_acceleration: 0 };
|
||||
|
||||
it('replaces all existing instances with the imported set', () => {
|
||||
createInstance({ ...base, name: 'old', vmid: 1 });
|
||||
importInstances([{ ...base, name: 'new', vmid: 2 }]);
|
||||
expect(getInstance(1)).toBeNull();
|
||||
expect(getInstance(2)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('clears all instances when passed an empty array', () => {
|
||||
createInstance({ ...base, name: 'a', vmid: 1 });
|
||||
importInstances([]);
|
||||
expect(getInstances()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Test environment boot isolation ───────────────────────────────────────────
|
||||
|
||||
describe('test environment boot isolation', () => {
|
||||
it('vitest runs with NODE_ENV=test', () => {
|
||||
// Vitest sets NODE_ENV=test automatically. This is the guard condition
|
||||
// that prevents the boot init() from opening the real database file.
|
||||
expect(process.env.NODE_ENV).toBe('test');
|
||||
});
|
||||
|
||||
it('db module loads cleanly in parallel workers without locking the real db file', () => {
|
||||
// Regression: the module-level init(DEFAULT_PATH) used to run unconditionally,
|
||||
// causing "database is locked" when multiple test workers imported db.js at
|
||||
// the same time. process.exit(1) then killed the worker mid-suite.
|
||||
// Fix: boot init is skipped when NODE_ENV=test. _resetForTest() handles setup.
|
||||
// Reaching this line proves the module loaded without calling process.exit.
|
||||
expect(() => _resetForTest()).not.toThrow();
|
||||
expect(getInstances()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
// ── esc() ─────────────────────────────────────────────────────────────────────
|
||||
// Mirrors the implementation in ui.js exactly (DOM-based).
|
||||
@@ -112,3 +114,53 @@ describe('fmtDateFull', () => {
|
||||
expect(fmtDateFull('')).toBe('—')
|
||||
})
|
||||
})
|
||||
|
||||
// ── versionLabel() ───────────────────────────────────────────────────────────
|
||||
// Mirrors the logic in app.js — semver strings get a v prefix, dev strings don't.
|
||||
|
||||
function versionLabel(v) {
|
||||
return /^\d/.test(v) ? `v${v}` : v
|
||||
}
|
||||
|
||||
describe('version label formatting', () => {
|
||||
it('prepends v for semver strings', () => {
|
||||
expect(versionLabel('1.1.2')).toBe('v1.1.2')
|
||||
expect(versionLabel('2.0.0')).toBe('v2.0.0')
|
||||
})
|
||||
|
||||
it('does not prepend v for dev build strings', () => {
|
||||
expect(versionLabel('dev-abc1234')).toBe('dev-abc1234')
|
||||
})
|
||||
})
|
||||
|
||||
// ── CSS regressions ───────────────────────────────────────────────────────────
|
||||
|
||||
const css = readFileSync(join(__dirname, '../css/app.css'), 'utf8')
|
||||
|
||||
describe('CSS regressions', () => {
|
||||
it('.badge has text-align: center so state labels are not left-skewed on cards', () => {
|
||||
// Regression: badges rendered left-aligned inside the card's flex-end column.
|
||||
// Without text-align: center, short labels (e.g. "deployed") appear
|
||||
// left-justified inside their pill rather than centred.
|
||||
expect(css).toMatch(/\.badge\s*\{[^}]*text-align\s*:\s*center/s)
|
||||
})
|
||||
})
|
||||
|
||||
// ── CI workflow regressions ───────────────────────────────────────────────────
|
||||
|
||||
const ciYml = readFileSync(join(__dirname, '../.gitea/workflows/ci.yml'), 'utf8')
|
||||
|
||||
describe('CI workflow regressions', () => {
|
||||
it('build-dev job passes BUILD_VERSION build arg', () => {
|
||||
// Regression: dev image showed semver instead of dev-<sha> because
|
||||
// BUILD_VERSION was never passed to docker build.
|
||||
expect(ciYml).toContain('BUILD_VERSION')
|
||||
})
|
||||
|
||||
it('short SHA is computed with git rev-parse, not $GITEA_SHA (which is empty)', () => {
|
||||
// Regression: ${GITEA_SHA::7} expands to "" on Gitea runners — nav showed "dev-".
|
||||
// git rev-parse --short HEAD works regardless of which env vars the runner sets.
|
||||
expect(ciYml).toContain('git rev-parse --short HEAD')
|
||||
expect(ciYml).not.toContain('GITEA_SHA')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user