mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-05 00:00:41 +00:00
Add comprehensive test suite for application functionality
- Implement tests for HTTP API endpoints, ensuring correct responses and security headers. - Create configuration tests to validate loading of defaults and environment overrides. - Add tests for FEDL service to verify data handling and snapshot functionality. - Introduce GitHub service tests to check API data normalization and caching behavior. - Develop monitor service tests for network checks and uptime calculations. - Implement persistence tests to ensure database migrations are idempotent and data persists across restarts. - Add vault service tests for session management and brute-force protection mechanisms. - Include helper functions for test context creation and JSON response handling.
This commit is contained in:
1 parent
84b7a7e302
commit
c250653961
55 files changed
+8174
-226
No files matched your search
@@ -0,0 +1,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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
Reference in new issue
Block a user