diff --git a/server/aws-public.js b/server/aws-public.js index 804e0e8..17b066a 100644 --- a/server/aws-public.js +++ b/server/aws-public.js @@ -1,4 +1,4 @@ -// The AWS inventory before sign-in: spend and breakdowns only. No resource +// The AWS inventory before sign-in: resource totals and breakdowns only. No resource // names, ids, addresses, DNS names or tags beyond the Dash network, and no // list of idle resources (that is for members). const add = (map, key, fields) => { @@ -8,7 +8,7 @@ const add = (map, key, fields) => { }; const rows = (map) => [...map.values()].map((e) => ({ ...e, memoryGiB: Math.round(e.memoryGiB) })).sort((a, b) => b.count - a.count || a.label.localeCompare(b.label)); -export function publicInventory(inv) { +export function publicInventory(inv, { includeCosts = false } = {}) { const running = inv.instances.filter((i) => i.state === 'running'); const byNetwork = new Map(), byRegion = new Map(), byFamily = new Map(), byArch = new Map(); for (const i of running) { @@ -21,7 +21,7 @@ export function publicInventory(inv) { for (const v of inv.volumes) ebsByType.set(v.type || 'unknown', (ebsByType.get(v.type || 'unknown') || 0) + (v.sizeGiB || 0)); const lbByType = {}; for (const l of inv.loadBalancers) lbByType[l.type] = (lbByType[l.type] || 0) + 1; - const c = inv.costs; + const c = includeCosts ? inv.costs : null; return { public: true, at: inv.at, regions: inv.regions.length, regionsInUse: new Set([...inv.instances, ...inv.volumes, ...inv.addresses, ...inv.loadBalancers, ...inv.natGateways].map((x) => x.region)).size, @@ -34,6 +34,6 @@ export function publicInventory(inv) { ecrImages: inv.ecr.reduce((a, r) => a + (r.images || 0), 0), s3Buckets: inv.s3.length }, network: { loadBalancers: inv.loadBalancers.length, loadBalancersByType: lbByType, natGateways: inv.natGateways.length, elasticIps: inv.addresses.length, cloudfront: inv.cloudfront.length }, serverless: { lambda: inv.lambda.length, dynamodb: inv.dynamodb.length }, - costs: c ? { at: c.at, month: c.month, currency: c.currency, monthToDate: c.monthToDate, monthEndEstimate: c.monthEndEstimate, lastMonth: c.lastMonth, byService: c.byService, daily: c.daily } : null, + ...(includeCosts ? { costs: c ? { at: c.at, month: c.month, currency: c.currency, monthToDate: c.monthToDate, monthEndEstimate: c.monthEndEstimate, lastMonth: c.lastMonth, byService: c.byService, daily: c.daily } : null } : {}), }; } diff --git a/server/web.js b/server/web.js index ff92a7e..9af0455 100644 --- a/server/web.js +++ b/server/web.js @@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, watch, openSync, readSync, closeSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { websiteReport } from './websites.js'; import { createAuth } from './auth.js'; import { createCi } from './ci.js'; import { createOrgQueue } from './ci-queue.js'; @@ -28,6 +29,21 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{1 const LIFECYCLE_ACTIONS = ['create-devnet', 'delete-devnet', 'devnet-services', 'devnet-platform', 'platform-reset']; +// Memo with a fixed lifetime. Expired entries are dropped on insert, so keys +// that embed a timestamp (the AWS inventory) cannot accumulate. +export function ttlCache(clock, ttl = 15_000) { + const entries = new Map(); + const cached = (key, fn) => { + const hit = entries.get(key); + if (hit && clock() - hit.at < ttl) return hit.value; + for (const [k, e] of entries) if (clock() - e.at >= ttl) entries.delete(k); + const value = fn(); + entries.set(key, { at: clock(), value }); + return value; + }; + return Object.assign(cached, { delete: (key) => entries.delete(key), size: () => entries.size }); +} + export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN } = {}) { const settingsPath = join(dataDir, 'settings.json'); const dirs = { state: join(dataDir, 'state'), requests: join(dataDir, 'requests'), ops: join(dataDir, 'ops') }; @@ -138,6 +154,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl res.status(stale ? 503 : 200).json({ ...body, stale }); }); + app.get('/api/websites', (req, res) => res.json(websiteReport(dataDir, clock()))); app.get('/api/health', (req, res) => res.json({ service: 'dash-status', status: 'ok' })); app.get('/api/remediation', (req, res) => { reloadSettings(); @@ -181,7 +198,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // A change to a private job is announced to members only: its timing is private too. const pushQueue = (scope) => { if (!scope) return; - if (scope === 'all') publicCache.delete('ci-queue'); + if (scope === 'all') cached.delete('ci-queue'); for (const members of scope === 'all' ? [true, false] : [true]) { const key = `ci-queue|${members}`; clearTimeout(debounce.get(key)); @@ -395,16 +412,10 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl res.json({ activityHistory }); }); - // Infrastructure pages: full detail for any account with access; before - // sign-in a sanitized view (statistics and spend, nothing identifying). - const publicCache = new Map(); - const cached = (key, fn) => { - const hit = publicCache.get(key); - if (hit && clock() - hit.at < 15_000) return hit.value; - const value = fn(); - publicCache.set(key, { at: clock(), value }); - return value; - }; + // Infrastructure pages: full detail for any account with access; otherwise a + // sanitized view (statistics, nothing identifying). Spend is never shown + // before sign-in. + const cached = ttlCache(clock); app.get('/api/ci', (req, res) => res.json(memberOf(settings, user(req)) ? ci.summary({ admin: isAdmin(req) }) : cached('ci', () => ci.publicSummary()))); app.get('/api/ci/queue/capacity', (req, res) => { const window = typeof req.query.window === 'string' ? req.query.window : '7d'; @@ -423,7 +434,10 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl app.get('/api/aws', (req, res) => { const inv = readJSON(join(awsDir, 'inventory.json')); if (!inv) return res.status(404).json({ error: 'No AWS inventory yet; the agent collects it every 10 minutes' }); - res.json(memberOf(settings, user(req)) ? inv : cached(`aws|${inv.at}`, () => publicInventory(inv))); + const viewer = user(req); + // Cost visibility follows the authenticated session, never query parameters. + // Keep signed-in summaries separate from the anonymous projection cache. + res.vary('Cookie').json(memberOf(settings, viewer) ? inv : cached(`aws|${viewer ? 'signed-in' : 'public'}|${inv.at}`, () => publicInventory(inv, { includeCosts: !!viewer }))); }); // GitHub account lookup so admins can grant access by login. diff --git a/server/web.test.js b/server/web.test.js index f8b998c..831f33f 100644 --- a/server/web.test.js +++ b/server/web.test.js @@ -4,7 +4,7 @@ import { createHmac } from 'node:crypto'; import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { createWeb } from './web.js'; +import { createWeb, ttlCache } from './web.js'; import { DEFAULT_SETTINGS } from '../shared/settings.js'; async function start(userId = 9920871, extraUsers = [], options = {}) { @@ -239,20 +239,51 @@ test('CI: admins issue reporter tokens; reporters post with them; infrastructure costs: { at: 'now', month: '2026-09', monthToDate: 3270.85, monthEndEstimate: 3503.4, lastMonth: 3109.17, byService: [{ service: 'EC2 - Other', amount: 1178.9 }], daily: [] } })); assert.equal((await (await w.req('/api/aws')).json()).at, 'now'); assert.equal((await (await w.req('/api/aws')).json()).instances[0].publicIp, '192.0.2.9', 'members see the inventory'); + assert.equal((await (await w.req('/api/aws')).json()).costs.monthToDate, 3270.85, 'members retain costs'); assert.equal((await w.req(`/api/ci/reporters/${id}`, { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 200); - // Signed out: spend and breakdowns, nothing that names or locates a resource. + // Signed out: resource aggregates, no spend or resource identity. await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } }); const pub = await (await w.req('/api/aws')).json(); assert.equal(pub.public, true); assert.deepEqual(pub.byNetwork, [{ label: 'testnet', count: 1, vcpus: 2, memoryGiB: 2 }]); - assert.equal(pub.costs.monthToDate, 3270.85); + assert.equal(pub.costs, undefined); const text = JSON.stringify(pub); - for (const leak of ['192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1']) + for (const leak of ['3270.85', '3503.4', '3109.17', '1178.9', '192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1']) assert.ok(!text.includes(leak), `leaked ${leak}`); assert.equal((await post(`Bearer ${token}`)).status, 401); } finally { w.close(); } }); +test('AWS costs require a valid session, including after cache warmup and logout', async () => { + const w = await start(42); // Signed-in user without inventory membership. + try { + const costs = { monthToDate: 1234.56, monthEndEstimate: 2345.67, lastMonth: 3456.78, + byService: [{ service: 'Fixture service', amount: 456.78 }], daily: [{ day: '2026-10-01', amount: 567.89 }] }; + writeFileSync(join(w.dataDir, 'aws', 'inventory.json'), JSON.stringify({ at: 'fixture', regions: [], + instances: [], volumes: [], addresses: [], natGateways: [], loadBalancers: [], lambda: [], + dynamodb: [], ecr: [], snapshots: [], cloudfront: [], s3: [], costs })); + const anonymous = async (path = '/api/aws', options) => { + const response = await w.req(path, options); + assert.equal(response.status, 200); + assert.equal(response.headers.get('cache-control'), 'no-store'); + assert.match(response.headers.get('vary'), /Cookie/i); + const body = await response.json(); + assert.equal(body.public, true); + assert.equal(Object.hasOwn(body, 'costs'), false); + for (const amount of [1234.56, 2345.67, 3456.78, 456.78, 567.89]) + assert.ok(!JSON.stringify(body).includes(String(amount))); + }; + await anonymous('/api/aws?as=9920871'); // Claimed identity never grants costs. + const csrf = await w.login(); + const signedIn = await (await w.req('/api/aws?as=public')).json(); + assert.equal(signedIn.public, true, 'sign-in does not grant detailed inventory'); + assert.deepEqual(signedIn.costs, costs, 'signed-in summaries retain all costs'); + await anonymous('/api/aws?as=42', { headers: { cookie: 'dash-session=invalid' } }); + assert.equal((await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } })).status, 200); + await anonymous(); // Same inventory timestamp must not reuse signed-in costs. + } finally { w.close(); } +}); + test('console devnet connection files reach members only', async () => { const w = await start(); try { @@ -444,3 +475,19 @@ test('a deleted devnet no longer blocks its name in the new-devnet form', async assert.ok(existing.includes('devnet-bonsai') && existing.includes('devnet-stuck') && existing.includes('testnet')); } finally { w.close(); } }); + +test('public projection cache keeps its 15 s lifetime and evicts expired keys on insert', () => { + let now = 0, calls = 0; + const cached = ttlCache(() => now); + for (const at of ['a', 'b']) for (const view of ['public', 'signed-in']) cached(`aws|${view}|${at}`, () => ++calls); + assert.equal(cached('aws|public|a', () => ++calls), 1, 'a live entry is reused'); + now = 14_999; + assert.equal(cached('ci', () => ++calls), 5); + assert.equal(cached.size(), 5, 'nothing is evicted before it expires'); + now = 15_000; + assert.equal(cached('aws|public|c', () => ++calls), 6); + assert.equal(cached.size(), 2, 'entries from the previous inventory are gone'); + assert.equal(cached('ci', () => ++calls), 5); + cached.delete('ci'); + assert.equal(cached('ci', () => ++calls), 7); +}); diff --git a/server/websites.js b/server/websites.js new file mode 100644 index 0000000..d0e6d1d --- /dev/null +++ b/server/websites.js @@ -0,0 +1,70 @@ +import { readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; + +// Public-data-only boundary: this file is served to anonymous callers, so only +// allowlisted, type-checked fields survive. Unknown fields never pass through. +const MAX_SITES = 16, MAX_HISTORY = 2016; // seven days of five-minute samples +const integer = (v) => Number.isSafeInteger(v) && v >= 0 ? v : null; +const finite = (v) => Number.isFinite(v) && v >= 0 ? v : null; +const percent = (v) => finite(v) !== null && v <= 100 ? v : null; +// Date.parse rolls an impossible date forward (30 February becomes 2 March), so the written date must be a real one. +const realDate = (v) => { const m = /^(\d{4})-(\d\d)-(\d\d)/.exec(v); return !!m && new Date(Date.UTC(m[1], m[2] - 1, m[3])).toISOString().startsWith(m[0]); }; +const timestamp = (v) => typeof v === 'string' && realDate(v) && Number.isFinite(Date.parse(v)) ? new Date(v).toISOString() : null; +const text = (v, max) => typeof v === 'string' ? v.slice(0, max) : null; +// Header-derived values may arrive as numbers or digit strings (HTTP version, Age). +const seconds = (v) => integer(typeof v === 'string' && /^\d{1,9}$/.test(v) ? Number(v) : v); +const token = (v) => ['string', 'number'].includes(typeof v) && /^[\w./-]{1,16}$/.test(String(v)) ? String(v) : null; +// Interpolated into an https:// link: a bare DNS name only (no port, path, userinfo or IP literal). +const hostname = (v) => typeof v === 'string' && v.length <= 253 && /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(v) ? v.toLowerCase() : null; +function httpsUrl(v) { + if (typeof v !== 'string' || v.length > 2048) return null; + try { const u = new URL(v); return u.protocol === 'https:' && !u.username && !u.password ? u.href : null; } catch { return null; } +} +const PHASES = ['dnsMs', 'tcpMs', 'tlsMs', 'waitMs', 'downloadMs']; + +function sample(s) { + const at = timestamp(s?.at); + if (!at) return null; + return { at, ok: s.ok === true, status: integer(s.status), error: text(s.error, 200), + ttfbMs: finite(s.ttfbMs), totalMs: finite(s.totalMs), redirects: integer(s.redirects), redirectMs: finite(s.redirectMs), + httpVersion: token(s.httpVersion), finalUrl: httpsUrl(s.finalUrl), htmlBytes: integer(s.htmlBytes), transferBytes: integer(s.transferBytes), + encoding: text(s.encoding, 32), cacheStatus: text(s.cacheStatus, 64), age: seconds(s.age), cacheControl: text(s.cacheControl, 200), + phases: Object.fromEntries(PHASES.map((k) => [k, finite(s.phases?.[k])])), + hints: { blockingScripts: integer(s.hints?.blockingScripts), imagesWithoutDimensions: integer(s.hints?.imagesWithoutDimensions) } }; +} + +// A site is usable only with a link-safe name and a latest sample; the page renders both unconditionally. +function site(s) { + const name = hostname(s?.site), latest = sample(s?.latest); + if (!name || !latest) return null; + const d = s.summary24h; + return { site: name, latest, + summary24h: { ttfbP50Ms: finite(d?.ttfbP50Ms), ttfbP95Ms: finite(d?.ttfbP95Ms), successes: integer(d?.successes), samples: integer(d?.samples), successPercent: percent(d?.successPercent) }, + history: (Array.isArray(s.history) ? s.history : []).map(sample).filter(Boolean).sort((a, b) => Date.parse(a.at) - Date.parse(b.at)).slice(-MAX_HISTORY) }; +} + +function normalize(report) { + if (report?.schemaVersion !== 1 || !Array.isArray(report.sites)) return null; + const sites = report.sites.slice(0, MAX_SITES).map(site).filter((s, i, all) => s && all.findIndex((x) => x?.site === s.site) === i); + return { generatedAt: timestamp(report.generatedAt), location: text(report.location, 80), sites }; +} + +// One parse per collector write. A file modified within the last two seconds is +// not trusted as a cache key: a second write could share its mtime and size. +// A failed read or parse is never cached: its cause can clear without changing the key. +let cache = null; +function load(file) { + const st = statSync(file), key = `${file}|${st.mtimeMs}|${st.size}|${st.ino}`; + if (cache?.key === key) return cache.report; + const report = (() => { try { return normalize(JSON.parse(readFileSync(file, 'utf8'))); } catch { return null; } })(); + cache = report && Date.now() - st.mtimeMs > 2000 ? { key, report } : null; + return report; +} + +export function websiteReport(dataDir, now = Date.now()) { + let report = null; + try { report = load(join(dataDir, 'websites', 'report.json')); } catch { /* A missing collector is unknown, not healthy. */ } + if (!report) return { stale: true, sites: [], error: 'Website checks have not reported yet.' }; + const age = now - Date.parse(report.generatedAt); + return { ...report, stale: !Number.isFinite(age) || age > 12 * 60_000 || age < -60_000 }; +} diff --git a/server/websites.test.js b/server/websites.test.js new file mode 100644 index 0000000..2fda0cd --- /dev/null +++ b/server/websites.test.js @@ -0,0 +1,140 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync, utimesSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { websiteReport } from './websites.js'; +import { segments, recommendations } from '../src/website-metrics.js'; + +test('missing, stale and future data never appear fresh', () => { + const dir = mkdtempSync(join(tmpdir(), 'websites-')); + try { + assert.equal(websiteReport(dir).stale, true); + mkdirSync(join(dir, 'websites')); + const now = Date.now(); + for (const [offset, stale] of [[0, false], [-13 * 60_000, true], [120_000, true]]) { + writeFileSync(join(dir, 'websites/report.json'), JSON.stringify({ schemaVersion: 1, generatedAt: new Date(now + offset).toISOString(), sites: [] })); + assert.equal(websiteReport(dir, now).stale, stale); + } + } finally { rmSync(dir, { recursive: true }); } +}); + +test('chart breaks lines on failed checks and missing intervals; no invented zeroes', () => { + const at = (n, ok = true) => ({ at: new Date(n * 300_000).toISOString(), ok, ttfbMs: 100 }); + const result = segments([at(0), at(1), at(2, false), at(3), at(8)], 'ttfbMs', 0, 9 * 300_000); + assert.deepEqual(result.map((g) => g.length), [2, 1, 1]); + assert.ok(result.flat().every((s) => s.value === 100)); +}); + +test('recommendations are evidence-based and failures are not performance advice', () => { + assert.deepEqual(recommendations({ ok: false, error: 'TLS validation failed' }), ['TLS validation failed']); + assert.ok(recommendations({ ok: true, redirects: 1, redirectMs: 95 }).some((s) => s.includes('95 ms'))); + assert.ok(!recommendations({ ok: true, encoding: 'br', htmlBytes: 1000 }).some((s) => s.includes('not compressed'))); +}); + +const sampleAt = (t, extra = {}) => ({ at: new Date(t).toISOString(), ok: true, status: 200, error: null, ttfbMs: 120, totalMs: 180, redirects: 0, redirectMs: 0, httpVersion: '2', + finalUrl: 'https://www.dash.org/', htmlBytes: 5000, transferBytes: 1500, encoding: 'br', cacheStatus: 'HIT', age: 12, cacheControl: 'public, max-age=60', + phases: { dnsMs: 1, tcpMs: 2, tlsMs: 3, waitMs: 100, downloadMs: 5 }, hints: { blockingScripts: 0, imagesWithoutDimensions: 2 }, ...extra }); +const siteAt = (t, extra = {}) => ({ site: 'dash.org', latest: sampleAt(t), summary24h: { ttfbP50Ms: 110, ttfbP95Ms: 300, successes: 287, samples: 288, successPercent: 99.7 }, history: [sampleAt(t)], ...extra }); +function withReport(report, fn) { + const dir = mkdtempSync(join(tmpdir(), 'websites-')); + try { + mkdirSync(join(dir, 'websites')); + const file = join(dir, 'websites/report.json'); + writeFileSync(file, JSON.stringify(report)); + return fn(dir, file); + } finally { rmSync(dir, { recursive: true }); } +} + +test('public report is rebuilt from an allowlist: unknown fields, unusable sites and oversized values never pass', () => { + const now = Date.now(), secret = 'PRIVATE-COLLECTOR-DETAIL'; + const report = { schemaVersion: 1, generatedAt: new Date(now).toISOString(), location: 'us-west-2', collectorHost: secret, sites: [ + siteAt(now, { resolvedIp: secret, latest: sampleAt(now, { ok: false, error: 'x'.repeat(500), finalUrl: 'http://dash.org/', ttfbMs: '120', headers: { cookie: secret }, phases: { dnsMs: 1, peer: secret } }), + history: [...Array.from({ length: 2020 }, (_, i) => sampleAt(now - (2020 - i) * 300_000, { remote: secret })), { at: 'not a time' }, null] }), + siteAt(now, { site: 'dash.dev', latest: undefined }), + siteAt(now, { site: 'DASH.dev', summary24h: undefined, history: 'none' }), + ...['evil.example/x', 'user@dash.org', 'dash.org:8443', 'javascript:alert(1)', '192.0.2.1', 'localhost', '', null, 7].map((site) => siteAt(now, { site })), + siteAt(now), null, 'dash.org', + ] }; + const out = withReport(report, (dir) => websiteReport(dir, now)); + assert.deepEqual(Object.keys(out).sort(), ['generatedAt', 'location', 'sites', 'stale']); + assert.equal(out.stale, false); + assert.doesNotMatch(JSON.stringify(out), /PRIVATE-COLLECTOR-DETAIL/); + assert.deepEqual(out.sites.map((s) => s.site), ['dash.org', 'dash.dev']); + for (const s of out.sites) assert.ok(s.latest && typeof s.latest.at === 'string' && s.summary24h && typeof s.summary24h === 'object' && Array.isArray(s.history)); + const [org, dev] = out.sites; + assert.equal(org.latest.error.length, 200); + assert.equal(org.latest.finalUrl, null); + assert.equal(org.latest.ttfbMs, null); + assert.deepEqual(org.latest.phases, { dnsMs: 1, tcpMs: null, tlsMs: null, waitMs: null, downloadMs: null }); + assert.equal(org.history.length, 2016); + assert.deepEqual(org.history.at(-1), sampleAt(now - 300_000)); + assert.deepEqual(dev.summary24h, { ttfbP50Ms: null, ttfbP95Ms: null, successes: null, samples: null, successPercent: null }); + assert.deepEqual(dev.history, []); + assert.deepEqual(dev.latest, sampleAt(now)); +}); + +test('an unchanged report file is parsed once while staleness still follows the clock', () => { + const now = Date.now(); + withReport({ schemaVersion: 1, generatedAt: new Date(now).toISOString(), sites: [siteAt(now)] }, (dir, file) => { + utimesSync(file, new Date(now - 60_000), new Date(now - 60_000)); + const first = websiteReport(dir, now), later = websiteReport(dir, now + 13 * 60_000); + assert.equal(first.sites, later.sites); + assert.equal(first.stale, false); + assert.equal(later.stale, true); + writeFileSync(file, JSON.stringify({ schemaVersion: 1, generatedAt: new Date(now).toISOString(), sites: [siteAt(now, { site: 'dash.dev' })] })); + assert.deepEqual(websiteReport(dir, now).sites.map((s) => s.site), ['dash.dev']); + writeFileSync(file, '{ truncated'); + assert.deepEqual(websiteReport(dir, now), { stale: true, sites: [], error: 'Website checks have not reported yet.' }); + }); +}); + +test('website page helpers tolerate samples with missing fields', () => { + assert.ok(recommendations({ ok: true, redirects: 2 }).some((s) => s.startsWith('2 redirects. '))); + assert.doesNotMatch(recommendations({ ok: true, redirects: 1, ttfbMs: 900, redirectMs: null }).join(' '), /NaN|null|undefined/); + assert.deepEqual(segments(undefined, 'ttfbMs', 0, 1), []); +}); + +test('an impossible calendar date is not a collection time; offsets and missing milliseconds are', () => { + const now = Date.parse('2026-03-02T12:00:00Z'); + const read = (generatedAt, at = generatedAt) => withReport({ schemaVersion: 1, generatedAt, sites: [{ ...siteAt(now), history: [{ ...sampleAt(now), at }] }] }, (dir) => websiteReport(dir, now)); + for (const good of ['2026-03-02T12:00:00Z', '2026-03-02T12:00:00+00:00', '2026-03-02T14:00:00.000000+02:00', '2026-03-02T12:00:00.000Z']) { + const out = read(good); + assert.equal(out.stale, false, good); + assert.equal(Date.parse(out.generatedAt), now, good); + assert.equal(out.sites[0].history.length, 1, good); + } + // Date.parse reads each of these as a real instant; the first is exactly `now`. + for (const bad of ['2026-02-30T12:00:00Z', '2026-02-29T12:00:00Z', '2026-04-31T12:00:00+00:00', 'Mar 2 2026 12:00:00 UTC']) { + assert.ok(Number.isFinite(Date.parse(bad)), bad); + const out = read(bad); + assert.equal(out.generatedAt, null, bad); + assert.equal(out.stale, true, bad); + assert.deepEqual(out.sites[0].history, [], bad); + } + assert.equal(read('2024-02-29T12:00:00Z').generatedAt, '2024-02-29T12:00:00.000Z'); +}); + +test('a failed read or parse is not cached under an unchanged mtime, size and inode', () => { + const now = Date.now(), old = new Date(now - 60_000); + const valid = JSON.stringify({ schemaVersion: 1, generatedAt: new Date(now).toISOString(), sites: [siteAt(now)] }); + withReport({}, (dir, file) => { + writeFileSync(file, 'x'.repeat(valid.length)); utimesSync(file, old, old); + assert.equal(websiteReport(dir, now).error, 'Website checks have not reported yet.'); + writeFileSync(file, valid); utimesSync(file, old, old); + assert.deepEqual(websiteReport(dir, now).sites.map((s) => s.site), ['dash.org']); + }); +}); + +test('history is served oldest first and the cap keeps the newest samples, whatever order the collector wrote', () => { + const now = Date.now(), times = Array.from({ length: 2020 }, (_, i) => now - i * 300_000); + const out = withReport({ schemaVersion: 1, generatedAt: new Date(now).toISOString(), sites: [siteAt(now, { history: times.map((t) => sampleAt(t)) })] }, (dir) => websiteReport(dir, now)); + assert.deepEqual(out.sites[0].history.map((s) => Date.parse(s.at)), times.slice(0, 2016).reverse()); +}); + +test('chart orders samples by time before grouping, so a late-written sample cannot draw a line across a gap', () => { + const at = (n) => ({ at: new Date(n * 300_000).toISOString(), ok: true, ttfbMs: n }); + const history = [at(9), at(1), at(0), at(8), at(2)], copy = structuredClone(history); + assert.deepEqual(segments(history, 'ttfbMs', 0, 10 * 300_000).map((g) => g.map((p) => p.value)), [[0, 1, 2], [8, 9]]); + assert.deepEqual(history, copy); +}); diff --git a/shared/evaluate.js b/shared/evaluate.js index c4024af..c1db29b 100644 --- a/shared/evaluate.js +++ b/shared/evaluate.js @@ -1,5 +1,6 @@ // Turns agent state into what the board shows. Every status comes with the // concrete facts that produced it; there is no status without a reason. +import { liveServiceEndpoints } from './mainnet.js'; import { convergence, monitoringSummary } from './monitoring.js'; import { COMPONENT_REPOS, SIDECAR_REPOS } from './settings.js'; @@ -218,7 +219,7 @@ export function evaluateNetwork(network, state, settings, now = Date.now(), tags const stale = !Number.isFinite(observed) || now - observed > maxAge || observed > now + 60_000; reportStale = stale; if (stale) { - const row = rows.find((r) => r.host.role === 'fullnode'); + const row = rows.find((r) => ['fullnode', 'validator'].includes(r.host.role)); if (row) { row.level = 'unreachable'; row.reasons.push({ level: 'unreachable', text: 'mainnet observer report is stale' }); } } } @@ -246,7 +247,7 @@ export function evaluateNetwork(network, state, settings, now = Date.now(), tags dapi: { ok: validatorRows.filter((r) => r.data.dapi?.ok).length, total: validatorRows.filter((r) => r.host.state === 'running').length }, }; if (network.chainType !== 'mainnet') summary.monitoring = monitoringSummary(rows, state?.endpoints || [], now); - const mainnetRow = rows.find((r) => r.host.role === 'fullnode' && r.data.mainnet); + const mainnetRow = rows.find((r) => ['fullnode', 'validator'].includes(r.host.role) && r.data.mainnet); if (network.chainType === 'mainnet' && mainnetRow) { const m = mainnetRow.data.mainnet || {}; summary.mainnet = { @@ -260,11 +261,12 @@ export function evaluateNetwork(network, state, settings, now = Date.now(), tags platformSyncing: m.platformSyncing ?? null, newBans: m.newBans ?? null, }; } - const endpointFailure = (state?.endpoints || []).some((e) => e.ok === false); + const endpoints = liveServiceEndpoints(state?.endpoints, now); + const endpointFailure = endpoints.some((e) => e.ok === false); const seedChains = summary.monitoring?.dapi.seedChains || []; const seedMismatch = seedChains.length > 1 || summary.monitoring?.dapi.seedHeightSpread > t.platformLagBlocks; const level = rows.reduce((a, r) => (r.host.duplicate || r.host.role === 'vpn' ? a : RANK[r.level] > RANK[a] ? r.level : a), 'ok'); - return { level: reportStale ? 'unreachable' : building ? 'deploying' : (endpointFailure || seedMismatch) && RANK[level] < RANK.warn ? 'warn' : level === 'stopped' ? 'ok' : level, rows, summary, tags, generatedAt: state?.generatedAt || null, ageSeconds: state?.generatedAt ? Math.round((now - Date.parse(state.generatedAt)) / 1000) : null }; + return { level: reportStale ? 'unreachable' : building ? 'deploying' : (endpointFailure || seedMismatch) && RANK[level] < RANK.warn ? 'warn' : level === 'stopped' ? 'ok' : level, rows, summary, tags, endpoints, generatedAt: state?.generatedAt || null, ageSeconds: state?.generatedAt ? Math.round((now - Date.parse(state.generatedAt)) / 1000) : null }; } function chainMatches(chain, network) { @@ -307,7 +309,7 @@ export function projectNetwork(network, evaluation, state, operator) { name: network.name, displayName: network.displayName, description: network.description || '', chainType: network.chainType, coreNetwork: network.coreNetwork, public: network.public, deployable: network.deployable, kind: network.kind || 'managed', upgradeScopes: network.upgradeScopes || null, images: network.images || null, dashmate: !!network.dashmate, lifecycle: network.lifecycle || null, observationWindow: network.observationWindow, operationTimeout: network.operationTimeout, level: evaluation.level, generatedAt: evaluation.generatedAt, ageSeconds: evaluation.ageSeconds, pollSeconds: state?.pollSeconds || null, discovery: state?.discovery ? { at: state.discovery.at, error: operator ? state.discovery.error : state.discovery.error ? 'discovery failed' : null } : null, - summary: evaluation.summary, endpoints: (state?.endpoints || []).map((e) => ({ label: e.label, kind: e.kind, url: e.url, status: e.status, ok: e.ok, ms: e.ms, error: e.error, height: e.height, version: e.version, chainId: e.chainId, state: e.state })), + summary: evaluation.summary, endpoints: (evaluation.endpoints ?? state?.endpoints ?? []).map((e) => ({ label: e.label, kind: e.kind, url: e.url, status: e.status, ok: e.ok, ms: e.ms, error: e.error, height: e.height, version: e.version, chainId: e.chainId, state: e.state })), hosts, journal: operator ? state?.journal || null : undefined, }; } diff --git a/shared/mainnet.js b/shared/mainnet.js index d145777..c68aa59 100644 --- a/shared/mainnet.js +++ b/shared/mainnet.js @@ -1,9 +1,50 @@ // Public-data-only boundary. Failure samples are data, never manufactured health. const integer = (v) => Number.isSafeInteger(v) && v >= 0 ? v : null; const finite = (v) => Number.isFinite(v) && v >= 0 ? v : null; -const text = (v, max = 80) => typeof v === 'string' ? v.slice(0, max) : null; +// A pre-release/build suffix starts with a letter, stays short and never has the shape of an IPv4 address. +const suffix = (s) => s === undefined || (/^[a-zA-Z][a-zA-Z0-9.-]{0,31}$/.test(s) && !/\d[.-]\d+[.-]\d+[.-]\d/.test(s)); +const version = (v) => { const m = typeof v === 'string' && v.length < 64 && /^(?:unreleased-)?\d+(?:\.\d+){0,2}(?:[-+]([a-zA-Z0-9.-]+))?$/.exec(v); return m && suffix(m[1]) ? v : null; }; +// Dash Core may append a user-agent comment, `/Dash Core:23.1.0(observer)/`; only the version is kept. +const coreVersion = (v) => { const m = typeof v === 'string' && /^\/Dash Core:(\d+\.\d+\.\d+(?:[-+]([a-zA-Z0-9.-]+))?)(?:\([^()]{0,256}\))?\/$/.exec(v); return m && suffix(m[2]) ? `/Dash Core:${m[1]}/` : null; }; +const enumeration = (v, allowed) => allowed.includes(v) ? v : null; const boolean = (v) => typeof v === 'boolean' ? v : null; -const timestamp = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v)) ? new Date(v).toISOString() : null; +// Date.parse rolls an impossible date forward (30 February becomes 2 March), so the written date must be a real one. +const realDate = (v) => { const m = /^(\d{4})-(\d\d)-(\d\d)/.exec(v); return !!m && new Date(Date.UTC(m[1], m[2] - 1, m[3])).toISOString().startsWith(m[0]); }; +const timestamp = (v) => typeof v === 'string' && realDate(v) && Number.isFinite(Date.parse(v)) ? new Date(v).toISOString() : null; + +// Every state Dash Core's `masternode status` can report. +const MASTERNODE_STATES = ['READY', 'WAITING_FOR_PROTX', 'POSE_BANNED', 'REMOVED', 'OPERATOR_KEY_CHANGED', 'PROTX_IP_CHANGED', 'ERROR', 'UNKNOWN']; + +const SERVICES = { + quorums: ['Quorums · fresh Core comparison', 'https://quorums.mainnet.networks.dash.org/quorums'], + insight: ['Insight · indexed block/transaction', 'https://insight.dash.org/insight/'], + 'seed-1': ['Platform seed 1 · TLS + bootstrap', 'https://seed-1.mainnet.networks.dash.org'], + 'seed-2': ['Platform seed 2 · TLS + bootstrap', 'https://seed-2.mainnet.networks.dash.org'], + 'seed-3': ['Platform seed 3 · TLS + bootstrap', 'https://seed-3.mainnet.networks.dash.org'], + bootstrap: ['Default SDK bootstrap', 'https://www.npmjs.com/package/@dashevo/dapi-client'], + 'quorums-tls': ['Quorum certificate', 'https://quorums.mainnet.networks.dash.org'], + 'insight-tls': ['Insight certificate', 'https://insight.dash.org'], + observer: ['Independent observer / data freshness', 'https://status.testnet.networks.dash.org/'], + core: ['Core chain progress', 'https://status.testnet.networks.dash.org/'], platform: ['Platform chain progress', 'https://status.testnet.networks.dash.org/'], chainlocks: ['ChainLocks', 'https://status.testnet.networks.dash.org/'], +}; +const STALE = 'monitor sample missing or stale'; +const sampleFresh = (at, now) => finite(at) !== null && now / 1000 - at >= -60 && now / 1000 - at <= 240; +export function serviceEndpoints(input, now) { + const fresh = sampleFresh(input?.at, now); + const rows = Array.isArray(input?.services) ? input.services : []; + return Object.entries(SERVICES).map(([id, [label, url]]) => { + const samples = rows.filter((s) => s?.id === id); + const s = fresh && samples.length === 1 ? samples[0] : null; + const reason = enumeration(s?.reason, ['healthy', 'reference-unavailable', 'stale-data', 'certificate-expiring', 'probe-failed', 'consensus-signal']); + return { label, url, kind: 'mainnet-service', ok: s ? boolean(s.ok) : false, + status: s?.ok === true ? 'OK' : null, ms: finite(s?.ms), height: integer(s?.height), + error: s?.ok === true ? null : reason || (!s ? STALE : boolean(s.ok) === null ? 'not observed' : 'probe-failed'), + ...(s ? { sampledAt: input.at } : {}) }; + }); +} +// Stored rows outlive the sample they came from, so freshness is decided again on every read. +export const liveServiceEndpoints = (endpoints, now) => (endpoints || []).map((e) => e?.kind !== 'mainnet-service' || sampleFresh(e.sampledAt, now) ? e + : { ...e, ok: false, status: null, ms: null, height: null, error: STALE }); export function validateMainnetReport(input, now = Date.now()) { if (!input || input.network !== 'mainnet') throw new Error('mainnet report required'); @@ -15,16 +56,43 @@ export function validateMainnetReport(input, now = Date.now()) { const c = input.core; core = { chain: 'main', blocks: c.blocks, headers: integer(c.headers), chainLockHeight: integer(c.chainLockHeight), bestBlockHash: /^[a-f0-9]{64}$/i.test(c.bestBlockHash || '') ? c.bestBlockHash : null, - blockTime: finite(c.blockTime), ibd: boolean(c.ibd), synced: boolean(c.synced), - subversion: text(c.subversion), protocol: integer(c.protocol), connections: integer(c.connections) }; + blockTime: finite(c.blockTime), difficulty: finite(c.difficulty), ibd: boolean(c.ibd), synced: boolean(c.synced), + subversion: coreVersion(c.subversion), protocol: integer(c.protocol), connections: integer(c.connections) }; } let platform = null; if (input.platform != null) { const p = input.platform; if (p.network !== 'evo1' || integer(p.height) === null) throw new Error('mainnet Platform chain and height required'); platform = { height: p.height, blockTime: timestamp(p.blockTime), network: p.network, - catchingUp: boolean(p.catchingUp), maxPeerHeight: integer(p.maxPeerHeight), peers: integer(p.peers), version: text(p.version) }; + catchingUp: boolean(p.catchingUp), maxPeerHeight: integer(p.maxPeerHeight), peers: integer(p.peers), version: version(p.version), protocolApp: integer(p.protocolApp), validatorSetSize: integer(p.validatorSetSize), round: integer(p.round), commitRound: integer(p.commitRound), thresholdSigned: boolean(p.thresholdSigned) }; } + // Explicit schema on ingress: no target/address, ProTx/node ID, payment height, + // certificate identity, arbitrary error, container name or untrusted text survives. + const evo = input.evo === true; + const mn = input.core?.masternode; + if (core && evo && mn) core.masternode = { + state: enumeration(mn.state, MASTERNODE_STATES), + type: enumeration(mn.type, ['Evo']), posePenalty: integer(mn.posePenalty), + }; + const d = input.dapi; + // A DAPI answering for another chain is a failure; the foreign ID itself is never stored. + const chainId = d?.chainId === 'evo1' ? 'evo1' : typeof d?.chainId === 'string' && d.chainId ? 'other' : null; + const dapi = evo ? { + ok: d?.ok === true && chainId !== 'other', latencyMs: finite(d?.latencyMs), height: integer(d?.height), + dapiVersion: version(d?.dapiVersion), driveVersion: version(d?.driveVersion), + chainId, + query: d?.query ? { ok: d.query.ok === true, method: 'getEpochsInfo', + latencyMs: finite(d.query.latencyMs), epoch: integer(d.query.epoch), + firstBlockHeight: integer(d.query.firstBlockHeight), protocol: integer(d.query.protocol) } : null, + } : null; + const components = { core: 'dashpay/dashd', drive: 'dashpay/drive', tenderdash: 'dashpay/tenderdash', dapi: 'dashpay/rs-dapi' }; + const containers = evo ? Object.entries(components).flatMap(([component, repo]) => { + const c = input.components?.[component]; + const tag = version(c?.version); + return c && tag ? [{ name: component, service: component, repo, image: `${repo}:${tag}`, + running: c.running === true, state: c.running === true ? 'running' : 'unavailable', + restarts: integer(c.restarts) }] : []; + }) : []; const q = input.quorumServer; const quorum = q && typeof q === 'object' ? Object.fromEntries(['status', 'quorums', 'listed', 'banned', 'enabled', 'versionFailures'].map((k) => [k, integer(q[k])])) : null; if (quorum) quorum.latencyMs = finite(q.latencyMs); @@ -34,8 +102,8 @@ export function validateMainnetReport(input, now = Date.now()) { quorumServer: quorum, coreStall: core?.ibd === false ? boolean(input.mainnet?.coreStall) : null, platformStall: platform?.catchingUp === false ? boolean(input.mainnet?.platformStall) : null }; return { network: 'mainnet', generatedAt: at, pollSeconds: 60, discovery: { at, error: null }, - endpoints: [{ label: 'Quorum list', kind: 'quorum', url: 'https://quorums.mainnet.networks.dash.org/masternodes', + endpoints: input.serviceChecks !== undefined ? serviceEndpoints(input.serviceChecks, now) : [{ label: 'Quorum list', kind: 'quorum', url: 'https://quorums.mainnet.networks.dash.org/masternodes', status: quorum?.status ?? null, ok: quorum?.status === 200 && quorum.quorums > 0 && quorum.listed > 0, ms: quorum?.latencyMs ?? null }], - hosts: [{ name: 'mainnet-observer', role: 'fullnode', state: 'running', publicIp: null, privateIp: null, - probe: { ok: true, at, ms: finite(input.probeMs) ?? 0, data: { core, tenderdash: platform, mainnet, containers: [], system: null } } }] }; + hosts: [{ name: 'mainnet-observer', role: evo ? 'validator' : 'fullnode', state: 'running', publicIp: null, privateIp: null, + probe: { ok: true, at, ms: finite(input.probeMs) ?? 0, data: { core, tenderdash: platform, mainnet, dapi, containers, system: null } } }] }; } diff --git a/shared/mainnet.test.js b/shared/mainnet.test.js index 9456f81..73f8edf 100644 --- a/shared/mainnet.test.js +++ b/shared/mainnet.test.js @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; import { validateMainnetReport } from './mainnet.js'; -import { evaluateNetwork } from './evaluate.js'; +import { evaluateNetwork, projectNetwork } from './evaluate.js'; import { DEFAULT_SETTINGS, validateSettings } from './settings.js'; const now = Date.parse('2026-09-30T08:00:00Z'); @@ -52,3 +52,154 @@ test('mainnet-support cannot enter EC2 discovery, even with malformed legacy set const bad = structuredClone(DEFAULT_SETTINGS); bad.networks[bad.networks.findIndex((n) => n.name === 'mainnet')] = forbidden; assert.throws(() => validateSettings(bad), /separate report observer/); }); + +test('private Evo fills dashboard metrics without disclosing source identity in state or projection', () => { + const r = fixture(); r.evo = true; r.core.difficulty = 123.25; + const privateValue = 'PRIVATE-NODE-IDENTITY'; + r.publicIp = privateValue; + r.core.masternode = { state: 'READY', type: 'Evo', posePenalty: 0, proTxHash: privateValue, + service: privateValue, lastPaidHeight: 123456, registeredHeight: 123456 }; + Object.assign(r.platform, { protocolApp: 13, validatorSetSize: 100, peers: 8, nodeId: privateValue, proTxHash: privateValue, proposer: privateValue }); + r.dapi = { ok: true, height: 200, dapiVersion: '4.1.1', driveVersion: '4.1.2', chainId: 'evo1', error: privateValue, + tls: { issuer: privateValue }, query: { ok: true, epoch: 300, protocol: 13, error: privateValue } }; + r.components = { drive: { version: '4.1.2', running: true, restarts: 0, name: privateValue } }; + const normalized = validateMainnetReport(r, now); + const publicView = projectNetwork(DEFAULT_SETTINGS.networks.find((n) => n.name === 'mainnet'), evaluate(r), normalized, false); + assert.doesNotMatch(JSON.stringify([normalized, publicView]), /PRIVATE-NODE-IDENTITY|123456/); + assert.equal(publicView.summary.core.difficulty, 123.25); + assert.equal(publicView.summary.mainnet.bigBans, 876); + assert.equal(publicView.summary.mainnet.quorumCount, 20); + assert.equal(publicView.summary.mainnet.coreStall, false); + assert.equal(publicView.summary.platform.protocol, 13); + assert.equal(publicView.summary.platform.validatorSet, 100); + assert.deepEqual(publicView.summary.masternodes, { ready: 1, total: 1, pose: 0 }); + assert.deepEqual(publicView.summary.dapi, { ok: 1, total: 1 }); + assert.equal(publicView.summary.versions.drive['4.1.2'], 1); + assert.equal(publicView.hosts[0].publicIp, null); +}); + +test('configured private Evo failure cannot manufacture readiness or DAPI health from fallback', () => { + const r = fixture(); r.evo = true; + const view = evaluate(r); + assert.equal(view.level, 'down'); + assert.equal(view.summary.masternodes.ready, 0); + assert.equal(view.summary.dapi.ok, 0); + assert.equal(view.summary.core.height, 100); + assert.equal(view.summary.platform.height, 200); +}); + +test('private text in allowed-looking fields is rejected before persistence', () => { + const r = fixture(); r.evo = true; + r.core.subversion = 'PRIVATE-NODE-IDENTITY'; r.platform.version = '192.0.2.123'; + r.core.masternode = { state: 'PRIVATE-NODE-IDENTITY', type: '192.0.2.123' }; + r.dapi = { driveVersion: 'PRIVATE-NODE-IDENTITY', chainId: 'PRIVATE-NODE-IDENTITY' }; + r.components = { drive: { version: '192.0.2.123', running: true } }; + assert.doesNotMatch(JSON.stringify(validateMainnetReport(r, now)), /PRIVATE-NODE-IDENTITY|192\.0\.2\.123/); +}); + +test('service projection allowlists identity, fails stale/missing samples, preserves unknown', () => { + const r = fixture(); + r.serviceChecks = { at: now/1000, services: [{ id: 'insight', ok: true, ms: 3, height: 100, password: 'SECRET' }, + { id: 'quorums', ok: false, reason: 'stale-data', url: 'https://SECRET' }, { id: 'observer', ok: null, reason: 'SECRET' }, + { id: 'seed-2', ok: false }, { id: 'seed-3', ok: false, reason: 'SECRET' }] }; + let endpoints = validateMainnetReport(r,now).endpoints; + assert.equal(endpoints.find(e=>e.label.startsWith('Insight ·')).ok,true); + assert.equal(endpoints.find(e=>e.label.startsWith('Quorums ·')).ok,false); + assert.equal(endpoints.find(e=>e.label.startsWith('Independent')).ok,null); + assert.equal(endpoints.find(e=>e.label.startsWith('Independent')).error,'not observed'); + assert.equal(endpoints.find(e=>e.label.startsWith('Quorums ·')).error,'stale-data'); + assert.equal(endpoints.find(e=>e.label.startsWith('Platform seed 1')).error,'monitor sample missing or stale'); + assert.equal(endpoints.find(e=>e.label.startsWith('Platform seed 1')).ok,false); + for (const seed of ['Platform seed 2', 'Platform seed 3']) assert.deepEqual([endpoints.find(e=>e.label.startsWith(seed)).ok, endpoints.find(e=>e.label.startsWith(seed)).error], [false, 'probe-failed']); + assert.doesNotMatch(JSON.stringify(endpoints),/SECRET/); + assert.ok(endpoints.every(e=>typeof e.url==='string' && e.url.startsWith('https://'))); + assert.equal(endpoints.find(e=>e.label.startsWith('Insight ·')).status,'OK'); + r.serviceChecks.at -= 241; + endpoints = validateMainnetReport(r,now).endpoints; + assert.ok(endpoints.every(e=>e.ok===false && e.error==='monitor sample missing or stale')); +}); + +test('every Dash Core masternode state survives normalization', () => { + for (const state of ['READY', 'WAITING_FOR_PROTX', 'POSE_BANNED', 'REMOVED', 'OPERATOR_KEY_CHANGED', 'PROTX_IP_CHANGED', 'ERROR', 'UNKNOWN']) { + const r = fixture(); r.evo = true; r.core.masternode = { state, type: 'Evo', posePenalty: 0 }; + assert.equal(validateMainnetReport(r, now).hosts[0].probe.data.core.masternode.state, state); + } +}); + +test('a stale Evo report is unreachable and says so on the observer row', () => { + const r = fixture(); r.evo = true; r.core.masternode = { state: 'READY', type: 'Evo', posePenalty: 0 }; + const mainnet = DEFAULT_SETTINGS.networks.find((n) => n.name === 'mainnet'), state = validateMainnetReport(r, now); + assert.equal(state.hosts[0].role, 'validator'); + assert.ok(!evaluateNetwork(mainnet, state, DEFAULT_SETTINGS, now).rows[0].reasons.some((x) => /stale/.test(x.text))); + const view = evaluateNetwork(mainnet, state, DEFAULT_SETTINGS, now + 181_000); + assert.equal(view.level, 'unreachable'); + assert.equal(view.rows[0].level, 'unreachable'); + assert.ok(view.rows[0].reasons.some((x) => x.level === 'unreachable' && x.text === 'mainnet observer report is stale')); +}); + +test('an impossible calendar date is not a report or block time', () => { + const later = Date.parse('2026-10-01T08:00:00Z'), r = fixture(); + r.generatedAt = '2026-10-01T08:00:00+00:00'; r.platform.blockTime = '2026-02-30T12:00:00Z'; + const state = validateMainnetReport(r, later); + assert.equal(state.generatedAt, '2026-10-01T08:00:00.000Z'); + assert.equal(state.hosts[0].probe.data.tenderdash.blockTime, null); + assert.equal(Date.parse('2026-09-31T08:00:00Z'), later); + assert.throws(() => validateMainnetReport({ ...r, generatedAt: '2026-09-31T08:00:00Z' }, later), /timestamp invalid/); +}); + +test('a version suffix is a short label, never an address; a Core user-agent comment is dropped', () => { + const seen = (v) => { const r = fixture(); r.platform.version = v; r.core.subversion = `/Dash Core:${v}/`; const d = validateMainnetReport(r, now).hosts[0].probe.data; return [d.tenderdash.version, d.core.subversion]; }; + for (const v of ['23.0.2', '1.5.0-dev.2', '2.1.0-rc.1', '3.0.0-hotfix.1', '4.1.2', '1.2.3+build.5', '2.0.0-pr.1234', `1.2.3-${'a'.repeat(32)}`]) assert.deepEqual(seen(v), [v, `/Dash Core:${v}/`], v); + assert.equal(seen('unreleased-2.0.0')[0], 'unreleased-2.0.0'); + for (const v of ['1.2.3-192.0.2.123', '1.2.3-10-0-0-5', '1.2.3+1.2.3.4', '1.2.3-rc192.0.2.123', '1.2.3-rc.10-0-0-5', '1.2.3-7', `1.2.3-${'a'.repeat(33)}`]) assert.deepEqual(seen(v), [null, null], v); + const core = (subversion) => { const r = fixture(); r.core.subversion = subversion; return validateMainnetReport(r, now).hosts[0].probe.data.core.subversion; }; + assert.equal(core('/Dash Core:23.1.0/'), '/Dash Core:23.1.0/'); + assert.equal(core('/Dash Core:23.1.0(observer)/'), '/Dash Core:23.1.0/'); + assert.equal(core('/Dash Core:23.1.0-rc.2(PRIVATE-NODE-IDENTITY; 192.0.2.123)/'), '/Dash Core:23.1.0-rc.2/'); + for (const bad of ['/Dash Core:23.1.0(observer)(two)/', '/Dash Core:23.1.0(observer)x/', '/Dash Core:23.1.0(observer/', '/Dash Core:23.1.0-192.0.2.123(observer)/', '/Dash Core:(observer)/']) assert.equal(core(bad), null, bad); +}); + +test('a service sample fresh at ingest expires when read later; a still-fresh one stays OK', () => { + const mainnet = DEFAULT_SETTINGS.networks.find((n) => n.name === 'mainnet'), r = fixture(); + const ids = ['quorums', 'insight', 'seed-1', 'seed-2', 'seed-3', 'bootstrap', 'quorums-tls', 'insight-tls', 'observer', 'core', 'platform', 'chainlocks']; + r.serviceChecks = { at: now / 1000 - 200, services: ids.map((id) => ({ id, ok: true, ms: 3, height: 100 })) }; + r.serviceChecks.services[0] = { id: 'quorums', ok: null }; + const state = validateMainnetReport(r, now); + assert.equal(state.endpoints.length, ids.length); + assert.ok(state.endpoints.every((e) => e.sampledAt === r.serviceChecks.at)); + const view = (at) => { const e = evaluateNetwork(mainnet, state, DEFAULT_SETTINGS, at); return { level: e.level, endpoints: projectNetwork(mainnet, e, state, false).endpoints }; }; + const fresh = view(now + 40_000); + assert.equal(fresh.level, 'ok'); + assert.deepEqual(fresh.endpoints.map((e) => e.ok), [null, ...ids.slice(1).map(() => true)]); + assert.equal(fresh.endpoints[0].error, 'not observed'); + assert.deepEqual([fresh.endpoints[1].status, fresh.endpoints[1].ms, fresh.endpoints[1].height], ['OK', 3, 100]); + const expired = view(now + 41_000); + assert.equal(expired.level, 'warn'); + assert.ok(expired.endpoints.every((e) => e.ok === false && e.status === null && e.ms === null && e.error === 'monitor sample missing or stale')); + assert.ok([...fresh.endpoints, ...expired.endpoints].every((e) => !('sampledAt' in e))); + // Rows stored before the sample time was kept cannot be shown as OK. + const legacy = { ...state, endpoints: state.endpoints.map((e) => ({ ...e, sampledAt: undefined })) }; + const old = evaluateNetwork(mainnet, legacy, DEFAULT_SETTINGS, now); + assert.equal(old.level, 'warn'); + assert.ok(projectNetwork(mainnet, old, legacy, false).endpoints.every((e) => e.ok === false)); + // Other networks' endpoint rows pass through untouched. + const other = [{ label: 'Seed', kind: 'dapi', url: 'https://seed.example', ok: true, status: 200, ms: 5 }]; + assert.deepEqual(evaluateNetwork(mainnet, { ...state, endpoints: other }, DEFAULT_SETTINGS, now + 41_000).endpoints, other); +}); + +test('a DAPI on another chain is a failed DAPI and its chain ID is never stored', () => { + const evo = (dapi) => { const r = fixture(); r.evo = true; r.core.masternode = { state: 'READY', type: 'Evo', posePenalty: 0 }; r.dapi = { ok: true, height: 200, ...dapi }; return r; }; + const disagree = (view) => view.rows[0].reasons.some((x) => x.text === 'DAPI and consensus chain IDs disagree'); + const wrong = evo({ chainId: 'PRIVATE-OTHER-CHAIN' }), state = validateMainnetReport(wrong, now).hosts[0].probe.data.dapi; + assert.deepEqual([state.ok, state.chainId], [false, 'other']); + assert.doesNotMatch(JSON.stringify(validateMainnetReport(wrong, now)), /PRIVATE-OTHER-CHAIN/); + assert.ok(disagree(evaluate(wrong))); + assert.equal(evaluate(wrong).level, 'down'); + assert.deepEqual(evaluate(wrong).summary.dapi, { ok: 0, total: 1 }); + for (const [dapi, chainId] of [[{ chainId: 'evo1' }, 'evo1'], [{}, null], [{ chainId: '' }, null]]) { + const right = evo(dapi), stored = validateMainnetReport(right, now).hosts[0].probe.data.dapi; + assert.deepEqual([stored.ok, stored.chainId], [true, chainId]); + assert.ok(!disagree(evaluate(right))); + assert.deepEqual(evaluate(right).summary.dapi, { ok: 1, total: 1 }); + } +}); diff --git a/src/App.jsx b/src/App.jsx index 997faef..4f85b6c 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -9,6 +9,7 @@ import Settings from './pages/Settings.jsx'; import NewDevnet from './pages/NewDevnet.jsx'; import ResetPlatform from './pages/ResetPlatform.jsx'; import CI from './pages/CI.jsx'; +import Websites from './pages/Websites.jsx'; import Queue from './pages/Queue.jsx'; import Aws from './pages/Aws.jsx'; import Remediation from './pages/Remediation.jsx'; @@ -28,6 +29,7 @@ export default function App() { else if (parts[0] === 'settings') page = ; else if (parts[0] === 'ci' && parts[1] === 'queue') page = ; else if (parts[0] === 'ci') page = ; + else if (parts[0] === 'websites') page = ; else if (parts[0] === 'aws') page = ; else if (parts[0] === 'remediation') page = ; else if (parts[0] === 'devnets' && parts[1] === 'new') page = ; @@ -60,6 +62,7 @@ function Header({ networks, active, session }) { {<>