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:
miles committed 2026-11-08 16:24:06 -06:00
1 parent 84b7a7e302
commit c250653961
55 files changed
+8174 -226

No files matched your search

+447
View File
@@ -0,0 +1,447 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { AppError, badRequest, forbidden, notFound, tooManyRequests } from './lib/errors.js';
import {
applySecurityHeaders,
corsFor,
getClientIp,
readBody,
sendError,
sendJson,
sendText
} from './lib/http.js';
import { createRateLimiter } from './lib/rate-limit.js';
import { sendFile } from './lib/static.js';
import { serveStatic } from './lib/static.js';
const PUBLIC_API_PREFIX = '/api';
const VAULT_PAGE = '/vault';
const VAULT_VIEW = 'server/views/vault.html';
function methodNotAllowed(res, allowed) {
sendJson(
res,
405,
{ error: { code: 'method_not_allowed', message: 'Method not allowed' } },
{ Allow: allowed.join(', ') }
);
}
function parseProjectId(pathname) {
const match = pathname.match(/^\/api\/projects\/([^/]+)$/);
if (!match) return null;
try {
return decodeURIComponent(match[1]);
} catch {
return null;
}
}
function requestId() {
return crypto.randomBytes(8).toString('hex');
}
export function createApp({ config, db, logger, services, now = () => new Date() }) {
const limiter = createRateLimiter();
const vaultViewPath = path.join(config.siteRoot, VAULT_VIEW);
let handled = 0;
function originAllowed(req, origin) {
if (!origin) return false;
if (config.allowedOrigins.has(origin)) return true;
// Same-origin requests are always acceptable. This keeps LAN access working
// without weakening the explicit cross-origin allowlist.
const host = req.headers.host;
if (!host) return false;
return origin === `http://${host}` || origin === `https://${host}`;
}
function applyCors(req, res) {
const origin = req.headers.origin;
if (!origin) return { allowed: true, headers: {} };
if (!originAllowed(req, origin)) {
return { allowed: false, headers: {} };
}
return { allowed: true, headers: corsFor(origin, new Set([origin])) || {} };
}
function requireVault(req, res) {
const session = services.vault.getSession(req.headers.cookie, now());
if (session) return session;
const wantsJson =
req.headers.accept?.includes('application/json') ||
String(req.headers['x-requested-with'] || '').toLowerCase() === 'fetch';
if (wantsJson) {
sendJson(res, 401, {
error: { code: 'unauthorized', message: 'Moon Vault session required' }
});
} else {
res.writeHead(302, {
Location: '/moon-vault.html',
'Cache-Control': 'no-store'
});
res.end();
}
return null;
}
async function route(req, res, url, context) {
const { pathname } = url;
const method = req.method || 'GET';
if (pathname === '/api' || pathname === '/api/') {
return sendJson(res, 200, {
name: 'milesallen.site dashboard API',
version: '1.0.0',
endpoints: [
'/api/status',
'/api/status/servers',
'/api/status/services',
'/api/status/history',
'/api/github/overview',
'/api/github/activity',
'/api/github/repositories',
'/api/projects',
'/api/projects/:id',
'/api/fedl/stats',
'/api/fedl/activity',
'/api/analytics/hit',
'/api/analytics/overview',
'/api/analytics/pages',
'/api/vault/login',
'/api/vault/logout',
'/api/vault/session',
'/api/health'
]
});
}
if (pathname === '/api/health') {
if (method !== 'GET' && method !== 'HEAD') return methodNotAllowed(res, ['GET', 'HEAD']);
return sendJson(res, 200, {
status: 'ok',
uptimeSeconds: Math.round(process.uptime()),
time: now().toISOString()
});
}
if (pathname === '/api/status') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, services.status.getStatus());
}
if (pathname === '/api/status/servers') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, {
generatedAt: now().toISOString(),
servers: services.status.getServers()
});
}
if (pathname === '/api/status/services') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, {
generatedAt: now().toISOString(),
services: services.status.getServices()
});
}
if (pathname === '/api/status/history') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
const days = Number.parseInt(url.searchParams.get('days') || '30', 10);
return sendJson(res, 200, services.status.getHistory(days));
}
if (pathname === '/api/github/overview') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, await services.github.getOverview());
}
if (pathname === '/api/github/activity') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, await services.github.getActivity());
}
if (pathname === '/api/github/repositories') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, await services.github.getRepositories());
}
if (pathname === '/api/projects') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
const rows = db
.prepare('SELECT * FROM projects WHERE visible = 1 ORDER BY display_order, id')
.all();
const statuses = new Map(services.status.getServices().map((s) => [s.url, s]));
return sendJson(res, 200, {
generatedAt: now().toISOString(),
projects: rows.map((row) => ({
id: row.id,
name: row.name,
description: row.description,
github: row.github_owner
? { owner: row.github_owner, repo: row.github_repo, url: `https://github.com/${row.github_owner}/${row.github_repo}` }
: null,
website: row.website_url,
api: row.api_type ? { type: row.api_type, base: row.api_base } : null,
featured: Boolean(row.featured),
health: row.website_url && statuses.has(row.website_url) ? statuses.get(row.website_url).status : null
}))
});
}
const projectId = parseProjectId(pathname);
if (projectId !== null) {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
const row = db
.prepare('SELECT * FROM projects WHERE id = ? AND visible = 1')
.get(projectId);
if (!row) throw notFound('Project not found');
return sendJson(res, 200, {
project: {
id: row.id,
name: row.name,
description: row.description,
github: row.github_owner
? { owner: row.github_owner, repo: row.github_repo, url: `https://github.com/${row.github_owner}/${row.github_repo}` }
: null,
website: row.website_url,
api: row.api_type ? { type: row.api_type, base: row.api_base } : null,
featured: Boolean(row.featured)
}
});
}
if (pathname === '/api/fedl/stats') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, await services.fedl.getStats());
}
if (pathname === '/api/fedl/activity') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, await services.fedl.getActivity());
}
if (pathname === '/api/analytics/hit') {
if (method !== 'POST') return methodNotAllowed(res, ['POST']);
const analyticsLimit = limiter.hit(`analytics:${context.ip}`, {
limit: config.rateLimits.analytics.limit,
windowMs: config.rateLimits.analytics.windowMs
});
if (!analyticsLimit.allowed) {
throw tooManyRequests('Too many analytics requests', analyticsLimit.retryAfterMs);
}
const body = await readBody(req, {
limitBytes: config.http.bodyLimitBytes,
timeoutMs: Math.min(10_000, config.http.requestTimeoutMs)
});
const payload = body.json || {};
const result = services.analytics.recordHit({
path: payload.path,
referrer: payload.referrer ?? req.headers.referer,
ip: context.ip,
userAgent: req.headers['user-agent'],
at: now()
});
return sendJson(res, 202, {
recorded: result.recorded,
reason: result.reason || null
});
}
if (pathname === '/api/analytics/overview') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(res, 200, services.analytics.getOverview({ at: now() }));
}
if (pathname === '/api/analytics/pages') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
return sendJson(
res,
200,
services.analytics.getPages({
at: now(),
days: Number.parseInt(url.searchParams.get('days') || '30', 10),
limit: Number.parseInt(url.searchParams.get('limit') || '50', 10)
})
);
}
if (pathname === '/api/vault/session') {
if (method !== 'GET') return methodNotAllowed(res, ['GET']);
const session = services.vault.getSession(req.headers.cookie, now());
return sendJson(res, 200, {
enabled: services.vault.enabled,
authenticated: Boolean(session),
expiresAt: session?.expiresAt || null
});
}
if (pathname === '/api/vault/login') {
if (method !== 'POST') return methodNotAllowed(res, ['POST']);
if (!services.vault.enabled) {
throw new AppError(
503,
'vault_disabled',
'Moon Vault is not configured. Set VAULT_PASSWORD_HASH on the server.',
undefined,
true
);
}
const loginLimit = limiter.hit(`login:${context.ip}`, {
limit: config.rateLimits.login.limit,
windowMs: config.rateLimits.login.windowMs
});
if (!loginLimit.allowed) {
throw tooManyRequests('Too many login attempts', loginLimit.retryAfterMs);
}
const body = await readBody(req, {
limitBytes: Math.min(config.http.bodyLimitBytes, 4096),
timeoutMs: Math.min(10_000, config.http.requestTimeoutMs)
});
const password = body.json?.password;
const at = now();
const result = await services.vault.login({
password,
ipHash: services.vault.ipHashFor(context.ip, at),
at
});
res.setHeader('Set-Cookie', result.cookie);
return sendJson(res, 200, {
ok: true,
expiresAt: result.expiresAt
});
}
if (pathname === '/api/vault/logout') {
if (method !== 'POST') return methodNotAllowed(res, ['POST']);
const cookie = services.vault.logout(req.headers.cookie);
res.setHeader('Set-Cookie', cookie);
return sendJson(res, 200, { ok: true });
}
if (pathname.startsWith('/api/')) {
throw notFound('API endpoint not found');
}
return null;
}
return async function handler(req, res) {
const id = requestId();
const started = Date.now();
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const pathname = url.pathname;
const method = req.method || 'GET';
res.setHeader('X-Request-Id', id);
applySecurityHeaders(res, { production: config.production });
const isApi = pathname === PUBLIC_API_PREFIX || pathname.startsWith(`${PUBLIC_API_PREFIX}/`);
const cors = applyCors(req, res);
if (isApi) {
for (const [key, value] of Object.entries(cors.headers)) res.setHeader(key, value);
if (!cors.allowed) {
return sendError(res, forbidden('Origin is not allowed'), cors.headers);
}
if (method === 'OPTIONS') {
res.writeHead(204, { 'Cache-Control': 'no-store' });
return res.end();
}
const limit = limiter.hit(`api:${getClientIp(req, { trustProxy: config.trustProxy })}`, {
limit: config.rateLimits.api.limit,
windowMs: config.rateLimits.api.windowMs
});
if (!limit.allowed) {
return sendError(
res,
tooManyRequests('Too many API requests', limit.retryAfterMs),
cors.headers
);
}
}
res.on('finish', () => {
const durationMs = Date.now() - started;
const fields = {
requestId: id,
method,
path: pathname,
status: res.statusCode,
durationMs
};
if (isApi) logger.info('request', fields);
else logger.debug('request', fields);
});
handled += 1;
if (handled % 500 === 0) limiter.cleanup();
try {
const context = {
ip: getClientIp(req, { trustProxy: config.trustProxy })
};
const apiResult = await route(req, res, url, context);
if (apiResult !== null) return;
if (pathname === VAULT_PAGE || pathname === `${VAULT_PAGE}/`) {
if (!requireVault(req, res)) return;
let stat;
try {
stat = fs.statSync(vaultViewPath);
} catch {
logger.error('vault view missing', { path: vaultViewPath });
return sendText(res, 500, 'Vault view is missing');
}
return sendFile(req, res, vaultViewPath, stat, { cache: 'no-store' });
}
if (pathname === '/games' || pathname.startsWith('/games/')) {
if (!requireVault(req, res)) return;
return serveStatic(req, res, {
root: config.siteRoot,
pathname,
// Never let a browser cache vault-protected content: a cached game
// must not remain viewable after logout or session expiry.
cache: 'no-store'
});
}
if (pathname === '/dashboard' || pathname === '/dashboard/') {
return serveStatic(req, res, {
root: config.siteRoot,
pathname: '/dashboard.html',
notFoundFile: path.join(config.siteRoot, '404.html')
});
}
if (method !== 'GET' && method !== 'HEAD') {
return sendText(res, 405, 'Method not allowed', { Allow: 'GET, HEAD' });
}
return serveStatic(req, res, {
root: config.siteRoot,
pathname,
notFoundFile: path.join(config.siteRoot, '404.html')
});
} catch (err) {
if (err instanceof AppError) {
return sendError(res, err, isApi ? cors.headers : {});
}
if (err?.message === 'Body too large' || err?.code === 'ERR_BODY_PARSE') {
return sendError(res, badRequest('Invalid request body'), isApi ? cors.headers : {});
}
logger.error('unhandled request error', {
requestId: id,
method,
path: pathname,
error: err?.message || String(err),
stack: config.env === 'development' ? err?.stack : undefined
});
return sendError(res, new AppError(500, 'internal_error', 'Internal server error'), isApi ? cors.headers : {});
}
};
}
+269
View File
@@ -0,0 +1,269 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { clampInt, parseBoolean } from './lib/validate.js';
const HERE = path.dirname(fileURLToPath(import.meta.url));
function readJson(file, label) {
let raw;
try {
raw = fs.readFileSync(file, 'utf8');
} catch (err) {
throw new Error(`Cannot read ${label} config at ${file}: ${err.message}`);
}
try {
return JSON.parse(raw);
} catch (err) {
throw new Error(`Invalid JSON in ${label} config at ${file}: ${err.message}`);
}
}
function resolvePath(value, fallback) {
const target = value || fallback;
return path.isAbsolute(target) ? target : path.resolve(process.cwd(), target);
}
function normalizeOrigins(values, fallback) {
const list = values && values.length ? values : fallback;
const out = new Set();
for (const value of list) {
if (!value) continue;
try {
out.add(new URL(String(value).trim()).origin);
} catch {
throw new Error(`Invalid origin in ALLOWED_ORIGINS: ${value}`);
}
}
return out;
}
function envKey(id, suffix) {
return `SERVICE_${id.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_${suffix}`;
}
function loadProjects(env) {
const file = resolvePath(env.PROJECTS_CONFIG_PATH, path.join(HERE, 'config', 'projects.json'));
const raw = readJson(file, 'projects');
if (!raw || !Array.isArray(raw.projects)) throw new Error('projects.json must contain a "projects" array');
const seen = new Set();
return raw.projects
.map((p, index) => {
if (!p || typeof p.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(p.id)) {
throw new Error(`Invalid project id at index ${index}`);
}
if (seen.has(p.id)) throw new Error(`Duplicate project id: ${p.id}`);
seen.add(p.id);
const github = p.github && p.github.owner && p.github.repo
? { owner: String(p.github.owner), repo: String(p.github.repo) }
: null;
return {
id: p.id,
name: String(p.name || p.id),
description: p.description ? String(p.description) : '',
github,
website: p.website ? String(p.website) : null,
api: p.api && p.api.type ? { type: String(p.api.type), base: p.api.base ? String(p.api.base) : null } : null,
order: Number.isFinite(p.order) ? p.order : index,
visible: p.visible !== false,
featured: p.featured === true
};
})
.sort((a, b) => a.order - b.order);
}
function loadServices(env) {
const file = resolvePath(env.SERVICES_CONFIG_PATH, path.join(HERE, 'config', 'services.json'));
const raw = readJson(file, 'services');
if (!raw || !Array.isArray(raw.services)) throw new Error('services.json must contain a "services" array');
const seen = new Set();
return raw.services
.map((s, index) => {
if (!s || typeof s.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(s.id)) {
throw new Error(`Invalid service id at index ${index}`);
}
if (seen.has(s.id)) throw new Error(`Duplicate service id: ${s.id}`);
seen.add(s.id);
const url = env[envKey(s.id, 'URL')] || s.url;
try {
const parsed = new URL(url);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('protocol');
} catch {
throw new Error(`Invalid URL for service ${s.id}: ${url}`);
}
return {
id: s.id,
name: String(s.name || s.id),
url: String(url),
order: Number.isFinite(s.order) ? s.order : index,
enabled: parseBoolean(env[envKey(s.id, 'ENABLED')], s.enabled !== false)
};
})
.sort((a, b) => a.order - b.order);
}
function loadServers(env) {
const file = resolvePath(env.SERVERS_CONFIG_PATH, path.join(HERE, 'config', 'servers.json'));
const raw = readJson(file, 'servers');
if (!raw || !Array.isArray(raw.servers)) throw new Error('servers.json must contain a "servers" array');
const seen = new Set();
return raw.servers
.map((s, index) => {
if (!s || typeof s.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(s.id)) {
throw new Error(`Invalid server id at index ${index}`);
}
if (seen.has(s.id)) throw new Error(`Duplicate server id: ${s.id}`);
seen.add(s.id);
const n = index + 1;
const name = env[`SERVER_${n}_NAME`] || s.name || s.id;
const ip = env[`SERVER_${n}_IP`] || s.ip;
if (!ip || !/^[A-Za-z0-9.:_-]+$/.test(String(ip))) {
throw new Error(`Invalid IP/hostname for server ${s.id}: ${ip}`);
}
return {
id: s.id,
name: String(name),
ip: String(ip),
order: Number.isFinite(s.order) ? s.order : index,
enabled: parseBoolean(env[`SERVER_${n}_ENABLED`], s.enabled !== false)
};
})
.sort((a, b) => a.order - b.order);
}
export function loadConfig(env = process.env) {
const nodeEnv = env.NODE_ENV || 'development';
const production = nodeEnv === 'production';
const warnings = [];
const port = clampInt(env.PORT, 8787, 1, 65535);
const host = env.HOST || '127.0.0.1';
const publicOrigin = (() => {
const value = env.PUBLIC_ORIGIN || (production ? 'https://milesallen.site' : `http://localhost:${port}`);
try {
return new URL(value).origin;
} catch {
throw new Error(`Invalid PUBLIC_ORIGIN: ${value}`);
}
})();
const productionOrigins = ['https://milesallen.site', 'https://www.milesallen.site'];
const defaultOrigins = production
? [publicOrigin, ...productionOrigins]
: [
publicOrigin,
...productionOrigins,
`http://localhost:${port}`,
`http://127.0.0.1:${port}`,
'http://localhost:3000',
'http://127.0.0.1:3000'
];
const allowedOrigins = normalizeOrigins(
env.ALLOWED_ORIGINS ? env.ALLOWED_ORIGINS.split(',') : null,
defaultOrigins
);
allowedOrigins.add(publicOrigin);
let sessionSecret = env.SESSION_SECRET || '';
if (!sessionSecret) {
if (production) throw new Error('SESSION_SECRET is required in production');
sessionSecret = crypto.randomBytes(32).toString('hex');
warnings.push('SESSION_SECRET is not set; generated an ephemeral development secret. Sessions and analytics identifiers reset on restart.');
}
if (sessionSecret.length < 32 && production) {
throw new Error('SESSION_SECRET must be at least 32 characters in production');
}
const vaultPasswordHash = env.VAULT_PASSWORD_HASH || null;
const vaultPassword = env.VAULT_PASSWORD || null;
if (!vaultPasswordHash && !vaultPassword) {
warnings.push('Moon Vault is disabled: set VAULT_PASSWORD_HASH (recommended) or VAULT_PASSWORD in .env.');
}
const projects = loadProjects(env);
const services = loadServices(env);
const servers = loadServers(env);
const fedlProject = projects.find((p) => p.id === 'fedl' && p.api?.type === 'fedl');
const fedlApiBase = env.FEDL_API_BASE || fedlProject?.api?.base || 'https://server.fedl.site/fedl/api';
const config = {
env: nodeEnv,
production,
host,
port,
siteRoot: resolvePath(env.SITE_ROOT, process.cwd()),
dbPath: resolvePath(env.DB_PATH, './data/dashboard.db'),
publicOrigin,
allowedOrigins,
sessionSecret,
trustProxy: parseBoolean(env.TRUST_PROXY, false),
cookie: {
name: env.VAULT_COOKIE_NAME || 'miles_vault',
secure: parseBoolean(env.COOKIE_SECURE, production),
sameSite: 'Strict',
ttlMs: clampInt(env.VAULT_SESSION_HOURS, 12, 1, 24 * 30) * 60 * 60 * 1000
},
vault: {
passwordHash: vaultPasswordHash,
password: vaultPassword,
maxAttempts: clampInt(env.VAULT_MAX_ATTEMPTS, 5, 1, 100),
windowMs: clampInt(env.VAULT_ATTEMPT_WINDOW_MINUTES, 15, 1, 1440) * 60 * 1000
},
monitor: {
servers,
services,
serverIntervalMs: clampInt(env.SERVER_CHECK_INTERVAL_MS, 60_000, 10_000, 24 * 60 * 60 * 1000),
pingTimeoutMs: clampInt(env.PING_TIMEOUT_MS, 2_000, 200, 30_000),
serviceIntervalMs: clampInt(env.SERVICE_CHECK_INTERVAL_MS, 120_000, 15_000, 24 * 60 * 60 * 1000),
httpTimeoutMs: clampInt(env.HTTP_CHECK_TIMEOUT_MS, 5_000, 500, 30_000),
retentionDays: clampInt(env.MONITOR_RETENTION_DAYS, 90, 7, 3650),
expectedSubnet: env.HOME_SUBNET || null
},
github: {
username: env.GITHUB_USERNAME || 'mileswolfallen2',
token: env.GITHUB_TOKEN || '',
apiBase: env.GITHUB_API_BASE || 'https://api.github.com',
refreshMs: clampInt(env.GITHUB_REFRESH_MS, 30 * 60 * 1000, 60_000, 24 * 60 * 60 * 1000),
timeoutMs: clampInt(env.GITHUB_TIMEOUT_MS, 10_000, 1_000, 60_000),
enrich: parseBoolean(env.GITHUB_ENRICH, false)
},
fedl: {
apiBase: fedlApiBase,
siteUrl: env.FEDL_SITE_URL || 'https://fedl.site',
github: fedlProject?.github || { owner: 'mileswolfallen2', repo: 'fedl' },
refreshMs: clampInt(env.FEDL_REFRESH_MS, 15 * 60 * 1000, 60_000, 24 * 60 * 60 * 1000),
timeoutMs: clampInt(env.FEDL_TIMEOUT_MS, 15_000, 1_000, 60_000)
},
analytics: {
retentionDays: clampInt(env.ANALYTICS_RETENTION_DAYS, 30, 1, 365),
dedupeSeconds: clampInt(env.ANALYTICS_DEDUPE_SECONDS, 10, 0, 3600)
},
rateLimits: {
api: {
limit: clampInt(env.API_RATE_LIMIT, 300, 10, 100_000),
windowMs: 60_000
},
analytics: {
limit: clampInt(env.ANALYTICS_RATE_LIMIT, 120, 5, 100_000),
windowMs: 60_000
},
login: {
limit: clampInt(env.LOGIN_RATE_LIMIT, 15, 1, 1000),
windowMs: 15 * 60 * 1000
}
},
http: {
requestTimeoutMs: clampInt(env.REQUEST_TIMEOUT_MS, 30_000, 1_000, 300_000),
bodyLimitBytes: clampInt(env.BODY_LIMIT_BYTES, 16_384, 512, 1024 * 1024)
},
logLevel: env.LOG_LEVEL || 'info',
projects,
services,
servers,
warnings
};
return config;
}
+179
View File
@@ -0,0 +1,179 @@
{
"projects": [
{
"id": "fedl",
"name": "FEDL",
"description": "Geometry Dash demon list with ranked levels, verified runs, moderation, accounts, and community features.",
"github": { "owner": "mileswolfallen2", "repo": "fedl" },
"website": "https://fedl.site",
"api": { "type": "fedl", "base": "https://server.fedl.site/fedl/api" },
"order": 1,
"visible": true,
"featured": true
},
{
"id": "miles-web",
"name": "milesallen.site",
"description": "This portfolio: static HTML, hand-written CSS, no build step.",
"github": { "owner": "mileswolfallen2", "repo": "miles-web" },
"website": "https://milesallen.site",
"order": 2,
"visible": true
},
{
"id": "vanilla",
"name": "Vanilla",
"description": "Clean, minimal web experiment built with pure vanilla JavaScript.",
"github": { "owner": "diskettelabs", "repo": "vanilla" },
"website": "https://vanilla.milesallen.site",
"order": 3,
"visible": true
},
{
"id": "gelectron",
"name": "Gelectron",
"description": "Drop-in Electron replacement using native web views instead of bundled Chromium.",
"github": { "owner": "mileswolfallen2", "repo": "gelectron" },
"website": "https://gelectron.milesallen.site/",
"order": 4,
"visible": true
},
{
"id": "noto",
"name": "Noto",
"description": "AI-enhanced note-taking app built with Flutter.",
"github": { "owner": "mileswolfallen2", "repo": "Noto" },
"website": "https://noto.fedl.site",
"order": 5,
"visible": true
},
{
"id": "omniemu",
"name": "OmniEmu 2.0",
"description": "Cross-platform emulator manager and game launcher.",
"github": { "owner": "mileswolfallen2", "repo": "OmniEmu2.0" },
"website": "https://om.milesallen.site",
"order": 6,
"visible": true
},
{
"id": "command-move",
"name": "CommandMove",
"description": "Control X on macOS.",
"github": { "owner": "mileswolfallen2", "repo": "command-move" },
"website": "https://command.milesallen.site",
"order": 7,
"visible": true
},
{
"id": "nova",
"name": "Nova AI",
"description": "Local AI assistant with desktop, web, and CLI interfaces.",
"github": { "owner": "mileswolfallen2", "repo": "nova" },
"website": "https://ai.fedl.site",
"order": 8,
"visible": true
},
{
"id": "moon-gaming",
"name": "Moon Gaming",
"description": "Browser game hub with a large commit history.",
"github": { "owner": "mileswolfallen2", "repo": "moon-gaming" },
"website": "https://fun-miles.free.nf",
"order": 9,
"visible": true
},
{
"id": "music-app",
"name": "Music App",
"description": "Ad-free music player inspired by YouTube Music.",
"github": { "owner": "mileswolfallen2", "repo": "music-app" },
"website": "https://mileswolfallen2.github.io/music-app/",
"order": 10,
"visible": true
},
{
"id": "rhythm-game",
"name": "Rhythm Game",
"description": "Browser-based rhythm game with keyboard controls.",
"github": { "owner": "mileswolfallen2", "repo": "new-game" },
"website": "https://mileswolfallen2.github.io/new-game/",
"order": 11,
"visible": true
},
{
"id": "decompilations",
"name": "Decompilations",
"description": "Native PC ports and reverse-engineered game projects.",
"github": { "owner": "mileswolfallen2", "repo": "Decompilations-web" },
"website": "https://comp.fedl.site/",
"order": 12,
"visible": true
},
{
"id": "issue-tracker",
"name": "Issue Tracker",
"description": "Custom issue tracking app built with Node.js.",
"github": { "owner": "mileswolfallen2", "repo": "Issue-tracker" },
"order": 13,
"visible": true
},
{
"id": "geode-mod",
"name": "FEDL Geode Mod",
"description": "In-game Geometry Dash mod for demon list integration.",
"github": { "owner": "mileswolfallen2", "repo": "FEDL-Geode-mod" },
"order": 14,
"visible": true
},
{
"id": "vanilla-site",
"name": "Vanilla Website",
"description": "Static website for Vanilla.",
"github": { "owner": "diskettelabs", "repo": "vanilla-site" },
"website": "https://diskettelabs.github.io/vanilla-site/",
"order": 15,
"visible": false
},
{
"id": "gelectron-web",
"name": "Gelectron Website",
"description": "Website for Gelectron.",
"github": { "owner": "mileswolfallen2", "repo": "gelectron-web" },
"order": 16,
"visible": false
},
{
"id": "noto-web",
"name": "Noto Website",
"description": "Website for Noto.",
"github": { "owner": "mileswolfallen2", "repo": "Noto-web" },
"order": 17,
"visible": false
},
{
"id": "omniemu-web",
"name": "OmniEmu Website",
"description": "Website for OmniEmu.",
"github": { "owner": "mileswolfallen2", "repo": "OmniEmu-web" },
"order": 18,
"visible": false
},
{
"id": "web-nova",
"name": "Nova Website",
"description": "Website for Nova.",
"github": { "owner": "mileswolfallen2", "repo": "web-nova" },
"order": 19,
"visible": false
},
{
"id": "command-move-web",
"name": "CommandMove Website",
"description": "Website for CommandMove.",
"github": { "owner": "mileswolfallen2", "repo": "CommandMove-web" },
"order": 20,
"visible": false
}
]
}
+18
View File
@@ -0,0 +1,18 @@
{
"servers": [
{
"id": "home-1",
"name": "Home Server 1",
"ip": "10.0.0.87",
"order": 1,
"enabled": true
},
{
"id": "home-2",
"name": "Home Server 2",
"ip": "10.0.0.119",
"order": 2,
"enabled": true
}
]
}
+39
View File
@@ -0,0 +1,39 @@
{
"services": [
{
"id": "milesallen",
"name": "milesallen.site",
"url": "https://milesallen.site/",
"order": 1,
"enabled": true
},
{
"id": "fedl",
"name": "FEDL",
"url": "https://fedl.site/",
"order": 2,
"enabled": true
},
{
"id": "vanilla",
"name": "Vanilla",
"url": "https://vanilla.milesallen.site/",
"order": 3,
"enabled": true
},
{
"id": "gelectron",
"name": "Gelectron",
"url": "https://gelectron.milesallen.site/",
"order": 4,
"enabled": true
},
{
"id": "noto",
"name": "Noto",
"url": "https://noto.fedl.site/",
"order": 5,
"enabled": true
}
]
}
+13
View File
@@ -0,0 +1,13 @@
import fs from 'node:fs';
import path from 'node:path';
import Database from 'better-sqlite3';
export function openDatabase(dbPath, { readonly = false } = {}) {
if (!readonly) fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new Database(dbPath, { readonly, fileMustExist: readonly });
db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL');
db.pragma('foreign_keys = ON');
db.pragma('busy_timeout = 5000');
return db;
}
+43
View File
@@ -0,0 +1,43 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_DIR = path.join(HERE, 'migrations');
export function migrate(db, { migrationsDir = MIGRATIONS_DIR } = {}) {
db.exec(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at TEXT NOT NULL
);
`);
const applied = new Set(
db.prepare('SELECT version FROM schema_migrations').all().map((row) => row.version)
);
const files = fs
.readdirSync(migrationsDir)
.filter((name) => /^\d+_.+\.sql$/.test(name))
.sort((a, b) => a.localeCompare(b));
const insert = db.prepare(
'INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)'
);
let count = 0;
for (const file of files) {
const version = Number.parseInt(file.split('_')[0], 10);
if (applied.has(version)) continue;
const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
const run = db.transaction(() => {
db.exec(sql);
insert.run(version, file, new Date().toISOString());
});
run();
count += 1;
}
return count;
}
+117
View File
@@ -0,0 +1,117 @@
CREATE TABLE servers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
ip TEXT NOT NULL,
display_order INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE server_checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
checked_at TEXT NOT NULL,
online INTEGER NOT NULL,
response_ms REAL,
reason TEXT NOT NULL DEFAULT 'ok',
on_home_network INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_server_checks_lookup ON server_checks (server_id, checked_at DESC);
CREATE INDEX idx_server_checks_time ON server_checks (checked_at);
CREATE TABLE services (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
url TEXT NOT NULL,
display_order INTEGER NOT NULL DEFAULT 0,
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE service_checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
service_id TEXT NOT NULL REFERENCES services(id) ON DELETE CASCADE,
checked_at TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('operational', 'degraded', 'offline', 'unknown')),
response_ms REAL,
http_status INTEGER,
error TEXT
);
CREATE INDEX idx_service_checks_lookup ON service_checks (service_id, checked_at DESC);
CREATE INDEX idx_service_checks_time ON service_checks (checked_at);
CREATE TABLE projects (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
github_owner TEXT,
github_repo TEXT,
website_url TEXT,
api_type TEXT,
api_base TEXT,
display_order INTEGER NOT NULL DEFAULT 0,
visible INTEGER NOT NULL DEFAULT 1,
featured INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
);
CREATE TABLE cache (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
etag TEXT,
fetched_at TEXT NOT NULL,
expires_at TEXT
);
CREATE TABLE fedl_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fetched_at TEXT NOT NULL,
list_json TEXT NOT NULL,
runs_json TEXT NOT NULL
);
CREATE INDEX idx_fedl_snapshots_time ON fedl_snapshots (fetched_at DESC);
CREATE TABLE fedl_stats (
id INTEGER PRIMARY KEY CHECK (id = 1),
stats_json TEXT NOT NULL,
fetched_at TEXT NOT NULL,
snapshot_id INTEGER REFERENCES fedl_snapshots(id) ON DELETE SET NULL
);
CREATE TABLE pageviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL,
visitor_hash TEXT NOT NULL,
referrer_domain TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX idx_pageviews_time ON pageviews (created_at DESC);
CREATE INDEX idx_pageviews_path_time ON pageviews (path, created_at DESC);
CREATE INDEX idx_pageviews_visitor_time ON pageviews (visitor_hash, created_at DESC);
CREATE INDEX idx_pageviews_dedupe ON pageviews (visitor_hash, path, created_at DESC);
CREATE TABLE vault_sessions (
id TEXT PRIMARY KEY,
token_hash TEXT NOT NULL,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL
);
CREATE INDEX idx_vault_sessions_expiry ON vault_sessions (expires_at);
CREATE TABLE vault_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip_hash TEXT NOT NULL,
attempted_at TEXT NOT NULL,
success INTEGER NOT NULL
);
CREATE INDEX idx_vault_attempts_lookup ON vault_attempts (ip_hash, attempted_at DESC);
CREATE INDEX idx_vault_attempts_time ON vault_attempts (attempted_at);
CREATE TABLE meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL
);
+89
View File
@@ -0,0 +1,89 @@
export function seedConfig(db, config, { now = new Date() } = {}) {
const ts = now.toISOString();
const upsertServer = db.prepare(`
INSERT INTO servers (id, name, ip, display_order, enabled, created_at, updated_at)
VALUES (@id, @name, @ip, @order, @enabled, @ts, @ts)
ON CONFLICT(id) DO UPDATE SET
name = excluded.name,
ip = excluded.ip,
display_order = excluded.display_order,
enabled = excluded.enabled,
updated_at = excluded.updated_at
`);
const upsertService = db.prepare(`
INSERT INTO services (id, name, url, display_order, enabled, created_at, updated_at)
VALUES (@id, @name, @url, @order, @enabled, @ts, @ts)
ON CONFLICT(id) DO UPDATE SET
name = excluded.name,
url = excluded.url,
display_order = excluded.display_order,
enabled = excluded.enabled,
updated_at = excluded.updated_at
`);
const upsertProject = db.prepare(`
INSERT INTO projects (
id, name, description, github_owner, github_repo, website_url,
api_type, api_base, display_order, visible, featured, updated_at
)
VALUES (
@id, @name, @description, @githubOwner, @githubRepo, @website,
@apiType, @apiBase, @order, @visible, @featured, @ts
)
ON CONFLICT(id) DO UPDATE SET
name = excluded.name,
description = excluded.description,
github_owner = excluded.github_owner,
github_repo = excluded.github_repo,
website_url = excluded.website_url,
api_type = excluded.api_type,
api_base = excluded.api_base,
display_order = excluded.display_order,
visible = excluded.visible,
featured = excluded.featured,
updated_at = excluded.updated_at
`);
db.transaction(() => {
for (const server of config.servers) {
upsertServer.run({
id: server.id,
name: server.name,
ip: server.ip,
order: server.order,
enabled: server.enabled ? 1 : 0,
ts
});
}
for (const service of config.services) {
upsertService.run({
id: service.id,
name: service.name,
url: service.url,
order: service.order,
enabled: service.enabled ? 1 : 0,
ts
});
}
for (const project of config.projects) {
upsertProject.run({
id: project.id,
name: project.name,
description: project.description,
githubOwner: project.github?.owner || null,
githubRepo: project.github?.repo || null,
website: project.website || null,
apiType: project.api?.type || null,
apiBase: project.api?.base || null,
order: project.order,
visible: project.visible ? 1 : 0,
featured: project.featured ? 1 : 0,
ts
});
}
})();
}
+136
View File
@@ -0,0 +1,136 @@
import http from 'node:http';
import { loadEnv } from './lib/env.js';
import { loadConfig } from './config.js';
import { createLogger } from './lib/logger.js';
import { openDatabase } from './db/index.js';
import { migrate } from './db/migrate.js';
import { seedConfig } from './db/seed.js';
import { createStatusService } from './services/status.js';
import { createAnalyticsService } from './services/analytics.js';
import { createVaultService } from './services/vault.js';
import { createGitHubService } from './services/github.js';
import { createFedlService } from './services/fedl.js';
import { createMonitor } from './services/monitor.js';
import { createApp } from './app.js';
loadEnv();
const config = loadConfig();
const logger = createLogger({ level: config.logLevel, name: 'milesallen-dashboard' });
for (const warning of config.warnings) logger.warn(warning);
const db = openDatabase(config.dbPath);
const appliedMigrations = migrate(db);
if (appliedMigrations > 0) logger.info('database migrations applied', { count: appliedMigrations });
seedConfig(db, config);
const status = createStatusService({ db, config });
const analytics = createAnalyticsService({ db, config });
const vault = await createVaultService({ db, config, logger });
const github = createGitHubService({ db, config, logger });
const fedl = createFedlService({ db, config, logger });
const monitor = createMonitor({ db, config, logger });
const handler = createApp({
config,
db,
logger,
services: { status, analytics, vault, github, fedl, monitor }
});
const server = http.createServer((req, res) => {
handler(req, res).catch((err) => {
logger.error('request handler rejected', { error: err?.message || String(err) });
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: { code: 'internal_error', message: 'Internal server error' } }));
} else {
res.destroy();
}
});
});
server.requestTimeout = config.http.requestTimeoutMs;
server.headersTimeout = Math.max(5_000, Math.min(20_000, config.http.requestTimeoutMs));
server.keepAliveTimeout = 65_000;
const monitorRetention = db.prepare(`DELETE FROM server_checks WHERE checked_at < ?`);
const serviceRetention = db.prepare(`DELETE FROM service_checks WHERE checked_at < ?`);
function cleanup() {
try {
const cutoff = new Date(
Date.now() - config.monitor.retentionDays * 24 * 60 * 60 * 1000
).toISOString();
const servers = monitorRetention.run(cutoff).changes;
const services = serviceRetention.run(cutoff).changes;
const views = analytics.cleanup();
const sessions = vault.cleanup();
logger.info('retention cleanup', {
serverChecks: servers,
serviceChecks: services,
pageviews: views,
sessions: sessions.sessions,
attempts: sessions.attempts
});
} catch (err) {
logger.error('retention cleanup failed', { error: err?.message || String(err) });
}
}
const cleanupTimer = setInterval(cleanup, 6 * 60 * 60 * 1000);
cleanupTimer.unref();
let shuttingDown = false;
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
logger.info('shutting down', { signal });
clearInterval(cleanupTimer);
monitor.stop();
github.stop();
fedl.stop();
server.close(() => {
try {
db.close();
} catch (err) {
logger.warn('database close failed', { error: err?.message || String(err) });
}
process.exit(0);
});
setTimeout(() => {
logger.error('forced shutdown after timeout');
process.exit(1);
}, 10_000).unref();
}
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('unhandledRejection', (reason) => {
logger.error('unhandled promise rejection', { error: reason?.message || String(reason) });
});
process.on('uncaughtException', (err) => {
logger.error('uncaught exception', { error: err?.message || String(err), stack: err?.stack });
});
server.listen(config.port, config.host, () => {
logger.info('dashboard listening', {
url: `http://${config.host}:${config.port}`,
env: config.env,
database: config.dbPath,
vault: vault.enabled ? 'enabled' : 'disabled',
github: config.github.token ? 'authenticated' : 'anonymous',
githubEnrich: config.github.enrich,
servers: config.servers.length,
services: config.services.length
});
monitor.start();
github.start();
fedl.start();
});
server.on('error', (err) => {
logger.error('server error', { error: err?.message || String(err), code: err?.code });
process.exitCode = 1;
});
+37
View File
@@ -0,0 +1,37 @@
export function parseCookies(header) {
const out = {};
if (!header) return out;
for (const part of header.split(';')) {
const eq = part.indexOf('=');
if (eq === -1) continue;
const name = part.slice(0, eq).trim();
if (!name) continue;
let value = part.slice(eq + 1).trim();
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
out[name] = value;
}
return out;
}
export function serializeCookie(name, value, options = {}) {
const {
path = '/',
maxAge,
expires,
httpOnly = true,
secure = false,
sameSite = 'Strict'
} = options;
const parts = [`${name}=${value}`, `Path=${path}`];
if (maxAge !== undefined) parts.push(`Max-Age=${Math.max(0, Math.floor(maxAge))}`);
if (expires) parts.push(`Expires=${expires.toUTCString()}`);
if (httpOnly) parts.push('HttpOnly');
if (secure) parts.push('Secure');
if (sameSite) parts.push(`SameSite=${sameSite}`);
return parts.join('; ');
}
export function clearCookie(name, options = {}) {
return serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) });
}
+48
View File
@@ -0,0 +1,48 @@
import crypto from 'node:crypto';
export function sha256Hex(value) {
return crypto.createHash('sha256').update(value).digest('hex');
}
export function hmacHex(secret, value) {
return crypto.createHmac('sha256', secret).update(value).digest('hex');
}
export function randomHex(bytes = 32) {
return crypto.randomBytes(bytes).toString('hex');
}
export function safeEqualHex(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
if (a.length !== b.length || a.length % 2 !== 0) return false;
try {
return crypto.timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));
} catch {
return false;
}
}
export function signValue(secret, value) {
return hmacHex(secret, value);
}
export function verifySignature(secret, value, signature) {
return safeEqualHex(signValue(secret, value), signature);
}
export function dayKey(date = new Date()) {
return date.toISOString().slice(0, 10);
}
/**
* Daily rotating key. Hashing an IP with this key gives a stable
* anonymous identifier for the day, but cannot be reversed.
*/
export function dailyKey(secret, date = new Date(), scope = 'analytics') {
return hmacHex(secret, `${scope}:${dayKey(date)}`);
}
export function hashIp(secret, ip, { date = new Date(), scope = 'analytics' } = {}) {
const key = dailyKey(secret, date, scope);
return hmacHex(key, String(ip || 'unknown')).slice(0, 32);
}
+40
View File
@@ -0,0 +1,40 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* Minimal .env loader. No dependency, no variable expansion.
* Existing process env values always win.
*/
export function loadEnv(file = path.resolve(process.cwd(), '.env')) {
let text;
try {
text = fs.readFileSync(file, 'utf8');
} catch {
return {};
}
const loaded = {};
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq === -1) continue;
let key = line.slice(0, eq).trim();
if (key.startsWith('export ')) key = key.slice(7).trim();
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
let value = line.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
// Basic escape support for double-quoted values.
value = value.replace(/\\n/g, '\n').replace(/\\r/g, '\r');
if (process.env[key] === undefined) {
process.env[key] = value;
loaded[key] = value;
}
}
return loaded;
}
+23
View File
@@ -0,0 +1,23 @@
export class AppError extends Error {
constructor(status, code, message, details, expose = status < 500) {
super(message);
this.name = 'AppError';
this.status = status;
this.code = code;
this.details = details;
this.expose = expose;
}
}
export const badRequest = (message = 'Invalid request', details) =>
new AppError(400, 'bad_request', message, details);
export const unauthorized = (message = 'Unauthorized') =>
new AppError(401, 'unauthorized', message);
export const forbidden = (message = 'Forbidden') =>
new AppError(403, 'forbidden', message);
export const notFound = (message = 'Not found') =>
new AppError(404, 'not_found', message);
export const tooManyRequests = (message = 'Too many requests', retryAfterMs) =>
new AppError(429, 'rate_limited', message, { retryAfterMs });
export const unavailable = (message = 'Service unavailable') =>
new AppError(503, 'unavailable', message);
+141
View File
@@ -0,0 +1,141 @@
import { badRequest, tooManyRequests } from './errors.js';
export function sendJson(res, status, data, extraHeaders = {}) {
const body = JSON.stringify(data);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Cache-Control': 'no-store',
...extraHeaders
});
res.end(body);
}
export function sendText(res, status, text, extraHeaders = {}) {
res.writeHead(status, {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Length': Buffer.byteLength(text),
'Cache-Control': 'no-store',
...extraHeaders
});
res.end(text);
}
export function sendError(res, error, extraHeaders = {}) {
const status = error.status || 500;
const payload = {
error: {
code: error.code || 'internal_error',
message: error.expose === false ? 'Internal server error' : error.message || 'Internal server error'
}
};
if (error.details && error.expose !== false) payload.error.details = error.details;
const headers = { ...extraHeaders };
if (status === 429 && error.details?.retryAfterMs) {
headers['Retry-After'] = String(Math.max(1, Math.ceil(error.details.retryAfterMs / 1000)));
}
sendJson(res, status, payload, headers);
}
export function getClientIp(req, { trustProxy = false } = {}) {
if (trustProxy) {
const cf = req.headers['cf-connecting-ip'];
if (typeof cf === 'string' && cf.trim()) return cf.trim();
const xff = req.headers['x-forwarded-for'];
if (typeof xff === 'string' && xff.trim()) return xff.split(',')[0].trim();
}
return req.socket?.remoteAddress || 'unknown';
}
export function applySecurityHeaders(res, { production = false } = {}) {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
if (production) {
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
}
export function corsFor(origin, allowedOrigins) {
if (!origin) return {};
if (!allowedOrigins.has(origin)) return null;
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '600',
Vary: 'Origin'
};
}
/**
* Read and parse a request body with a hard size limit.
* Supports JSON and (for the vault login form) urlencoded bodies.
*/
export function readBody(req, { limitBytes = 16384, timeoutMs = 10000 } = {}) {
return new Promise((resolve, reject) => {
const declared = Number(req.headers['content-length'] || 0);
if (declared && declared > limitBytes) {
reject(badRequest('Request body too large'));
return;
}
let size = 0;
const chunks = [];
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
req.destroy();
reject(tooManyRequests('Request body timeout'));
}, timeoutMs);
function finish(fn) {
if (settled) return;
settled = true;
clearTimeout(timer);
fn();
}
req.on('data', (chunk) => {
if (settled) return;
size += chunk.length;
if (size > limitBytes) {
finish(() => {
req.destroy();
reject(badRequest('Request body too large'));
});
return;
}
chunks.push(chunk);
});
req.on('error', (err) => finish(() => reject(err)));
req.on('end', () => {
finish(() => {
const raw = Buffer.concat(chunks).toString('utf8');
if (!raw) return resolve({ raw: '', json: {}, type: 'empty' });
const contentType = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
if (contentType === 'application/x-www-form-urlencoded') {
return resolve({ raw, json: Object.fromEntries(new URLSearchParams(raw)), type: 'form' });
}
if (contentType !== 'application/json' && contentType !== 'text/json') {
return reject(badRequest('Expected application/json'));
}
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return reject(badRequest('Expected a JSON object'));
}
resolve({ raw, json: parsed, type: 'json' });
} catch {
reject(badRequest('Malformed JSON'));
}
});
});
});
}
+38
View File
@@ -0,0 +1,38 @@
const LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
export function createLogger({ level = 'info', name = 'dashboard' } = {}) {
const threshold = LEVELS[level] ?? LEVELS.info;
function write(lvl, message, fields = {}) {
if ((LEVELS[lvl] ?? LEVELS.info) > threshold) return;
const entry = {
ts: new Date().toISOString(),
level: lvl,
logger: name,
msg: message,
...fields
};
const line = JSON.stringify(entry);
if (lvl === 'error' || lvl === 'warn') process.stderr.write(line + '\n');
else process.stdout.write(line + '\n');
}
return {
level,
error: (msg, fields) => write('error', msg, fields),
warn: (msg, fields) => write('warn', msg, fields),
info: (msg, fields) => write('info', msg, fields),
debug: (msg, fields) => write('debug', msg, fields),
child: (fields) => {
const parent = createLogger({ level, name });
return {
...parent,
error: (msg, f = {}) => parent.error(msg, { ...fields, ...f }),
warn: (msg, f = {}) => parent.warn(msg, { ...fields, ...f }),
info: (msg, f = {}) => parent.info(msg, { ...fields, ...f }),
debug: (msg, f = {}) => parent.debug(msg, { ...fields, ...f }),
child: parent.child
};
}
};
}
+47
View File
@@ -0,0 +1,47 @@
/**
* Small in-memory sliding-window rate limiter.
* Single-process by design; the vault login also has a DB-backed limit
* so brute-force protection survives restarts.
*/
export function createRateLimiter({ now = () => Date.now(), maxEntries = 20000 } = {}) {
const buckets = new Map();
function hit(key, { limit, windowMs }) {
const t = now();
const cutoff = t - windowMs;
let hits = buckets.get(key) || [];
hits = hits.filter((ts) => ts > cutoff);
if (hits.length >= limit) {
buckets.set(key, hits);
const retryAfterMs = Math.max(0, hits[0] + windowMs - t);
return { allowed: false, remaining: 0, retryAfterMs };
}
hits.push(t);
buckets.set(key, hits);
if (buckets.size > maxEntries) {
for (const [k, list] of buckets) {
if (!list.length || list[list.length - 1] <= cutoff) buckets.delete(k);
}
}
return { allowed: true, remaining: Math.max(0, limit - hits.length), retryAfterMs: 0 };
}
function reset(key) {
buckets.delete(key);
}
function cleanup() {
const cutoff = now() - 60 * 60 * 1000;
for (const [key, list] of buckets) {
const kept = list.filter((ts) => ts > cutoff);
if (kept.length) buckets.set(key, kept);
else buckets.delete(key);
}
}
return { hit, reset, cleanup, buckets };
}
+191
View File
@@ -0,0 +1,191 @@
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
const MIME = new Map(Object.entries({
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.md': 'text/plain; charset=utf-8',
'.xml': 'application/xml; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.avif': 'image/avif',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.ogg': 'audio/ogg',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.wasm': 'application/wasm',
'.data': 'application/octet-stream',
'.unityweb': 'application/octet-stream',
'.mem': 'application/octet-stream',
'.pck': 'application/octet-stream',
'.zip': 'application/zip'
}));
const DENY_SEGMENTS = new Set([
'.git',
'.github',
'node_modules',
'server',
'tests',
'data',
'docs',
'share-server'
]);
const DENY_FILES = new Set([
'.env',
'.env.local',
'.env.example',
'.DS_Store',
'package.json',
'package-lock.json'
]);
function contentType(file) {
return MIME.get(path.extname(file).toLowerCase()) || 'application/octet-stream';
}
function cacheControl(file) {
return path.extname(file).toLowerCase() === '.html'
? 'no-cache'
: 'public, max-age=3600';
}
export async function resolveStaticPath(root, rawPathname) {
let pathname;
try {
pathname = decodeURIComponent(rawPathname);
} catch {
return { error: 400 };
}
if (!pathname.startsWith('/') || pathname.includes('\\') || pathname.includes('\0')) {
return { error: 400 };
}
if (pathname.length > 2048) return { error: 414 };
const normalized = path.posix.normalize(pathname);
if (normalized.includes('..')) return { error: 403 };
let relative = normalized.replace(/^\/+/, '');
if (!relative || normalized.endsWith('/')) relative = path.posix.join(relative, 'index.html');
const segments = relative.split('/').filter(Boolean);
for (const segment of segments) {
if (segment.startsWith('.') || DENY_SEGMENTS.has(segment)) return { error: 403 };
}
if (DENY_FILES.has(segments[segments.length - 1])) return { error: 403 };
if (/\.(db|db-wal|db-shm|sqlite|sqlite3)$/i.test(relative)) return { error: 403 };
const resolved = path.resolve(root, relative);
const rootWithSep = root.endsWith(path.sep) ? root : root + path.sep;
if (resolved !== root && !resolved.startsWith(rootWithSep)) return { error: 403 };
try {
const realRoot = await fsp.realpath(root);
const realFile = await fsp.realpath(resolved);
const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
if (realFile !== realRoot && !realFile.startsWith(realRootWithSep)) return { error: 403 };
const stat = await fsp.stat(realFile);
if (stat.isDirectory()) {
const indexFile = path.join(realFile, 'index.html');
const indexStat = await fsp.stat(indexFile);
return { file: indexFile, stat: indexStat };
}
return { file: realFile, stat };
} catch {
return { error: 404 };
}
}
function parseRange(header, size) {
if (!header) return null;
const match = String(header).match(/^bytes=(\d*)-(\d*)$/);
if (!match) return { invalid: true };
const [, startRaw, endRaw] = match;
let start = startRaw === '' ? null : Number.parseInt(startRaw, 10);
let end = endRaw === '' ? null : Number.parseInt(endRaw, 10);
if (start === null && end === null) return { invalid: true };
if (start === null) {
start = Math.max(0, size - end);
end = size - 1;
} else if (end === null || end >= size) {
end = size - 1;
}
if (start < 0 || start >= size || end < start) return { invalid: true };
return { start, end };
}
export async function sendFile(req, res, file, stat, { status = 200, cache = null, contentTypeOverride = null } = {}) {
const type = contentTypeOverride || contentType(file);
const headers = {
'Content-Type': type,
'Content-Length': stat.size,
'Cache-Control': cache || cacheControl(file),
'Accept-Ranges': 'bytes'
};
const range = parseRange(req.headers.range, stat.size);
if (range?.invalid) {
res.writeHead(416, { 'Content-Range': `bytes */${stat.size}`, 'Cache-Control': 'no-store' });
res.end();
return;
}
if (range) {
const length = range.end - range.start + 1;
res.writeHead(206, {
...headers,
'Content-Length': length,
'Content-Range': `bytes ${range.start}-${range.end}/${stat.size}`
});
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file, { start: range.start, end: range.end }).pipe(res);
return;
}
res.writeHead(status, headers);
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).pipe(res);
}
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null }) {
const result = await resolveStaticPath(root, pathname);
if (result.error === 404) {
if (notFoundFile) {
try {
const stat = await fsp.stat(notFoundFile);
await sendFile(req, res, notFoundFile, stat, { status: 404, cache: 'no-store' });
return true;
} catch {
// fall through
}
}
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
res.end('Not found');
return true;
}
if (result.error) {
res.writeHead(result.error, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(result.error === 403 ? 'Forbidden' : 'Bad request');
return true;
}
await sendFile(req, res, result.file, result.stat, { cache });
return true;
}
+63
View File
@@ -0,0 +1,63 @@
const BOT_RE = /bot|crawler|spider|slurp|bingpreview|facebookexternalhit|headless|lighthouse|pagespeed|curl\/|wget\/|python-requests|go-http-client|httpclient|scrapy|semrush|ahrefs|mj12|dotbot|petalbot|yandex|baiduspider|duckduckbot|applebot|archive\.org/i;
const PATH_RE = /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/;
const HOST_RE = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
export function clampInt(value, fallback, min, max) {
const n = Number.parseInt(value, 10);
if (!Number.isFinite(n)) return fallback;
return Math.min(max, Math.max(min, n));
}
export function limitString(value, maxLength) {
if (typeof value !== 'string') return '';
return value.length > maxLength ? value.slice(0, maxLength) : value;
}
/**
* Normalize a page path for analytics. Returns null for anything that is
* not a safe, same-site path.
*/
export function normalizePath(raw) {
if (typeof raw !== 'string' || raw.length > 1024) return null;
let value = raw.trim().split('#')[0].split('?')[0];
if (!value.startsWith('/')) return null;
if (value.includes('\\') || value.includes('\0')) return null;
let decoded;
try {
decoded = decodeURIComponent(value);
} catch {
return null;
}
if (decoded.includes('..') || decoded.includes('\\') || decoded.includes('\0')) return null;
if (!PATH_RE.test(decoded)) return null;
decoded = decoded.replace(/\/{2,}/g, '/');
if (decoded === '/index.html') decoded = '/';
if (decoded.length > 1) decoded = decoded.replace(/\/+$/, '');
if (!decoded.startsWith('/')) decoded = '/' + decoded;
return decoded;
}
export function referrerDomain(raw) {
if (typeof raw !== 'string' || !raw || raw.length > 2048) return null;
try {
const url = new URL(raw);
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
const host = url.hostname.toLowerCase();
if (!HOST_RE.test(host)) return null;
return host.slice(0, 255);
} catch {
return null;
}
}
export function isLikelyBot(userAgent) {
if (!userAgent) return true;
return BOT_RE.test(userAgent);
}
export function parseBoolean(value, fallback = false) {
if (value === undefined || value === null || value === '') return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
+34
View File
@@ -0,0 +1,34 @@
import argon2 from 'argon2';
import { ARGON2_OPTIONS } from '../services/vault.js';
function readStdin() {
return new Promise((resolve) => {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => { data += chunk; });
process.stdin.on('end', () => resolve(data.trim()));
process.stdin.resume();
});
}
const supplied = process.argv.slice(2).join(' ').trim();
const password = supplied || process.env.VAULT_PASSWORD || (await readStdin());
if (!password) {
console.error('Usage: npm run hash-password -- "your passphrase"');
console.error(' or: printf "your passphrase" | npm run hash-password');
process.exit(1);
}
if (password.length < 8) {
console.error('Refusing to hash a passphrase shorter than 8 characters.');
process.exit(1);
}
const hash = await argon2.hash(password, ARGON2_OPTIONS);
console.log('');
console.log('Add this line to .env on the server:');
console.log('');
console.log(`VAULT_PASSWORD_HASH=${hash}`);
console.log('');
console.log('Keep the passphrase out of shell history, git, and frontend files.');
+20
View File
@@ -0,0 +1,20 @@
import { loadEnv } from '../lib/env.js';
import { loadConfig } from '../config.js';
import { openDatabase } from '../db/index.js';
import { migrate } from '../db/migrate.js';
import { seedConfig } from '../db/seed.js';
loadEnv();
const config = loadConfig();
const db = openDatabase(config.dbPath);
const count = migrate(db);
seedConfig(db, config);
const tables = db
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
.all()
.map((row) => row.name);
db.close();
console.log(`Database ready: ${config.dbPath}`);
console.log(`Migrations applied: ${count}`);
console.log(`Tables: ${tables.join(', ')}`);
+54
View File
@@ -0,0 +1,54 @@
const base = process.env.SMOKE_BASE_URL || `http://127.0.0.1:${process.env.PORT || 8787}`;
const checks = [
['health', '/api/health', 200],
['status', '/api/status', 200],
['servers', '/api/status/servers', 200],
['services', '/api/status/services', 200],
['github overview', '/api/github/overview', 200],
['github activity', '/api/github/activity', 200],
['projects', '/api/projects', 200],
['fedl stats', '/api/fedl/stats', 200],
['fedl activity', '/api/fedl/activity', 200],
['analytics overview', '/api/analytics/overview', 200],
['analytics pages', '/api/analytics/pages', 200],
['vault session', '/api/vault/session', 200],
['home page', '/', 200],
['dashboard', '/dashboard.html', 200],
['vault lock', '/moon-vault.html', 200],
['vault content gate', '/vault', 302]
];
let failures = 0;
for (const [name, path, expected] of checks) {
const started = Date.now();
try {
const response = await fetch(base + path, { redirect: 'manual' });
const ok = response.status === expected;
if (!ok) failures += 1;
console.log(`${ok ? 'PASS' : 'FAIL'} ${name.padEnd(20)} ${response.status} (${Date.now() - started}ms)`);
} catch (err) {
failures += 1;
console.log(`FAIL ${name.padEnd(20)} ${err.message}`);
}
}
try {
const response = await fetch(base + '/api/analytics/hit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 smoke-test'
},
body: JSON.stringify({ path: '/smoke-test?ignored=1', referrer: 'https://example.com/page' })
});
const body = await response.json();
const ok = response.status === 202 && body.recorded === true && body.path === undefined;
if (!ok) failures += 1;
console.log(`${ok ? 'PASS' : 'FAIL'} ${'analytics hit'.padEnd(20)} ${response.status} recorded=${body.recorded}`);
} catch (err) {
failures += 1;
console.log(`FAIL ${'analytics hit'.padEnd(20)} ${err.message}`);
}
process.exit(failures ? 1 : 0);
+152
View File
@@ -0,0 +1,152 @@
import { badRequest } from '../lib/errors.js';
import { hashIp } from '../lib/crypto.js';
import { isLikelyBot, normalizePath, referrerDomain } from '../lib/validate.js';
const DAY_MS = 24 * 60 * 60 * 1000;
function startOfUtcDay(date) {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}
function dayKey(date) {
return date.toISOString().slice(0, 10);
}
export function createAnalyticsService({ db, config, now = () => new Date() }) {
const stmts = {
insert: db.prepare(
'INSERT INTO pageviews (path, visitor_hash, referrer_domain, created_at) VALUES (?, ?, ?, ?)'
),
recentDuplicate: db.prepare(
'SELECT 1 AS found FROM pageviews WHERE visitor_hash = ? AND path = ? AND created_at >= ? LIMIT 1'
),
total: db.prepare('SELECT COUNT(*) AS views FROM pageviews'),
range: db.prepare(
'SELECT COUNT(*) AS views, COUNT(DISTINCT visitor_hash) AS visitors FROM pageviews WHERE created_at >= ? AND created_at < ?'
),
daily: db.prepare(`
SELECT substr(created_at, 1, 10) AS day,
COUNT(*) AS views,
COUNT(DISTINCT visitor_hash) AS visitors
FROM pageviews
WHERE created_at >= ? AND created_at < ?
GROUP BY day
ORDER BY day
`),
topPages: db.prepare(`
SELECT path, COUNT(*) AS views, COUNT(DISTINCT visitor_hash) AS visitors
FROM pageviews
WHERE created_at >= ? AND created_at < ?
GROUP BY path
ORDER BY views DESC, path ASC
LIMIT ?
`),
pageStats: db.prepare(`
SELECT path,
COUNT(*) AS views,
COUNT(DISTINCT visitor_hash) AS visitors,
MAX(created_at) AS last_seen
FROM pageviews
WHERE created_at >= ? AND created_at < ?
GROUP BY path
ORDER BY views DESC, path ASC
LIMIT ?
`),
recent: db.prepare(`
SELECT path, referrer_domain, created_at
FROM pageviews
ORDER BY created_at DESC
LIMIT ?
`),
cleanup: db.prepare('DELETE FROM pageviews WHERE created_at < ?')
};
function recordHit({ path, referrer, ip, userAgent, at = now() }) {
if (isLikelyBot(userAgent)) return { recorded: false, reason: 'bot' };
const normalized = normalizePath(path);
if (!normalized) throw badRequest('Invalid page path');
const visitorHash = hashIp(config.sessionSecret, ip, { date: at, scope: 'analytics' });
if (config.analytics.dedupeSeconds > 0) {
const cutoff = new Date(at.getTime() - config.analytics.dedupeSeconds * 1000).toISOString();
if (stmts.recentDuplicate.get(visitorHash, normalized, cutoff)) {
return { recorded: false, reason: 'duplicate' };
}
}
const domain = referrerDomain(referrer);
stmts.insert.run(normalized, visitorHash, domain, at.toISOString());
return { recorded: true, path: normalized };
}
function getOverview({ at = now() } = {}) {
const today = startOfUtcDay(at);
const tomorrow = new Date(today.getTime() + DAY_MS);
const sevenDays = new Date(today.getTime() - 6 * DAY_MS);
const thirtyDays = new Date(today.getTime() - 29 * DAY_MS);
const todayRow = stmts.range.get(today.toISOString(), tomorrow.toISOString());
const weekRow = stmts.range.get(sevenDays.toISOString(), tomorrow.toISOString());
const monthRow = stmts.range.get(thirtyDays.toISOString(), tomorrow.toISOString());
const dailyRows = stmts.daily.all(thirtyDays.toISOString(), tomorrow.toISOString());
const byDay = new Map(dailyRows.map((row) => [row.day, row]));
const daily = [];
for (let i = 0; i < 30; i += 1) {
const date = new Date(thirtyDays.getTime() + i * DAY_MS);
const key = dayKey(date);
const row = byDay.get(key);
daily.push({ day: key, views: row?.views || 0, visitors: row?.visitors || 0 });
}
const total = stmts.total.get()?.views || 0;
const topPages = stmts.topPages.all(thirtyDays.toISOString(), tomorrow.toISOString(), 10);
const recent = stmts.recent.all(20);
return {
generatedAt: at.toISOString(),
retentionDays: config.analytics.retentionDays,
totals: {
pageviews: total,
pageviewsToday: todayRow.views,
pageviews7d: weekRow.views,
pageviews30d: monthRow.views,
uniqueVisitorsToday: todayRow.visitors,
uniqueVisitors7d: weekRow.visitors,
uniqueVisitors30d: monthRow.visitors
},
daily,
topPages,
recentActivity: recent
};
}
function getPages({ at = now(), days = 30, limit = 50 } = {}) {
const safeDays = Math.max(1, Math.min(config.analytics.retentionDays, Number(days) || 30));
const safeLimit = Math.max(1, Math.min(200, Number(limit) || 50));
const today = startOfUtcDay(at);
const end = new Date(today.getTime() + DAY_MS);
const start = new Date(today.getTime() - (safeDays - 1) * DAY_MS);
const rows = stmts.pageStats.all(start.toISOString(), end.toISOString(), safeLimit);
const total = rows.reduce((sum, row) => sum + row.views, 0);
return {
generatedAt: at.toISOString(),
range: { days: safeDays, from: start.toISOString(), to: end.toISOString() },
totalPageviews: total,
pages: rows.map((row) => ({
path: row.path,
views: row.views,
visitors: row.visitors,
share: total ? Math.round((row.views / total) * 10000) / 100 : 0,
lastSeen: row.last_seen
}))
};
}
function cleanup(at = now()) {
const cutoff = new Date(at.getTime() - config.analytics.retentionDays * DAY_MS).toISOString();
return stmts.cleanup.run(cutoff).changes;
}
return { recordHit, getOverview, getPages, cleanup };
}
+296
View File
@@ -0,0 +1,296 @@
import { unavailable } from '../lib/errors.js';
function normalizeLevel(item) {
if (!item || typeof item.title !== 'string') return null;
const position = Number.parseInt(item.position, 10);
return {
title: item.title,
position: Number.isFinite(position) ? position : null,
url: typeof item.url === 'string' ? item.url : null
};
}
function normalizeRun(item) {
if (!item || typeof item.id !== 'string') return null;
return {
id: item.id,
playerName: typeof item.playerName === 'string' ? item.playerName : 'unknown',
levelTitle: typeof item.levelTitle === 'string' ? item.levelTitle : 'unknown',
percent: typeof item.percent === 'string' ? item.percent : String(item.percent ?? ''),
videoUrl: typeof item.videoUrl === 'string' ? item.videoUrl : null,
status: typeof item.status === 'string' ? item.status : 'unknown',
notes: typeof item.notes === 'string' ? item.notes.slice(0, 500) : '',
submittedAt: typeof item.submittedAt === 'string' ? item.submittedAt : null,
updatedAt: typeof item.updatedAt === 'string' ? item.updatedAt : null,
reviewedBy: typeof item.reviewedBy === 'string' ? item.reviewedBy : null
};
}
function levelKey(level) {
return String(level.title || '').trim().toLowerCase();
}
// Snapshots were originally stored as the full API object ({ items: [...] })
// and are now stored as the items array. Accept both shapes so upgrades do
// not silently lose the previous list and report every level as "added".
export function parseSnapshotItems(raw) {
let parsed;
try {
parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
} catch {
return [];
}
const items = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.items) ? parsed.items : [];
return items.map(normalizeLevel).filter(Boolean);
}
function computeChanges(previous, current) {
if (!previous) {
return {
comparedTo: null,
added: [],
removed: [],
rankChanges: [],
counts: { added: 0, removed: 0, rankChanges: 0 }
};
}
const prevMap = new Map(previous.items.map((item) => [levelKey(item), item]));
const currentMap = new Map(current.items.map((item) => [levelKey(item), item]));
const added = current.items
.filter((item) => !prevMap.has(levelKey(item)))
.slice(0, 25)
.map((item) => ({ title: item.title, position: item.position }));
const removed = previous.items
.filter((item) => !currentMap.has(levelKey(item)))
.slice(0, 25)
.map((item) => ({ title: item.title, position: item.position }));
const rankChanges = [];
for (const [key, item] of currentMap) {
const before = prevMap.get(key);
if (!before || !Number.isFinite(before.position) || !Number.isFinite(item.position)) continue;
const delta = before.position - item.position;
if (delta !== 0) {
rankChanges.push({
title: item.title,
from: before.position,
to: item.position,
delta
});
}
}
rankChanges.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.title.localeCompare(b.title));
return {
comparedTo: previous.fetchedAt,
added,
removed,
rankChanges: rankChanges.slice(0, 25),
counts: { added: added.length, removed: removed.length, rankChanges: rankChanges.length }
};
}
function buildStats({ list, runs, fetchedAt, previous, config }) {
const levels = (Array.isArray(list) ? list : [])
.map(normalizeLevel)
.filter(Boolean)
.sort((a, b) => (a.position ?? 1e9) - (b.position ?? 1e9));
const records = (Array.isArray(runs) ? runs : []).map(normalizeRun).filter(Boolean);
const approved = records.filter((run) => run.status === 'approved');
const rejected = records.filter((run) => run.status === 'rejected');
const pending = records.filter((run) => run.status !== 'approved' && run.status !== 'rejected');
const players = new Set(approved.map((run) => run.playerName.toLowerCase()));
const recentRecords = [...approved]
.sort((a, b) => String(b.submittedAt || '').localeCompare(String(a.submittedAt || '')))
.slice(0, 12);
const latestUpdates = [...records]
.sort((a, b) => String(b.updatedAt || b.submittedAt || '').localeCompare(String(a.updatedAt || a.submittedAt || '')))
.slice(0, 10);
return {
generatedAt: fetchedAt,
site: config.fedl.siteUrl,
apiBase: config.fedl.apiBase,
github: config.fedl.github,
totals: {
rankedLevels: levels.length,
records: approved.length,
submissions: records.length,
rejected: rejected.length,
pending: pending.length,
players: players.size
},
topLevels: levels.slice(0, 15),
recentRecords,
latestUpdates,
changes: computeChanges(previous, { items: levels })
};
}
export function createFedlService({
config,
db,
logger,
fetchFn = globalThis.fetch,
now = () => new Date()
}) {
const stmts = {
insertSnapshot: db.prepare(
'INSERT INTO fedl_snapshots (fetched_at, list_json, runs_json) VALUES (?, ?, ?)'
),
latestSnapshot: db.prepare('SELECT * FROM fedl_snapshots ORDER BY id DESC LIMIT 1'),
previousSnapshot: db.prepare('SELECT * FROM fedl_snapshots ORDER BY id DESC LIMIT 1 OFFSET 1'),
getStats: db.prepare('SELECT * FROM fedl_stats WHERE id = 1'),
upsertStats: db.prepare(`
INSERT INTO fedl_stats (id, stats_json, fetched_at, snapshot_id)
VALUES (1, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
stats_json = excluded.stats_json,
fetched_at = excluded.fetched_at,
snapshot_id = excluded.snapshot_id
`),
pruneSnapshots: db.prepare(`
DELETE FROM fedl_snapshots
WHERE id NOT IN (SELECT id FROM fedl_snapshots ORDER BY id DESC LIMIT 50)
`)
};
let refreshPromise = null;
let timer = null;
async function fetchJson(url) {
const response = await fetchFn(url, {
signal: AbortSignal.timeout(config.fedl.timeoutMs),
headers: {
Accept: 'application/json',
'User-Agent': 'milesallen-dashboard/1.0'
}
});
if (!response.ok) throw new Error(`FEDL API ${response.status} for ${url}`);
return response.json();
}
function readStats() {
const row = stmts.getStats.get();
if (!row) return null;
try {
return { stats: JSON.parse(row.stats_json), fetchedAt: row.fetched_at, snapshotId: row.snapshot_id };
} catch {
return null;
}
}
function isStale(fetchedAt) {
const at = new Date(fetchedAt).getTime();
return !Number.isFinite(at) || now().getTime() - at > config.fedl.refreshMs;
}
async function doRefresh({ force = false } = {}) {
const existing = readStats();
if (existing && !force && !isStale(existing.fetchedAt)) {
return existing.stats;
}
const started = Date.now();
const base = config.fedl.apiBase.replace(/\/+$/, '');
try {
const [list, runs] = await Promise.all([
fetchJson(`${base}/list`),
fetchJson(`${base}/runs`)
]);
if (!list || !Array.isArray(list.items)) throw new Error('FEDL /list returned an unexpected shape');
if (!runs || !Array.isArray(runs.items)) throw new Error('FEDL /runs returned an unexpected shape');
const fetchedAt = now().toISOString();
const previousRow = stmts.latestSnapshot.get();
const previous = previousRow
? {
fetchedAt: previousRow.fetched_at,
items: parseSnapshotItems(previousRow.list_json)
}
: null;
const snapshot = stmts.insertSnapshot.run(
fetchedAt,
JSON.stringify(list.items),
JSON.stringify(runs.items)
);
const stats = buildStats({ list: list.items, runs: runs.items, fetchedAt, previous, config });
stmts.upsertStats.run(JSON.stringify(stats), fetchedAt, snapshot.lastInsertRowid);
stmts.pruneSnapshots.run();
logger.info('FEDL refresh complete', {
levels: stats.totals.rankedLevels,
records: stats.totals.records,
additions: stats.changes.counts.added,
removals: stats.changes.counts.removed,
rankChanges: stats.changes.counts.rankChanges,
durationMs: Date.now() - started
});
return stats;
} catch (err) {
if (existing) {
logger.warn('FEDL refresh failed; serving cached stats', { error: err.message });
return existing.stats;
}
throw unavailable(`FEDL data is unavailable: ${err.message}`);
}
}
function refresh(options = {}) {
if (refreshPromise) return refreshPromise;
refreshPromise = doRefresh(options).finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
async function ensure() {
const existing = readStats();
if (existing) {
if (isStale(existing.fetchedAt) && !refreshPromise) refresh().catch(() => {});
return { stats: existing.stats, stale: isStale(existing.fetchedAt) };
}
const stats = await refresh();
return { stats, stale: false };
}
async function getStats() {
const { stats, stale } = await ensure();
return { ...stats, stale };
}
async function getActivity() {
const { stats, stale } = await ensure();
return {
generatedAt: stats.generatedAt,
stale,
site: stats.site,
github: stats.github,
changes: stats.changes,
recentRecords: stats.recentRecords,
latestUpdates: stats.latestUpdates
};
}
function start() {
const existing = readStats();
if (!existing || isStale(existing.fetchedAt)) {
refresh().catch((err) => logger.error('FEDL refresh failed', { error: err.message }));
}
timer = setInterval(() => {
refresh().catch((err) => logger.error('FEDL refresh failed', { error: err.message }));
}, config.fedl.refreshMs);
}
function stop() {
if (timer) clearInterval(timer);
timer = null;
}
return { refresh, getStats, getActivity, start, stop };
}
+505
View File
@@ -0,0 +1,505 @@
import { AppError, unavailable } from '../lib/errors.js';
const DAY_MS = 24 * 60 * 60 * 1000;
function shortSha(sha) {
return typeof sha === 'string' ? sha.slice(0, 7) : null;
}
function firstLine(value) {
return String(value || '').split('\n')[0].slice(0, 240);
}
function lastPageFromLink(link) {
if (!link) return null;
const match = String(link).match(/[?&]page=(\d+)>;\s*rel="last"/);
return match ? Number(match[1]) : null;
}
async function mapLimit(items, limit, fn) {
const results = new Array(items.length);
let index = 0;
async function worker() {
while (index < items.length) {
const current = index;
index += 1;
results[current] = await fn(items[current], current);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
export function createGitHubService({
config,
db,
logger,
fetchFn = globalThis.fetch,
now = () => new Date()
}) {
const stmts = {
getCache: db.prepare('SELECT * FROM cache WHERE key = ?'),
upsertCache: db.prepare(`
INSERT INTO cache (key, value, etag, fetched_at, expires_at)
VALUES (@key, @value, @etag, @fetchedAt, @expiresAt)
ON CONFLICT(key) DO UPDATE SET
value = excluded.value, etag = excluded.etag,
fetched_at = excluded.fetched_at, expires_at = excluded.expires_at
`),
touchCache: db.prepare('UPDATE cache SET fetched_at = ?, expires_at = ? WHERE key = ?'),
getMeta: db.prepare('SELECT value FROM meta WHERE key = ?'),
setMeta: db.prepare(`
INSERT INTO meta (key, value, updated_at) VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`)
};
let refreshPromise = null;
let timer = null;
function meta(key) {
return stmts.getMeta.get(key)?.value ?? null;
}
function setMeta(key, value) {
stmts.setMeta.run(key, String(value), now().toISOString());
}
function readCache(key) {
const row = stmts.getCache.get(key);
if (!row) return null;
try {
return { ...row, data: JSON.parse(row.value) };
} catch {
return null;
}
}
function writeCache(key, data, { etag = null, ttlMs }) {
const at = now();
stmts.upsertCache.run({
key,
value: JSON.stringify(data),
etag,
fetchedAt: at.toISOString(),
expiresAt: new Date(at.getTime() + ttlMs).toISOString()
});
}
function rateLimitInfo() {
const remaining = meta('github:rate_remaining');
const reset = meta('github:rate_reset');
return {
authenticated: Boolean(config.github.token),
remaining: remaining === null ? null : Number(remaining),
resetAt: reset ? new Date(Number(reset) * 1000).toISOString() : null
};
}
function sleepUntilReset() {
const reset = meta('github:rate_reset');
return reset ? Number(reset) * 1000 > now().getTime() : false;
}
async function apiRequest(
path,
{ key, ttlMs, force = false, withHeaders = false, allowStale = true } = {}
) {
const cache = key ? readCache(key) : null;
if (cache && !force) {
const expires = new Date(cache.expires_at).getTime();
if (Number.isFinite(expires) && expires > now().getTime()) {
return withHeaders ? { data: cache.data, headers: null, stale: false } : cache.data;
}
}
if (sleepUntilReset() && allowStale && cache) {
return withHeaders ? { data: cache.data, headers: null, stale: true } : cache.data;
}
const url = `${config.github.apiBase}${path}`;
const headers = {
Accept: 'application/vnd.github+json',
'User-Agent': 'milesallen-dashboard/1.0',
'X-GitHub-Api-Version': '2022-11-28'
};
if (config.github.token) headers.Authorization = `Bearer ${config.github.token}`;
if (cache?.etag && !force) headers['If-None-Match'] = cache.etag;
let response;
try {
response = await fetchFn(url, {
headers,
signal: AbortSignal.timeout(config.github.timeoutMs)
});
} catch (err) {
if (allowStale && cache) return withHeaders ? { data: cache.data, headers: null, stale: true } : cache.data;
throw unavailable(`GitHub request failed: ${err.message}`);
}
const remaining = response.headers?.get?.('x-ratelimit-remaining');
const reset = response.headers?.get?.('x-ratelimit-reset');
if (remaining !== null && remaining !== undefined) setMeta('github:rate_remaining', remaining);
if (reset !== null && reset !== undefined) setMeta('github:rate_reset', reset);
if (response.status === 304 && cache) {
const at = now();
stmts.touchCache.run(
at.toISOString(),
new Date(at.getTime() + (ttlMs || config.github.refreshMs)).toISOString(),
key
);
return withHeaders ? { data: cache.data, headers: response.headers, stale: false } : cache.data;
}
if (!response.ok) {
const body = await response.text().catch(() => '');
const rateLimited = response.status === 403 || response.status === 429;
if (rateLimited && allowStale && cache) {
if (allowStale) logger.warn('GitHub rate limited; serving cache', { path, status: response.status });
return withHeaders ? { data: cache.data, headers: response.headers, stale: true } : cache.data;
}
if (response.status === 404) throw new AppError(404, 'github_not_found', `GitHub resource not found: ${path}`);
throw unavailable(`GitHub API error (${response.status}) for ${path}${body ? ': ' + body.slice(0, 120) : ''}`);
}
const data = await response.json();
if (key) writeCache(key, data, { etag: response.headers?.get?.('etag') || null, ttlMs: ttlMs || config.github.refreshMs });
return withHeaders ? { data, headers: response.headers, stale: false } : data;
}
function normalizeCommit(commit, repoFullName) {
if (!commit) return null;
return {
sha: shortSha(commit.sha),
message: firstLine(commit.commit?.message),
author: commit.commit?.author?.name || commit.author?.login || 'unknown',
date: commit.commit?.author?.date || commit.commit?.committer?.date || null,
url: commit.html_url || (repoFullName ? `https://github.com/${repoFullName}/commit/${commit.sha}` : null)
};
}
function normalizeRepo(project, repo, latestCommit, release, contributors) {
return {
id: project.id,
name: project.name,
description: repo?.description || project.description || '',
fullName: repo?.full_name || `${project.github.owner}/${project.github.repo}`,
url: repo?.html_url || `https://github.com/${project.github.owner}/${project.github.repo}`,
website: repo?.homepage || project.website || null,
language: repo?.language || null,
stars: repo?.stargazers_count ?? 0,
forks: repo?.forks_count ?? 0,
openIssues: repo?.open_issues_count ?? 0,
watchers: repo?.subscribers_count ?? repo?.watchers_count ?? 0,
defaultBranch: repo?.default_branch || null,
archived: Boolean(repo?.archived),
fork: Boolean(repo?.fork),
topics: Array.isArray(repo?.topics) ? repo.topics.slice(0, 6) : [],
pushedAt: repo?.pushed_at || null,
updatedAt: repo?.updated_at || null,
createdAt: repo?.created_at || null,
latestCommit,
release,
contributors,
featured: project.featured
};
}
function buildActivity(events, repositories, profile) {
const projectByFullName = new Map(
repositories.map((repo) => [repo.fullName.toLowerCase(), repo])
);
const recentCommits = [];
for (const event of events || []) {
if (event.type !== 'PushEvent') continue;
const fullName = event.repo?.name || '';
const project = projectByFullName.get(fullName.toLowerCase());
const branch = (event.payload?.ref || '').replace('refs/heads/', '');
for (const commit of event.payload?.commits || []) {
recentCommits.push({
repo: fullName,
project: project?.name || fullName.split('/').pop(),
branch,
sha: shortSha(commit.sha),
message: firstLine(commit.message),
author: commit.author?.name || event.actor?.login || 'unknown',
date: event.created_at,
url: commit.sha && fullName ? `https://github.com/${fullName}/commit/${commit.sha}` : null
});
}
}
recentCommits.sort((a, b) => String(b.date).localeCompare(String(a.date)));
const since = now().getTime() - 30 * DAY_MS;
const dayMap = new Map();
for (let i = 29; i >= 0; i -= 1) {
const day = new Date(now().getTime() - i * DAY_MS).toISOString().slice(0, 10);
dayMap.set(day, { day, events: 0, pushes: 0 });
}
const repoEvents = new Map();
for (const event of events || []) {
const at = new Date(event.created_at);
if (!Number.isFinite(at.getTime()) || at.getTime() < since) continue;
const day = at.toISOString().slice(0, 10);
const bucket = dayMap.get(day);
if (bucket) {
bucket.events += 1;
if (event.type === 'PushEvent') bucket.pushes += 1;
}
const fullName = event.repo?.name || 'unknown';
const current = repoEvents.get(fullName) || { repo: fullName, events: 0, pushes: 0 };
current.events += 1;
if (event.type === 'PushEvent') current.pushes += 1;
repoEvents.set(fullName, current);
}
const byRepo = [...repoEvents.values()]
.map((entry) => ({
...entry,
project: projectByFullName.get(entry.repo.toLowerCase())?.name || entry.repo.split('/').pop()
}))
.sort((a, b) => b.events - a.events || b.pushes - a.pushes)
.slice(0, 10);
const totals = { stars: 0, forks: 0, openIssues: 0 };
const languages = new Map();
for (const repo of repositories) {
totals.stars += repo.stars;
totals.forks += repo.forks;
totals.openIssues += repo.openIssues;
if (repo.language) languages.set(repo.language, (languages.get(repo.language) || 0) + 1);
}
return {
profile: profile
? {
login: profile.login,
name: profile.name,
avatarUrl: profile.avatar_url,
bio: profile.bio,
company: profile.company,
location: profile.location,
blog: profile.blog,
followers: profile.followers,
following: profile.following,
publicRepos: profile.public_repos,
createdAt: profile.created_at
}
: null,
totals: { ...totals, trackedRepos: repositories.length, publicRepos: profile?.public_repos ?? null },
languages: [...languages.entries()]
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
recentCommits: recentCommits.slice(0, 40),
activity: { days: [...dayMap.values()], byRepo }
};
}
async function doRefresh({ force = false } = {}) {
const started = Date.now();
const username = config.github.username;
const ttlMs = config.github.refreshMs;
const [profile, repos, events] = await Promise.all([
apiRequest(`/users/${username}`, { key: `github:profile:${username}`, ttlMs, force }),
apiRequest(`/users/${username}/repos?per_page=100&sort=updated`, {
key: `github:repos:${username}`,
ttlMs,
force
}),
apiRequest(`/users/${username}/events/public?per_page=100`, {
key: `github:events:${username}`,
ttlMs,
force
})
]);
const tracked = config.projects.filter((project) => project.visible && project.github);
const repoList = Array.isArray(repos) ? repos : [];
const byFullName = new Map(repoList.map((repo) => [String(repo.full_name).toLowerCase(), repo]));
const repositories = await mapLimit(tracked, 4, async (project) => {
const fullName = `${project.github.owner}/${project.github.repo}`;
const keyBase = fullName.toLowerCase();
let repo = byFullName.get(keyBase) || null;
let latestCommit = null;
let release = null;
let contributors = null;
const errors = [];
if (!repo) {
try {
repo = await apiRequest(`/repos/${fullName}`, {
key: `github:repo:${keyBase}`,
ttlMs,
force
});
} catch (err) {
errors.push(`repo: ${err.message}`);
}
}
try {
const commits = await apiRequest(`/repos/${fullName}/commits?per_page=1`, {
key: `github:commits:${keyBase}`,
ttlMs,
force
});
latestCommit = normalizeCommit(Array.isArray(commits) ? commits[0] : null, fullName);
} catch (err) {
errors.push(`commits: ${err.message}`);
}
if (config.github.enrich && config.github.token) {
try {
const releases = await apiRequest(`/repos/${fullName}/releases?per_page=1`, {
key: `github:release:${keyBase}`,
ttlMs: 6 * 60 * 60 * 1000,
force
});
const item = Array.isArray(releases) ? releases[0] : null;
if (item) {
release = {
tag: item.tag_name,
name: item.name || item.tag_name,
publishedAt: item.published_at,
url: item.html_url,
prerelease: Boolean(item.prerelease)
};
}
} catch (err) {
errors.push(`releases: ${err.message}`);
}
try {
const result = await apiRequest(`/repos/${fullName}/contributors?per_page=1&anon=1`, {
key: `github:contributors:${keyBase}`,
ttlMs: 6 * 60 * 60 * 1000,
force,
withHeaders: true
});
const link = result.headers?.get?.('link');
const last = lastPageFromLink(link);
contributors = last ?? (Array.isArray(result.data) ? result.data.length : null);
} catch (err) {
errors.push(`contributors: ${err.message}`);
}
}
return {
...normalizeRepo(project, repo, latestCommit, release, contributors),
errors: errors.length ? errors : undefined
};
});
const activity = buildActivity(Array.isArray(events) ? events : [], repositories, profile);
const summary = {
generatedAt: now().toISOString(),
username,
rateLimit: rateLimitInfo(),
profile: activity.profile,
totals: activity.totals,
languages: activity.languages,
repositories,
recentCommits: activity.recentCommits,
activity: activity.activity,
recentlyUpdated: [...repositories]
.sort((a, b) => String(b.pushedAt || '').localeCompare(String(a.pushedAt || '')))
.slice(0, 8)
.map((repo) => ({ id: repo.id, name: repo.name, pushedAt: repo.pushedAt, latestCommit: repo.latestCommit }))
};
writeCache('github:summary', summary, { ttlMs });
logger.info('GitHub refresh complete', {
repos: repositories.length,
commits: summary.recentCommits.length,
durationMs: Date.now() - started
});
return summary;
}
function refresh(options = {}) {
if (refreshPromise) return refreshPromise;
refreshPromise = doRefresh(options)
.catch((err) => {
logger.error('GitHub refresh failed', { error: err.message });
throw err;
})
.finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
function cachedSummary() {
const row = readCache('github:summary');
return row?.data || null;
}
async function ensureSummary() {
const summary = cachedSummary();
if (summary) {
const row = readCache('github:summary');
const expires = new Date(row.expires_at).getTime();
if (Number.isFinite(expires) && expires <= now().getTime() && !refreshPromise) {
refresh().catch(() => {});
}
return summary;
}
return refresh();
}
async function getOverview() {
const summary = await ensureSummary();
return {
generatedAt: summary.generatedAt,
username: summary.username,
profile: summary.profile,
rateLimit: summary.rateLimit,
totals: summary.totals,
languages: summary.languages,
recentCommits: summary.recentCommits.slice(0, 12),
recentlyUpdated: summary.recentlyUpdated,
topActive: summary.activity.byRepo.slice(0, 6)
};
}
async function getActivity() {
const summary = await ensureSummary();
return {
generatedAt: summary.generatedAt,
username: summary.username,
rateLimit: summary.rateLimit,
recentCommits: summary.recentCommits,
activity: summary.activity
};
}
async function getRepositories() {
const summary = await ensureSummary();
return {
generatedAt: summary.generatedAt,
rateLimit: summary.rateLimit,
repositories: summary.repositories
};
}
function start() {
refresh({ force: false }).catch(() => {});
timer = setInterval(() => {
refresh({ force: false }).catch(() => {});
}, config.github.refreshMs);
}
function stop() {
if (timer) clearInterval(timer);
timer = null;
}
return { refresh, getOverview, getActivity, getRepositories, start, stop, rateLimitInfo };
}
+50
View File
@@ -0,0 +1,50 @@
export function classifyHttpStatus(code) {
if (code >= 200 && code < 400) return 'operational';
if (code >= 400 && code < 500) return 'degraded';
if (code >= 500) return 'offline';
return 'unknown';
}
export async function checkHttp(
url,
{ timeoutMs = 5000, fetchFn = globalThis.fetch, now = () => Date.now() } = {}
) {
const started = now();
try {
const response = await fetchFn(url, {
method: 'GET',
redirect: 'follow',
signal: AbortSignal.timeout(timeoutMs),
headers: {
'User-Agent': 'milesallen-status/1.0 (+https://milesallen.site)',
Accept: 'text/html,application/xhtml+xml,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br'
}
});
const responseMs = Math.max(0, now() - started);
try {
await response.body?.cancel();
} catch {
// ignore body cancellation errors
}
return {
status: classifyHttpStatus(response.status),
responseMs,
httpStatus: response.status,
error: null
};
} catch (err) {
const responseMs = Math.max(0, now() - started);
const name = err?.name || '';
let message = 'request failed';
if (name === 'TimeoutError' || name === 'AbortError') message = 'timeout';
else if (err?.cause?.code) message = String(err.cause.code);
else if (err?.message) message = String(err.message);
return {
status: 'offline',
responseMs,
httpStatus: null,
error: message.slice(0, 200)
};
}
}
+152
View File
@@ -0,0 +1,152 @@
import { checkHost, networkContext } from './ping.js';
import { checkHttp } from './http-check.js';
const MONITORING_ERRORS = new Set(['ping_unavailable', 'invalid_target']);
export function createMonitor({
config,
db,
logger,
deps = {},
now = () => new Date()
}) {
const pingHost = deps.pingHost || checkHost;
const httpCheck = deps.checkHttp || checkHttp;
const getNetworkContext =
deps.getNetworkContext ||
(() =>
networkContext(config.monitor.servers, {
subnet: config.monitor.expectedSubnet || null
}));
const insertServerCheck = db.prepare(`
INSERT INTO server_checks (server_id, checked_at, online, response_ms, reason, on_home_network)
VALUES (@serverId, @at, @online, @responseMs, @reason, @onHomeNetwork)
`);
const insertServiceCheck = db.prepare(`
INSERT INTO service_checks (service_id, checked_at, status, response_ms, http_status, error)
VALUES (@serviceId, @at, @status, @responseMs, @httpStatus, @error)
`);
const timers = [];
const running = { servers: false, services: false };
async function runServers() {
if (running.servers) return { skipped: true };
running.servers = true;
const started = Date.now();
let online = 0;
let checked = 0;
try {
const context = getNetworkContext();
for (const server of config.monitor.servers) {
if (!server.enabled) continue;
const result = await pingHost(server.ip, {
timeoutMs: config.monitor.pingTimeoutMs,
platform: deps.platform
});
const monitoringError = MONITORING_ERRORS.has(result.reason);
const onHomeNetwork = monitoringError ? 0 : context.onHomeNetwork ? 1 : 0;
let reason;
if (monitoringError) reason = `monitor_error:${result.reason}`;
else if (result.online) reason = 'ok';
else if (!context.onHomeNetwork) reason = 'not_on_home_network';
else reason = result.reason || 'unreachable';
insertServerCheck.run({
serverId: server.id,
at: now().toISOString(),
online: result.online ? 1 : 0,
responseMs: result.responseMs,
reason,
onHomeNetwork
});
checked += 1;
if (result.online) online += 1;
logger.debug('server check', {
server: server.id,
ip: server.ip,
online: result.online,
reason,
responseMs: result.responseMs,
onHomeNetwork: Boolean(onHomeNetwork)
});
}
logger.info('server monitor pass', {
checked,
online,
onHomeNetwork: context.onHomeNetwork,
durationMs: Date.now() - started
});
return { checked, online, onHomeNetwork: context.onHomeNetwork };
} finally {
running.servers = false;
}
}
async function runServices() {
if (running.services) return { skipped: true };
running.services = true;
const started = Date.now();
const counts = { operational: 0, degraded: 0, offline: 0, unknown: 0 };
let checked = 0;
try {
for (const service of config.services) {
if (!service.enabled) continue;
const result = await httpCheck(service.url, {
timeoutMs: config.monitor.httpTimeoutMs
});
insertServiceCheck.run({
serviceId: service.id,
at: now().toISOString(),
status: result.status,
responseMs: result.responseMs,
httpStatus: result.httpStatus,
error: result.error
});
counts[result.status] = (counts[result.status] || 0) + 1;
checked += 1;
logger.debug('service check', {
service: service.id,
url: service.url,
status: result.status,
httpStatus: result.httpStatus,
responseMs: result.responseMs,
error: result.error
});
}
logger.info('website monitor pass', { checked, ...counts, durationMs: Date.now() - started });
return { checked, ...counts };
} finally {
running.services = false;
}
}
function start() {
runServers().catch((err) => logger.error('server monitor failed', { error: err.message }));
runServices().catch((err) => logger.error('website monitor failed', { error: err.message }));
timers.push(
setInterval(() => {
runServers().catch((err) => logger.error('server monitor failed', { error: err.message }));
}, config.monitor.serverIntervalMs)
);
timers.push(
setInterval(() => {
runServices().catch((err) => logger.error('website monitor failed', { error: err.message }));
}, config.monitor.serviceIntervalMs)
);
}
function stop() {
while (timers.length) clearInterval(timers.pop());
}
async function runOnce(kind = 'all') {
if (kind === 'servers') return runServers();
if (kind === 'services') return runServices();
return { servers: await runServers(), services: await runServices() };
}
return { start, stop, runOnce, runServers, runServices };
}
+124
View File
@@ -0,0 +1,124 @@
import { execFile } from 'node:child_process';
import os from 'node:os';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
export function pingArgs(host, { platform = process.platform, timeoutMs = 2000 } = {}) {
if (!/^[A-Za-z0-9.:_-]+$/.test(host)) throw new Error('Invalid ping target');
if (platform === 'darwin') {
return ['-n', '-c', '1', '-W', String(Math.max(1, Math.round(timeoutMs))), host];
}
if (platform === 'win32') {
return ['-n', '1', '-w', String(Math.max(1, Math.round(timeoutMs))), host];
}
// Linux iputils accepts -W in seconds.
return ['-n', '-c', '1', '-W', String(Math.max(1, Math.ceil(timeoutMs / 1000))), host];
}
export function parsePingTime(stdout) {
const match = String(stdout || '').match(/time[=<]\s*([\d.]+)\s*ms/i);
if (match) {
const value = Number.parseFloat(match[1]);
return Number.isFinite(value) ? value : null;
}
if (/1 packets transmitted,\s*1 received/i.test(stdout) || /1 received/i.test(stdout)) return null;
return null;
}
export async function checkHost(
host,
{ timeoutMs = 2000, platform = process.platform, execFileFn = execFileAsync } = {}
) {
let args;
try {
args = pingArgs(host, { platform, timeoutMs });
} catch (err) {
return { online: false, responseMs: null, reason: 'invalid_target', error: err.message };
}
const started = Date.now();
try {
const result = await execFileFn('ping', args, {
timeout: timeoutMs + 1500,
maxBuffer: 64 * 1024,
windowsHide: true
});
return {
online: true,
responseMs: parsePingTime(result.stdout) ?? Date.now() - started,
reason: 'ok',
error: null
};
} catch (err) {
const killed = err.killed || err.signal === 'SIGTERM';
const code = err.code;
let reason = 'unreachable';
if (code === 'ENOENT') reason = 'ping_unavailable';
else if (killed) reason = 'timeout';
else if (/timed out/i.test(String(err.message))) reason = 'timeout';
return {
online: false,
responseMs: null,
reason,
error: String(err.message || 'ping failed').slice(0, 200)
};
}
}
export function getLocalIPv4s(interfaces = os.networkInterfaces()) {
const out = [];
if (!interfaces) return out;
for (const [name, list] of Object.entries(interfaces)) {
for (const item of list || []) {
if (item && item.family === 'IPv4' && !item.internal) {
out.push({ name, address: item.address, netmask: item.netmask });
}
}
}
return out;
}
function ipv4ToInt(ip) {
const parts = String(ip).split('.').map(Number);
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
}
export function inSubnet(ip, cidr) {
const [base, bitsRaw] = String(cidr).split('/');
const bits = Number.parseInt(bitsRaw ?? '24', 10);
const a = ipv4ToInt(ip);
const b = ipv4ToInt(base);
if (a === null || b === null || !Number.isInteger(bits) || bits < 0 || bits > 32) return false;
if (bits === 0) return true;
const mask = (0xffffffff << (32 - bits)) >>> 0;
return (a & mask) === (b & mask);
}
/**
* Heuristic: are we on the same LAN as the home servers?
* If a subnet is explicitly configured, honor it. Otherwise infer /24s from targets.
*/
export function networkContext(
servers,
{ interfaces = os.networkInterfaces(), subnet = null, localAddresses = null } = {}
) {
const local = localAddresses || getLocalIPv4s(interfaces);
const cidrs = subnet
? [subnet]
: servers
.map((s) => {
const ip = String(s.ip);
if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return null;
return ip.split('.').slice(0, 3).join('.') + '.0/24';
})
.filter(Boolean);
const onHomeNetwork = local.some((entry) => cidrs.some((cidr) => inSubnet(entry.address, cidr)));
return {
onHomeNetwork,
localAddresses: local.map((entry) => entry.address),
targets: cidrs
};
}
+243
View File
@@ -0,0 +1,243 @@
const DAY_MS = 24 * 60 * 60 * 1000;
const WINDOWS = [
['24h', DAY_MS],
['7d', 7 * DAY_MS],
['30d', 30 * DAY_MS]
];
function pct(up, total) {
if (!total) return null;
return Math.round((up / total) * 10000) / 100;
}
function iso(date) {
return date.toISOString();
}
export function deriveServerStatus(check) {
if (!check) return { status: 'unknown', reason: 'no_data', networkContext: null };
if (check.reason?.startsWith('monitor_error:')) {
return { status: 'unknown', reason: check.reason, networkContext: null };
}
if (check.online) return { status: 'online', reason: check.reason || 'ok', networkContext: true };
if (!check.on_home_network) {
return { status: 'unknown', reason: 'not_on_home_network', networkContext: false };
}
return { status: 'offline', reason: check.reason || 'unreachable', networkContext: true };
}
export function deriveServiceStatus(check) {
if (!check) return { status: 'unknown', reason: 'no_data' };
return { status: check.status, reason: check.error || 'ok' };
}
export function createStatusService({ db, config, now = () => new Date() }) {
const stmts = {
servers: db.prepare('SELECT * FROM servers WHERE enabled = 1 ORDER BY display_order, id'),
services: db.prepare('SELECT * FROM services WHERE enabled = 1 ORDER BY display_order, id'),
latestServerCheck: db.prepare(
'SELECT * FROM server_checks WHERE server_id = ? ORDER BY checked_at DESC LIMIT 1'
),
latestServiceCheck: db.prepare(
'SELECT * FROM service_checks WHERE service_id = ? ORDER BY checked_at DESC LIMIT 1'
),
lastServerSuccess: db.prepare(
'SELECT MAX(checked_at) AS at FROM server_checks WHERE server_id = ? AND online = 1'
),
lastServiceSuccess: db.prepare(
"SELECT MAX(checked_at) AS at FROM service_checks WHERE service_id = ? AND status IN ('operational','degraded')"
),
recentServerChecks: db.prepare(
'SELECT checked_at, online, on_home_network, reason FROM server_checks WHERE server_id = ? ORDER BY checked_at DESC LIMIT 500'
),
recentServiceChecks: db.prepare(
'SELECT checked_at, status, error FROM service_checks WHERE service_id = ? ORDER BY checked_at DESC LIMIT 500'
),
serverUptime: db.prepare(
'SELECT COUNT(*) AS total, COALESCE(SUM(online), 0) AS up FROM server_checks WHERE server_id = ? AND checked_at >= ? AND on_home_network = 1'
),
serviceUptime: db.prepare(
"SELECT COUNT(*) AS total, COALESCE(SUM(CASE WHEN status IN ('operational','degraded') THEN 1 ELSE 0 END), 0) AS up FROM service_checks WHERE service_id = ? AND checked_at >= ?"
),
serverHistory: db.prepare(
'SELECT substr(checked_at, 1, 10) AS day, COUNT(*) AS total, COALESCE(SUM(online), 0) AS up FROM server_checks WHERE server_id = ? AND checked_at >= ? AND on_home_network = 1 GROUP BY day'
),
serviceHistory: db.prepare(
"SELECT substr(checked_at, 1, 10) AS day, COUNT(*) AS total, COALESCE(SUM(CASE WHEN status IN ('operational','degraded') THEN 1 ELSE 0 END), 0) AS up FROM service_checks WHERE service_id = ? AND checked_at >= ? GROUP BY day"
),
lastCheckTime: db.prepare(
'SELECT MAX(checked_at) AS at FROM (SELECT checked_at FROM server_checks UNION ALL SELECT checked_at FROM service_checks)'
)
};
function uptimeWindows(rows, at) {
const out = {};
for (const [label, span] of WINDOWS) {
const row = rows.get(at - span) || { total: 0, up: 0 };
out[label] = pct(row.up, row.total);
}
return out;
}
function currentRun(rows, derive) {
if (!rows.length) return { since: null, previous: null };
const current = derive(rows[0]).status;
let since = rows[0].checked_at;
let previous = null;
for (let i = 1; i < rows.length; i += 1) {
const status = derive(rows[i]).status;
if (status === current) since = rows[i].checked_at;
else {
previous = status;
break;
}
}
return { since, previous, current };
}
function serverStatus(server, at) {
const latest = stmts.latestServerCheck.get(server.id);
const derived = deriveServerStatus(latest);
const recent = stmts.recentServerChecks.all(server.id);
const run = currentRun(recent, deriveServerStatus);
const success = stmts.lastServerSuccess.get(server.id)?.at || null;
const windows = {};
for (const [label, span] of WINDOWS) {
const row = stmts.serverUptime.get(server.id, iso(new Date(at - span)));
windows[label] = pct(row.up, row.total);
}
return {
id: server.id,
name: server.name,
ip: server.ip,
status: derived.status,
reason: derived.reason,
networkContext: derived.networkContext,
lastCheckAt: latest?.checked_at || null,
lastSuccessAt: success,
lastChangeAt: run.since,
previousStatus: run.previous,
responseMs: latest?.response_ms ?? null,
uptime: windows,
checks: recent.length
};
}
function serviceStatus(service, at) {
const latest = stmts.latestServiceCheck.get(service.id);
const derived = deriveServiceStatus(latest);
const recent = stmts.recentServiceChecks.all(service.id);
const run = currentRun(recent, deriveServiceStatus);
const success = stmts.lastServiceSuccess.get(service.id)?.at || null;
const windows = {};
for (const [label, span] of WINDOWS) {
const row = stmts.serviceUptime.get(service.id, iso(new Date(at - span)));
windows[label] = pct(row.up, row.total);
}
return {
id: service.id,
name: service.name,
url: service.url,
status: derived.status,
reason: derived.reason,
lastCheckAt: latest?.checked_at || null,
lastSuccessAt: success,
lastChangeAt: run.since,
previousStatus: run.previous,
responseMs: latest?.response_ms ?? null,
httpStatus: latest?.http_status ?? null,
uptime: windows,
checks: recent.length
};
}
function overallStatus(servers, services) {
const all = [...servers.map((s) => s.status), ...services.map((s) => s.status)];
const counts = { operational: 0, degraded: 0, offline: 0, unknown: 0 };
for (const status of all) counts[status] = (counts[status] || 0) + 1;
let status = 'unknown';
if (counts.offline > 0) status = 'offline';
else if (counts.degraded > 0) status = 'degraded';
else if (counts.operational > 0) status = 'operational';
return {
status,
counts,
total: all.length,
healthy: counts.operational,
checkedAt: stmts.lastCheckTime.get()?.at || null
};
}
function getServers(at = now().getTime()) {
return stmts.servers.all().map((server) => serverStatus(server, at));
}
function getServices(at = now().getTime()) {
return stmts.services.all().map((service) => serviceStatus(service, at));
}
function onHomeNetwork(servers) {
const contexts = servers.map((s) => s.networkContext).filter((v) => v !== null);
if (!contexts.length) return null;
return contexts.some(Boolean);
}
function getStatus(at = now().getTime()) {
const servers = getServers(at);
const services = getServices(at);
const overall = overallStatus(servers, services);
return {
generatedAt: new Date(at).toISOString(),
overall,
network: {
onHomeNetwork: onHomeNetwork(servers),
monitoredSubnet: config.monitor.expectedSubnet || 'inferred /24'
},
servers,
services
};
}
function historyFor(days) {
const at = now().getTime();
const span = Math.max(1, Math.min(90, days)) * DAY_MS;
const start = new Date(at - span + DAY_MS);
const startIso = start.toISOString();
const dayKeys = [];
for (let i = 0; i < Math.max(1, Math.min(90, days)); i += 1) {
dayKeys.push(new Date(start.getTime() + i * DAY_MS).toISOString().slice(0, 10));
}
function series(rows) {
const map = new Map(rows.map((row) => [row.day, row]));
return dayKeys.map((day) => {
const row = map.get(day);
return {
day,
availability: row ? pct(row.up, row.total) : null,
up: row?.up ?? 0,
total: row?.total ?? 0
};
});
}
const servers = {};
for (const server of stmts.servers.all()) {
servers[server.id] = series(stmts.serverHistory.all(server.id, startIso));
}
const services = {};
for (const service of stmts.services.all()) {
services[service.id] = series(stmts.serviceHistory.all(service.id, startIso));
}
return { generatedAt: new Date(at).toISOString(), days: dayKeys.length, servers, services };
}
return { getStatus, getServers, getServices, getHistory: historyFor };
}
+167
View File
@@ -0,0 +1,167 @@
import argon2 from 'argon2';
import { tooManyRequests, unavailable, unauthorized } from '../lib/errors.js';
import { hashIp, randomHex, safeEqualHex, sha256Hex, signValue, verifySignature } from '../lib/crypto.js';
import { clearCookie, parseCookies, serializeCookie } from '../lib/cookies.js';
const ARGON2_OPTIONS = {
type: argon2.argon2id,
memoryCost: 19456,
timeCost: 2,
parallelism: 1,
hashLength: 32
};
export async function createVaultService({ config, db, logger, now = () => new Date() }) {
let passwordHash = config.vault.passwordHash;
if (!passwordHash && config.vault.password) {
passwordHash = await argon2.hash(config.vault.password, ARGON2_OPTIONS);
logger.warn('VAULT_PASSWORD was hashed at startup; prefer VAULT_PASSWORD_HASH for production');
}
if (passwordHash && !passwordHash.startsWith('$argon2')) {
throw new Error('VAULT_PASSWORD_HASH must be an Argon2 hash (generate one with: npm run hash-password)');
}
const enabled = Boolean(passwordHash);
const stmts = {
insertSession: db.prepare(`
INSERT INTO vault_sessions (id, token_hash, created_at, expires_at, last_seen_at)
VALUES (?, ?, ?, ?, ?)
`),
getSession: db.prepare('SELECT * FROM vault_sessions WHERE id = ?'),
deleteSession: db.prepare('DELETE FROM vault_sessions WHERE id = ?'),
touchSession: db.prepare('UPDATE vault_sessions SET last_seen_at = ? WHERE id = ?'),
cleanupSessions: db.prepare('DELETE FROM vault_sessions WHERE expires_at < ?'),
failures: db.prepare(`
SELECT COUNT(*) AS count, MIN(attempted_at) AS first
FROM vault_attempts
WHERE ip_hash = ? AND success = 0 AND attempted_at >= ?
`),
insertAttempt: db.prepare(
'INSERT INTO vault_attempts (ip_hash, attempted_at, success) VALUES (?, ?, ?)'
),
cleanupAttempts: db.prepare('DELETE FROM vault_attempts WHERE attempted_at < ?')
};
function cookieAttributes() {
return {
httpOnly: true,
secure: config.cookie.secure,
sameSite: config.cookie.sameSite,
path: '/',
maxAge: Math.floor(config.cookie.ttlMs / 1000)
};
}
function makeCookie(sessionId, token) {
const payload = `${sessionId}.${token}`;
const signature = signValue(config.sessionSecret, `vault:${payload}`);
return serializeCookie(config.cookie.name, `${payload}.${signature}`, cookieAttributes());
}
function readSessionCookie(cookieHeader) {
const cookies = parseCookies(cookieHeader);
const raw = cookies[config.cookie.name];
if (!raw) return null;
const parts = raw.split('.');
if (parts.length !== 3) return null;
const [id, token, signature] = parts;
if (!/^[a-f0-9]{32}$/.test(id) || !/^[a-f0-9]{64}$/.test(token) || !/^[a-f0-9]{64}$/.test(signature)) {
return null;
}
if (!verifySignature(config.sessionSecret, `vault:${id}.${token}`, signature)) return null;
return { id, token };
}
function getSession(cookieHeader, at = now()) {
if (!enabled) return null;
const parsed = readSessionCookie(cookieHeader);
if (!parsed) return null;
const row = stmts.getSession.get(parsed.id);
if (!row) return null;
if (!safeEqualHex(row.token_hash, sha256Hex(parsed.token))) return null;
const expires = new Date(row.expires_at);
if (!Number.isFinite(expires.getTime()) || expires <= at) {
stmts.deleteSession.run(row.id);
return null;
}
const lastSeen = new Date(row.last_seen_at);
if (!Number.isFinite(lastSeen.getTime()) || at.getTime() - lastSeen.getTime() > 5 * 60 * 1000) {
stmts.touchSession.run(at.toISOString(), row.id);
}
return { sessionId: row.id, expiresAt: row.expires_at };
}
async function login({ password, ipHash, at = now() }) {
if (!enabled) throw unavailable('Moon Vault is not configured');
if (typeof password !== 'string' || password.length < 1 || password.length > 512) {
throw unauthorized('Invalid credentials');
}
const windowStart = new Date(at.getTime() - config.vault.windowMs).toISOString();
const failures = stmts.failures.get(ipHash, windowStart);
if (failures.count >= config.vault.maxAttempts) {
const first = new Date(failures.first);
const retryAfterMs = Math.max(1000, first.getTime() + config.vault.windowMs - at.getTime());
throw tooManyRequests('Too many failed attempts. Try again later.', retryAfterMs);
}
let ok = false;
try {
ok = await argon2.verify(passwordHash, password);
} catch (err) {
logger.error('argon2 verification failed', { error: err.message });
ok = false;
}
stmts.insertAttempt.run(ipHash, at.toISOString(), ok ? 1 : 0);
if (!ok) throw unauthorized('Invalid credentials');
const sessionId = randomHex(16);
const token = randomHex(32);
const expiresAt = new Date(at.getTime() + config.cookie.ttlMs).toISOString();
stmts.insertSession.run(sessionId, sha256Hex(token), at.toISOString(), expiresAt, at.toISOString());
return {
cookie: makeCookie(sessionId, token),
expiresAt,
sessionId
};
}
function logout(cookieHeader) {
const parsed = readSessionCookie(cookieHeader);
if (parsed) stmts.deleteSession.run(parsed.id);
return clearCookie(config.cookie.name, {
httpOnly: true,
secure: config.cookie.secure,
sameSite: config.cookie.sameSite,
path: '/'
});
}
function cleanup(at = now()) {
const sessions = stmts.cleanupSessions.run(at.toISOString()).changes;
const attempts = stmts.cleanupAttempts.run(
new Date(at.getTime() - 24 * 60 * 60 * 1000).toISOString()
).changes;
return { sessions, attempts };
}
function ipHashFor(ip, at = now()) {
return hashIp(config.sessionSecret, ip, { date: at, scope: 'vault' });
}
return {
enabled,
cookieName: config.cookie.name,
ttlMs: config.cookie.ttlMs,
login,
logout,
getSession,
cleanup,
ipHashFor
};
}
export { ARGON2_OPTIONS };
+154
View File
@@ -0,0 +1,154 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>moon vault</title>
<meta name="robots" content="noindex, nofollow, noarchive, noimageindex">
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/projects/style.css">
<style>
:root{--vault-bg:#07070c;}
body{background:var(--vault-bg);}
nav{position:fixed;top:0;left:0;right:0;z-index:100;background:rgba(7,7,12,0.95);padding:14px 24px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid rgba(255,255,255,0.06);}
.nav-logo{font-family:var(--font-pixel);font-size:10px;color:var(--text);text-decoration:none;display:flex;align-items:center;gap:8px;}
.nav-logo .logo-dot{width:10px;height:10px;background:var(--accent);display:inline-block;}
.nav-links{display:flex;gap:18px;align-items:center;}
.nav-links a,.nav-links button{font-family:var(--font-mono);font-size:11px;color:var(--muted);background:none;border:none;cursor:pointer;text-decoration:none;text-transform:uppercase;letter-spacing:.04em;padding:0;}
.nav-links a:hover,.nav-links button:hover{color:var(--accent);}
@media (min-width:641px){nav{padding-right:76px;}}
.scroll-content{position:relative;z-index:1;padding-top:60px;}
.hero{min-height:42vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:70px 5vw 30px;position:relative;overflow:hidden;}
.hero h1{font-family:var(--font-pixel);font-size:clamp(22px,5vw,44px);color:var(--text);text-shadow:4px 4px 0 var(--accent);line-height:1.3;}
.hero .sub{font-family:var(--font-mono);font-size:12px;color:var(--muted);margin-top:14px;max-width:560px;line-height:1.8;}
.hero .emoji{font-size:54px;opacity:.3;margin-top:24px;}
.section-header{text-align:center;padding:40px 5vw 26px;}
.section-header .tag{font-family:var(--font-pixel);font-size:10px;color:var(--accent);letter-spacing:.12em;text-transform:uppercase;}
.section-header h2{font-family:var(--font-pixel);font-size:clamp(16px,3vw,28px);color:var(--text);margin-top:8px;text-transform:uppercase;}
.section-header p{font-family:var(--font-mono);font-size:12px;color:#999;max-width:520px;margin:10px auto 0;line-height:1.7;}
.vault-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:24px;max-width:980px;margin:0 auto;padding:0 5vw 60px;}
.vcard{border:2px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.02);overflow:hidden;text-decoration:none;display:flex;flex-direction:column;transition:border-color .3s,transform .3s;}
.vcard:hover{border-color:var(--accent);transform:translateY(-4px);}
.vthumb{position:relative;aspect-ratio:16/10;background:linear-gradient(135deg,#12121c,#0a0a12);display:flex;align-items:center;justify-content:center;overflow:hidden;}
.vthumb img{width:100%;height:100%;object-fit:cover;display:block;}
.vthumb .vemoji{font-size:56px;opacity:.65;position:absolute;inset:0;display:flex;align-items:center;justify-content:center;}
.vbody{padding:16px 18px 18px;display:flex;flex-direction:column;gap:8px;flex:1;}
.vbody h3{font-family:var(--font-pixel);font-size:11px;color:var(--text);text-transform:uppercase;line-height:1.5;}
.vbody p{font-family:var(--font-mono);font-size:11px;color:var(--muted);line-height:1.7;flex:1;}
.vplay{font-family:var(--font-pixel);font-size:8px;color:var(--accent);border:1px solid var(--accent);padding:7px 14px;text-align:center;text-transform:uppercase;transition:all .2s;}
.vcard:hover .vplay{background:var(--accent);color:#000;}
.session{font-family:var(--font-mono);font-size:10px;color:#666;text-align:center;padding:0 5vw 10px;}
.session strong{color:var(--green);font-weight:400;}
footer{border-top:1px solid rgba(255,255,255,0.06);padding:34px 5vw;text-align:center;}
footer .ft{font-family:var(--font-mono);font-size:10px;color:#666;line-height:1.9;}
@media (max-width:640px){.nav-links{gap:12px;}.nav-links a,.nav-links button{font-size:10px;}}
</style>
</head>
<body data-no-design-picker>
<div class="cursor-dot" id="cursorDot"></div>
<div class="cursor-ring" id="cursorRing"></div>
<div class="progress-bar" id="progressBar"></div>
<button class="theme-toggle" id="themeToggle" aria-label="Toggle theme"></button>
<div class="shortcut-modal" id="shortcutModal">
<div class="shortcut-card">
<h3>Keyboard Shortcuts</h3>
<div class="shortcut-row"><span>Go Home</span><kbd>H</kbd></div>
<div class="shortcut-row"><span>Toggle theme</span><kbd>T</kbd></div>
<div class="shortcut-row"><span>Show shortcuts</span><kbd>?</kbd></div>
<div class="close-hint">Press Esc or ? to close</div>
</div>
</div>
<div class="flash" id="flash"></div>
<div class="toast-stack" id="toastStack"></div>
<nav>
<a href="/index.html" class="nav-logo"><span class="logo-dot"></span> milesallen</a>
<div class="nav-links">
<a href="/index.html#projects">Projects</a>
<a href="/dashboard.html">Dashboard</a>
<button type="button" id="vaultLogout">Lock vault</button>
</div>
</nav>
<div class="scroll-content">
<section class="hero">
<h1>MOON VAULT</h1>
<p class="sub">smuggled straight out of <strong style="color:var(--accent)">moon-gaming</strong>. seven games, zero witnesses. opens in a new tab so the door stays unlocked.</p>
<div class="emoji">🌘</div>
</section>
<p class="session">server-verified session · <strong id="sessionExpiry">active</strong></p>
<div class="section-header">
<div class="tag">▸ Contraband ◂</div>
<h2>The Goods</h2>
<p>Games copied from the moon-gaming repo and stashed behind server-side authentication.</p>
</div>
<div class="vault-grid">
<a class="vcard" href="/games/monkey-mart/index.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🐒</span><img src="/games/monkey-mart/bg_loading.png" alt="" loading="lazy" onerror="this.remove()"></div>
<div class="vbody"><h3>Monkey Mart</h3><p>Stock the aisles, serve the customers, grow your little supermarket.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/drive-mad/index.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🚗</span><img src="/games/drive-mad/webapp/cover.jpg" alt="" loading="lazy" onerror="this.remove()"></div>
<div class="vbody"><h3>Drive Mad</h3><p>Physics driving puzzles. Reach the finish without flipping the car.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/stacktris/index.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🧱</span><img src="/games/stacktris/webapp/cover.jpg" alt="" loading="lazy" onerror="this.remove()"></div>
<div class="vbody"><h3>Stacktris</h3><p>Stack falling blocks as high as you dare. One bad drop and it's over.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/snow-rider/index.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🛷</span><img src="/games/snow-rider/snow-rider-3d.png" alt="" loading="lazy" onerror="this.remove()"></div>
<div class="vbody"><h3>Snow Rider 3D</h3><p>Hurtle down the mountain, dodge the obstacles, collect the gifts.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/dino.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🦖</span></div>
<div class="vbody"><h3>Dino Runner</h3><p>The endless desert runner. Jump the cacti, count your high score.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/eaglercraft-26.2-8c167d43.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">⛏️</span></div>
<div class="vbody"><h3>Eaglecraft 26.2</h3><p>Classic block-building survival, playable right in the browser.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="/games/jumping-man/index.html" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">👾</span><img src="/games/jumping-man/icon64.png" alt="" loading="lazy" onerror="this.remove()"></div>
<div class="vbody"><h3>Jumpie Boi</h3><p>Pixel-perfect platform hopping. Bounce up, dodge the deadly blocks.</p><span class="vplay">Play ▸</span></div>
</a>
<a class="vcard" href="https://vel.gg/bo1z" target="_blank" rel="noopener">
<div class="vthumb"><span class="vemoji">🧟</span></div>
<div class="vbody"><h3>Black Ops Zombies (BO1Z)</h3><p>Black Ops Zombies in your browser. All classic maps, survive the waves.</p><span class="vplay">Play ▸</span></div>
</a>
</div>
<footer>
<div class="ft">moon vault · protected · 2026<br>source: github.com/mileswolfallen2/moon-gaming</div>
</footer>
</div>
<script src="/projects/script.js"></script>
<script>
(function () {
var logout = document.getElementById('vaultLogout');
var expiry = document.getElementById('sessionExpiry');
fetch('/api/vault/session', { credentials: 'same-origin', cache: 'no-store' })
.then(function (r) { return r.json(); })
.then(function (data) {
if (!data.authenticated) { window.location.replace('/moon-vault.html'); return; }
if (data.expiresAt) {
var d = new Date(data.expiresAt);
if (!isNaN(d.getTime())) expiry.textContent = 'until ' + d.toLocaleString();
}
})
.catch(function () {});
logout.addEventListener('click', function () {
logout.disabled = true;
fetch('/api/vault/logout', { method: 'POST', credentials: 'same-origin' })
.catch(function () {})
.finally(function () { window.location.replace('/moon-vault.html'); });
});
})();
</script>
</body>
</html>