diff --git a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md index fac4431f75..151f8c6ce1 100644 --- a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md +++ b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md @@ -113,3 +113,61 @@ Not checked before going live: the owner's real sign-in token at the edge. The edge counts requests it answered as the owner's and requests it left to the laptop (`/console/health`), so the first real visit shows which happened. + +## 2026-11-22T11:50Z Update: going live, and the first review + +Two things stopped the first go-live, and neither was in the design. + +- The laptop's checkout had stopped following `main` two hours earlier. + A system rebuild had left an empty marker commit on the local `main`, + and the sync only ever fast-forwards, so it stood still, 28 commits + behind, and nothing merged since had been deployed. The marker was + kept under the tag `rebuild-marker/amd-569` and `main` was moved to + `origin/main` (nothing was discarded: the commit was empty and the + tree was clean). The sync still cannot do this by itself; that is a + separate change to `pm-git-sync`. +- The setup script judged the Worker "not deployed" while it was + answering. Its health check went out under Python's default client + name, which Cloudflare refuses with a 403; `curl` from the same + machine got the answer. The check now names its program (and nothing + else), asks three times before believing a failure, and is covered by + a test that looks at the request actually made. + +What the first review found, and what was done: + +- **An action could run twice.** If the laptop did a relayed action and + its answer was lost on the way back, the edge held the action under a + new name and the laptop ran it again at the next report. An action is + now named at the edge before it goes anywhere; the laptop writes the + name down before starting and the outcome after; a held action + offered under a name the laptop knows is answered from that record, + and one still running is left to finish. Tested with the answer lost + after the work, and with the edge giving up while the work was still + going. +- **A source the laptop could no longer read looked healthy at the + edge.** The laptop keeps its last good copy, so the data and its + fingerprint do not change; the report now says of every section + whether its latest read failed and why, and the edge shows that with + the copy, across its own restarts. +- **A late answer the dashboard refused was logged as done.** It is now + logged as not recorded, with the reason. +- **Notifications after the move.** A browser's subscription is made + for one sender's key, and the edge has its own. The app now checks, on + opening, whether the sender still holds this device and under which + key, and makes the subscription again or hands it over again without + asking (the owner already said yes on that device). The sender tells + the app which devices it holds by a short mark of each address, never + the address. Until a device next opens the app, the laptop goes on + sending to it. Phones linked for the widget are not carried across an + edge on/off change yet: one linked on one side has to be linked again + on the other. +- **The setup script**: `--check --edge off` now previews that choice + instead of ignoring it; a Worker built for another hostname is not + given this one (the Worker says which it is built for); the redeploy + check reads quoted settings the way the service does; the build and + the smoke check refuse arguments they do not take. + +One change nobody asked for: the contact handed to push services with +every notification was the owner's address. It is now the project's +page. Delivery does not depend on it, and an address has no reason to +travel to Google or Mozilla with each message. diff --git a/pm-stack/console/edge/build.mjs b/pm-stack/console/edge/build.mjs index 708dc6bcf7..9cbac1b1d2 100644 --- a/pm-stack/console/edge/build.mjs +++ b/pm-stack/console/edge/build.mjs @@ -5,6 +5,10 @@ import { cpSync, mkdirSync, rmSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +if (process.argv.length > 2) { + console.error("usage: node build.mjs (it takes no arguments)"); + process.exit(2); +} const here = dirname(fileURLToPath(import.meta.url)); const dist = join(here, "dist"); rmSync(dist, { recursive: true, force: true }); diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 0cb0816ad5..4c1f194d68 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -49,7 +49,7 @@ import { sameSiteWrite, } from "../../src/http.ts"; import { Notifier } from "../../src/notify.ts"; -import { Push } from "../../src/push.ts"; +import { contact, Push } from "../../src/push.ts"; import type { Store } from "../../src/store.ts"; /** The edge's own storage: small values by key. */ @@ -94,6 +94,7 @@ const STATIC: Record = { "icon.svg": "image/svg+xml", "sw.js": "text/javascript; charset=utf-8", }; +const ACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const ICONS = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; interface Mirror { @@ -142,7 +143,7 @@ export class Edge { private hostSeq: number | null = null; /** For each section, the content the host last said it has and when * it read it: a copy with that content is current as of that read. */ - private confirmed: Record = {}; + private confirmed: Record = {}; private sure = 0; private unsure = 0; readonly docs: Docs; @@ -165,7 +166,8 @@ export class Edge { load: async () => { const m = await this.mirror(name); if (!m) throw new Error("the laptop has not reported this yet"); - return new Stamped(m.data, m.at); + // With the laptop's own word on whether it could still read it. + return new Stamped(m.data, m.at, this.confirmed[name]?.error ?? null); }, }, ]), @@ -174,8 +176,8 @@ export class Edge { ); this.push = new Push( kvStore(this.kv, "push"), - // Who a push service may write to about these messages: the owner. - () => `mailto:${this.cfg?.owners[0] ?? "owner@invalid.example"}`, + // The contact a push service is given: the project's page. + () => contact(this.cfg?.repo ?? "developing-today/code"), (url, init) => this.fetchImpl(url, init as RequestInit), this.now, ); @@ -295,7 +297,7 @@ export class Edge { if (this.ownActs === null) await this.showActs(); if (this.hostSeen === null) { const host = (await this.kv.get("host")) as - | { seen: number; seq: number; confirmed?: Record } + | { seen: number; seq: number; confirmed?: Record } | undefined; this.hostSeen = host?.seen ?? 0; this.hostSeq = host?.seq ?? 0; @@ -350,16 +352,25 @@ export class Edge { await this.kv.put("cfg", cfg); this.cfg = cfg; } - const changed = await this.take(msg.sections); - // A section that has not changed is not sent again, but the host - // says when it last read it: the copy here is as current as that. - const fresher: string[] = []; + // What the host says of every section it has: how current it is, and + // whether it could still read it. Taken first, so a section that + // arrives in this report is shown with its health as of this report. + const told: { name: string; healthChanged: boolean }[] = []; for (const [name, theirs] of Object.entries(msg.have ?? {})) { if (!Object.hasOwn(SECTIONS, name) || typeof theirs?.hash !== "string" || typeof theirs.at !== "number") continue; - this.confirmed[name] = { hash: theirs.hash, at: Math.min(theirs.at, now) }; + const error = typeof theirs.error === "string" && theirs.error !== "" ? theirs.error.slice(0, 300) : null; + told.push({ name, healthChanged: (this.confirmed[name]?.error ?? null) !== error }); + this.confirmed[name] = { hash: theirs.hash, at: Math.min(theirs.at, now), error }; + } + const changed = await this.take(msg.sections); + // A section that has not changed is not sent again: the copy here is + // as current as the host says, and as healthy. + const fresher: string[] = []; + for (const { name, healthChanged } of told) { const copy = await this.mirror(name); - if (copy && copy.hash === theirs.hash && this.confirmed[name].at > copy.at) { - copy.at = this.confirmed[name].at; + if (!copy || copy.hash !== this.confirmed[name].hash) continue; + if (this.confirmed[name].at > copy.at || healthChanged) { + copy.at = Math.max(copy.at, this.confirmed[name].at); if (!changed.includes(name)) fresher.push(name); } } @@ -583,7 +594,18 @@ export class Edge { if (!Object.hasOwn(this.table, kind)) { // The host's to do. The stateless part relays it, and if the // host cannot be reached comes back to have it held. - return next("relay", { mode: "act", kind, args, who: by, holdable: HOLDABLE.has(kind) }); + // It is named here, before it goes anywhere. If the host's answer + // is lost on the way back, the action is held under the same + // name, and the host, which wrote the name down before starting, + // does not do it a second time. + return next("relay", { + mode: "act", + id: crypto.randomUUID(), + kind, + args, + who: by, + holdable: HOLDABLE.has(kind), + }); } return await this.own(kind, args as Record, by, who.via); } catch (error) { @@ -618,6 +640,7 @@ export class Edge { * that may be done late. */ private async hold(req: Request): Promise { const body = (await req.json().catch(() => null)) as { + id?: unknown; kind?: unknown; args?: unknown; who?: unknown; @@ -626,7 +649,12 @@ export class Edge { const args = body?.args; if (!HOLDABLE.has(kind) || args === null || typeof args !== "object" || Array.isArray(args)) { return json( - { error: "The laptop cannot be reached, and this is not safe to do late. Try again when it is back." }, + // No answer is not "not done": the laptop may have got it and its + // answer been lost. Nothing is kept to do later, and it says so. + { + error: + "The laptop did not answer, and this is not something to do late, so it is not kept. Check whether it happened before trying again.", + }, 503, ); } @@ -636,7 +664,8 @@ export class Edge { return json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, 503); } const item: Held = { - id: crypto.randomUUID(), + // The name it was relayed under, so the host can tell it has seen it. + id: typeof body?.id === "string" && ACT_ID.test(body.id) ? body.id : crypto.randomUUID(), kind, args: args as Record, who: String(body?.who ?? "owner"), diff --git a/pm-stack/console/edge/src/entry.ts b/pm-stack/console/edge/src/entry.ts index 09c4b64b87..1f49eaeed2 100644 --- a/pm-stack/console/edge/src/entry.ts +++ b/pm-stack/console/edge/src/entry.ts @@ -93,7 +93,9 @@ export async function route(request: Request, io: Io): Promise { } if (url.pathname === "/console/health" && request.method === "GET") { const body = (await (await io.state(request)).json()) as Record; - return new Response(JSON.stringify({ ...body, version: io.version }), { + // The hostname it is built for is said too: the host's setup script + // will not put any other hostname behind this Worker. + return new Response(JSON.stringify({ ...body, version: io.version, host: io.publicHost }), { headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, }); } @@ -142,7 +144,11 @@ export async function route(request: Request, io: Io): Promise { if (!routed) return offline("this address has no host behind it"); if (detail.mode === "act") { - const answer = await io.host(withHeader(forHost, "x-pm-edge", "1"), ACT_MS); + // The host is told the action's name with the action. No answer may + // mean the host never got it, or did it and the answer was lost: it + // is held under that name, and the host sorts out which. + const named = withHeader(withHeader(forHost, "x-pm-edge", "1"), "x-pm-act", String(detail.id ?? "")); + const answer = await io.host(named, ACT_MS); if (answer === null) return tell("/internal/hold", detail); // The host's answer says what it read again; keep that here, and // send the owner the rest. diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index f06866e45e..d868690e7e 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -861,6 +861,52 @@ export function deviceLabel(agent = navigator.userAgent) { return (m ? m[1] : agent).trim().slice(0, 60); } +/** A short mark for a push address: how this device tells whether the + * sender of notifications still has it, without the address going + * anywhere. The same as endpointMark in src/push.ts. */ +export async function endpointMark(endpoint) { + const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint))); + return b64url(hash).slice(0, 16); +} + +function b64url(bytes) { + return btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +/** What this device's notification subscription needs, given what the + * sender says of itself: "keep" it, hand it over "again" (the sender + * has lost it), or "renew" it (it was made for a key the sender does not + * use, as when the app moved from the laptop to the edge). `madeFor` is + * the key it was made for, or "" where the browser does not say. */ +export function subscriptionState(madeFor, mark, status) { + if (!status || !status.key) return "keep"; + if (madeFor && madeFor !== status.key) return "renew"; + return (status.known || []).includes(mark) ? "keep" : "again"; +} + +/** Notifications that are on for this device stay on: nothing is asked, + * because the owner already said yes on this device. A device where + * they are off is left alone. */ +async function keepSubscribed() { + if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) return; + if (Notification.permission !== "granted") return; + const reg = await navigator.serviceWorker.getRegistration("/console/"); + let sub = reg ? await reg.pushManager.getSubscription() : null; + if (!sub) return; + const status = await api("push"); + const key = sub.options?.applicationServerKey; + const state = subscriptionState(key ? b64url(new Uint8Array(key)) : "", await endpointMark(sub.endpoint), status); + if (state === "keep") return; + if (state === "renew") { + await sub.unsubscribe(); + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(status.key) }); + } + await api("act", { kind: "push.on", args: { subscription: sub.toJSON(), label: deviceLabel() } }); +} + function keyBytes(b64) { const text = atob((b64 + "=".repeat((4 - (b64.length % 4)) % 4)).replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(text, (c) => c.charCodeAt(0)); @@ -1409,6 +1455,9 @@ if (typeof document !== "undefined" && view) { .catch(() => {}); // The worker shows notifications and opens the right screen when one is tapped. if ("serviceWorker" in navigator) navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }).catch(() => {}); + // And a device that has notifications on keeps getting them when the + // sender changed or lost track of it. + keepSubscribed().catch(() => {}); draw(); refresh(true); } diff --git a/pm-stack/console/redeploy.sh b/pm-stack/console/redeploy.sh index 6c852e8bc1..7c15dca1c5 100755 --- a/pm-stack/console/redeploy.sh +++ b/pm-stack/console/redeploy.sh @@ -45,13 +45,23 @@ if [ "$want" = "$(cat "$STATE/deploy-failed" 2>/dev/null || true)" ]; then fi mkdir -p "$STATE" -# The service's own settings, one KEY=value a line, passed as they are. +# The service's own settings, read the way systemd reads them: one +# KEY=value a line, and one pair of quotes around a value is not part of +# the value (install.sh reads PM_CONSOLE_PORT="4872" the same way). settings=() if [ -f "$STATE/.env" ]; then while IFS= read -r line || [ -n "$line" ]; do case "$line" in '' | '#'* | ';'*) continue ;; - *=*) settings+=("$line") ;; + *=*) + key="${line%%=*}" + value="${line#*=}" + case "$value" in + \"*\") value="${value#\"}" && value="${value%\"}" ;; + \'*\') value="${value#\'}" && value="${value%\'}" ;; + esac + settings+=("$key=$value") + ;; esac done <"$STATE/.env" fi diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index b500515146..85b3b943c1 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -19,6 +19,10 @@ import { type Deps, handle, heldRunner, marked } from "../src/server.ts"; import { memoryStore } from "../src/store.ts"; import { EdgeLink } from "../src/sync.ts"; +if (process.argv.length > 2) { + console.error("usage: bun run scripts/edge-smoke.ts (it takes no arguments; EDGE names the Worker's address)"); + process.exit(2); +} const EDGE = process.env.EDGE ?? "http://localhost:8799"; const cfg = readConfig({ HOME: "/tmp/pm-edge-smoke", PM_CONSOLE_OWNER_EMAILS: "owner@example.com" }); cfg.issuers = [ diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 2ef78780b0..604be33c0a 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -29,8 +29,9 @@ 6. The hostname's traffic goes through the edge Worker (pm-console-edge, which serves the app from Cloudflare and reaches this host through the same tunnel), and the console is told where to report to it. This - happens only once the Worker answers its health check; until then, - and after `--edge off`, the hostname goes straight to this host. + happens only once the Worker answers its health check and says it is + built for this hostname; until then, and after `--edge off`, the + hostname goes straight to this host. The gate comes first and the routes last, so the origin is never reachable without sign-in in front of it. If the console does not come @@ -40,7 +41,8 @@ memory. Nothing printed is a secret. Usage: expose.py [--check] [--edge on|off] [--host pm.security.cab] [--owner EMAIL] - --check report what would change and exit 1 if anything would. + --check report what would change and exit 1 if anything would; + with --edge, what that choice would change, keeping nothing. --edge off take the hostname off the edge Worker; remembered by later runs (the timer's included) until --edge on. """ @@ -167,36 +169,63 @@ def plain(rule: dict) -> dict: ) +# Cloudflare answers 403 to a client that calls itself Python-urllib. The +# name sent is this program's and nothing more: no address, no contact. +USER_AGENT = "pm-console-expose" +# A health check that fails once is asked again before the hostname is +# taken off the edge over it. +HEALTH_TRIES = 3 +HEALTH_WAIT_SECONDS = 3 + + def fetch_json(url: str) -> dict | None: """One GET of a JSON document, or None if it cannot be had.""" try: - with urllib.request.urlopen(url, timeout=10) as res: + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(request, timeout=10) as res: out = json.load(res) return out if isinstance(out, dict) else None except (OSError, ValueError): return None -def edge_choice(state: pathlib.Path, choice: str | None) -> bool: - """Whether the hostname should go through the edge Worker. The choice - is kept in a file, so a timer's run keeps what was last asked for; - with no file the answer is yes.""" +def edge_choice(state: pathlib.Path, choice: str | None, keep: bool) -> bool: + """Whether the hostname should go through the edge Worker. A choice + given now decides, and with `keep` it is written to a file, so a + timer's run keeps what was last asked for. With no choice given the + file decides, and with no file the answer is yes.""" marker = state / "edge" if choice is not None: - state.mkdir(parents=True, exist_ok=True, mode=0o700) - marker.write_text(choice + "\n") + if keep: + state.mkdir(parents=True, exist_ok=True, mode=0o700) + marker.write_text(choice + "\n") + return choice != "off" return not marker.exists() or marker.read_text().strip() != "off" -def worker_ready(cf: Cloudflare, account: str) -> bool: - """True when the edge Worker is deployed and answers its health check - as the edge. Until then the hostname keeps going straight to the - host, so there is never a route to a Worker that is not there.""" +def worker_ready(cf: Cloudflare, account: str, host: str) -> bool: + """True when the edge Worker is deployed, answers its health check as + the edge, and is built for this hostname (it treats any other as + having no host behind it). Until then the hostname keeps going + straight to the host, so there is never a route to a Worker that is + not there or would not serve it. One failed answer is not believed: + it is asked again, so a passing fault does not take the hostname off + the edge.""" subdomain = cf.get(f"/accounts/{account}/workers/subdomain").get("subdomain") if not subdomain: return False - health = fetch_json(f"https://{WORKER}.{subdomain}.workers.dev/console/health") - return bool(health and health.get("ok") is True and health.get("edge") is True) + for attempt in range(HEALTH_TRIES): + if attempt: + time.sleep(HEALTH_WAIT_SECONDS) + health = fetch_json(f"https://{WORKER}.{subdomain}.workers.dev/console/health") + if ( + health + and health.get("ok") is True + and health.get("edge") is True + and health.get("host") == host + ): + return True + return False def ensure_edge_route(cf: Cloudflare, zone: str, host: str, wanted: bool) -> None: @@ -522,12 +551,13 @@ def main() -> int: console = console_origin(env) # Through the edge only if that is wanted and the Worker is really # there; otherwise straight to this host, as before the edge existed. - edge = edge_choice(env.parent, None if args.check else args.edge) - if edge and not worker_ready(cf, account): + # --check previews a choice given with it, and keeps nothing. + edge = edge_choice(env.parent, args.edge, keep=not args.check) + if edge and not worker_ready(cf, account, args.host): edge = False print( - f"note: the edge Worker {WORKER} is not deployed or does not answer; " - "the hostname goes straight to this host" + f"note: the edge Worker {WORKER} is not deployed, does not answer, or is " + f"not built for {args.host}; the hostname goes straight to this host" ) # Order matters. The sign-in gate is put in place first and the route diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index a178267d48..6ca36afe67 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -41,6 +41,10 @@ def __init__(self, check=False): # Workers routes on the zone, and whether the edge Worker answers. self.routes = [] self.worker_up = True + # The hostname the Worker says it is built for, and how many of + # its next health checks get no answer. + self.worker_host = HOST + self.health_misses = 0 def call(self, method, path, body=None): path, _, query = path.partition("?") @@ -132,6 +136,18 @@ def up(self, origin, seconds=20): def run(account, home, *args, machine=None): argv = ["expose.py", *args] machine = machine or Machine() + + def health(url): + if account.health_misses > 0: + account.health_misses -= 1 + return None + if ( + not account.worker_up + or url != f"https://{expose.WORKER}.acct.workers.dev/console/health" + ): + return None + return {"ok": True, "edge": True, "host": account.worker_host} + with ( mock.patch.object(expose, "Cloudflare", lambda token, check: account), mock.patch.object( @@ -142,16 +158,8 @@ def run(account, home, *args, machine=None): mock.patch.object(expose.pathlib.Path, "home", lambda: pathlib.Path(home)), mock.patch.object(expose.subprocess, "run", machine.systemctl), mock.patch.object(expose, "console_up", machine.up), - mock.patch.object( - expose, - "fetch_json", - lambda url: ( - {"ok": True, "edge": True} - if account.worker_up - and url == f"https://{expose.WORKER}.acct.workers.dev/console/health" - else None - ), - ), + mock.patch.object(expose, "fetch_json", health), + mock.patch.object(expose.time, "sleep", lambda seconds: None), mock.patch.object(sys, "argv", argv), mock.patch("builtins.print"), ): @@ -501,14 +509,102 @@ def test_another_workers_route_on_the_hostname_is_left_alone(self): self.assertEqual(run(account, self.home), 0) self.assertEqual(len(account.routes), 2) - def test_check_never_records_an_edge_choice(self): + def test_check_previews_an_edge_choice_and_keeps_nothing(self): account = Account() run(account, self.home) - self.assertEqual(run(account, self.home, "--check", "--edge", "off"), 0) + # Asked what turning the edge off would change: both things, and exit 1. + self.assertEqual(run(account, self.home, "--check", "--edge", "off"), 1) + self.assertEqual( + account.changes, + [ + "console environment: PM_CONSOLE_EDGE_URL", + f"workers: take {HOST}/* off {expose.WORKER}", + ], + ) + # Nothing was done and nothing was remembered. self.assertFalse( (pathlib.Path(self.home) / ".local/state/pm-console/edge").exists() ) self.assertEqual(len(account.routes), 1) + self.assertEqual(self.env()["PM_CONSOLE_EDGE_URL"], f"https://{HOST}") + self.assertEqual(run(account, self.home, "--check"), 0) + # And the other way: off for real, then asked what on would change. + self.assertEqual(run(account, self.home, "--edge", "off"), 0) + self.assertEqual(run(account, self.home, "--check", "--edge", "on"), 1) + self.assertEqual(len(account.changes), 2) + self.assertEqual(account.routes, []) + self.assertEqual(run(account, self.home, "--check"), 0) + + def test_a_worker_built_for_another_hostname_is_not_routed(self): + account = Account() + account.worker_host = "pm.other.example" + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.routes, []) + self.assertNotIn("PM_CONSOLE_EDGE_URL", self.env()) + # A Worker from before it said which hostname it is built for. + with mock.patch.object(expose, "HEALTH_TRIES", 1): + account.worker_host = None + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.routes, []) + + def test_one_unanswered_health_check_does_not_take_the_hostname_off_the_edge(self): + account = Account() + run(account, self.home) + self.assertEqual(len(account.routes), 1) + # Two checks in a row get no answer; the third does. + account.health_misses = expose.HEALTH_TRIES - 1 + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + self.assertEqual(len(account.routes), 1) + # None of them does: the hostname goes back to this host, which is + # what keeps it reachable when the Worker is what is broken. + account.health_misses = expose.HEALTH_TRIES + self.assertEqual(run(account, self.home), 0) + self.assertEqual( + account.changes, + [ + "console environment: PM_CONSOLE_EDGE_URL", + f"workers: take {HOST}/* off {expose.WORKER}", + ], + ) + self.assertEqual(account.routes, []) + # And returns by itself once the Worker answers again. + self.assertEqual(run(account, self.home), 0) + self.assertEqual(len(account.routes), 1) + + def test_the_health_check_names_itself(self): + # Found live: the edge's health check answered 403 to Python's + # default client name, so the Worker looked undeployed. + seen = [] + + class Answer: + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def read(self, *_): + return b'{"ok": true, "edge": true}' + + def urlopen(request, timeout): + seen.append((request.full_url, request.get_header("User-agent"), timeout)) + return Answer() + + with mock.patch.object(expose.urllib.request, "urlopen", urlopen): + self.assertEqual( + expose.fetch_json("https://w.example/console/health"), + {"ok": True, "edge": True}, + ) + self.assertEqual(len(seen), 1) + self.assertEqual(seen[0][0], "https://w.example/console/health") + # The program's name and nothing more: no address, no contact. + self.assertEqual(seen[0][1], "pm-console-expose") + # Anything that is not a JSON object, or cannot be had, is "no answer". + with mock.patch.object( + expose.urllib.request, "urlopen", mock.Mock(side_effect=OSError("403")) + ): + self.assertIsNone(expose.fetch_json("https://w.example/x")) if __name__ == "__main__": diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index 3ae9936d35..d74c154c28 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -37,6 +37,9 @@ export class Stamped { constructor( public data: unknown, public at: number, + /** Why the place that read it could not read it again, if it could + * not: the data is then its last good copy. */ + public error: string | null = null, ) {} } @@ -95,8 +98,8 @@ export class Docs { // A copy read elsewhere is as old as that read, never newer than now. s.data = loaded instanceof Stamped ? loaded.data : loaded; s.goodAt = loaded instanceof Stamped ? Math.min(now, loaded.at) : now; - s.ok = true; - s.error = null; + s.error = loaded instanceof Stamped ? loaded.error : null; + s.ok = s.error === null; } catch (error) { s.ok = false; s.error = (error as Error).message.slice(0, 300); @@ -205,12 +208,13 @@ export class Docs { /** Every section that has been read, with when and a fingerprint of * its content: what is reported to the edge, and how it tells that a * section has not changed. */ - snapshot(): { name: string; at: number; hash: string; data: unknown }[] { - const out: { name: string; at: number; hash: string; data: unknown }[] = []; + snapshot(): { name: string; at: number; hash: string; data: unknown; error: string | null }[] { + const out: { name: string; at: number; hash: string; data: unknown; error: string | null }[] = []; for (const [name, s] of this.sections) { if (s.goodAt === 0) continue; const hash = createHash("sha1").update(JSON.stringify(s.data)).digest("base64url"); - out.push({ name, at: s.goodAt, hash, data: s.data }); + // The data is the last good copy; `error` says the latest read failed. + out.push({ name, at: s.goodAt, hash, data: s.data, error: s.ok ? null : s.error }); } return out; } diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index b47101e256..0d721ca335 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -49,11 +49,12 @@ export interface SyncRequest { config: EdgeConfig; /** Sections that changed since the edge last had them. */ sections: SyncSection[]; - /** Every section the host has: its fingerprint and when the host last - * read it. A section that has not changed is not sent again, and this - * is how the edge knows its copy is still current as of that read, and - * how it asks for one it has lost. */ - have: Record; + /** Every section the host has: its fingerprint, when the host last + * read it, and why its latest read failed if it did. A section that + * has not changed is not sent again, and this is how the edge knows + * its copy is still current as of that read, shows the same "could + * not read" notice the host would, and asks for a copy it has lost. */ + have: Record; /** What became of the held actions the host was given. */ acks: { id: string; ok: boolean; error?: string }[]; } diff --git a/pm-stack/console/src/push.ts b/pm-stack/console/src/push.ts index 70c6789dc6..b1440c86e6 100644 --- a/pm-stack/console/src/push.ts +++ b/pm-stack/console/src/push.ts @@ -10,6 +10,21 @@ import type { Store } from "./store.ts"; const enc = new TextEncoder(); const b64u = (bytes: Uint8Array | ArrayBuffer) => Buffer.from(bytes as ArrayBuffer).toString("base64url"); + +/** The contact a push service is given with every message (the "sub" a + * sender must name): the project's page. It is not a person's address: + * it goes to Google, Mozilla or Apple each time, and nothing about + * delivery depends on whose it is. */ +export const contact = (repo: string): string => `https://github.com/${repo}`; + +/** A short mark for a push address. The app compares its own with the + * marks of the addresses held here, and so can tell that this sender has + * lost it, without any address being sent back. The app computes the + * same (public/app.js, endpointMark). */ +export async function endpointMark(endpoint: string): Promise { + const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint)); + return b64u(hash).slice(0, 16); +} const unb64u = (text: string) => new Uint8Array(Buffer.from(text, "base64url")); const concat = (...parts: Uint8Array[]) => { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); @@ -148,6 +163,7 @@ export class Push { return { key: s.vapid?.publicKey ?? "", devices: s.subscriptions.length, + known: await Promise.all(s.subscriptions.map((x) => endpointMark(x.endpoint))), classes: Object.fromEntries(CLASSES.map((c) => [c, !s.off.includes(c)])), }; } diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 02b6d42a46..4cd11ed899 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -34,7 +34,7 @@ import { } from "./http.ts"; import { Notifier } from "./notify.ts"; import { OpError, Ops } from "./ops.ts"; -import { Push } from "./push.ts"; +import { contact, Push } from "./push.ts"; import { EdgeLink } from "./sync.ts"; import { Work } from "./work.ts"; @@ -47,6 +47,7 @@ const STATIC = new Map([ ]); const APK_NAME = "pm-console.apk"; +const ACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; /** The dashboard's files that are public, matched against the parsed * path in full. They say nothing about the fleet. */ const PUBLIC_DASHBOARD = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; @@ -102,7 +103,7 @@ export interface Deps { * exist only when their limits do. */ phones?: Phones; /** This host's link to the edge, when the app is served from one. */ - link?: Pick; + link?: Pick & Partial>; } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -368,17 +369,25 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul acts: docs.recentActs(), }) : undefined; + // Relayed by the edge under a name: the name is written down before + // the action starts and its outcome after, so that if this answer + // is lost and the edge offers the action again, it is not repeated. + const name = req.headers.get("x-pm-act") ?? ""; + const link = ACT_ID.test(name) && deps.link?.begin && deps.link.end ? deps.link : null; return await act( kind || "unknown", kept, async () => { + await link?.begin?.(name); docs.logAct({ ...entry, status: "running" }); try { const result = await perform(table, docs, kind, args); docs.logAct({ ...entry, status: "done" }); + await link?.end?.(name, { ok: true }); return result; } catch (error) { docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + await link?.end?.(name, { ok: false, error: (error as Error).message.slice(0, 300) }); throw error; } }, @@ -497,7 +506,22 @@ export function heldRunner(deps: Pick): (hel .audit({ ...base, phase: "done", ...more }) .catch((error) => console.error(`pm-console: audit: ${(error as Error).message}`)); try { - await perform(table, docs, held.kind, held.args); + const result = (await perform(table, docs, held.kind, held.args)) as { + applied?: number; + refused?: { why?: string }[]; + } | null; + // An answer can come back "not recorded" without anything being + // thrown (the question was settled in the meantime). Sent at once, + // the app says so; sent late, this has to. + const refused = Array.isArray(result?.refused) ? result.refused : []; + if (refused.length > 0) { + const why = String(refused[0]?.why ?? "no reason given"); + throw new Error( + (result?.applied ?? 0) > 0 + ? `${result?.applied} recorded, ${refused.length} not recorded: ${why}` + : `not recorded: ${why}`, + ); + } docs.logAct({ ...entry, status: "done", note: "Sent late: held while the laptop could not be reached." }); await done({ ok: true }); } catch (error) { @@ -528,7 +552,7 @@ if (import.meta.main) { const work = new Work(ops); const docs = new Docs(loaders(ops, work, await morePages())); const state = dirname(cfg.auditFile); - const push = new Push(fileStore(join(state, "push.json")), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`); + const push = new Push(fileStore(join(state, "push.json")), contact(cfg.repo)); const notifier = new Notifier(docs, push, fileStore(join(state, "notified.json"))); const devices = new Devices(fileStore(cfg.devicesFile)); const deps: Deps = { diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index ac589ddf55..5627bccd41 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -62,6 +62,8 @@ export class EdgeLink { private watchedAt = 0; private timer: ReturnType | null = null; private busy = false; + /** Actions being done right now, by the name the edge gave them. */ + private running = new Set(); private now: () => number; private fetchImpl: typeof fetch; private log: (line: string) => void; @@ -117,9 +119,28 @@ export class EdgeLink { await this.o.done.write(JSON.stringify(Object.fromEntries(fates))); } + /** The edge relayed an action under this name and it is about to be + * done. Written down first, so that if the answer never reaches the + * edge and the edge offers the action again, it is not done twice. */ + async begin(id: string): Promise { + this.running.add(id); + await this.record(id, "started"); + } + + /** How a relayed action came out. */ + async end(id: string, fate: { ok: boolean; error?: string }): Promise { + try { + await this.record(id, fate); + } finally { + this.running.delete(id); + } + } + /** A held action from the edge: run it unless it has been seen before. */ private async take(held: Held): Promise { if (this.acks.some((a) => a.id === held.id)) return; + // Still being done (its answer was slow, not lost): say nothing yet. + if (this.running.has(held.id)) return; const seen = (await this.fate()).get(held.id); if (seen === "started") { // The host stopped while this was running. Whether it happened is @@ -165,7 +186,7 @@ export class EdgeLink { at, config: await this.o.config(), sections, - have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at }])), + have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), acks, acts: this.o.docs.recentActs(), }; diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 2c55e5a36f..63d62a0a60 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -3,7 +3,8 @@ // Oracles: the elapsed-time phrases and the device labels are written // out here by hand for real inputs (two real browser names). import { expect, test } from "bun:test"; -import { ago, band, deviceLabel } from "../public/app.js"; +import { ago, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; +import { contact, endpointMark as serverMark } from "../src/push.ts"; test("elapsed time reads as a phrase on its own, never 'just now ago'", () => { const now = Date.parse("2026-11-22T12:00:00Z"); @@ -39,3 +40,29 @@ test("priority bands in words", () => { expect([10, 20, 30, 40, 50, 70, 90].map(band)).toEqual(["Top", "High", "Normal", "Low", "Low", "Later", "Later"]); expect([band(null), band(undefined), band("")]).toEqual(["Normal", "Normal", "Normal"]); }); + +test("a device with notifications on tells whether the sender still has it, and for which key", async () => { + // The app and the sender must compute the same mark, or every device + // would look lost on every load. + const endpoint = "https://fcm.googleapis.com/fcm/send/abc:DEF-123"; + expect(await endpointMark(endpoint)).toBe(await serverMark(endpoint)); + // Worked by hand: SHA-256 of the text, base64url, first 16 characters. + expect(await endpointMark("a")).toBe("ypeBEsobvcr6wjGz"); + const status = { key: "KEY-NOW", known: ["mine"] }; + expect(subscriptionState("KEY-NOW", "mine", status)).toBe("keep"); + // The sender has lost it (a new store, a restore from an old copy). + expect(subscriptionState("KEY-NOW", "other", status)).toBe("again"); + expect(subscriptionState("KEY-NOW", "mine", { key: "KEY-NOW" })).toBe("again"); + // It was made for another sender's key: the app moved from the laptop to the edge. + expect(subscriptionState("KEY-OLD", "mine", status)).toBe("renew"); + // A browser that does not say which key it was made for is judged by the mark alone. + expect(subscriptionState("", "mine", status)).toBe("keep"); + expect(subscriptionState("", "other", status)).toBe("again"); + // No answer worth acting on: leave it. + expect(subscriptionState("KEY-OLD", "mine", { key: "" })).toBe("keep"); + expect(subscriptionState("KEY-OLD", "mine", null)).toBe("keep"); +}); + +test("the contact given to push services is the project's page, never a person's address", () => { + expect(contact("developing-today/code")).toBe("https://github.com/developing-today/code"); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 3e817c27d9..0a1e91f393 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -55,12 +55,12 @@ async function setup() { const now = { t: START }; const clock = () => now.t; const access = await signer("k1"); - const pushes: { url: string; body: Uint8Array }[] = []; - const outward = async (url: string | URL | Request, init?: { body?: unknown }) => { + const pushes: { url: string; body: Uint8Array; authorization: string }[] = []; + const outward = async (url: string | URL | Request, init?: { body?: unknown; headers?: Record }) => { const u = String(url); if (u === ISSUER.jwksUri) return { ok: true, status: 200, json: async () => ({ keys: [access.jwk] }) }; if (u.startsWith("https://fcm.googleapis.com/")) { - pushes.push({ url: u, body: init?.body as Uint8Array }); + pushes.push({ url: u, body: init?.body as Uint8Array, authorization: init?.headers?.Authorization ?? "" }); return { status: 201 }; } throw new Error(`unexpected fetch ${u}`); @@ -110,10 +110,23 @@ async function setup() { }; const hostDocs = new Docs( Object.fromEntries( - SECTION_NAMES.map((name) => [name, { ttlMs: 10_000, load: async () => structuredClone(data[name]) }]), + SECTION_NAMES.map((name) => [ + name, + { + ttlMs: 10_000, + load: async () => { + if (failing.has(name)) throw new Error(`${name}: the source is down`); + return structuredClone(data[name]); + }, + }, + ]), ), clock, ); + /** Sections whose source cannot be read just now. */ + const failing = new Set(); + /** Held open by a test to keep an action running. */ + const gate: { wait: Promise | null } = { wait: null }; const ran: { kind: string; args: Record }[] = []; const table: Record = { "ask.send": { @@ -149,6 +162,26 @@ async function setup() { touch: ["prs"], audit: (a) => ({ pr: a.pr }), }, + // An answer the dashboard may refuse without anything being thrown. + "question.answer": { + run: async (a) => { + ran.push({ kind: "question.answer", args: a }); + return a.qid === "settled" + ? { applied: 0, refused: [{ qid: a.qid, why: "already-resolved" }] } + : { applied: 1, refused: [] }; + }, + touch: [], + audit: (a) => ({ qid: a.qid }), + }, + "need.comment": { + run: async (a) => { + ran.push({ kind: "need.comment", args: a }); + await gate.wait; + return { commented: a.ref }; + }, + touch: [], + audit: (a) => ({ ref: a.ref }), + }, }; const audited: Record[] = []; const hostDeps: Deps = { @@ -162,7 +195,9 @@ async function setup() { audited.push(entry); }, }; - const net = { hostUp: true, edgeUp: true }; + const net = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false }; + /** Requests to the host still running after the edge stopped waiting. */ + const stillRunning: Promise[] = []; const hostSaw: string[] = []; const edgeConfig: EdgeConfig = { owners: [OWNER], @@ -189,7 +224,18 @@ async function setup() { if (!net.hostUp) return null; hostSaw.push(`${r.method} ${new URL(r.url).pathname}`); // Through the tunnel: the connection is local, the headers are the edge's. - return marked(await handle(r, hostDeps, "127.0.0.1")); + const answer = handle(r, hostDeps, "127.0.0.1").then(marked); + // The edge stops waiting while the host is still at it. + if (net.giveUpEarly) { + stillRunning.push(answer); + return null; + } + // The host does the work and its answer is lost on the way back. + if (net.loseAnswer) { + await answer; + return null; + } + return answer; }, publicHost: HOST, version: "test", @@ -217,7 +263,11 @@ async function setup() { log: () => {}, }); const link = { now: makeLink() }; - hostDeps.link = { publicKey: () => link.now.publicKey() }; + hostDeps.link = { + publicKey: () => link.now.publicKey(), + begin: (id) => link.now.begin(id), + end: (id, fate) => link.now.end(id, fate), + }; const token = (claims: Record = {}) => access.sign({ @@ -288,6 +338,9 @@ async function setup() { act, core, hostReads, + failing, + gate, + stillRunning, table, access, edgeConfig, @@ -311,6 +364,7 @@ describe("before the host's first report", () => { answered: 0, deferred: 0, version: "test", + host: HOST, }); // The owner's page is the host's own, reached through the edge. const page = await w.browse("/console/api/me"); @@ -470,6 +524,33 @@ describe("the owner, at the edge", () => { expect(Number(res.headers.get("x-host-seen"))).toBe(last); }); + test("when the host cannot read a source, the edge says so, and stops saying so when it can", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + expect((await w.core()).doc.health.census).toEqual({ ok: true, error: null }); + // The source goes down. The host keeps its last good copy, so the + // data does not change, and neither does its fingerprint. + w.failing.add("census"); + w.now.t += 11_000; + await w.hostReads(); + await w.link.now.once(); + let { doc } = await w.core(); + expect(doc.health.census).toEqual({ ok: false, error: "census: the source is down" }); + expect(doc.census).toEqual(w.data.census); + expect(doc.health.board).toEqual({ ok: true, error: null }); + // The edge restarts: it still knows. + w.edge.now = w.makeEdge(); + expect((await w.core()).doc.health.census.ok).toBe(false); + // The source comes back with the same data. + w.failing.delete("census"); + w.now.t += 11_000; + await w.hostReads(); + await w.link.now.once(); + ({ doc } = await w.core()); + expect(doc.health.census).toEqual({ ok: true, error: null }); + }); + test("a large section is kept in pieces and read back whole after a restart", async () => { const w = await setup(); const big = { open: Array.from({ length: 4000 }, (_, i) => ({ qid: `q${i}`, question: "é".repeat(400) })) }; @@ -550,7 +631,9 @@ describe("actions", () => { // A merge acts on what the owner saw; it is never done late. const merge = await w.act("pr.merge", { pr: 7 }); expect(merge.status).toBe(503); - expect(((await merge.json()) as { error: string }).error).toMatch(/not safe to do late/); + expect(((await merge.json()) as { error: string }).error).toMatch( + /not something to do late, so it is not kept\. Check whether it happened/, + ); expect(w.ran).toEqual([]); // The app says what is waiting. let { doc } = await w.core(); @@ -651,6 +734,84 @@ describe("actions", () => { expect(notes.join(" | ")).toMatch(/restarted while doing this/); }); + test("an action the host did, whose answer was lost on the way back, is not done again", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.loseAnswer = true; + const res = await w.act("ask.send", { text: "only once" }); + w.net.loseAnswer = false; + // The edge cannot tell "never arrived" from "done, answer lost": it holds it. + expect(await res.json()).toEqual({ ok: true, held: true, result: null }); + expect(w.ran).toHaveLength(1); + // The host is offered it under the name it was relayed with, knows + // it did it, and says so instead of doing it again. + w.now.t += 1_000; + const offered = await w.link.now.once(); + expect(offered?.commands.map((c) => c.kind)).toEqual(["ask.send"]); + expect(w.ran).toHaveLength(1); + w.now.t += 1_000; + expect((await w.link.now.once())?.commands).toEqual([]); + const { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 0 }); + expect(doc.asks.map((a: { text: string }) => a.text)).toEqual(["only once"]); + expect( + doc.acts.filter((a: { kind: string }) => a.kind === "ask.send").map((a: { status: string }) => a.status), + ).toEqual(["done"]); + }); + + test("an action the host is still doing when the edge stops waiting is neither repeated nor reported early", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + let open = () => {}; + w.gate.wait = new Promise((resolve) => { + open = resolve; + }); + w.net.giveUpEarly = true; + const res = await w.act("need.comment", { ref: "code#1", text: "slow" }); + w.net.giveUpEarly = false; + expect(await res.json()).toEqual({ ok: true, held: true, result: null }); + // Offered again while still running: not run a second time, and not answered for yet. + w.now.t += 1_000; + const during = await w.link.now.once(); + expect(during?.commands.map((c) => c.kind)).toEqual(["need.comment"]); + w.now.t += 1_000; + expect((await w.link.now.once())?.commands).toHaveLength(1); + expect(w.ran).toHaveLength(1); + // It finishes. Now the host answers for it, once. + open(); + await Promise.all(w.stillRunning); + w.now.t += 1_000; + await w.link.now.once(); + w.now.t += 1_000; + expect((await w.link.now.once())?.commands).toEqual([]); + expect(w.ran).toHaveLength(1); + expect((await w.core()).doc.edge).toEqual({ held: 0 }); + }); + + test("an answer sent late that the dashboard no longer takes is reported as not recorded", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + await w.act("question.answer", { set: "s", ledger: "l", qid: "settled", optionId: "a" }); + await w.act("question.answer", { set: "s", ledger: "l", qid: "open", optionId: "a" }); + w.net.hostUp = true; + w.now.t += 1_000; + await w.link.now.once(); + w.now.t += 1_000; + await w.link.now.once(); + expect(w.ran.map((r) => r.args.qid)).toEqual(["settled", "open"]); + const { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 0 }); + const answers = doc.acts.filter((a: { kind: string }) => a.kind === "question.answer"); + expect(answers.map((a: { status: string }) => a.status).sort()).toEqual(["done", "failed"]); + expect(answers.find((a: { status: string }) => a.status === "failed").note).toMatch( + /not recorded: already-resolved/, + ); + }); + test("a held action is dropped after a day, and said to have been", async () => { const w = await setup(); await w.hostReads(); @@ -931,6 +1092,12 @@ describe("notifications and phones, from the edge", () => { await w.link.now.once(); expect(w.pushes).toHaveLength(1); expect(JSON.parse(await phone.open(w.pushes[0].body))).toMatchObject({ url: "/console/#ask" }); + // The push service is given the project's page as the contact, and nobody's address. + const claims = JSON.parse( + Buffer.from((/^vapid t=[^.]+\.([^.]+)\./.exec(w.pushes[0].authorization) ?? [])[1] ?? "", "base64url").toString(), + ); + expect(claims.sub).toBe("https://github.com/developing-today/code"); + expect(w.pushes[0].authorization).not.toContain("mailto"); // The host stops reporting. The alarm set at its last report finds it quiet, once. expect(w.alarm.at).toBe(w.now.t + SILENT_MS + 1000); diff --git a/pm-stack/console/test/push.test.ts b/pm-stack/console/test/push.test.ts index 9ad9685f7c..ef3e80aeb2 100644 --- a/pm-stack/console/test/push.test.ts +++ b/pm-stack/console/test/push.test.ts @@ -12,7 +12,7 @@ import { join } from "node:path"; import { Docs } from "../src/docs.ts"; import { fileStore } from "../src/file-store.ts"; import { changes, NOTHING_SEEN, Notifier, type Seen } from "../src/notify.ts"; -import { encrypt, Push, validSubscription } from "../src/push.ts"; +import { contact, encrypt, endpointMark, Push, validSubscription } from "../src/push.ts"; import { b64u, browser, raw } from "./support.ts"; describe("the message a phone receives", () => { @@ -91,7 +91,13 @@ describe("the message a phone receives", () => { const again = new Push(fileStore(join(dir, "push.json")), "mailto:owner@example.com", async () => ({ status: 201, })); - expect(await again.status()).toEqual(status.devices === 0 ? { ...status, devices: 2 } : status); + // It still holds both devices, each known by its mark and not by its address. + const marks = [await endpointMark(a.subscription.endpoint), await endpointMark(m.subscription.endpoint)]; + expect(await again.status()).toEqual({ ...status, devices: 2, known: marks }); + expect(status.known).toEqual([]); + expect(marks[0]).toMatch(/^[A-Za-z0-9_-]{16}$/); + expect(marks[0]).not.toBe(marks[1]); + expect(JSON.stringify(await again.status())).not.toContain("fcm.googleapis.com"); expect((await again.status()).key).toBe(status.key); expect(JSON.parse(readFileSync(join(dir, "push.json"), "utf8")).vapid.privateJwk.d.length).toBeGreaterThan(20); } finally { diff --git a/pm-stack/console/test/redeploy.test.ts b/pm-stack/console/test/redeploy.test.ts index 73c0b9b5eb..e9a27e28fd 100644 --- a/pm-stack/console/test/redeploy.test.ts +++ b/pm-stack/console/test/redeploy.test.ts @@ -83,10 +83,14 @@ beforeEach(() => { // in and one setting from the service's file, then passes or fails. writeFileSync( join(dir, "fake-bun"), - `#!/usr/bin/env bash\necho "check $* in=$(basename "$PWD") port=\${PM_CONSOLE_PORT:-} note=\${PM_NOTE:-}" >>"${log}"\n[ "$CHECK" = pass ] || { echo "boom: cannot start" >&2; exit 1; }\necho "pm-console: check passed"\n`, + `#!/usr/bin/env bash\necho "check $* in=$(basename "$PWD") port=\${PM_CONSOLE_PORT:-} note=\${PM_NOTE:-} plain=\${PM_PLAIN:-}" >>"${log}"\n[ "$CHECK" = pass ] || { echo "boom: cannot start" >&2; exit 1; }\necho "pm-console: check passed"\n`, ); chmodSync(join(dir, "fake-bun"), 0o755); - writeFileSync(join(home, ".local/state/pm-console/.env"), "# settings\nPM_CONSOLE_PORT=4872\n\nPM_NOTE=two words\n"); + // As systemd allows: a comment, a blank line, quoted values, a value with a space. + writeFileSync( + join(home, ".local/state/pm-console/.env"), + '# settings\nPM_CONSOLE_PORT="4872"\n\nPM_NOTE=\'two words\'\nPM_PLAIN=it\'s "kept"\n', + ); git("init", "-q", "-b", "main"); git("add", "-A"); git("commit", "-q", "-m", "one"); @@ -100,7 +104,10 @@ describe("redeploy.sh", () => { expect(first.code).toBe(0); expect(first.out).toContain("is in service"); // The check ran in the console's directory, with the settings file's values, spaces and all. - expect(events()).toEqual(["check run src/server.ts --check in=console port=4872 note=two words", "install"]); + expect(events()).toEqual([ + 'check run src/server.ts --check in=console port=4872 note=two words plain=it\'s "kept"', + "install", + ]); expect(state("deployed")).not.toBeNull(); // Nothing has changed: nothing is checked or installed again. expect(run().code).toBe(0);