feat(db,schemas): add migration 004, runtime throttle profile, and v1.1 Zod schemas

This commit is contained in:
tyuXX 2026-11-27 22:15:50 +00:00
parent d7c3e11d7e
commit afc2d6358a
30 changed files with 792 additions and 118 deletions

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
@ -205,6 +205,8 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
return { status: res.status, data };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -225,7 +227,11 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
await api('/api/vault/credentials', {

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -132,6 +132,8 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
return { status: res.status, data };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -152,7 +154,11 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
@ -115,7 +115,9 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
expect(health.status).toBe(200);
await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401');
// 2. Bootstrap Admin + TOTP
// 2. Bootstrap Admin + TOTP (offset 65s back so step-up tests below have fresh TOTP steps)
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 65_000);
const bootInfo = await api('/api/auth/bootstrap');
expect(bootInfo.status).toBe(200);
const secretBase32 = String(bootInfo.data.secretBase32);
@ -138,6 +140,7 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
initialSafeMode: false,
},
});
vi.setSystemTime(Date.now() + 31_000);
expect(bootDone.status).toBe(201);
csrfToken = String(bootDone.data.csrfToken);
const recoveryCodes = bootDone.data.recoveryCodes as string[];
@ -198,17 +201,14 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
(await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
).toBe(200);
// 6. Vault Init + Drop Elevation -> Step-Up guard + Generate Ed25519 key
// 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key
const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201);
const generatedMasterKey = String(vInit.data.generatedKeyHex);
// Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement
const statusBeforeDrop = await api('/api/auth/status');
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
expect(dropped.status).toBe(200);
expect(dropped.data.elevatedUntil).toBeNull();
// v1.1 defaults elevateOnLogin=false; step up first, then verify drop-elevation clears it
const statusInitial = await api('/api/auth/status');
expect(statusInitial.data.elevatedUntil).toBeNull();
const noStepUp = await api('/api/vault/generate-ed25519', {
method: 'POST',
@ -223,6 +223,23 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
});
expect(stepUpRes.status).toBe(200);
const statusBeforeDrop = await api('/api/auth/status');
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
expect(dropped.status).toBe(200);
expect(dropped.data.elevatedUntil).toBeNull();
const afterDropDenied = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' },
});
expect(afterDropDenied.status).toBe(403);
vi.useRealTimers();
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status,
).toBe(200);
const genRes = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' },

View file

@ -164,7 +164,7 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
db.close();
});
it('grants default 1h elevation on bootstrap/login and preserves elevation across Safe Mode toggle', async () => {
it('keeps elevateOnLogin disabled by default (15m step-up policy) and preserves elevation across Safe Mode toggle', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
@ -180,11 +180,18 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
userAgent: 'vitest',
});
expect(boot.session.elevatedUntil).toBe(t0 + 60 * 60 * 1000);
expect(boot.session.elevatedUntil).toBeNull();
vi.setSystemTime(t0 + 31_000);
const step = await auth.stepUp(boot.session.idHash, generateTotp(enroll.secretBase32, t0 + 31_000));
expect(step).toEqual({
ok: true,
elevatedUntil: t0 + 31_000 + 15 * 60 * 1000,
});
const safeSession = auth.setSafeMode(boot.session.idHash, true);
expect(safeSession?.safeMode).toBe(true);
expect(safeSession?.elevatedUntil).toBe(t0 + 60 * 60 * 1000);
expect(safeSession?.elevatedUntil).toBe(t0 + 31_000 + 15 * 60 * 1000);
db.close();
});

View file

