diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3a9abd..6eed415 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,6 +70,9 @@ jobs: docker-stack: name: docker build + pytest (live stack, kill, join and leave tests) - engine ${{ matrix.engine }} runs-on: ubuntu-latest + env: + # the dashboard's admin account for this throwaway stack (compose creates it; the tests log in with it) + MEDCHAIN_ADMIN_PASSWORD: ci-dashboard-admin-password strategy: fail-fast: false matrix: diff --git a/README.md b/README.md index 480376e..55a1ec9 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ docker compose ps | --- | --- | --- | | `pki` (container `medchain-pki`) | - | Runs once on start: `scripts/pki.py` issues the demo network CA, each node's, the directory's and the observer's TLS certificate, each node's Ed25519 update-signing key and each hospital's directory credential into `./.pki/` (gitignored). Later starts keep what exists. | | `directory` | 8100 | The membership directory (`directory/`): decides where a hospital sits in the chain and tells hospitals who to connect to when one joins or leaves. Its own SQLite store, not Postgres. See [The directory](#the-directory). | -| `hospital-a` ... `hospital-d` | 8001 ... 8004 | FastAPI node over HTTPS: `GET /health`, `GET /status`, `POST /round/start`, `POST /update`, `GET /snapshot`, `GET /metrics`, `GET`/`POST /membership`, `POST /membership/leave` (+ `POST /round/pause`, `/round/resume`, and the `POST /assess*` risk-assessment endpoints). All run the same image, and the mounted `config/hospital-*.yaml` decides which hospital it is and which engine it runs. Each node mounts only its own data slice. `hospital-d` (8004, the Swiss data) is the mid-demo joiner and only starts on request (profile `join`). `hospital-e` (8005) is a spare (profile `spare`). | +| `hospital-a` ... `hospital-d` | 8001 ... 8004 | FastAPI node over HTTPS: `GET /health`, `GET /status`, `POST /round/start`, `POST /update`, `GET /snapshot`, `GET /metrics`, `GET`/`POST /membership`, `POST /membership/leave` (+ `POST /round/pause`, `/round/resume`, `/round/stop`, and the `POST /assess*` risk-assessment endpoints). All run the same image, and the mounted `config/hospital-*.yaml` decides which hospital it is and which engine it runs. Each node mounts only its own data slice. `hospital-d` (8004, the Swiss data) is the mid-demo joiner and only starts on request (profile `join`). `hospital-e` (8005) is a spare (profile `spare`). | | `observer` | 8200 | Takes the nodes' telemetry (`POST /ingest`, over HTTPS with its token; `observer/`) and writes it to Postgres with the same schema. Nodes push to it from a background queue, so training never waits for it. Nodes on other machines need only its URL and token, never Postgres credentials. | | `postgres` (container `medchain-postgres`) | 5432, loopback only | Holds `nodes`, `runs`, `rounds`, `updates_meta`, `metrics` and `audit_logs`. Only the observer writes it and only the dashboard reads it. | | `dashboard` | 8080 | Observer UI. It reads Postgres and pushes snapshots and update events over `/ws`. | @@ -211,7 +211,7 @@ configured round limit (`training.rounds`, 400). Q-GADMM stops earlier, on the same round everywhere, once every edge's residual has stayed below epsilon for 3 rounds (about round 70 for this three-hospital chain at b=2; a longer chain takes longer, which is expected). A request without the header gets `401`. The -same header works for `POST /round/pause` and `POST /round/resume`. +same header works for `POST /round/pause`, `POST /round/resume` and `POST /round/stop`. Once the run finishes, you can read any node's per-round history: @@ -221,9 +221,22 @@ curl --cacert .pki/ca.crt https://localhost:8002/metrics ### 2. Open the dashboard -Open in a browser. - -- Press **START TRAINING ROUND** in the top bar. The button changes to show +Open in a browser and log in. The dashboard has one admin +account and shows nothing, not even the live snapshot, to anyone without its session +(`dashboard/server/auth.js`). The account (user `admin`) is created on first run from +`MEDCHAIN_ADMIN_PASSWORD` (at least 10 characters): set it before `make up`, or in +`hub.env` for `make hub`. Without it nobody can log in, and the login screen says to +set it and restart the dashboard. + +The password is stored as a bcrypt hash. The session is an httpOnly, SameSite=Strict +cookie (12 hours; **LOG OUT** in the top bar ends it), and Postgres keeps only its +SHA-256. Five wrong passwords from one address lock it out for 5 minutes. **JOIN CODES** +(admin) creates and revokes the one-time codes hospitals enroll with (see +[Join with a code instead of a kit](#join-with-a-code-instead-of-a-kit)). **NODES** +shows each hospital's signed proof of origin. + +- Press **START TRAINING ROUND** in the top bar. While a run is going, **STOP** ends it on every + hospital (the way out of a run a dead neighbour keeps from finishing). The button changes to show `TRAINING: ROUND n OF 400`, and a **PAUSE** button becomes active. - Use the top navigation (**TOPOLOGY**, **TRAINING MONITOR**, **COMMUNICATION**, **AUDIT LOG**) to watch the run live. With @@ -411,8 +424,8 @@ epsilon on four or more. ### The directory -`directory/` is a small FastAPI service with three calls: `POST /register`, -`POST /leave` and `GET /membership`. Be clear about what it is: it **does +`directory/` is a small FastAPI service with three membership calls: `POST /register`, +`POST /leave` and `GET /membership` (plus `POST /enroll` for join codes, below). Be clear about what it is: it **does coordinate membership**. It decides where a new hospital goes in the chain and tells the existing hospitals who to connect to, so it is more than a phone book. It is a **single point of failure for joins and leaves, not for @@ -615,7 +628,7 @@ is never re-keyed. Every hospital kit holds: - `README.md`, with the exact commands, including how to leave the chain. `--image repo[:tag]` names a different image (for example a private registry). By -default the kits use the published `ghcr.io/denimworld12/medchain-node:v1.0.0`. +default the kits use the published `ghcr.io/denimworld12/medchain-node:v1.1.0`. The directory kit is the hub's. It holds the directory's config, its TLS certificate, its document-signing key and `hospitals.yaml` (who may register: ids and credential @@ -672,6 +685,92 @@ with `-` and other characters turned into `_`. runs next to Postgres. It never coordinates training. A node with no observer still trains and still serves `/status` and `/metrics`. +### Join with a code instead of a kit + +A kit has to be made, zipped and sent, and it carries the network's shared secret. +For a hospital on another laptop there is a second way in, next to the kits (which +keep working unchanged): a **join code**. + +1. The organiser creates a code on the dashboard's admin page. It works **once** and + **expires** (30 minutes by default); the organiser can revoke it. The directory + keeps only its SHA-256. +2. On the hospital's laptop, `python -m node.enroll` (run by the install script in + `deploy/install/`, inside the published image) makes the hospital's keys **on that + laptop**: a TLS key, an Ed25519 signing key and a directory credential. It sends the + hub only a certificate signing request, the public signing key and the credential's + hash, with the display name the person typed, to `POST /enroll` on the directory. + It proves it holds the code with an HMAC keyed by the code's hash, so the code itself + never crosses the network. +3. The directory checks the code (known, unused, unrevoked, unexpired, the right + secret; five wrong tries revoke it), marks it used, and answers with: a certificate + for the hospital's key from the network CA, the CA certificate, the directory's + document key and certificate, the observer's certificate and port, an **observer + token for this hospital alone**, a generated node id, the engine settings, a data + slice, and the network secret. Its answer carries an HMAC under the same key, and + the node checks it, the nonce, and that the TLS key that answered is the + directory's, before trusting any of it. +4. The node writes a kit folder with the same layout as a provisioned one, so + `deploy/node.yml` runs it. + +On the hospital's laptop this is one command: `deploy/install/install.ps1` (Windows) +or `deploy/install/install.sh` (macOS, Linux), fetched from the release tag. It checks +Docker, Tailscale, the hub and disk space (each with a plain-English fix), asks for +the name and the code, reads the Tailscale address, enrolls inside the published +image (no Python, no checkout) and starts the node. Running it again keeps the +enrollment. The dashboard's **JOIN CODES** page shows the command with the hub's +address filled in (`HUB_ADDRESS`). The secret goes to `pki/network/shared_secret` + (`SHARED_SECRET_FILE`): nobody types it, nothing prints it. + +**Names.** The person enrolling types the hospital's display name as free text; it +is what the dashboard, the node's logs and the audit log show. No two hospitals may +share one (compared ignoring case and spacing; the code stays valid for another try). +The node id is separate and generated by the directory, a slug of the name plus random +hex (`st-marys-leeds-3f9a`). TLS pins, signatures and chain placement stay keyed on the +id and its keys, never on the name, and an enrolled hospital always appears under the +name it enrolled with. `hospital-a` ... `hospital-e` stay as they are for `make up` +and the kits. + +The organiser can take a hospital out on its behalf (`POST /admin/members//remove`, +the **Remove** button on **NODES**): a laptop that is off cannot call `/leave` itself, and +until it is out, the hospitals beyond it never start a run (once such a run ends, the +control strip flags it as incomplete). An enrolled hospital is forgotten at the same time: +its credential and observer token stop working and its name is free again, even if it +was once in the chain. Unlike `/leave`, this works in a two-hospital chain: the hospital +left alone waits there, unable to start a run, until another one joins. + +Every attempt is in the audit log (`enrolled`, `enroll_rejected`, +`join_code_created`, `join_code_revoked`). An enrolled hospital may only register +with the keys it enrolled with. Its observer token only writes rows as that hospital; +the observer checks it against `hospital_keys`, which only the directory writes. The +directory needs the CA key for this: `provision.py` puts it in the hub kit +(`pki/ca.key`), and `deploy/hub.yml` mounts `data/slices/` and +`config/hospital-a.yaml` (the engine settings) into it. + +### Proof of origin on the dashboard + +Every node with a signing key and an observer sends the observer a status message every +10 seconds (`node/proof.py`, `POST /proof`), signed with the Ed25519 key that signs its +training updates. It holds the computer's hostname, OS and version, uptime and Tailscale +device name (read on the host by the install script; without it, what the container +sees, labelled as such), the round-trip time it measures right then to each chain +neighbour over the pinned TLS links training uses, and how many data rows it holds (the +count only). It also carries a per-start boot id and a rising sequence number. + +The observer checks the signature against the key the directory has on record for that +hospital (`hospital_keys`, written by the directory when the hospital registers or +enrolls). It refuses a message that does not verify, comes from a hospital with no key +on record or is a replay, and writes each refusal to the +audit log (`proof_rejected`, at most once per hospital and reason every 5 minutes). +Freshness is judged by arrival order (the boot id and sequence), not by the sender's +clock, which on a laptop's Docker VM drifts after sleep; the page shows the clock skew +when it exceeds a minute. A caller without that hospital's observer token (or the +network's) is refused before any of this and only logged, so it cannot mark someone +else's hospital rejected. The dashboard's **Nodes** page shows each hospital's facts +with a **Signature verified** badge and the key's fingerprint, or **Rejected** with the +reason. This is in addition to the Start/Pause controls. One limit: the host's uptime +counts from the boot time the install script saw, so after a reboot, run the installer +again to refresh it. The round-trip times and data rows are always live. + ### Prove it `scripts/verify_multihost.py` is the acceptance test, on real laptops or on one @@ -890,8 +989,8 @@ leaves, though not for training. - **Observer service and dashboard**: nodes push their telemetry to the observer (`observer/`, `POST /ingest`), which writes Postgres; the dashboard reads it. Neither coordinates training. The dashboard's buttons relay a - single start/pause request to one node in the chain, which floods it to the - others; it learns about each `/update` from the `updates_meta` rows the nodes + single start/pause/resume request to one node in the chain, which floods it to the + others (Stop goes to every alive node, so it gets past a dead one); it learns about each `/update` from the `updates_meta` rows the nodes report. Killing the dashboard does not affect a run (tested). It follows membership from what the nodes write: the topology page draws the current chain in order, the consensus panel shows only the current links and resets with each diff --git a/config/directory.yaml b/config/directory.yaml index 9b182ff..aaa78c2 100644 --- a/config/directory.yaml +++ b/config/directory.yaml @@ -14,3 +14,17 @@ tls: cert: /pki/directory/tls.crt key: /pki/directory/tls.key ca: /pki/ca.crt +# the hub's admin token, for the dashboard's admin page (join codes): made on first start; the +# dashboard reads the same file +admin_token_file: /hub/admin_token +# Join codes (directory/enroll.py): a hospital on another laptop enrolls with a one-time code +# from the dashboard instead of a kit. Its own keys stay on its laptop; the directory issues +# its certificate with the network CA, so it needs the CA key. +enrollment: + ca_cert: /pki/ca.crt + ca_key: /pki/ca.key + observer_cert: /pki/observer/tls.crt # enrolled hospitals pin the observer's key + observer_port: 8200 + slices_dir: /slices # the data slices a code hands out + node_template: /templates/node.yaml # its engine settings are every hospital's + code_ttl_minutes: 30 diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index 7027fc6..6df334a 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -8,6 +8,7 @@ "name": "medchain-dashboard", "version": "0.1.0", "dependencies": { + "bcryptjs": "^2.4.3", "pg": "^8.13.1", "ws": "^8.18.0" }, @@ -1893,6 +1894,12 @@ "node": ">=6.0.0" } }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "1.1.21", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", diff --git a/dashboard/package.json b/dashboard/package.json index 7356fcd..7486c42 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -12,6 +12,7 @@ "test": "node --test server/*.test.js" }, "dependencies": { + "bcryptjs": "^2.4.3", "pg": "^8.13.1", "ws": "^8.18.0" }, diff --git a/dashboard/server/admin.js b/dashboard/server/admin.js new file mode 100644 index 0000000..777eba3 --- /dev/null +++ b/dashboard/server/admin.js @@ -0,0 +1,32 @@ +// The admin page's join codes: relayed to the directory's admin API (directory/app.py, /admin/join-codes) +// with the hub's admin token, which the directory writes on first start to a volume the dashboard reads. +// The full code exists only in the answer to "create"; the directory keeps its hash. + +import fs from "node:fs"; + +const DIRECTORY = (process.env.DIRECTORY_ADMIN_URL || "https://directory:8100").replace(/\/$/, ""); +const TOKEN_FILE = process.env.DIRECTORY_ADMIN_TOKEN_FILE || "/hub/admin_token"; + +function token() { + try { + return fs.readFileSync(TOKEN_FILE, "utf8").trim(); + } catch { + return ""; + } +} + +export async function directoryAdmin(method, path, body) { + const t = token(); + if (!t) return { status: 503, body: { detail: `No hub admin token at ${TOKEN_FILE}: is the directory running?` } }; + try { + const resp = await fetch(`${DIRECTORY}/admin${path}`, { + method, + headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(8000), + }); + return { status: resp.status, body: await resp.json().catch(() => ({})) }; + } catch (err) { + return { status: 502, body: { detail: `The directory is unreachable: ${err.message}` } }; + } +} diff --git a/dashboard/server/auth.js b/dashboard/server/auth.js new file mode 100644 index 0000000..1c72be2 --- /dev/null +++ b/dashboard/server/auth.js @@ -0,0 +1,175 @@ +// The dashboard's one admin account and its sessions. Everything except the login screen itself +// (the built UI and /api/auth/*) needs a session: the snapshot WebSocket, Start / Pause, the risk +// assessment relay and the admin pages. +// +// - One admin account, created on first run from DASHBOARD_ADMIN_PASSWORD (compose maps +// MEDCHAIN_ADMIN_PASSWORD to it). Unset, there is no account and the login screen says so. The password is stored as a bcrypt hash (cost 12), never in the clear. +// - A session is a random 32-byte token in an httpOnly, SameSite=Strict cookie; Postgres keeps only +// its SHA-256 and expiry (SESSION_HOURS, default 12). Logout deletes it. +// - Five failed logins from one address lock that address out for 5 minutes. +// - A state-changing request whose Origin is another site is refused (SameSite already keeps the +// cookie off it; this is the second lock). +// +// These tables are the dashboard's own; it still never writes the training tables. + +import crypto from "node:crypto"; +import bcrypt from "bcryptjs"; + +export const COOKIE = "medchain_session"; +const SESSION_HOURS = Number(process.env.SESSION_HOURS || 12); +const BCRYPT_COST = 12; +export const MIN_PASSWORD = 10; +const LOCKOUT = { failures: 5, windowMs: 5 * 60 * 1000 }; +// compared against for an unknown username, so a wrong name and a wrong password take the same time +const NO_SUCH_USER = bcrypt.hashSync(crypto.randomBytes(16).toString("hex"), BCRYPT_COST); + +const SCHEMA = ` +CREATE TABLE IF NOT EXISTS admin_users ( + username TEXT PRIMARY KEY, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + one_admin BOOLEAN NOT NULL DEFAULT true UNIQUE CHECK (one_admin) -- exactly one account +); +CREATE TABLE IF NOT EXISTS admin_sessions ( + token_sha256 TEXT PRIMARY KEY, + username TEXT NOT NULL REFERENCES admin_users (username) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL +);`; + +const sha256 = (s) => crypto.createHash("sha256").update(s).digest("hex"); + +export function parseCookies(header = "") { + const out = {}; + for (const part of header.split(";")) { + const i = part.indexOf("="); + if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); + } + return out; +} + +export function sessionCookie(token, { secure = false, maxAge = SESSION_HOURS * 3600 } = {}) { + return `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; +} + +// A browser sends Origin on cross-site POSTs; when it is there it must be this dashboard. +export function sameOrigin(req) { + const origin = req.headers.origin; + if (!origin) return true; + try { + return new URL(origin).host === req.headers.host; + } catch { + return false; + } +} + +export function checkNewPassword(username, password) { + if (!/^[A-Za-z0-9._-]{3,40}$/.test(username || "")) return "The username is 3 to 40 letters, digits, dots, dashes or underscores."; + if (typeof password !== "string" || password.length < MIN_PASSWORD) return `The password needs at least ${MIN_PASSWORD} characters.`; + if (password.length > 72) return "The password can be at most 72 characters (bcrypt's limit)."; + return null; +} + +// Failed logins per client address (in memory: a restart forgets them, which is fine for a lockout). +export class Lockout { + constructor({ failures, windowMs } = LOCKOUT, now = () => Date.now()) { + Object.assign(this, { failures, windowMs, now, seen: new Map() }); + } + + locked(who) { + const times = (this.seen.get(who) || []).filter((t) => this.now() - t < this.windowMs); + this.seen.set(who, times); + return times.length >= this.failures; + } + + fail(who) { + this.seen.set(who, [...(this.seen.get(who) || []), this.now()]); + } + + clear(who) { + this.seen.delete(who); + } +} + +export class Auth { + constructor(pool, { adminUser = process.env.DASHBOARD_ADMIN_USER || "admin", + adminPassword = process.env.DASHBOARD_ADMIN_PASSWORD || "" } = {}) { + Object.assign(this, { pool, adminUser, adminPassword, ready: null, lockout: new Lockout() }); + } + + // Create the tables, and make the one account match DASHBOARD_ADMIN_PASSWORD, once Postgres answers. A changed + // password (or username) replaces the old one and ends every existing session. + async init() { + this.ready ||= (async () => { + await this.pool.query(SCHEMA); + if (this.adminPassword) { + const problem = checkNewPassword(this.adminUser, this.adminPassword); + if (problem) throw new Error(`DASHBOARD_ADMIN_PASSWORD: ${problem}`); + const { rows } = await this.pool.query(`SELECT username, password_hash FROM admin_users`); + const same = rows[0]?.username === this.adminUser && (await bcrypt.compare(this.adminPassword, rows[0].password_hash)); + if (!same) { + const hash = await bcrypt.hash(this.adminPassword, BCRYPT_COST); + await this.pool.query(`DELETE FROM admin_sessions`); + await this.pool.query( + `INSERT INTO admin_users (username, password_hash) VALUES ($1, $2) + ON CONFLICT (one_admin) DO UPDATE SET username = EXCLUDED.username, password_hash = EXCLUDED.password_hash`, + [this.adminUser, hash], + ); + } + } + })().catch((err) => { + this.ready = null; // try again on the next request + throw err; + }); + return this.ready; + } + + async accountExists() { + await this.init(); + const { rows } = await this.pool.query(`SELECT count(*)::int AS n FROM admin_users`); + return rows[0].n > 0; + } + + async login(username, password, who) { + await this.init(); + if (this.lockout.locked(who)) { + return { ok: false, status: 429, detail: "Too many failed logins from here: wait 5 minutes and try again." }; + } + const { rows } = await this.pool.query(`SELECT password_hash FROM admin_users WHERE username = $1`, [username || ""]); + const good = await bcrypt.compare(String(password || ""), rows[0]?.password_hash || NO_SUCH_USER); + if (!rows.length || !good) { + this.lockout.fail(who); + return { ok: false, status: 401, detail: "Wrong username or password." }; + } + this.lockout.clear(who); + return { ok: true, ...(await this.newSession(username)) }; + } + + async newSession(username) { + const token = crypto.randomBytes(32).toString("base64url"); + await this.pool.query( + `INSERT INTO admin_sessions (token_sha256, username, expires_at) + VALUES ($1, $2, now() + make_interval(hours => $3))`, + [sha256(token), username, SESSION_HOURS], + ); + await this.pool.query(`DELETE FROM admin_sessions WHERE expires_at < now()`); + return { token, username }; + } + + // The logged-in username for this request's cookie, or null. + async user(req) { + const token = parseCookies(req.headers.cookie)[COOKIE]; + if (!token) return null; + await this.init(); + const { rows } = await this.pool.query( + `SELECT username FROM admin_sessions WHERE token_sha256 = $1 AND expires_at > now()`, + [sha256(token)], + ); + return rows[0]?.username || null; + } + + async logout(req) { + const token = parseCookies(req.headers.cookie)[COOKIE]; + if (token) await this.pool.query(`DELETE FROM admin_sessions WHERE token_sha256 = $1`, [sha256(token)]); + } +} diff --git a/dashboard/server/auth.test.js b/dashboard/server/auth.test.js new file mode 100644 index 0000000..e140512 --- /dev/null +++ b/dashboard/server/auth.test.js @@ -0,0 +1,89 @@ +// node --test: the admin login (server/auth.js), with an in-memory stand-in for Postgres. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { Auth, COOKIE, Lockout, checkNewPassword, parseCookies, sameOrigin, sessionCookie } from "./auth.js"; + +test("the session cookie is httpOnly, SameSite=Strict, and Secure over HTTPS", () => { + const c = sessionCookie("tok", { secure: false, maxAge: 60 }); + assert.match(c, new RegExp(`^${COOKIE}=tok; HttpOnly; SameSite=Strict; Path=/; Max-Age=60$`)); + assert.match(sessionCookie("tok", { secure: true }), /; Secure$/); + assert.equal(parseCookies(`a=1; ${COOKIE}=x%2By; b`)[COOKIE], "x+y"); +}); + +test("a request from another site is refused, one from the dashboard or without Origin is not", () => { + const req = (origin) => ({ headers: { host: "localhost:8080", ...(origin ? { origin } : {}) } }); + assert.ok(sameOrigin(req())); + assert.ok(sameOrigin(req("http://localhost:8080"))); + assert.ok(!sameOrigin(req("http://evil.example"))); + assert.ok(!sameOrigin(req("not a url"))); +}); + +test("five failed logins lock an address out for the window, and only that address", () => { + let now = 0; + const l = new Lockout({ failures: 5, windowMs: 1000 }, () => now); + for (let i = 0; i < 5; i++) { + assert.ok(!l.locked("a")); + l.fail("a"); + } + assert.ok(l.locked("a") && !l.locked("b")); + now = 1001; + assert.ok(!l.locked("a"), "the window passed"); +}); + +test("the admin account needs a sensible username and a 10-72 character password", () => { + assert.equal(checkNewPassword("admin", "correct horse"), null); + assert.match(checkNewPassword("ad", "correct horse"), /username/); + assert.match(checkNewPassword("admin", "short"), /at least 10/); + assert.match(checkNewPassword("admin", "x".repeat(73)), /72/); +}); + +// admin_users (at most one row: its one_admin column is unique) and admin_sessions, as Postgres would hold them +function fakePool() { + const users = new Map(); + const sessions = new Set(["an-old-session"]); + return { + users, + sessions, + async query(sql, params = []) { + if (sql.includes("INSERT INTO admin_users")) { + users.clear(); // ON CONFLICT (one_admin) DO UPDATE: the one row becomes this one + users.set(params[0], params[1]); + return { rowCount: 1, rows: [] }; + } + if (sql.includes("DELETE FROM admin_sessions")) { + sessions.clear(); + return { rowCount: 0, rows: [] }; + } + if (sql.includes("SELECT username, password_hash")) { + return { rows: [...users].map(([username, password_hash]) => ({ username, password_hash })) }; + } + if (sql.includes("count(*)")) return { rows: [{ n: users.size }] }; + return { rowCount: 0, rows: [] }; + }, + }; +} + +test("the admin account comes only from DASHBOARD_ADMIN_PASSWORD: unset, there is none", async () => { + const none = new Auth(fakePool(), { adminUser: "admin", adminPassword: "" }); + assert.equal(await none.accountExists(), false); + const pool = fakePool(); + const set = new Auth(pool, { adminUser: "admin", adminPassword: "a-long-enough-password" }); + assert.equal(await set.accountExists(), true); + assert.deepEqual([...pool.users.keys()], ["admin"]); +}); + +test("a changed DASHBOARD_ADMIN_PASSWORD replaces the old one and ends every session; an unchanged one keeps them", async () => { + const pool = fakePool(); + await new Auth(pool, { adminUser: "admin", adminPassword: "the-first-password" }).init(); + const first = pool.users.get("admin"); + pool.sessions.add("logged-in"); + await new Auth(pool, { adminUser: "admin", adminPassword: "the-first-password" }).init(); + assert.equal(pool.users.get("admin"), first, "a restart with the same password changes nothing"); + assert.ok(pool.sessions.has("logged-in")); + await new Auth(pool, { adminUser: "admin", adminPassword: "a-new-better-password" }).init(); + assert.notEqual(pool.users.get("admin"), first); + assert.equal(pool.sessions.size, 0, "everyone logged in with the old password is logged out"); + await new Auth(pool, { adminUser: "organiser", adminPassword: "a-new-better-password" }).init(); + assert.deepEqual([...pool.users.keys()], ["organiser"], "still exactly one account"); +}); diff --git a/dashboard/server/index.js b/dashboard/server/index.js index ef5ad39..78b6e38 100644 --- a/dashboard/server/index.js +++ b/dashboard/server/index.js @@ -5,6 +5,9 @@ // the nodes; killing this process does not affect it. It also relays risk // assessment requests to the hospital node the user picks (inference only; the // patient inputs pass straight through and are not stored). +// +// Everything but the login screen needs the admin's session (server/auth.js): the snapshot +// WebSocket, the buttons, the relay and the admin page's join codes (server/admin.js). import http from "node:http"; import fs from "node:fs"; @@ -13,15 +16,22 @@ import { fileURLToPath } from "node:url"; import pg from "pg"; import { WebSocketServer } from "ws"; import { buildSnapshot, latestUpdateId, STALE_AFTER_S, updatesSince } from "./snapshot.js"; +import { Auth, sameOrigin, sessionCookie } from "./auth.js"; +import { directoryAdmin } from "./admin.js"; +import { relayTo } from "./relay.js"; const PORT = Number(process.env.PORT || 8080); const DIST = process.env.DASHBOARD_DIST || fileURLToPath(new URL("../dist", import.meta.url)); const TICK_MS = Number(process.env.SNAPSHOT_INTERVAL_MS || 1000); const UPDATES_TICK_MS = Number(process.env.UPDATES_INTERVAL_MS || 250); const SHARED_SECRET = process.env.MEDCHAIN_SHARED_SECRET || ""; +// the published install scripts (deploy/install/) the Join codes page links to, at their release tag +const INSTALLER_VERSION = process.env.INSTALLER_VERSION || "v1.1.0"; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 }); pool.on("error", (err) => console.warn("postgres pool error:", err.message)); +const auth = new Auth(pool); +auth.init().catch((err) => console.warn("admin accounts not ready yet:", err.message)); const TYPES = { ".html": "text/html; charset=utf-8", @@ -33,8 +43,8 @@ const TYPES = { ".json": "application/json", }; -function send(res, status, body, type = "application/json") { - res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store" }); +function send(res, status, body, type = "application/json", headers = {}) { + res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", ...headers }); res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body)); } @@ -48,7 +58,7 @@ async function readJson(req) { } } -// Relay a button press to one alive chain member; the node floods it to its neighbours. +// Relay a button press to the alive chain members (server/relay.js decides which ones). // (A hospital that left the chain has no neighbours to flood to, so it is skipped.) async function relay(action, body) { const { rows } = await pool.query( @@ -56,24 +66,15 @@ async function relay(action, body) { ORDER BY node_id`, [STALE_AFTER_S], ); - if (!rows.length) return { status: 503, body: { detail: "No hospital node is alive." } }; - let last = null; - for (const node of rows) { - try { - const resp = await fetch(`${node.url}/round/${action}`, { - method: "POST", - headers: { "Content-Type": "application/json", "X-MedChain-Secret": SHARED_SECRET }, - body: JSON.stringify(action === "start" ? { rounds: body.rounds, initiated_by: "dashboard" } : {}), - signal: AbortSignal.timeout(8000), - }); - const data = await resp.json().catch(() => ({})); - if (resp.ok || resp.status === 409) return { status: resp.status, body: { via: node.node_id, ...data } }; - last = { status: resp.status, body: { via: node.node_id, ...data } }; - } catch (err) { - last = { status: 502, body: { detail: `${node.node_id} unreachable: ${err.message}` } }; - } - } - return last; + return relayTo(action, body, rows, async (node, payload) => { + const resp = await fetch(`${node.url}/round/${action}`, { + method: "POST", + headers: { "Content-Type": "application/json", "X-MedChain-Secret": SHARED_SECRET }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(8000), + }); + return { status: resp.status, data: await resp.json().catch(() => ({})) }; + }); } const MAX_ASSESS_BYTES = 16 * 1024 * 1024; @@ -128,11 +129,69 @@ function serveStatic(req, res) { fs.createReadStream(file).pipe(res); } +// /api/auth/*: who is logged in (and whether the admin account exists), login and logout. +async function authRoute(req, res, action) { + const cookie = (token, maxAge) => ({ "Set-Cookie": sessionCookie(token, { secure: !!req.socket.encrypted, maxAge }) }); + if (action === "me" && req.method === "GET") { + const user = await auth.user(req); + return send(res, 200, { authenticated: !!user, username: user, account_exists: !!user || (await auth.accountExists()) }); + } + if (req.method !== "POST") return send(res, 405, { detail: "method not allowed" }); + if (action === "logout") { + await auth.logout(req); + return send(res, 200, { authenticated: false }, "application/json", cookie("", 0)); + } + const body = await readJson(req); + const out = action === "login" ? await auth.login(body.username, body.password, req.socket.remoteAddress) + : { ok: false, status: 404, detail: "not found" }; + if (!out.ok) return send(res, out.status, { detail: out.detail }); + return send(res, 200, { authenticated: true, username: out.username }, "application/json", cookie(out.token)); +} + +// /api/admin/join-codes...: create, list and revoke join codes (the directory does the work). +async function adminRoute(req, res, url, user) { + if (url.pathname === "/api/admin/join-codes" && req.method === "GET") { + const out = await directoryAdmin("GET", "/join-codes"); + // what the install commands on the page fill in: where hospitals reach this hub's directory + const hub = process.env.HUB_ADDRESS ? `${process.env.HUB_ADDRESS}:${process.env.HUB_DIRECTORY_PORT || 8100}` : null; + return send(res, out.status, { ...out.body, install: { hub, version: INSTALLER_VERSION } }); + } + if (url.pathname === "/api/admin/join-codes" && req.method === "POST") { + const body = await readJson(req); + const ttl = Number.isInteger(body.ttl_minutes) ? body.ttl_minutes : undefined; + const out = await directoryAdmin("POST", "/join-codes", { + created_by: user, ttl_minutes: ttl, data_slice: typeof body.data_slice === "string" && body.data_slice ? body.data_slice : null, + }); + return send(res, out.status, out.body); + } + // the organiser takes a hospital out on its behalf (its laptop is off or gone) and frees an enrolled one's name + const m = url.pathname.match(/^\/api\/admin\/members\/([a-z0-9][a-z0-9_-]{0,63})\/remove$/); + if (m && req.method === "POST") { + const out = await directoryAdmin("POST", `/members/${m[1]}/remove`, { removed_by: user }); + return send(res, out.status, out.body); + } + const r = url.pathname.match(/^\/api\/admin\/join-codes\/([A-Z0-9]{4})\/revoke$/); + if (r && req.method === "POST") { + const out = await directoryAdmin("POST", `/join-codes/${r[1]}/revoke`, { revoked_by: user }); + return send(res, out.status, out.body); + } + return send(res, 404, { detail: "not found" }); +} + const server = http.createServer(async (req, res) => { try { if (req.url === "/healthz") return send(res, 200, { status: "ok" }); + if (req.url.startsWith("/api/") && req.method !== "GET" && !sameOrigin(req)) { + return send(res, 403, { detail: "cross-site request refused" }); + } + const login = req.url.match(/^\/api\/auth\/(me|setup|login|logout)$/); + if (login) return await authRoute(req, res, login[1]); + if (!req.url.startsWith("/api/")) return serveStatic(req, res); + const user = await auth.user(req); + if (!user) return send(res, 401, { detail: "Log in first." }); + if (req.url.startsWith("/api/admin/")) return await adminRoute(req, res, new URL(req.url, "http://x"), user); if (req.url === "/api/snapshot" && req.method === "GET") return send(res, 200, await buildSnapshot(pool)); - const m = req.url.match(/^\/api\/round\/(start|pause|resume)$/); + const m = req.url.match(/^\/api\/round\/(start|pause|resume|stop)$/); if (m && req.method === "POST") { const body = await readJson(req); const rounds = Number.isInteger(body.rounds) && body.rounds > 0 ? body.rounds : undefined; @@ -142,15 +201,27 @@ const server = http.createServer(async (req, res) => { const url = new URL(req.url, "http://x"); const a = url.pathname.match(/^\/api\/assess(\/pdf|\/ecg|\/ecg\/pdf)?$/); if (a && req.method === "POST") return await relayAssess(req, res, a[1] || "", url.searchParams.get("node")); - if (req.url.startsWith("/api/")) return send(res, 404, { detail: "not found" }); - return serveStatic(req, res); + return send(res, 404, { detail: "not found" }); } catch (err) { console.warn("request failed:", err.message); return send(res, 503, { detail: err.message }); } }); -const wss = new WebSocketServer({ server, path: "/ws" }); +// The snapshot stream is for the logged-in admin only: the upgrade is refused without a session. +const wss = new WebSocketServer({ noServer: true }); +server.on("upgrade", async (req, socket, head) => { + try { + if (new URL(req.url, "http://x").pathname !== "/ws" || !sameOrigin(req) || !(await auth.user(req))) { + socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n"); + return; + } + wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req)); + } catch (err) { + console.warn("websocket upgrade failed:", err.message); + socket.destroy(); + } +}); let latest = null; async function tick() { diff --git a/dashboard/server/relay.js b/dashboard/server/relay.js new file mode 100644 index 0000000..83bb799 --- /dev/null +++ b/dashboard/server/relay.js @@ -0,0 +1,43 @@ +// How a button press reaches the chain. Start, pause and resume go to the first alive member that +// answers and that node floods them on. Stop goes to every alive member with one shared op_id, so a +// hospital beyond a dead neighbour stops too; each node drops the copies it has already seen. +// `post(node, payload)` sends one request and resolves to { status, data } (or throws). + +import crypto from "node:crypto"; + +export async function relayTo(action, body, nodes, post) { + if (!nodes.length) return { status: 503, body: { detail: "No hospital node is alive." } }; + if (action === "stop") return stopAll(nodes, post); + const payload = action === "start" ? { rounds: body.rounds, initiated_by: "dashboard" } : {}; + let last = null; + for (const node of nodes) { + const out = await attempt(node, payload, post); + if (out.ok) return { status: out.status, body: { via: node.node_id, ...out.data } }; + last = { status: out.status, body: out.error ? { detail: out.error } : { via: node.node_id, ...out.data } }; + } + return last; +} + +async function stopAll(nodes, post) { + const payload = { op_id: `stop-${crypto.randomBytes(6).toString("hex")}`, origin: "dashboard" }; + const outs = await Promise.all(nodes.map((node) => attempt(node, payload, post))); + const results = Object.fromEntries( + nodes.map((node, i) => [node.node_id, outs[i].error ? { status: "unreachable", detail: outs[i].error } + : { http: outs[i].status, ...outs[i].data }]), + ); + const ok = outs.some((o) => o.ok); + return { + status: ok ? 200 : outs.at(-1).error ? 502 : outs.at(-1).status, + body: ok ? { status: "stopped", op_id: payload.op_id, results } + : { detail: "No hospital accepted the stop.", op_id: payload.op_id, results }, + }; +} + +async function attempt(node, payload, post) { + try { + const { status, data } = await post(node, payload); + return { ok: (status >= 200 && status < 300) || status === 409, status, data }; + } catch (err) { + return { ok: false, status: 502, error: `${node.node_id} unreachable: ${err.message}` }; + } +} diff --git a/dashboard/server/relay.test.js b/dashboard/server/relay.test.js new file mode 100644 index 0000000..d8cced9 --- /dev/null +++ b/dashboard/server/relay.test.js @@ -0,0 +1,63 @@ +// node --test: which hospitals a dashboard button press is sent to (server/relay.js). + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { relayTo } from "./relay.js"; + +const CHAIN = ["a", "b", "c"].map((id) => ({ node_id: id, url: `https://${id}:8000` })); + +function fakeChain({ dead = [], refuse = [] } = {}) { + const calls = []; + const post = async (node, payload) => { + calls.push({ node: node.node_id, payload }); + if (dead.includes(node.node_id)) throw new Error("connect ECONNREFUSED"); + if (refuse.includes(node.node_id)) return { status: 403, data: { detail: "no" } }; + return { status: 200, data: { status: "stopped", node_id: node.node_id } }; + }; + return { calls, post }; +} + +test("stop reaches a hospital beyond a dead one, with one shared op_id", async () => { + const { calls, post } = fakeChain({ dead: ["b"] }); + const out = await relayTo("stop", {}, CHAIN, post); + assert.equal(out.status, 200); + assert.deepEqual(calls.map((c) => c.node).sort(), ["a", "b", "c"]); + const ops = new Set(calls.map((c) => c.payload.op_id)); + assert.equal(ops.size, 1); + assert.match([...ops][0], /^stop-/); + assert.equal(out.body.op_id, [...ops][0]); + assert.equal(out.body.results.a.status, "stopped"); + assert.equal(out.body.results.c.status, "stopped"); + assert.equal(out.body.results.b.status, "unreachable"); +}); + +test("stop that no hospital accepts is reported as a failure, per node", async () => { + const { post } = fakeChain({ dead: ["a", "b", "c"] }); + const out = await relayTo("stop", {}, CHAIN, post); + assert.equal(out.status, 502); + assert.match(out.body.detail, /No hospital accepted/); + assert.deepEqual(Object.keys(out.body.results).sort(), ["a", "b", "c"]); +}); + +test("each stop press gets a fresh op_id so a second press is not dropped as seen", async () => { + const { calls, post } = fakeChain(); + await relayTo("stop", {}, CHAIN, post); + await relayTo("stop", {}, CHAIN, post); + assert.equal(new Set(calls.map((c) => c.payload.op_id)).size, 2); +}); + +test("start, pause and resume still go to the first member that answers", async () => { + for (const action of ["start", "pause", "resume"]) { + const { calls, post } = fakeChain({ dead: ["a"] }); + const out = await relayTo(action, { rounds: 5 }, CHAIN, post); + assert.equal(out.status, 200); + assert.equal(out.body.via, "b"); + assert.deepEqual(calls.map((c) => c.node), ["a", "b"]); + assert.deepEqual(calls[1].payload, action === "start" ? { rounds: 5, initiated_by: "dashboard" } : {}); + } +}); + +test("no alive hospital is a 503", async () => { + const out = await relayTo("stop", {}, [], fakeChain().post); + assert.equal(out.status, 503); +}); diff --git a/dashboard/server/snapshot.js b/dashboard/server/snapshot.js index 87cb4dd..f37e5a1 100644 --- a/dashboard/server/snapshot.js +++ b/dashboard/server/snapshot.js @@ -8,6 +8,8 @@ // pure functions below, which are unit-tested (snapshot.test.js). export const STALE_AFTER_S = Number(process.env.HEARTBEAT_STALE_S || 7); +// node/proof.py sends a signed proof-of-origin message every 10 s; older than this, it no longer counts as live +export const PROOF_STALE_S = Number(process.env.PROOF_STALE_S || 35); const AUDIT_ROWS = Number(process.env.AUDIT_ROWS || 80); const edgeKey = (a, b) => `${a}|${b}`; @@ -19,6 +21,7 @@ function runState(run, nodes) { if (states.has("running")) return "running"; if (states.has("paused")) return "paused"; if (states.has("failed")) return "failed"; + if (states.has("stopped")) return "stopped"; if (states.has("completed")) return "completed"; return inRun.length ? [...states][0] : "stalled"; } @@ -153,10 +156,61 @@ export function commFrom(perRoundRows, topology, hospitals = new Map()) { }; } +// Proof of origin per hospital (node/proof.py, checked by the observer): "verified" while its newest signed +// message is fresh and newer than any refused one, "rejected" when the newest thing it sent was refused, +// "stale" once it goes quiet, "none" if the observer never accepted one from it. +export function proofsFrom(rows, staleAfter = PROOF_STALE_S) { + return rows.map((r) => { + const since = r.seconds_since_proof; + const rejectedSince = r.seconds_since_rejection; + let status = "none"; + if (rejectedSince != null && (since == null || rejectedSince < since)) status = "rejected"; + else if (since != null) status = since <= staleAfter ? "verified" : "stale"; + return { + node_id: r.node_id, + display_name: r.display_name || r.node_id, + enrolled: !!r.enrolled, + status, + seconds_since_proof: since, + key_fingerprint: r.key_fingerprint || null, + rejection: status === "rejected" ? r.rejection : null, + message: r.message || null, + }; + }); +} + +async function proofRows(pool) { + try { + const { rows } = await pool.query( + `SELECT p.node_id, p.message, p.key_fingerprint, p.rejection, k.display_name, k.enrolled, + EXTRACT(EPOCH FROM (now() - p.received_at))::float AS seconds_since_proof, + EXTRACT(EPOCH FROM (now() - p.rejected_at))::float AS seconds_since_rejection + FROM node_proofs p LEFT JOIN hospital_keys k USING (node_id) ORDER BY p.node_id`, + ); + return rows; + } catch { + return []; // an observer older than node_proofs has not created the table + } +} + +// The chain's hospitals that were registered before a run started but never took part in it (no round logged, +// never on its run id): a laptop that was off, or one cut off behind it. A run that "completed" without them +// did not train on their data, and the control strip says so. Only once the run is over: while it starts, the +// others are still hearing of it. +export function missingFromRun(run, state, nodes, topology, metrics) { + if (!run || !["completed", "failed", "stopped"].includes(state)) return []; + const started = new Date(run.started_at).getTime(); + return nodes + .filter((n) => (topology?.chain || []).includes(n.node_id)) + .filter((n) => !n.registered_at || new Date(n.registered_at).getTime() <= started) + .filter((n) => n.run_id !== run.run_id && !(metrics[n.node_id] || []).length) + .map((n) => ({ node_id: n.node_id, display_name: n.display_name })); +} + export async function buildSnapshot(pool) { const nodesRes = await pool.query( `SELECT node_id, display_name, url, patients, neighbours, engine, run_id, run_state, current_round, - epoch, chain, in_chain, membership_round, + epoch, chain, in_chain, membership_round, registered_at, EXTRACT(EPOCH FROM (now() - last_heartbeat))::float AS seconds_since_heartbeat FROM nodes ORDER BY node_id`, ); @@ -218,18 +272,20 @@ export async function buildSnapshot(pool) { ); const engine = run?.engine || nodes.find((n) => n.engine)?.engine || "naive gossip baseline"; + const state = runState(run, nodes); return { generated_at: new Date().toISOString(), engine, heartbeat_stale_after_s: STALE_AFTER_S, nodes, topology, - run: run ? { ...run, state: runState(run, nodes) } : null, + run: run ? { ...run, state, missing: missingFromRun(run, state, nodes, topology, metrics) } : null, metrics, network_loss: networkLoss, consensus, comm, audit: auditRes.rows, + proofs: proofsFrom(await proofRows(pool)), }; } diff --git a/dashboard/server/snapshot.test.js b/dashboard/server/snapshot.test.js index 79abd31..2b25450 100644 --- a/dashboard/server/snapshot.test.js +++ b/dashboard/server/snapshot.test.js @@ -5,7 +5,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { commFrom, consensusFrom, currentTopology, hospitalsByRound, networkLossFrom } from "./snapshot.js"; +import { commFrom, consensusFrom, currentTopology, hospitalsByRound, missingFromRun, networkLossFrom, proofsFrom } from "./snapshot.js"; import { W, chainLinks, chainMembers, layout } from "../src/topologyLayout.js"; const EPS = 1e-3; @@ -149,7 +149,12 @@ test("network training loss: a round counts only once every member of its chain assert.ok(!rounds.includes(7) && !rounds.includes(12)); assert.ok(rounds.includes(6) && rounds.includes(11)); // rows from before chain_size existed fall back to the registered member count - const legacy = metricsRows(3).map(({ chain_size, epoch, ...r }) => r); + const legacy = metricsRows(3).map((row) => { + const r = { ...row }; + delete r.chain_size; + delete r.epoch; + return r; + }); assert.equal(networkLossFrom(legacy, 4).length, 3); assert.equal(networkLossFrom(legacy, 5).length, 0); }); @@ -204,3 +209,47 @@ test("topology layout: a member without a node row yet still gets a placeholder" assert.equal(placed[1].node_id, "hospital-e"); assert.equal(placed[1].status, "down"); }); + +test("proof of origin: verified only while the newest signed message is fresh and was accepted", () => { + const msg = { host: { hostname: "alex-laptop" }, data_rows: 62 }; + const rows = [ + { node_id: "st-marys-3f9a", display_name: "St Mary's", enrolled: true, seconds_since_proof: 4, message: msg, + key_fingerprint: "ab12" }, + { node_id: "hospital-b", seconds_since_proof: 120, message: msg }, + { node_id: "hospital-c", seconds_since_proof: 20, seconds_since_rejection: 3, rejection: "signature: does not verify" }, + { node_id: "hospital-d", seconds_since_rejection: 9, rejection: "no signing key is on record" }, + { node_id: "hospital-e", seconds_since_proof: 2, seconds_since_rejection: 50, rejection: "old" }, + ]; + const out = Object.fromEntries(proofsFrom(rows, 35).map((p) => [p.node_id, p])); + assert.equal(out["st-marys-3f9a"].status, "verified"); + assert.equal(out["st-marys-3f9a"].display_name, "St Mary's"); + assert.equal(out["hospital-b"].status, "stale"); + assert.equal(out["hospital-b"].display_name, "hospital-b"); + assert.equal(out["hospital-c"].status, "rejected"); + assert.equal(out["hospital-c"].rejection, "signature: does not verify"); + assert.equal(out["hospital-d"].status, "rejected"); + assert.equal(out["hospital-e"].status, "verified", "a later accepted message clears an older refusal"); + assert.equal(out["hospital-e"].rejection, null); +}); + +test("a run that never reached a chain member is flagged, not reported as plainly complete", () => { + const run = { run_id: "run-1", started_at: "2026-10-11T10:00:00Z" }; + const topology = { chain: ["hospital-a", "dead-laptop", "st-marys-3f9a"] }; + const nodes = [ + { node_id: "hospital-a", display_name: "Hospital A", run_id: "run-1", registered_at: "2026-10-11T09:00:00Z" }, + { node_id: "dead-laptop", display_name: "Dead Laptop", run_id: null, registered_at: "2026-10-11T09:00:00Z" }, + { node_id: "st-marys-3f9a", display_name: "St Mary's", run_id: null, registered_at: "2026-10-11T09:30:00Z" }, + { node_id: "late-joiner", display_name: "Late", run_id: null, registered_at: "2026-10-11T11:00:00Z" }, + ]; + const metrics = { "hospital-a": [{ round: 1 }] }; + assert.deepEqual(missingFromRun(run, "completed", nodes, topology, metrics).map((n) => n.node_id), ["dead-laptop", "st-marys-3f9a"]); + // one that took part (it logged rounds, even if it has since moved on) is not missing + assert.deepEqual(missingFromRun(run, "completed", nodes, topology, { ...metrics, "dead-laptop": [{ round: 1 }], "st-marys-3f9a": [{ round: 2 }] }), []); + // a hospital that registered after the run started (or is not in the chain) is not counted + assert.deepEqual(missingFromRun(run, "completed", nodes, { chain: ["hospital-a", "late-joiner"] }, metrics), []); + assert.deepEqual(missingFromRun(null, "idle", nodes, topology, metrics), []); + // while the run is starting or going, the others may simply not have heard of it yet + for (const state of ["stalled", "running", "paused"]) assert.deepEqual(missingFromRun(run, state, nodes, topology, metrics), []); + assert.equal(missingFromRun(run, "failed", nodes, topology, metrics).length, 2); + assert.equal(missingFromRun(run, "stopped", nodes, topology, metrics).length, 2, "a run the organiser stopped too"); +}); diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 2d75340..786bc83 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -7,14 +7,18 @@ import TrainingMonitor from "./pages/TrainingMonitor.jsx"; import Communication from "./pages/Communication.jsx"; import AuditLog from "./pages/AuditLog.jsx"; import Assessment from "./pages/Assessment.jsx"; +import Nodes from "./pages/Nodes.jsx"; +import JoinCodes from "./pages/JoinCodes.jsx"; import { control, useSnapshot } from "./useSnapshot.js"; const ROUTES = [ { hash: "#/", label: "Topology" }, { hash: "#/training", label: "Training monitor" }, { hash: "#/communication", label: "Communication" }, + { hash: "#/nodes", label: "Nodes" }, { hash: "#/audit", label: "Audit log" }, { hash: "#/assessment", label: "Risk assessment" }, + { hash: "#/join-codes", label: "Join codes" }, ]; function useHashRoute() { @@ -57,6 +61,11 @@ function ControlStrip({ snapshot }) { {run ? `${run.run_id} / ${state}` : "No training run yet"} + {run?.missing?.length > 0 && ( + + {" "}- incomplete: {run.missing.map((n) => n.display_name).join(", ")} never took part + + )}
@@ -72,6 +81,13 @@ function ControlStrip({ snapshot }) { Pause )} + {running && ( + // ends the run on every alive hospital (sent to each, not passed along): the way out of a run that cannot finish (a neighbour is gone) + window.confirm("Stop this training run on every hospital?") + && act("stop")} disabled={busy}> + Stop + + )}
{message &&

{message}

} @@ -79,7 +95,7 @@ function ControlStrip({ snapshot }) { ); } -export default function App() { +export default function App({ username, onLogout }) { const route = useHashRoute(); const { snapshot, connection } = useSnapshot(); @@ -97,6 +113,9 @@ export default function App() { {r.label} ))} + {connection === "live" ? "Live" : connection} @@ -112,8 +131,10 @@ export default function App() { )} {route === "#/training" && } {route === "#/communication" && } + {route === "#/nodes" && } {route === "#/audit" && } {route === "#/assessment" && } + {route === "#/join-codes" && }