mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-05 00:00:41 +00:00
Add comprehensive test suite for application functionality
- Implement tests for HTTP API endpoints, ensuring correct responses and security headers. - Create configuration tests to validate loading of defaults and environment overrides. - Add tests for FEDL service to verify data handling and snapshot functionality. - Introduce GitHub service tests to check API data normalization and caching behavior. - Develop monitor service tests for network checks and uptime calculations. - Implement persistence tests to ensure database migrations are idempotent and data persists across restarts. - Add vault service tests for session management and brute-force protection mechanisms. - Include helper functions for test context creation and JSON response handling.
This commit is contained in:
1 parent
84b7a7e302
commit
c250653961
55 files changed
+8174
-226
No files matched your search
@@ -0,0 +1,108 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createAnalyticsService } from '../server/services/analytics.js';
|
||||
import { createTestContext } from './helpers.js';
|
||||
|
||||
test('analytics records normalized, deduplicated, non-bot pageviews', (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
let at = new Date('2026-11-07T12:00:00.000Z');
|
||||
const service = createAnalyticsService({ db, config, now: () => at });
|
||||
const userAgent = 'Mozilla/5.0 (Macintosh) AppleWebKit/537.36 Chrome/130 Safari/537.36';
|
||||
|
||||
const first = service.recordHit({
|
||||
path: '/projects/fedl.html?utm=1#top',
|
||||
referrer: 'https://www.google.com/search?q=test',
|
||||
ip: '203.0.113.9',
|
||||
userAgent,
|
||||
at
|
||||
});
|
||||
assert.equal(first.recorded, true);
|
||||
assert.equal(first.path, '/projects/fedl.html');
|
||||
|
||||
const duplicate = service.recordHit({
|
||||
path: '/projects/fedl.html',
|
||||
referrer: null,
|
||||
ip: '203.0.113.9',
|
||||
userAgent,
|
||||
at
|
||||
});
|
||||
assert.equal(duplicate.recorded, false);
|
||||
assert.equal(duplicate.reason, 'duplicate');
|
||||
|
||||
const bot = service.recordHit({
|
||||
path: '/',
|
||||
referrer: null,
|
||||
ip: '203.0.113.9',
|
||||
userAgent: 'Googlebot/2.1 (+http://www.google.com/bot.html)',
|
||||
at
|
||||
});
|
||||
assert.equal(bot.recorded, false);
|
||||
assert.equal(bot.reason, 'bot');
|
||||
|
||||
at = new Date(at.getTime() + 11 * 1000);
|
||||
const afterDedupe = service.recordHit({
|
||||
path: '/',
|
||||
referrer: null,
|
||||
ip: '203.0.113.9',
|
||||
userAgent,
|
||||
at
|
||||
});
|
||||
assert.equal(afterDedupe.recorded, true);
|
||||
|
||||
const rows = db.prepare('SELECT path, visitor_hash, referrer_domain FROM pageviews ORDER BY id').all();
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0].path, '/projects/fedl.html');
|
||||
assert.equal(rows[0].referrer_domain, 'www.google.com');
|
||||
assert.equal(rows[1].path, '/');
|
||||
assert.notEqual(rows[0].visitor_hash, '203.0.113.9');
|
||||
assert.equal(rows[0].visitor_hash.length, 32);
|
||||
|
||||
const columns = db.prepare('PRAGMA table_info(pageviews)').all().map((row) => row.name);
|
||||
assert.equal(columns.includes('ip'), false);
|
||||
assert.equal(columns.includes('ip_address'), false);
|
||||
});
|
||||
|
||||
test('analytics returns correct totals, daily series, pages, and recent activity', (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const at = new Date('2026-11-07T12:00:00.000Z');
|
||||
const service = createAnalyticsService({ db, config, now: () => at });
|
||||
const ua = 'Mozilla/5.0 (Macintosh) AppleWebKit/537.36 Chrome/130 Safari/537.36';
|
||||
|
||||
const insert = service.recordHit.bind(service);
|
||||
insert({ path: '/', ip: '198.51.100.1', userAgent: ua, at: new Date('2026-11-01T10:00:00.000Z') });
|
||||
insert({ path: '/projects/fedl.html', ip: '198.51.100.1', userAgent: ua, at: new Date('2026-11-06T10:00:00.000Z') });
|
||||
insert({ path: '/', ip: '198.51.100.2', userAgent: ua, at: new Date('2026-11-07T09:00:00.000Z') });
|
||||
insert({ path: '/', ip: '198.51.100.3', userAgent: ua, at: new Date('2026-11-07T10:00:00.000Z') });
|
||||
|
||||
const overview = service.getOverview({ at });
|
||||
assert.equal(overview.totals.pageviews, 4);
|
||||
assert.equal(overview.totals.pageviewsToday, 2);
|
||||
assert.equal(overview.totals.uniqueVisitorsToday, 2);
|
||||
assert.equal(overview.totals.pageviews7d, 4);
|
||||
assert.equal(overview.daily.length, 30);
|
||||
assert.equal(overview.daily.find((day) => day.day === '2026-11-07').views, 2);
|
||||
assert.equal(overview.topPages[0].path, '/');
|
||||
assert.equal(overview.topPages[0].views, 3);
|
||||
assert.equal(overview.recentActivity.length, 4);
|
||||
|
||||
const pages = service.getPages({ at, days: 7, limit: 10 });
|
||||
assert.equal(pages.totalPageviews, 4);
|
||||
assert.equal(pages.pages.find((page) => page.path === '/').share, 75);
|
||||
});
|
||||
|
||||
test('analytics hashing rotates daily and retention cleanup removes old rows', (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const dayOne = new Date('2026-11-07T12:00:00.000Z');
|
||||
const dayTwo = new Date('2026-11-08T12:00:00.000Z');
|
||||
const service = createAnalyticsService({ db, config, now: () => dayOne });
|
||||
const ua = 'Mozilla/5.0 Chrome/130 Safari/537.36';
|
||||
|
||||
service.recordHit({ path: '/one', ip: '198.51.100.5', userAgent: ua, at: dayOne });
|
||||
service.recordHit({ path: '/two', ip: '198.51.100.5', userAgent: ua, at: dayTwo });
|
||||
const hashes = db.prepare('SELECT visitor_hash FROM pageviews ORDER BY id').all().map((row) => row.visitor_hash);
|
||||
assert.notEqual(hashes[0], hashes[1], 'daily salt must rotate visitor hashes');
|
||||
|
||||
const removed = service.cleanup(new Date('2026-12-10T12:00:00.000Z'));
|
||||
assert.equal(removed, 2);
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS c FROM pageviews').get().c, 0);
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import argon2 from 'argon2';
|
||||
import { createApp } from '../server/app.js';
|
||||
import { createStatusService } from '../server/services/status.js';
|
||||
import { createAnalyticsService } from '../server/services/analytics.js';
|
||||
import { createVaultService } from '../server/services/vault.js';
|
||||
import { resolveStaticPath } from '../server/lib/static.js';
|
||||
import { createTestContext, silentLogger } from './helpers.js';
|
||||
|
||||
async function buildServer(t, overrides = {}) {
|
||||
const ctx = createTestContext(t, overrides);
|
||||
const hash = await argon2.hash('test-passphrase', {
|
||||
type: argon2.argon2id,
|
||||
timeCost: 1,
|
||||
memoryCost: 8192,
|
||||
parallelism: 1,
|
||||
hashLength: 32
|
||||
});
|
||||
ctx.config.vault.passwordHash = hash;
|
||||
const logger = silentLogger();
|
||||
const status = createStatusService({ db: ctx.db, config: ctx.config });
|
||||
const analytics = createAnalyticsService({ db: ctx.db, config: ctx.config });
|
||||
const vault = await createVaultService({ db: ctx.db, config: ctx.config, logger });
|
||||
const github = {
|
||||
getOverview: async () => ({ generatedAt: new Date().toISOString(), totals: { stars: 1 } }),
|
||||
getActivity: async () => ({ generatedAt: new Date().toISOString(), activity: { days: [] } }),
|
||||
getRepositories: async () => ({ generatedAt: new Date().toISOString(), repositories: [] })
|
||||
};
|
||||
const fedl = {
|
||||
getStats: async () => ({
|
||||
generatedAt: new Date().toISOString(),
|
||||
totals: { rankedLevels: 2, records: 1 },
|
||||
topLevels: [],
|
||||
changes: { comparedTo: null, counts: {} }
|
||||
}),
|
||||
getActivity: async () => ({ generatedAt: new Date().toISOString(), changes: {} })
|
||||
};
|
||||
const app = createApp({
|
||||
config: ctx.config,
|
||||
db: ctx.db,
|
||||
logger,
|
||||
services: { status, analytics, vault, github, fedl, monitor: {} }
|
||||
});
|
||||
const server = http.createServer((req, res) => app(req, res));
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
t.after(() => new Promise((resolve) => server.close(resolve)));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
return { ...ctx, app, server, base, vault };
|
||||
}
|
||||
|
||||
test('HTTP app exposes documented APIs, security headers, and CORS allowlist', async (t) => {
|
||||
const { base } = await buildServer(t);
|
||||
|
||||
const health = await fetch(base + '/api/health');
|
||||
assert.equal(health.status, 200);
|
||||
assert.equal(health.headers.get('x-content-type-options'), 'nosniff');
|
||||
assert.equal(health.headers.get('x-frame-options'), 'DENY');
|
||||
assert.ok(health.headers.get('x-request-id'));
|
||||
const healthBody = await health.json();
|
||||
assert.equal(healthBody.status, 'ok');
|
||||
|
||||
const status = await fetch(base + '/api/status');
|
||||
assert.equal(status.status, 200);
|
||||
const statusBody = await status.json();
|
||||
assert.equal(statusBody.servers.length, 1);
|
||||
assert.equal(statusBody.services.length, 1);
|
||||
|
||||
const preflight = await fetch(base + '/api/status', {
|
||||
method: 'OPTIONS',
|
||||
headers: {
|
||||
Origin: 'https://milesallen.site',
|
||||
'Access-Control-Request-Method': 'GET'
|
||||
}
|
||||
});
|
||||
assert.equal(preflight.status, 204);
|
||||
assert.equal(preflight.headers.get('access-control-allow-origin'), 'https://milesallen.site');
|
||||
|
||||
const blocked = await fetch(base + '/api/status', {
|
||||
headers: { Origin: 'https://evil.example' }
|
||||
});
|
||||
assert.equal(blocked.status, 403);
|
||||
|
||||
const missing = await fetch(base + '/api/nope');
|
||||
assert.equal(missing.status, 404);
|
||||
const missingBody = await missing.json();
|
||||
assert.equal(missingBody.error.code, 'not_found');
|
||||
|
||||
const wrongMethod = await fetch(base + '/api/status', { method: 'POST' });
|
||||
assert.equal(wrongMethod.status, 405);
|
||||
});
|
||||
|
||||
test('Moon Vault content is server-gated and the old passphrase is gone from public files', async (t) => {
|
||||
const { base } = await buildServer(t);
|
||||
|
||||
const lockResponse = await fetch(base + '/moon-vault.html');
|
||||
assert.equal(lockResponse.status, 200);
|
||||
const lockHtml = await lockResponse.text();
|
||||
assert.equal(/password\s*===/.test(lockHtml), false, 'no client-side password comparison');
|
||||
assert.equal(lockHtml.includes('localStorage'), false);
|
||||
assert.equal(lockHtml.includes('sessionStorage'), false);
|
||||
|
||||
const gate = await fetch(base + '/vault', { redirect: 'manual' });
|
||||
assert.equal(gate.status, 302);
|
||||
assert.equal(gate.headers.get('location'), '/moon-vault.html');
|
||||
|
||||
const deniedGame = await fetch(base + '/games/dino.html', { redirect: 'manual' });
|
||||
assert.equal(deniedGame.status, 302);
|
||||
|
||||
const badLogin = await fetch(base + '/api/vault/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'wrong' })
|
||||
});
|
||||
assert.equal(badLogin.status, 401);
|
||||
|
||||
const login = await fetch(base + '/api/vault/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'test-passphrase' })
|
||||
});
|
||||
assert.equal(login.status, 200);
|
||||
const setCookie = login.headers.get('set-cookie');
|
||||
assert.match(setCookie, /HttpOnly/);
|
||||
assert.match(setCookie, /SameSite=Strict/);
|
||||
const cookie = setCookie.split(';')[0];
|
||||
|
||||
const session = await fetch(base + '/api/vault/session', { headers: { Cookie: cookie } });
|
||||
const sessionBody = await session.json();
|
||||
assert.equal(sessionBody.enabled, true);
|
||||
assert.equal(sessionBody.authenticated, true);
|
||||
assert.ok(sessionBody.expiresAt);
|
||||
|
||||
const vault = await fetch(base + '/vault', { headers: { Cookie: cookie } });
|
||||
assert.equal(vault.status, 200);
|
||||
const vaultHtml = await vault.text();
|
||||
assert.match(vaultHtml, /MOON VAULT/);
|
||||
assert.match(vaultHtml, /data-no-design-picker/, 'vault page must not auto-open the site-wide design picker');
|
||||
assert.equal(/password\s*===/.test(vaultHtml), false, 'vault content is not gated in client code');
|
||||
|
||||
const game = await fetch(base + '/games/dino.html', { headers: { Cookie: cookie } });
|
||||
assert.equal(game.status, 200);
|
||||
assert.equal(game.headers.get('cache-control'), 'no-store', 'protected games must not be cached');
|
||||
|
||||
const logout = await fetch(base + '/api/vault/logout', {
|
||||
method: 'POST',
|
||||
headers: { Cookie: cookie }
|
||||
});
|
||||
assert.equal(logout.status, 200);
|
||||
assert.match(logout.headers.get('set-cookie'), /Max-Age=0/);
|
||||
|
||||
const afterLogout = await fetch(base + '/vault', {
|
||||
headers: { Cookie: cookie },
|
||||
redirect: 'manual'
|
||||
});
|
||||
assert.equal(afterLogout.status, 302);
|
||||
});
|
||||
|
||||
test('analytics endpoint records normalized hits and rejects oversized bodies', async (t) => {
|
||||
const { base, db } = await buildServer(t, { http: { bodyLimitBytes: 2048 } });
|
||||
const response = await fetch(base + '/api/analytics/hit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'Mozilla/5.0 Chrome/130 Safari/537.36'
|
||||
},
|
||||
body: JSON.stringify({ path: '/hello?secret=1', referrer: 'https://example.com/x' })
|
||||
});
|
||||
assert.equal(response.status, 202);
|
||||
assert.deepEqual(await response.json(), { recorded: true, reason: null });
|
||||
const row = db.prepare('SELECT path, referrer_domain FROM pageviews').get();
|
||||
assert.equal(row.path, '/hello');
|
||||
assert.equal(row.referrer_domain, 'example.com');
|
||||
|
||||
const huge = await fetch(base + '/api/analytics/hit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{"path":"/' + 'a'.repeat(3000) + '"}'
|
||||
});
|
||||
assert.equal(huge.status, 400);
|
||||
});
|
||||
|
||||
test('login rate limiting returns 429 with Retry-After', async (t) => {
|
||||
const { base } = await buildServer(t, {
|
||||
rateLimits: {
|
||||
api: { limit: 1000, windowMs: 60_000 },
|
||||
analytics: { limit: 1000, windowMs: 60_000 },
|
||||
login: { limit: 1, windowMs: 60_000 }
|
||||
}
|
||||
});
|
||||
const first = await fetch(base + '/api/vault/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'wrong' })
|
||||
});
|
||||
assert.equal(first.status, 401);
|
||||
const second = await fetch(base + '/api/vault/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: 'wrong' })
|
||||
});
|
||||
assert.equal(second.status, 429);
|
||||
assert.ok(second.headers.get('retry-after'));
|
||||
});
|
||||
|
||||
test('static resolver blocks traversal and private server files', async () => {
|
||||
const root = process.cwd();
|
||||
assert.deepEqual(await resolveStaticPath(root, '/../package.json'), { error: 403 });
|
||||
assert.deepEqual(await resolveStaticPath(root, '/server/config.js'), { error: 403 });
|
||||
assert.deepEqual(await resolveStaticPath(root, '/.env'), { error: 403 });
|
||||
assert.deepEqual(await resolveStaticPath(root, '/data/dashboard.db'), { error: 403 });
|
||||
assert.deepEqual(await resolveStaticPath(root, '/node_modules/argon2/package.json'), { error: 403 });
|
||||
|
||||
const index = await resolveStaticPath(root, '/');
|
||||
assert.equal(index.file.endsWith('index.html'), true);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { loadConfig } from '../server/config.js';
|
||||
|
||||
const secret = 'a'.repeat(48);
|
||||
|
||||
test('config loads local defaults and project registry', () => {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: 'development',
|
||||
SESSION_SECRET: secret,
|
||||
VAULT_PASSWORD: 'a local passphrase'
|
||||
});
|
||||
|
||||
assert.equal(config.port, 8787);
|
||||
assert.equal(config.host, '127.0.0.1');
|
||||
assert.equal(config.production, false);
|
||||
assert.ok(config.allowedOrigins.has('http://localhost:8787'));
|
||||
assert.ok(config.allowedOrigins.has('https://milesallen.site'));
|
||||
assert.ok(config.projects.length > 5);
|
||||
assert.equal(config.projects.find((p) => p.id === 'fedl').featured, true);
|
||||
assert.equal(config.services.length, 5);
|
||||
assert.equal(config.servers[0].ip, '10.0.0.87');
|
||||
});
|
||||
|
||||
test('config honors environment overrides without changing code', () => {
|
||||
const config = loadConfig({
|
||||
NODE_ENV: 'development',
|
||||
SESSION_SECRET: secret,
|
||||
VAULT_PASSWORD: 'a local passphrase',
|
||||
PORT: '9001',
|
||||
HOST: '0.0.0.0',
|
||||
SERVER_1_NAME: 'Rack One',
|
||||
SERVER_1_IP: '192.168.1.50',
|
||||
SERVICE_FEDL_URL: 'https://fedl.example.test/',
|
||||
SERVICE_FEDL_ENABLED: 'false',
|
||||
HOME_SUBNET: '192.168.1.0/24'
|
||||
});
|
||||
|
||||
assert.equal(config.port, 9001);
|
||||
assert.equal(config.host, '0.0.0.0');
|
||||
assert.equal(config.servers[0].name, 'Rack One');
|
||||
assert.equal(config.servers[0].ip, '192.168.1.50');
|
||||
assert.equal(config.services.find((s) => s.id === 'fedl').url, 'https://fedl.example.test/');
|
||||
assert.equal(config.services.find((s) => s.id === 'fedl').enabled, false);
|
||||
assert.equal(config.monitor.expectedSubnet, '192.168.1.0/24');
|
||||
});
|
||||
|
||||
test('production refuses missing or short session secrets', () => {
|
||||
assert.throws(
|
||||
() => loadConfig({ NODE_ENV: 'production', VAULT_PASSWORD: 'a local passphrase' }),
|
||||
/SESSION_SECRET is required/
|
||||
);
|
||||
assert.throws(
|
||||
() => loadConfig({ NODE_ENV: 'production', SESSION_SECRET: 'short', VAULT_PASSWORD: 'a local passphrase' }),
|
||||
/at least 32 characters/
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid origins and service URLs are rejected at startup', () => {
|
||||
assert.throws(
|
||||
() => loadConfig({
|
||||
NODE_ENV: 'development',
|
||||
SESSION_SECRET: secret,
|
||||
VAULT_PASSWORD: 'x',
|
||||
ALLOWED_ORIGINS: 'not a url'
|
||||
}),
|
||||
/Invalid origin/
|
||||
);
|
||||
assert.throws(
|
||||
() => loadConfig({
|
||||
NODE_ENV: 'development',
|
||||
SESSION_SECRET: secret,
|
||||
VAULT_PASSWORD: 'x',
|
||||
SERVICE_FEDL_URL: 'javascript:alert(1)'
|
||||
}),
|
||||
/Invalid URL/
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFedlService } from '../server/services/fedl.js';
|
||||
import { createTestContext, jsonResponse, silentLogger } from './helpers.js';
|
||||
|
||||
function fedlPayloads() {
|
||||
return {
|
||||
list: {
|
||||
items: [
|
||||
{ level: 'new', position: '1', title: 'Alpha Demon', url: 'https://youtu.be/a' },
|
||||
{ level: 'new', position: '2', title: 'Beta Demon', url: 'https://youtu.be/b' },
|
||||
{ level: 'new', position: '3', title: 'Gamma Demon', url: 'https://youtu.be/c' }
|
||||
]
|
||||
},
|
||||
runs: {
|
||||
items: [
|
||||
{
|
||||
id: 'run_1',
|
||||
playerName: 'player1',
|
||||
levelTitle: 'Alpha Demon',
|
||||
percent: '100',
|
||||
status: 'approved',
|
||||
submittedAt: '2026-11-01T00:00:00.000Z',
|
||||
updatedAt: '2026-11-01T00:00:00.000Z',
|
||||
videoUrl: 'https://youtu.be/run1'
|
||||
},
|
||||
{
|
||||
id: 'run_2',
|
||||
playerName: 'player2',
|
||||
levelTitle: 'Beta Demon',
|
||||
percent: '75',
|
||||
status: 'approved',
|
||||
submittedAt: '2026-10-20T00:00:00.000Z',
|
||||
updatedAt: '2026-10-20T00:00:00.000Z'
|
||||
},
|
||||
{
|
||||
id: 'run_3',
|
||||
playerName: 'player3',
|
||||
levelTitle: 'Beta Demon',
|
||||
percent: '12',
|
||||
status: 'rejected',
|
||||
submittedAt: '2026-10-19T00:00:00.000Z',
|
||||
updatedAt: '2026-10-19T00:00:00.000Z'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
test('FEDL service uses the real /list and /runs shapes and diffs snapshots', async (t) => {
|
||||
const { config, db } = createTestContext(t, {
|
||||
fedl: { apiBase: 'https://fedl.test/fedl/api' }
|
||||
});
|
||||
const state = fedlPayloads();
|
||||
let calls = 0;
|
||||
const fetchFn = async (url) => {
|
||||
calls += 1;
|
||||
const value = String(url);
|
||||
if (value.endsWith('/list')) return jsonResponse(state.list);
|
||||
if (value.endsWith('/runs')) return jsonResponse(state.runs);
|
||||
throw new Error('Unexpected FEDL URL ' + url);
|
||||
};
|
||||
const now = new Date('2026-11-07T12:00:00.000Z');
|
||||
const service = createFedlService({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
fetchFn,
|
||||
now: () => now
|
||||
});
|
||||
|
||||
const first = await service.refresh({ force: true });
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(first.totals.rankedLevels, 3);
|
||||
assert.equal(first.totals.records, 2);
|
||||
assert.equal(first.totals.rejected, 1);
|
||||
assert.equal(first.totals.players, 2);
|
||||
assert.equal(first.topLevels[0].title, 'Alpha Demon');
|
||||
assert.equal(first.changes.comparedTo, null);
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS c FROM fedl_snapshots').get().c, 1);
|
||||
|
||||
state.list.items = [
|
||||
{ level: 'new', position: '1', title: 'Beta Demon', url: 'https://youtu.be/b' },
|
||||
{ level: 'new', position: '2', title: 'Alpha Demon', url: 'https://youtu.be/a' },
|
||||
{ level: 'new', position: '4', title: 'Delta Demon', url: 'https://youtu.be/d' }
|
||||
];
|
||||
const second = await service.refresh({ force: true });
|
||||
assert.equal(second.changes.counts.added, 1);
|
||||
assert.equal(second.changes.counts.removed, 1);
|
||||
assert.equal(second.changes.added[0].title, 'Delta Demon');
|
||||
assert.equal(second.changes.removed[0].title, 'Gamma Demon');
|
||||
assert.equal(second.changes.counts.rankChanges, 2);
|
||||
|
||||
const activity = await service.getActivity();
|
||||
assert.equal(activity.changes.counts.added, 1);
|
||||
assert.equal(activity.recentRecords[0].id, 'run_1');
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS c FROM fedl_snapshots').get().c, 2);
|
||||
});
|
||||
|
||||
test('FEDL service serves its last good snapshot when refresh fails', async (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const state = fedlPayloads();
|
||||
const now = new Date('2026-11-07T12:00:00.000Z');
|
||||
let good = true;
|
||||
const service = createFedlService({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
now: () => now,
|
||||
fetchFn: async (url) => {
|
||||
if (!good) throw new Error('network down');
|
||||
if (String(url).endsWith('/list')) return jsonResponse(state.list);
|
||||
return jsonResponse(state.runs);
|
||||
}
|
||||
});
|
||||
|
||||
const first = await service.refresh({ force: true });
|
||||
good = false;
|
||||
const fallback = await service.refresh({ force: true });
|
||||
assert.equal(fallback.generatedAt, first.generatedAt);
|
||||
assert.equal(fallback.totals.rankedLevels, 3);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createGitHubService } from '../server/services/github.js';
|
||||
import { createTestContext, jsonResponse, silentLogger } from './helpers.js';
|
||||
|
||||
function mockGitHub(now, calls) {
|
||||
return async function fetchFn(url, options = {}) {
|
||||
calls.push({ url: String(url), headers: options.headers || {} });
|
||||
const pathname = new URL(String(url)).pathname;
|
||||
if (pathname === '/users/octocat') {
|
||||
return jsonResponse(
|
||||
{
|
||||
login: 'octocat',
|
||||
name: 'The Octocat',
|
||||
avatar_url: 'https://avatars.example/octocat.png',
|
||||
bio: 'test',
|
||||
followers: 10,
|
||||
following: 2,
|
||||
public_repos: 165,
|
||||
created_at: '2020-01-01T00:00:00Z'
|
||||
},
|
||||
{ headers: { 'x-ratelimit-remaining': '4999', 'x-ratelimit-reset': '1900000000' } }
|
||||
);
|
||||
}
|
||||
if (pathname === '/users/octocat/repos') {
|
||||
return jsonResponse([
|
||||
{
|
||||
full_name: 'octocat/alpha',
|
||||
description: 'Alpha repository',
|
||||
html_url: 'https://github.com/octocat/alpha',
|
||||
homepage: 'https://alpha.test',
|
||||
language: 'JavaScript',
|
||||
stargazers_count: 12,
|
||||
forks_count: 3,
|
||||
open_issues_count: 1,
|
||||
subscribers_count: 4,
|
||||
default_branch: 'main',
|
||||
archived: false,
|
||||
fork: false,
|
||||
topics: ['test'],
|
||||
pushed_at: new Date(now.getTime() - 60 * 60 * 1000).toISOString(),
|
||||
updated_at: now.toISOString(),
|
||||
created_at: '2024-01-01T00:00:00Z'
|
||||
}
|
||||
]);
|
||||
}
|
||||
if (pathname === '/users/octocat/events/public') {
|
||||
return jsonResponse([
|
||||
{
|
||||
type: 'PushEvent',
|
||||
created_at: new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString(),
|
||||
repo: { name: 'octocat/alpha' },
|
||||
actor: { login: 'octocat' },
|
||||
payload: {
|
||||
ref: 'refs/heads/main',
|
||||
commits: [
|
||||
{
|
||||
sha: 'abcdef1234567890',
|
||||
message: 'Add a real feature\n\nWith details',
|
||||
author: { name: 'Miles' }
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'WatchEvent',
|
||||
created_at: new Date(now.getTime() - 3 * 60 * 60 * 1000).toISOString(),
|
||||
repo: { name: 'octocat/alpha' }
|
||||
}
|
||||
]);
|
||||
}
|
||||
if (pathname === '/repos/octocat/alpha/commits') {
|
||||
return jsonResponse([
|
||||
{
|
||||
sha: 'fedcba9876543210',
|
||||
commit: {
|
||||
message: 'Latest commit subject\n\nBody',
|
||||
author: { name: 'Miles', date: new Date(now.getTime() - 60 * 60 * 1000).toISOString() }
|
||||
},
|
||||
html_url: 'https://github.com/octocat/alpha/commit/fedcba9876543210'
|
||||
}
|
||||
]);
|
||||
}
|
||||
throw new Error('Unexpected GitHub URL: ' + url);
|
||||
};
|
||||
}
|
||||
|
||||
test('GitHub service normalizes live API data and caches it', async (t) => {
|
||||
const { config, db } = createTestContext(t, {
|
||||
github: { token: 'secret-github-token', enrich: false },
|
||||
projects: [
|
||||
{
|
||||
id: 'alpha',
|
||||
name: 'Alpha',
|
||||
description: 'Configured description',
|
||||
github: { owner: 'octocat', repo: 'alpha' },
|
||||
website: 'https://alpha.test/',
|
||||
api: null,
|
||||
order: 1,
|
||||
visible: true,
|
||||
featured: true
|
||||
}
|
||||
]
|
||||
});
|
||||
const now = new Date('2026-11-07T12:00:00.000Z');
|
||||
const calls = [];
|
||||
const service = createGitHubService({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
fetchFn: mockGitHub(now, calls),
|
||||
now: () => now
|
||||
});
|
||||
|
||||
const overview = await service.getOverview();
|
||||
assert.equal(overview.profile.login, 'octocat');
|
||||
assert.equal(overview.totals.publicRepos, 165);
|
||||
assert.equal(overview.totals.trackedRepos, 1);
|
||||
assert.equal(overview.totals.stars, 12);
|
||||
assert.equal(overview.totals.forks, 3);
|
||||
assert.equal(overview.languages[0].name, 'JavaScript');
|
||||
assert.equal(overview.recentCommits[0].message, 'Add a real feature');
|
||||
assert.equal(overview.recentCommits[0].sha, 'abcdef1');
|
||||
assert.equal(overview.rateLimit.authenticated, true);
|
||||
assert.equal(overview.rateLimit.remaining, 4999);
|
||||
|
||||
const repos = await service.getRepositories();
|
||||
assert.equal(repos.repositories[0].latestCommit.sha, 'fedcba9');
|
||||
assert.equal(repos.repositories[0].website, 'https://alpha.test');
|
||||
assert.equal(JSON.stringify(overview).includes('secret-github-token'), false);
|
||||
assert.ok(calls.some((call) => call.headers.Authorization === 'Bearer secret-github-token'));
|
||||
|
||||
const countAfterFirst = calls.length;
|
||||
await service.getActivity();
|
||||
assert.equal(calls.length, countAfterFirst, 'fresh cached summary should not refetch GitHub');
|
||||
});
|
||||
|
||||
test('GitHub service falls back to cached data when the API fails', async (t) => {
|
||||
const { config, db } = createTestContext(t, {
|
||||
projects: [
|
||||
{
|
||||
id: 'alpha',
|
||||
name: 'Alpha',
|
||||
description: 'Test',
|
||||
github: { owner: 'octocat', repo: 'alpha' },
|
||||
website: 'https://alpha.test/',
|
||||
api: null,
|
||||
order: 1,
|
||||
visible: true,
|
||||
featured: true
|
||||
}
|
||||
]
|
||||
});
|
||||
const now = new Date('2026-11-07T12:00:00.000Z');
|
||||
const calls = [];
|
||||
const first = createGitHubService({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
fetchFn: mockGitHub(now, calls),
|
||||
now: () => now
|
||||
});
|
||||
const fresh = await first.getOverview();
|
||||
|
||||
const later = new Date(now.getTime() + 2 * 60 * 60 * 1000);
|
||||
const stale = createGitHubService({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
fetchFn: async () => { throw new Error('offline'); },
|
||||
now: () => later
|
||||
});
|
||||
const cached = await stale.getOverview();
|
||||
assert.equal(cached.generatedAt, fresh.generatedAt);
|
||||
assert.equal(cached.totals.stars, 12);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { openDatabase } from '../server/db/index.js';
|
||||
import { migrate } from '../server/db/migrate.js';
|
||||
import { seedConfig } from '../server/db/seed.js';
|
||||
|
||||
export const repoRoot = process.cwd();
|
||||
|
||||
export function makeConfig(overrides = {}) {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'miles-dashboard-test-'));
|
||||
const projects = overrides.projects || [
|
||||
{
|
||||
id: 'alpha',
|
||||
name: 'Alpha',
|
||||
description: 'Test project',
|
||||
github: { owner: 'octocat', repo: 'alpha' },
|
||||
website: 'https://alpha.test/',
|
||||
api: null,
|
||||
order: 1,
|
||||
visible: true,
|
||||
featured: true
|
||||
}
|
||||
];
|
||||
const services = overrides.services || [
|
||||
{
|
||||
id: 'alpha',
|
||||
name: 'Alpha',
|
||||
url: 'https://alpha.test/',
|
||||
order: 1,
|
||||
enabled: true
|
||||
}
|
||||
];
|
||||
const servers = overrides.servers || [
|
||||
{
|
||||
id: 'home-1',
|
||||
name: 'Home Server',
|
||||
ip: '10.0.0.87',
|
||||
order: 1,
|
||||
enabled: true
|
||||
}
|
||||
];
|
||||
|
||||
const config = {
|
||||
env: 'test',
|
||||
production: false,
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
siteRoot: repoRoot,
|
||||
dbPath: path.join(tempDir, 'dashboard.db'),
|
||||
tempDir,
|
||||
publicOrigin: 'http://localhost:8787',
|
||||
allowedOrigins: new Set(['http://localhost:8787', 'https://milesallen.site']),
|
||||
sessionSecret: 'test-session-secret-that-is-long-enough-0123456789',
|
||||
trustProxy: false,
|
||||
cookie: {
|
||||
name: 'miles_vault',
|
||||
secure: false,
|
||||
sameSite: 'Strict',
|
||||
ttlMs: 60 * 60 * 1000
|
||||
},
|
||||
vault: {
|
||||
passwordHash: null,
|
||||
password: null,
|
||||
maxAttempts: 3,
|
||||
windowMs: 15 * 60 * 1000
|
||||
},
|
||||
monitor: {
|
||||
servers,
|
||||
services,
|
||||
serverIntervalMs: 60_000,
|
||||
pingTimeoutMs: 2_000,
|
||||
serviceIntervalMs: 120_000,
|
||||
httpTimeoutMs: 5_000,
|
||||
retentionDays: 90,
|
||||
expectedSubnet: '10.0.0.0/24'
|
||||
},
|
||||
github: {
|
||||
username: 'octocat',
|
||||
token: '',
|
||||
apiBase: 'https://api.github.com',
|
||||
refreshMs: 30 * 60 * 1000,
|
||||
timeoutMs: 5_000,
|
||||
enrich: false
|
||||
},
|
||||
fedl: {
|
||||
apiBase: 'https://fedl.test/api',
|
||||
siteUrl: 'https://fedl.test',
|
||||
github: { owner: 'octocat', repo: 'alpha' },
|
||||
refreshMs: 15 * 60 * 1000,
|
||||
timeoutMs: 5_000
|
||||
},
|
||||
analytics: { retentionDays: 30, dedupeSeconds: 10 },
|
||||
rateLimits: {
|
||||
api: { limit: 1000, windowMs: 60_000 },
|
||||
analytics: { limit: 1000, windowMs: 60_000 },
|
||||
login: { limit: 100, windowMs: 60_000 }
|
||||
},
|
||||
http: { requestTimeoutMs: 10_000, bodyLimitBytes: 16_384 },
|
||||
logLevel: 'error',
|
||||
projects,
|
||||
services,
|
||||
servers,
|
||||
warnings: []
|
||||
};
|
||||
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
cookie: { ...config.cookie, ...(overrides.cookie || {}) },
|
||||
vault: { ...config.vault, ...(overrides.vault || {}) },
|
||||
monitor: { ...config.monitor, ...(overrides.monitor || {}) },
|
||||
github: { ...config.github, ...(overrides.github || {}) },
|
||||
fedl: { ...config.fedl, ...(overrides.fedl || {}) },
|
||||
analytics: { ...config.analytics, ...(overrides.analytics || {}) },
|
||||
rateLimits: { ...config.rateLimits, ...(overrides.rateLimits || {}) },
|
||||
http: { ...config.http, ...(overrides.http || {}) },
|
||||
projects,
|
||||
services,
|
||||
servers
|
||||
};
|
||||
}
|
||||
|
||||
export function createTestContext(t, overrides = {}) {
|
||||
const config = makeConfig(overrides);
|
||||
const db = openDatabase(config.dbPath);
|
||||
migrate(db);
|
||||
seedConfig(db, config);
|
||||
t.after(() => {
|
||||
try { db.close(); } catch {}
|
||||
fs.rmSync(config.tempDir, { recursive: true, force: true });
|
||||
});
|
||||
return { config, db };
|
||||
}
|
||||
|
||||
export function silentLogger() {
|
||||
return {
|
||||
error() {},
|
||||
warn() {},
|
||||
info() {},
|
||||
debug() {},
|
||||
child() { return this; }
|
||||
};
|
||||
}
|
||||
|
||||
export function jsonResponse(data, { status = 200, headers = {} } = {}) {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json', ...headers }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { checkHost, parsePingTime, pingArgs, inSubnet, networkContext } from '../server/services/ping.js';
|
||||
import { checkHttp, classifyHttpStatus } from '../server/services/http-check.js';
|
||||
import { createStatusService } from '../server/services/status.js';
|
||||
import { createMonitor } from '../server/services/monitor.js';
|
||||
import { createTestContext, silentLogger } from './helpers.js';
|
||||
|
||||
test('ping arguments adapt to macOS and Linux', () => {
|
||||
assert.deepEqual(pingArgs('10.0.0.87', { platform: 'darwin', timeoutMs: 2000 }), [
|
||||
'-n', '-c', '1', '-W', '2000', '10.0.0.87'
|
||||
]);
|
||||
assert.deepEqual(pingArgs('10.0.0.87', { platform: 'linux', timeoutMs: 2000 }), [
|
||||
'-n', '-c', '1', '-W', '2', '10.0.0.87'
|
||||
]);
|
||||
assert.throws(() => pingArgs('10.0.0.87; rm -rf /', { platform: 'linux' }), /Invalid ping target/);
|
||||
});
|
||||
|
||||
test('ping output parsing and failure reasons are honest', async () => {
|
||||
assert.equal(parsePingTime('64 bytes from 10.0.0.87: icmp_seq=0 ttl=64 time=2.34 ms'), 2.34);
|
||||
assert.equal(parsePingTime('64 bytes from 10.0.0.87: icmp_seq=0 ttl=64 time<1 ms'), 1);
|
||||
assert.equal(parsePingTime('1 packets transmitted, 0 received'), null);
|
||||
|
||||
const online = await checkHost('10.0.0.87', {
|
||||
execFileFn: async () => ({ stdout: '64 bytes from 10.0.0.87: time=4.2 ms' })
|
||||
});
|
||||
assert.equal(online.online, true);
|
||||
assert.equal(online.responseMs, 4.2);
|
||||
|
||||
const timeout = await checkHost('10.0.0.87', {
|
||||
execFileFn: async () => {
|
||||
const err = new Error('process timed out');
|
||||
err.killed = true;
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
assert.equal(timeout.online, false);
|
||||
assert.equal(timeout.reason, 'timeout');
|
||||
});
|
||||
|
||||
test('network context distinguishes home LAN from remote networks', () => {
|
||||
assert.equal(inSubnet('10.0.0.131', '10.0.0.0/24'), true);
|
||||
assert.equal(inSubnet('192.168.1.20', '10.0.0.0/24'), false);
|
||||
const local = networkContext(
|
||||
[{ ip: '10.0.0.87' }],
|
||||
{
|
||||
localAddresses: [{ address: '10.0.0.131', name: 'en0' }]
|
||||
}
|
||||
);
|
||||
assert.equal(local.onHomeNetwork, true);
|
||||
|
||||
const remote = networkContext(
|
||||
[{ ip: '10.0.0.87' }],
|
||||
{ localAddresses: [{ address: '172.16.0.8', name: 'en0' }] }
|
||||
);
|
||||
assert.equal(remote.onHomeNetwork, false);
|
||||
});
|
||||
|
||||
test('HTTP checks classify status and timeouts', async () => {
|
||||
assert.equal(classifyHttpStatus(200), 'operational');
|
||||
assert.equal(classifyHttpStatus(301), 'operational');
|
||||
assert.equal(classifyHttpStatus(404), 'degraded');
|
||||
assert.equal(classifyHttpStatus(503), 'offline');
|
||||
|
||||
const ok = await checkHttp('https://alpha.test/', {
|
||||
fetchFn: async () => new Response('hello', { status: 200 })
|
||||
});
|
||||
assert.equal(ok.status, 'operational');
|
||||
assert.equal(ok.httpStatus, 200);
|
||||
|
||||
const fail = await checkHttp('https://alpha.test/', {
|
||||
fetchFn: async () => {
|
||||
const err = new Error('timed out');
|
||||
err.name = 'TimeoutError';
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
assert.equal(fail.status, 'offline');
|
||||
assert.match(fail.error, /timeout/);
|
||||
});
|
||||
|
||||
test('monitor stores server and service checks, and remote failures become unknown', async (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const fixed = new Date('2026-11-07T12:00:00.000Z');
|
||||
let call = 0;
|
||||
const monitor = createMonitor({
|
||||
config,
|
||||
db,
|
||||
logger: silentLogger(),
|
||||
now: () => fixed,
|
||||
deps: {
|
||||
platform: 'linux',
|
||||
pingHost: async () => {
|
||||
call += 1;
|
||||
return { online: true, responseMs: 3.5, reason: 'ok', error: null };
|
||||
},
|
||||
checkHttp: async () => ({
|
||||
status: 'operational',
|
||||
responseMs: 42,
|
||||
httpStatus: 200,
|
||||
error: null
|
||||
}),
|
||||
getNetworkContext: () => ({ onHomeNetwork: true, localAddresses: ['10.0.0.131'] })
|
||||
}
|
||||
});
|
||||
|
||||
const result = await monitor.runOnce('all');
|
||||
assert.equal(result.servers.online, 1);
|
||||
assert.equal(result.services.checked, 1);
|
||||
assert.equal(call, 1);
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS c FROM server_checks').get().c, 1);
|
||||
assert.equal(db.prepare('SELECT COUNT(*) AS c FROM service_checks').get().c, 1);
|
||||
|
||||
const status = createStatusService({ db, config, now: () => fixed });
|
||||
const snapshot = status.getStatus();
|
||||
assert.equal(snapshot.servers[0].status, 'online');
|
||||
assert.equal(snapshot.services[0].status, 'operational');
|
||||
assert.equal(snapshot.network.onHomeNetwork, true);
|
||||
|
||||
// The same offline result must not be called an outage when the laptop is remote.
|
||||
const remote = createTestContext(t);
|
||||
const remoteMonitor = createMonitor({
|
||||
config: remote.config,
|
||||
db: remote.db,
|
||||
logger: silentLogger(),
|
||||
now: () => fixed,
|
||||
deps: {
|
||||
pingHost: async () => ({ online: false, responseMs: null, reason: 'unreachable', error: 'no route' }),
|
||||
checkHttp: async () => ({ status: 'offline', responseMs: 1, httpStatus: null, error: 'timeout' }),
|
||||
getNetworkContext: () => ({ onHomeNetwork: false, localAddresses: ['172.16.0.5'] })
|
||||
}
|
||||
});
|
||||
await remoteMonitor.runServers();
|
||||
const remoteStatus = createStatusService({ db: remote.db, config: remote.config, now: () => fixed });
|
||||
const remoteSnapshot = remoteStatus.getStatus();
|
||||
assert.equal(remoteSnapshot.servers[0].status, 'unknown');
|
||||
assert.equal(remoteSnapshot.servers[0].reason, 'not_on_home_network');
|
||||
});
|
||||
|
||||
test('uptime windows are computed from stored history', (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const now = new Date('2026-11-07T12:00:00.000Z');
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO server_checks (server_id, checked_at, online, response_ms, reason, on_home_network)
|
||||
VALUES (?, ?, ?, ?, ?, 1)
|
||||
`);
|
||||
insert.run('home-1', new Date(now.getTime() - 30 * 60 * 1000).toISOString(), 0, null, 'unreachable');
|
||||
insert.run('home-1', new Date(now.getTime() - 2 * 60 * 60 * 1000).toISOString(), 1, 2.1, 'ok');
|
||||
insert.run('home-1', new Date(now.getTime() - 3 * 60 * 60 * 1000).toISOString(), 1, 1.9, 'ok');
|
||||
insert.run('home-1', new Date(now.getTime() - 8 * 24 * 60 * 60 * 1000).toISOString(), 1, 3.1, 'ok');
|
||||
|
||||
const status = createStatusService({ db, config, now: () => now });
|
||||
const server = status.getServers()[0];
|
||||
assert.equal(server.status, 'offline');
|
||||
assert.equal(server.uptime['24h'], 66.67);
|
||||
assert.equal(server.uptime['7d'], 66.67);
|
||||
assert.equal(server.uptime['30d'], 75);
|
||||
assert.equal(server.lastChangeAt, new Date(now.getTime() - 30 * 60 * 1000).toISOString());
|
||||
|
||||
const history = status.getHistory(30);
|
||||
assert.equal(history.days, 30);
|
||||
assert.equal(history.servers['home-1'].length, 30);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { openDatabase } from '../server/db/index.js';
|
||||
import { migrate } from '../server/db/migrate.js';
|
||||
import { seedConfig } from '../server/db/seed.js';
|
||||
import { createAnalyticsService } from '../server/services/analytics.js';
|
||||
import { createVaultService } from '../server/services/vault.js';
|
||||
import { makeConfig, silentLogger } from './helpers.js';
|
||||
|
||||
test('migrations are idempotent and data persists across a restart', async (t) => {
|
||||
const config = makeConfig();
|
||||
t.after(() => fs.rmSync(config.tempDir, { recursive: true, force: true }));
|
||||
|
||||
const first = openDatabase(config.dbPath);
|
||||
assert.equal(migrate(first), 1);
|
||||
assert.equal(migrate(first), 0);
|
||||
seedConfig(first, config);
|
||||
const analytics = createAnalyticsService({ db: first, config });
|
||||
analytics.recordHit({
|
||||
path: '/persisted',
|
||||
ip: '198.51.100.9',
|
||||
userAgent: 'Mozilla/5.0 Chrome/130 Safari/537.36',
|
||||
at: new Date('2026-11-07T12:00:00.000Z')
|
||||
});
|
||||
const vault = await createVaultService({ db: first, config, logger: silentLogger() });
|
||||
assert.equal(vault.enabled, false);
|
||||
first.close();
|
||||
|
||||
const second = openDatabase(config.dbPath);
|
||||
assert.equal(migrate(second), 0);
|
||||
seedConfig(second, config);
|
||||
const rows = second.prepare('SELECT path FROM pageviews').all();
|
||||
assert.deepEqual(rows, [{ path: '/persisted' }]);
|
||||
assert.equal(second.prepare('SELECT COUNT(*) AS c FROM projects WHERE visible = 1').get().c, 1);
|
||||
assert.equal(second.prepare('SELECT COUNT(*) AS c FROM servers').get().c, 1);
|
||||
second.close();
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import argon2 from 'argon2';
|
||||
import { createVaultService } from '../server/services/vault.js';
|
||||
import { createTestContext, silentLogger } from './helpers.js';
|
||||
|
||||
async function passwordHash(password = 'correct horse battery staple') {
|
||||
return argon2.hash(password, {
|
||||
type: argon2.argon2id,
|
||||
timeCost: 1,
|
||||
memoryCost: 8192,
|
||||
parallelism: 1,
|
||||
hashLength: 32
|
||||
});
|
||||
}
|
||||
|
||||
test('vault issues signed HttpOnly sessions and rejects bad credentials', async (t) => {
|
||||
const hash = await passwordHash();
|
||||
const { config, db } = createTestContext(t, {
|
||||
vault: { passwordHash: hash, maxAttempts: 3, windowMs: 60_000 }
|
||||
});
|
||||
const at = new Date('2026-11-07T12:00:00.000Z');
|
||||
const vault = await createVaultService({ config, db, logger: silentLogger(), now: () => at });
|
||||
assert.equal(vault.enabled, true);
|
||||
|
||||
const ipHash = vault.ipHashFor('203.0.113.8', at);
|
||||
assert.notEqual(ipHash, '203.0.113.8');
|
||||
await assert.rejects(
|
||||
() => vault.login({ password: 'wrong', ipHash, at }),
|
||||
(err) => err.status === 401 && /Invalid credentials/.test(err.message)
|
||||
);
|
||||
|
||||
const result = await vault.login({ password: 'correct horse battery staple', ipHash, at });
|
||||
assert.match(result.cookie, /^miles_vault=[a-f0-9.]+\.[a-f0-9.]+\.[a-f0-9]+;/);
|
||||
assert.match(result.cookie, /HttpOnly/);
|
||||
assert.match(result.cookie, /SameSite=Strict/);
|
||||
assert.doesNotMatch(result.cookie, /Secure/);
|
||||
|
||||
const session = vault.getSession(result.cookie, at);
|
||||
assert.equal(session.sessionId.length, 32);
|
||||
assert.equal(session.expiresAt, new Date(at.getTime() + config.cookie.ttlMs).toISOString());
|
||||
|
||||
// A restart must not invalidate a signed, unexpired database-backed session.
|
||||
const restarted = await createVaultService({ config, db, logger: silentLogger(), now: () => at });
|
||||
assert.ok(restarted.getSession(result.cookie, at));
|
||||
|
||||
const tampered = result.cookie.replace(/([a-f0-9])\./g, (match, char) => {
|
||||
return (char === 'a' ? 'b' : 'a') + '.';
|
||||
});
|
||||
assert.equal(vault.getSession(tampered, at), null);
|
||||
|
||||
assert.equal(vault.getSession(result.cookie, new Date(at.getTime() + config.cookie.ttlMs + 1000)), null);
|
||||
assert.equal(vault.getSession(result.cookie, at), null, 'expired session row should be deleted');
|
||||
|
||||
const loggedOut = vault.logout(result.cookie);
|
||||
assert.match(loggedOut, /Max-Age=0/);
|
||||
});
|
||||
|
||||
test('vault brute-force protection uses database-backed attempt counts', async (t) => {
|
||||
const hash = await passwordHash('only password');
|
||||
const { config, db } = createTestContext(t, {
|
||||
vault: { passwordHash: hash, maxAttempts: 2, windowMs: 60_000 }
|
||||
});
|
||||
const at = new Date('2026-11-07T12:00:00.000Z');
|
||||
const vault = await createVaultService({ config, db, logger: silentLogger(), now: () => at });
|
||||
const ipHash = vault.ipHashFor('198.51.100.7', at);
|
||||
|
||||
await assert.rejects(() => vault.login({ password: 'a', ipHash, at }), /Invalid credentials/);
|
||||
await assert.rejects(() => vault.login({ password: 'b', ipHash, at }), /Invalid credentials/);
|
||||
await assert.rejects(
|
||||
() => vault.login({ password: 'only password', ipHash, at }),
|
||||
(err) => err.status === 429 && err.code === 'rate_limited'
|
||||
);
|
||||
assert.equal(
|
||||
db.prepare('SELECT COUNT(*) AS c FROM vault_attempts WHERE ip_hash = ? AND success = 0').get(ipHash).c,
|
||||
2
|
||||
);
|
||||
});
|
||||
|
||||
test('vault reports disabled state without accepting any password', async (t) => {
|
||||
const { config, db } = createTestContext(t);
|
||||
const vault = await createVaultService({ config, db, logger: silentLogger() });
|
||||
assert.equal(vault.enabled, false);
|
||||
await assert.rejects(
|
||||
() => vault.login({ password: 'anything', ipHash: 'x', at: new Date() }),
|
||||
(err) => err.status === 503 && err.code === 'unavailable'
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user