@ -4,7 +4,7 @@ import os from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createGCoordinatorServer } from '../src/server/app.js';
import { openDatabase } from '../src/server/db/database.js';
import { VaultService } from '../src/server/security/vault.js';
@ -84,6 +84,8 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
return { status: res.status, data };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -104,7 +106,11 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -103,6 +103,8 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
return { status: res.status, data: data as Record<string, unknown> };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -123,7 +125,11 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -192,7 +192,13 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
).status,
).toBe(201);
// Initialize vault & generate key while default 1h login elevation is active
// Explicitly step up before vault mutations (v1.1 default elevateOnLogin=false)
vi.setSystemTime(t0 + 31_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status,
).toBe(200);
// Initialize vault & generate key while elevated
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
expect(
(
@ -231,7 +237,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf();
vi.setSystemTime(t0 + 31_000);
vi.setSystemTime(t0 + 62_000);
const anyLogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
@ -275,7 +281,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
// Logout and test 'all' enforcement
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf();
vi.setSystemTime(t0 + 62_000);
vi.setSystemTime(t0 + 93_000);
const partialPw = await api.call('/api/auth/login', {
method: 'POST',
@ -288,7 +294,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
});
expect(partialPw.status).toBe(401);
vi.setSystemTime(t0 + 93_000);
vi.setSystemTime(t0 + 124_000);
const partialTotp = await api.call('/api/auth/login', {
method: 'POST',
body: {
@ -300,7 +306,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
});
expect(partialTotp.status).toBe(401);
vi.setSystemTime(t0 + 124_000);
vi.setSystemTime(t0 + 155_000);
const fullAllLogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
@ -364,6 +370,24 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
}
});
const curSettings = server.configManager.getSettings();
server.configManager.saveConfigText(
'settings.json',
JSON.stringify(
{
...curSettings,
security: {
...curSettings.security,
enableEmergencySecretsBackup: true,
},
},
null,
2,
),
'ui',
'Enable emergency recovery for test',
);
let api = createApiClient(server);
const bootInfo = await api.call('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
@ -382,6 +406,11 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
expect(boot.status).toBe(201);
const recoveryCodes = boot.data.recoveryCodes as string[];
vi.setSystemTime(t0 + 31_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
const vInit = await api.call('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201);
const masterKeyHex = String(vInit.data.generatedKeyHex);
@ -478,6 +507,11 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
).status,
).toBe(200);
vi.setSystemTime(t0 + 62_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
const wipeRes = await api.call('/api/auth/recovery-backup?disable=1', {
method: 'DELETE',
});

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createGCoordinatorServer } from '../src/server/app.js';
const cleanups: Array<() => Promise<void> | void> = [];
@ -202,6 +202,8 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
return { status: res.status, data };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -226,6 +228,10 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
})
).status,
).toBe(201);
vi.useRealTimers();
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -82,6 +82,8 @@ async function setupServerWithSsh() {
return { status: res.status, data: data as Record<string, unknown> };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -102,7 +104,11 @@ async function setupServerWithSsh() {
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -2,7 +2,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -88,6 +88,8 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic
};
// Bootstrap + Auth + Vault + Ed25519 Key
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -108,6 +110,7 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic
secretBase32,
},
});
vi.useRealTimers();
expect(bootRes.status).toBe(201);
csrfToken = String(bootRes.data.csrfToken);

View file

@ -4,7 +4,7 @@ import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket, { WebSocketServer } from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -127,6 +127,8 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
return { status: res.status, data: data as Record<string, unknown> };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -147,7 +149,11 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -2,7 +2,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -104,6 +104,8 @@ describe('Always-on background collectors & write-only Vault lock', () => {
}
});
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 65_000);
let api = createApiClient(activeServer);
const bootInfo = await api.call('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
@ -130,6 +132,12 @@ describe('Always-on background collectors & write-only Vault lock', () => {
const recoveryCodes = bootRes.data.recoveryCodes as string[];
expect(recoveryCodes.length).toBeGreaterThan(0);
vi.setSystemTime(Date.now() + 31_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
vi.useRealTimers();
// Explicitly initialize & add SSH key, register server, then lock Vault
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
const keyRes = await api.call('/api/vault/generate-ed25519', {
@ -230,6 +238,11 @@ describe('Always-on background collectors & write-only Vault lock', () => {
expect((await api.call('/api/servers/srv-1/inspect')).status).toBe(200);
expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).status).toBe(200);
// Step up so the Vault write-lock guard (423 VAULT_LOCKED) is reached
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
// Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked
const addBlocked = await api.call('/api/vault/credentials', {
method: 'POST',

View file

@ -141,6 +141,8 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
return { status: res.status, data };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({
@ -161,7 +163,11 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {
@ -751,20 +757,36 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
expect(dCancelled.run.status).toBe('cancelled');
expect(dCancelled.run.cancelledBy).toBe('admin');
// --- 5. Cron Workflow Scheduling ---
await api('/api/workflows', {
// --- 5. Cron Workflow Scheduling (5-field enforced; 6-field rejected) ---
const badCronRes = await api('/api/workflows', {
method: 'POST',
body: {
id: 'wf-cron-bad',
name: '6-Field Spam Cron',
enabled: true,
trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' },
overlapPolicy: 'skip',
display: { mode: 'log' },
inputs: [],
steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo NOPE' }],
},
});
expect(badCronRes.status).toBe(400);
const okCronRes = await api('/api/workflows', {
method: 'POST',
body: {
id: 'wf-cron-sec',
name: 'Every Second Cron',
name: 'Every Minute Cron',
enabled: true,
trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' },
trigger: { type: 'cron', expression: '* * * * *', timezone: 'UTC' },
overlapPolicy: 'skip',
display: { mode: 'log' },
inputs: [],
steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }],
},
});
expect(okCronRes.status).toBe(201);
const listSummary = await api('/api/workflows');
const cronSummary = (
@ -776,6 +798,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
expect(typeof cronSummary?.nextRunAt).toBe('number');
expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000);
expect(await server.workflowEngine.triggerScheduledCron('wf-cron-sec')).toBe(true);
const cronRun = await waitFor(
() => {
const runs = server.workflowEngine.listRuns('wf-cron-sec');