From b7b881dc3730320ae43c781bda499864e2bb23ce Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:14:24 -0600 Subject: [PATCH 1/2] feat(pm-stack): serve the PM app from the edge; the laptop becomes a worker behind it The app ran only on the laptop, behind a tunnel, so it was as available as the laptop's uplink and processor: on 2026-11-22 the uplink dropped every tunnel connection for a quarter hour (#12414) and nothing loaded. A Cloudflare Worker (pm-stack/console/edge) now sits in front of the hostname and serves the app, its state, notifications and the phone widget from Cloudflare. - State is a copy the laptop reports (only the sections that changed, signed with a key made on the laptop; the edge learns the public half by asking the laptop through the tunnel, so there is no shared secret). The app shows how old the copy is. - An action that needs the laptop is relayed at once when it is in reach. Taken while it is not, one that is safe to do late (a prompt, an answer, a comment) is held and run at most once when the laptop is back; a merge, a unit operation or a task state change is refused. - The edge answers only when it is sure of the owner and otherwise passes the request to the laptop, so a fault in its check cannot lock the owner out. If the Worker throws, or has not heard from the laptop yet, requests go to the laptop as before. - Notifications are sent from the edge, and one says when the laptop has gone quiet for ten minutes, and when it is back. - Deploys run from GitHub Actions with the Cloudflare secrets message-bridge already uses. The Worker has no secrets of its own and no route in its config: expose.py sends the hostname through it once it answers its health check, and `expose.py --edge off` takes it off. - Merged console code now puts itself into service on the laptop (redeploy.sh, every minute), after a self-check that listens on nothing; code that does not start is left out. The classes that keep state (notifications, linked phones) take a Store instead of a file path, so the same code runs in both places. Tests: 98 bun tests (18 drive the Worker's real routing and state with the laptop's real handler behind them; 6 run redeploy.sh against a checkout made for the test), 12 python tests for expose.py. 36 of 37 planted faults caught; the one left changes no behaviour. The Worker was also run in the real runtime (wrangler dev) against a local host, 17 checks, and the app was driven in Chrome through the edge code with the host up, down and back. Design record: doc/2026-11-22T11-10-00Z_architecture_pm_console_edge. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- .github/workflows/pm-console-edge-deploy.yml | 124 ++ ...T11-10-00Z_architecture_pm_console_edge.md | 115 ++ pm-stack/console/README.md | 46 +- pm-stack/console/edge/.gitignore | 3 + pm-stack/console/edge/README.md | 125 ++ pm-stack/console/edge/build.mjs | 19 + pm-stack/console/edge/package-lock.json | 1544 +++++++++++++++++ pm-stack/console/edge/package.json | 15 + pm-stack/console/edge/src/edge.ts | 671 +++++++ pm-stack/console/edge/src/entry.ts | 166 ++ pm-stack/console/edge/src/worker.ts | 89 + pm-stack/console/edge/wrangler.jsonc | 35 + pm-stack/console/install.sh | 9 +- pm-stack/console/public/app.js | 74 +- pm-stack/console/redeploy.sh | 68 + pm-stack/console/scripts/demo-state.ts | 382 ++++ pm-stack/console/scripts/demo.ts | 381 +--- pm-stack/console/scripts/edge-demo.ts | 153 ++ pm-stack/console/scripts/edge-smoke.ts | 205 +++ pm-stack/console/scripts/expose.py | 123 +- pm-stack/console/scripts/test_expose.py | 116 +- pm-stack/console/src/actions.ts | 17 +- pm-stack/console/src/config.ts | 35 + pm-stack/console/src/devices.ts | 22 +- pm-stack/console/src/docs.ts | 59 +- pm-stack/console/src/edge-proto.ts | 201 +++ pm-stack/console/src/errors.ts | 11 + pm-stack/console/src/file-store.ts | 30 + pm-stack/console/src/http.ts | 174 ++ pm-stack/console/src/notify.ts | 14 +- pm-stack/console/src/ops.ts | 10 +- pm-stack/console/src/push.ts | 20 +- pm-stack/console/src/server.ts | 313 ++-- pm-stack/console/src/store.ts | 24 + pm-stack/console/src/sync.ts | 248 +++ pm-stack/console/test/devices.test.ts | 5 +- pm-stack/console/test/edge.test.ts | 989 +++++++++++ pm-stack/console/test/push.test.ts | 74 +- pm-stack/console/test/redeploy.test.ts | 182 ++ pm-stack/console/test/support.ts | 83 + pm-stack/systemd/pm-console-redeploy.service | 13 + pm-stack/systemd/pm-console-redeploy.timer | 10 + 42 files changed, 6308 insertions(+), 689 deletions(-) create mode 100644 .github/workflows/pm-console-edge-deploy.yml create mode 100644 doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md create mode 100644 pm-stack/console/edge/.gitignore create mode 100644 pm-stack/console/edge/README.md create mode 100644 pm-stack/console/edge/build.mjs create mode 100644 pm-stack/console/edge/package-lock.json create mode 100644 pm-stack/console/edge/package.json create mode 100644 pm-stack/console/edge/src/edge.ts create mode 100644 pm-stack/console/edge/src/entry.ts create mode 100644 pm-stack/console/edge/src/worker.ts create mode 100644 pm-stack/console/edge/wrangler.jsonc create mode 100755 pm-stack/console/redeploy.sh create mode 100644 pm-stack/console/scripts/demo-state.ts create mode 100644 pm-stack/console/scripts/edge-demo.ts create mode 100644 pm-stack/console/scripts/edge-smoke.ts create mode 100644 pm-stack/console/src/edge-proto.ts create mode 100644 pm-stack/console/src/errors.ts create mode 100644 pm-stack/console/src/file-store.ts create mode 100644 pm-stack/console/src/http.ts create mode 100644 pm-stack/console/src/store.ts create mode 100644 pm-stack/console/src/sync.ts create mode 100644 pm-stack/console/test/edge.test.ts create mode 100644 pm-stack/console/test/redeploy.test.ts create mode 100644 pm-stack/console/test/support.ts create mode 100644 pm-stack/systemd/pm-console-redeploy.service create mode 100644 pm-stack/systemd/pm-console-redeploy.timer diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml new file mode 100644 index 0000000000..0e6425a8cd --- /dev/null +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -0,0 +1,124 @@ +name: pm-console-edge deploy + +# CI tier policy: see .github/ci-policy.md. This is a deploy, not CI, +# so it keeps a push trigger (restricted to main). +# +# Deploys the Worker that serves the PM app from the edge +# (pm-stack/console/edge): every push to main that touches the console, +# or a manual run, runs the console's tests (which drive the Worker's +# routing and state against the host's real handler), bundles the +# Worker, and uploads it with the CLOUDFLARE_API_TOKEN and +# CLOUDFLARE_ACCOUNT_ID repository secrets, the ones message-bridge +# deploys with. +# +# The Worker has no secrets: the keys it uses it makes itself, or are +# published by the host. It has no route here either. The host's +# pm-stack/console/scripts/expose.py sends the hostname through it once +# it answers its health check, and `expose.py --edge off` takes the +# hostname off it again, which is the rollback that needs no deploy. A +# manual run with rollback_version puts an earlier version back. +# +# Until both secrets exist the job says so in its summary and skips the +# upload instead of failing. +on: + push: + branches: [main] + paths: + - "pm-stack/console/**" + - "!pm-stack/console/android/**" + - "pm-stack/aggregator/src/assets/icons/**" + - ".github/workflows/pm-console-edge-deploy.yml" + workflow_dispatch: + inputs: + rollback_version: + description: "Existing Worker version id to put back instead of uploading; empty deploys this commit" + required: false + default: "" + +permissions: + contents: read + +# Deploys run one at a time, in order; a newer push never cancels one +# that is uploading. +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + +jobs: + deploy: + name: deploy pm-console-edge + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Check deploy secrets + id: secrets + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + run: | + if [ -n "$CLOUDFLARE_API_TOKEN" ] && [ -n "$CLOUDFLARE_ACCOUNT_ID" ]; then + echo "ready=true" >> "$GITHUB_OUTPUT" + else + echo "ready=false" >> "$GITHUB_OUTPUT" + echo "Skipped the upload: set the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID repository secrets to deploy pm-console-edge from the repo." >> "$GITHUB_STEP_SUMMARY" + fi + - uses: actions/checkout@v7 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - name: Test the console and its edge + working-directory: pm-stack/console + run: bun test + - name: Install the deploy tool + working-directory: pm-stack/console/edge + run: npm ci --no-audit --no-fund + - name: Bundle the Worker + working-directory: pm-stack/console/edge + run: | + node build.mjs + npx wrangler deploy --dry-run --outdir .wrangler/dry + - name: Deploy + if: steps.secrets.outputs.ready == 'true' + working-directory: pm-stack/console/edge + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + ROLLBACK_VERSION: ${{ inputs.rollback_version }} + run: | + # The input goes through the env, never into the script text, + # and must look like a version id before it is used. + if [ -n "${ROLLBACK_VERSION:-}" ]; then + if ! printf '%s' "$ROLLBACK_VERSION" | grep -Eq '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'; then + echo "rollback_version is not a version id" >&2 + exit 2 + fi + npx wrangler rollback "$ROLLBACK_VERSION" --yes --message "rollback from workflow run ${GITHUB_RUN_ID}" + echo "Put pm-console-edge back to version ${ROLLBACK_VERSION}." >> "$GITHUB_STEP_SUMMARY" + else + npx wrangler deploy --var "VERSION:${GITHUB_SHA::12}" --message "git ${GITHUB_SHA}" + echo "Deployed pm-console-edge from ${GITHUB_SHA}." >> "$GITHUB_STEP_SUMMARY" + fi + - name: Check the deployed Worker answers + if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + run: | + # The workers.dev address answers the health check and the + # public files only. Its subdomain is the account's. + sub="$(curl -fsS -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \ + "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["result"]["subdomain"])')" + url="https://pm-console-edge.${sub}.workers.dev/console/health" + want="${GITHUB_SHA::12}" + for attempt in $(seq 1 20); do + got="$(curl -fsS --max-time 10 "$url" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("version") if d.get("ok") and d.get("edge") else "")' 2>/dev/null || true)" + if [ "$got" = "$want" ]; then + echo "pm-console-edge answers as ${want}." >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + sleep 6 + done + echo "the deployed Worker did not answer its health check as ${want} (last answer: ${got:-none})" >&2 + exit 1 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 new file mode 100644 index 0000000000..fac4431f75 --- /dev/null +++ b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md @@ -0,0 +1,115 @@ +# PM console served from the edge + +Status at writing: built and tested, about to be deployed. Later +sections record what happened when it went live. + +## What was asked + +The owner, 2026-11-21 23:58 CST: the app's pages "still don't load +correctly", and "making everything work inside of the PM stack from +Cloudflare without requiring the laptop is completely within your +purview". Then, 2026-11-22 04:32 CST: "continue fully implementing this +system and relying on cloudflare instead of laptop for operations where +possible". + +## What was wrong + +The app (`pm-stack/console`) ran only on the laptop, behind a Cloudflare +tunnel. Measured on 2026-11-22: + +- The laptop's uplink dropped every tunnel connection at 04:58:53Z and + flapped until 05:14 (evidence on #12414). During that time nothing at + `pm.security.cab` loaded at all. +- The laptop ran at load average 47 to 75 on 16 cores while the fleet + compiled, which starved the management services (`CPUWeight=900` was + set on them in #12452). + +A service on one laptop is as available as that laptop's uplink and +processor. The app should not be. + +## Decision + +Put a Cloudflare Worker in front of the hostname and serve the app from +it. The laptop stays the machine with the fleet's tools, and becomes a +worker behind the edge. + +1. **The edge serves** the app's files, its state (from a copy the + laptop reports), notifications (keys, subscriptions, sending) and the + linked-phone summary. +2. **The laptop reports** the sections of state that changed, signed + with its own key, and says how current each unchanged section is. +3. **An action that needs the laptop is relayed at once** when it is in + reach. When it is not, an action that is safe to do late is held at + the edge and run once when the laptop is back; one that is not safe + (a merge, a unit operation, a change to a task's state) is refused. +4. **The edge never refuses on its own.** It answers when it is sure of + the owner; otherwise it passes the request to the laptop. With the + laptop out of reach an unsure caller gets a plain notice and nothing + else. +5. **Deploys run from GitHub Actions**; the laptop's `expose.py` only + decides whether the hostname goes through the Worker, and can take it + off again. + +## Why this shape + +| Choice | Instead of | Reason | +| ----------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Laptop pushes state to the edge | Edge pulls from the laptop | A push needs the edge to recognise the laptop (a public key). A pull needs the laptop to recognise the edge (a secret kept at the edge). | +| The laptop's key, fetched through the tunnel | A shared secret in Bitwarden and in the Worker | Nothing to store, rotate or leak. Only the laptop can answer through its tunnel. | +| Edge config (owner, issuer, audience) arrives in the report | Worker variables | One place it is set, and nothing private in a public repository. | +| Serve from the copy, tell the laptop someone is looking | Ask the laptop first and fall back | The copy answers in milliseconds whatever the laptop's load; asking first makes every read as slow as the laptop. | +| Held actions limited to a named list | Hold everything | A merge or a unit operation acts on what the owner saw. Done hours later it may act on something else. | +| At most once for a held action | At least once | A second prompt or a second comment is worse than one reported as interrupted. | +| Defer to the laptop when unsure | Refuse at the edge | A fault in the edge's check must not lock the owner out. The laptop's check is the one already proven. | +| One Durable Object | KV or D1 | One writer, small state, an alarm for the silent-laptop check, and consistent reads straight after writes. | +| `wrangler deploy` from CI | The `cf` versions flow under Nix used by message-bridge | The Worker has no secrets, so a code-only deploy is the whole deploy, and it could be run and checked on the build machine before it was written into CI. Moving to the `cf` flow is a packaging change with no change of behaviour. | + +## What the laptop trusts + +The laptop used to act only for a caller with a sign-in token it had +verified. It now also runs the held actions in the answer to its own +report. That answer comes over TLS from the hostname's Worker, in the +owner's Cloudflare account, which verified the owner's token when the +action was taken. An attacker who controls that account already controls +the sign-in in front of the laptop, so this adds no one to the set of +parties the laptop relies on. The laptop still limits what it will run +late to the named list, runs each at most once, and records each with +who took it and when. + +## What this does not do + +- With the laptop off, state does not go on changing at the edge: it is + the last report, with its age shown. Reading the queue store and + GitHub straight from the edge would fix that for the queue and for + prompts; it needs those two credentials at the edge and is a separate + step. +- Questions and their answers still live in the laptop's decision store. + An answer given with the laptop away is held, not applied. +- The dashboard's own pages are the laptop's. With it away they are a + notice with a link to the app. + +## How it was checked before going live + +- `bun test` in `pm-stack/console`: the Worker's real routing and state, + with the laptop's real handler behind them and the laptop's real link + reporting through the same routing. Stand-ins only at the outside + (storage, the sign-in issuer's key, the push service). +- A mutation check: 37 planted faults in the edge, the routing, the link + and the protocol. 36 were caught. The one left (dropping a length + check on a signature) changes no behaviour: verification refuses a + short signature anyway. +- One of those faults found a real defect: a section that had not + changed looked stale at the edge while the laptop was reporting + normally, because only changed sections carried a time. The report now + says how current every section is. +- The Worker in the real runtime (`wrangler dev`) against a local host: + 17 checks, including the signed report, the key fetch, a 2 MB section + kept in pieces, and the host going away. +- The app driven in Chrome through the edge code: open, send a prompt + with the host up, take the host down, send another (held), bring it + back (sent once, shown as sent late). + +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. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 6676ad94d8..40372d6227 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -76,6 +76,39 @@ the coverage reconciliation. The rank sets the task's place in the queue. If the enqueue fails, the issue still exists and the page says it is not queued. +### Served from the edge + +The app is served by a Cloudflare Worker in front of the hostname +([`edge/`](edge/README.md)), so it opens and works whether or not this +host can be reached. This service stays what it is, the machine with the +fleet's tools on it, and becomes a worker behind the edge: + +- It reports its state to the edge (`src/sync.ts`): the sections that + changed, signed with a key made here whose private half never leaves. + The edge learns the public half by asking this host through the tunnel + (`GET /console/edge/key`). +- An action that needs this host is relayed to it at once. One taken + while it could not be reached is held at the edge if it is safe to do + late, and run here at most once when it is back, recorded in the audit + log as `via: edge-held`. +- Every response this service writes carries `X-PM-Console: 1`, so the + edge can tell "the host answered, with an error" from "the host could + not be reached". + +Set `PM_CONSOLE_EDGE_URL` to turn the reporting on; `scripts/expose.py` +does that when it sends the hostname through the Worker. Without it this +service reports to nobody and serves the app itself, as before. + +### Merges deploy themselves + +`pm-console-redeploy.timer` runs `redeploy.sh` every minute. When the +checkout holds console code that is not the code in service, the new +code is started in a self-check that listens on nothing +(`bun run src/server.ts --check`, with the service's own settings); only +if that passes is it put into service. Code that does not start is left +out, the old code keeps running, and the unit fails, which the Services +screen and notifications show. + ## Sign-in The console runs no sign-in of its own. A caller arrives with a signed @@ -112,10 +145,13 @@ app's link to this origin), and the two phone paths under ## Run ```bash -bash pm-stack/console/install.sh # user unit pm-console, port 4872, loopback only +bash pm-stack/console/install.sh # user unit pm-console, port 4872, loopback only; and its two timers python3 pm-stack/console/scripts/expose.py --check # what public exposure would change -python3 pm-stack/console/scripts/expose.py # Access, console env, tunnel route, DNS +python3 pm-stack/console/scripts/expose.py # Access, console env, tunnel route, DNS, the edge's route +python3 pm-stack/console/scripts/expose.py --edge off # hostname straight to this host, not through the edge cd pm-stack/console && bun test +bun run scripts/demo.ts # the app with made-up state, on this host alone +bun run scripts/edge-demo.ts # the same behind the edge ``` `expose.py` is safe to run again: it changes only what is not already so @@ -137,11 +173,13 @@ the route if the console does not come up with its sign-in settings. | `PM_CONSOLE_ANDROID_PACKAGE`, `PM_CONSOLE_ANDROID_SHA256` | `today.developing.pmconsole`, none | The Android app's identity in the asset-links file | | `PM_CONSOLE_ANDROID_APK` | `~/.local/state/pm-console/android/pm-console.apk` | The signed build the console hands to the owner | | `PM_CONSOLE_DEVICES_FILE` | `~/.local/state/pm-console/devices.json` | Linked phones (hashes of their tokens) | +| `PM_CONSOLE_EDGE_URL` | unset (reports to nobody) | The public address the edge answers on, `https://` | +| `PM_CONSOLE_EDGE_KEY_FILE`, `PM_CONSOLE_EDGE_DONE_FILE` | `edge-key.json`, `edge-done.json` in the state dir | This host's signing key; what it ran for the edge | | `PM_CONSOLE_REPO`, `PM_CONSOLE_QUEUE` | `developing-today/code`, `repo-health-code-pilot` | What it operates on | A malformed port, a listen address or dashboard address that is not -loopback, or a malformed issuer stops the process at boot and names the -variable. +loopback, an edge address that is not plain `https://host`, or a +malformed issuer stops the process at boot and names the variable. ## Android diff --git a/pm-stack/console/edge/.gitignore b/pm-stack/console/edge/.gitignore new file mode 100644 index 0000000000..d27f2ecb05 --- /dev/null +++ b/pm-stack/console/edge/.gitignore @@ -0,0 +1,3 @@ +dist/ +node_modules/ +.wrangler/ diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md new file mode 100644 index 0000000000..18890a7619 --- /dev/null +++ b/pm-stack/console/edge/README.md @@ -0,0 +1,125 @@ +# pm-console-edge + +The Cloudflare Worker in front of `https://pm.security.cab`. It serves +the PM app, its state, its notifications and the phone widget from +Cloudflare, so the app opens and works whether or not the laptop that +runs the fleet's tools can be reached. + +## What runs where + +| Thing | Where | When the laptop cannot be reached | +| -------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------- | +| The app's page, script and icons | edge | unchanged | +| Checking who is calling | edge, and again on the laptop | the edge still answers the owner; anyone it is unsure of gets nothing | +| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | served as of the last report, with that time shown | +| Notifications: keys, subscriptions, sending | edge | unchanged; and one says the laptop has gone quiet | +| Linked phones and the widget's summary | edge | unchanged | +| Actions safe to do late (prompts, answers, comments, …) | laptop, relayed at once | held at the edge, run once when it is back, dropped after a day and said so | +| Actions not safe to do late (merge, units, unblock, …) | laptop, relayed at once | refused, saying why | +| The dashboard's own pages, logs, one pull request's page | laptop | a plain notice with a link to the app | + +The list of actions that may be done late is `HOLDABLE` in +`../src/edge-proto.ts`. + +## How it is put together + +``` +phone / browser + │ HTTPS +Cloudflare Access ── sign-in (email code; Google once its client exists) + │ +pm-console-edge (this Worker, on the hostname's route) + ├─ src/worker.ts wiring: the object, the app's files, the laptop + ├─ src/entry.ts what to do with a request + └─ src/edge.ts the state, in one Durable Object + │ same hostname, through the tunnel +laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts +``` + +- **Every request goes to the object first**, which checks who is + calling with the same code the laptop uses (`../src/auth.ts`). It + answers only when it is sure of the owner. When it is not, it does not + refuse: it passes the request to the laptop, which decides as it always + has. So a mistake at the edge can cost the edge's speed, never the + owner's way in, and a stranger gets from the laptop exactly what a + stranger got before. +- **The laptop reports** to `POST /console/edge/sync`: the sections of + state that changed, how current each unchanged one is, and what became + of anything held for it. The answer says whether anyone is looking, and + carries the actions the owner took while it was away. +- **An action for the laptop is relayed at once** when the laptop is in + reach; its answer carries what it read again, so the edge's copy shows + the change before the next report. +- **A held action is run at most once.** The laptop writes its id down + before starting it; if it dies part-way, the action is reported as + interrupted and never run again. +- **Before the laptop's first report, and whenever the Worker throws**, + requests go to the laptop exactly as they did before this Worker + existed. + +## Who trusts what + +- **The owner** is whoever presents a sign-in token that verifies + against the issuer's published keys, for this application, carrying the + owner's address. The edge learns the issuer and the address from the + laptop's report. +- **The laptop** is whoever signs a report with the laptop's key. The + key pair is made on the laptop and the private half never leaves it. + The edge learns the public half by asking the laptop through the + tunnel (`GET /console/edge/key`), which only the laptop can answer. + There is no shared secret, here or in the repository. A report is + refused unless the signature verifies, its time is within two minutes + of the edge's clock, and it is later than the last one accepted. +- **A phone** is whoever holds a token the edge issued after the owner + approved it. The edge keeps only the token's hash. +- **The laptop trusts the edge** for one thing: the held actions in the + answer to its own report, fetched over TLS from this hostname. It runs + only actions on the late list, and records each in its audit log as + `via: edge-held` with who took it and when. + +The Worker has no secrets configured. The keys it uses it made itself +(notification signing) or were published to it (the laptop's, the +sign-in issuer's). + +## Deploy, and going back + +Pushes to `main` that touch the console deploy it +(`.github/workflows/pm-console-edge-deploy.yml`): the console's tests, +which drive this Worker's routing and state against the laptop's real +handler; a bundle; `wrangler deploy`; then a check that the deployed +Worker answers its health check as that commit. + +The Worker has no route in `wrangler.jsonc` on purpose. The laptop's +`scripts/expose.py` (on a 15 minute timer) sends the hostname through it +once it answers its health check, after telling the console where to +report. Three ways back, quickest first: + +```bash +python3 pm-stack/console/scripts/expose.py --edge off # hostname goes straight to the laptop; remembered +gh workflow run pm-console-edge-deploy.yml -f rollback_version= # an earlier version of the Worker +git revert # and the next push deploys it +``` + +## Run it here + +```bash +cd pm-stack/console && bun test # routing, state and the laptop's link, end to end +bun run scripts/edge-demo.ts # the app behind the edge with made-up state: http://127.0.0.1:4897/ +cd edge && npm ci && node build.mjs +npx wrangler deploy --dry-run --outdir .wrangler/dry # does it bundle +npx wrangler dev --port 8799 --var PUBLIC_HOST:localhost --var HOST_ORIGIN:http://127.0.0.1:4898 --var VERSION:smoke +bun run ../scripts/edge-smoke.ts # in another shell: the real Worker runtime against a local host +``` + +`HOST_ORIGIN` exists for that last run only. Deployed, the laptop is +simply what is behind the hostname. + +## Limits worth knowing + +- State at the edge is the laptop's last report. With the laptop gone it + ages, and the app says how old it is; it does not go on changing. +- Reading the queue and filing a prompt straight from the edge, with the + laptop off, is not built: it needs the queue store's and GitHub's + credentials at the edge. +- The storage is one Durable Object. A section larger than one stored + value is kept in pieces. diff --git a/pm-stack/console/edge/build.mjs b/pm-stack/console/edge/build.mjs new file mode 100644 index 0000000000..708dc6bcf7 --- /dev/null +++ b/pm-stack/console/edge/build.mjs @@ -0,0 +1,19 @@ +// Puts the app's files where the Worker serves them from: dist/console/ +// (the page, its script and style, its service worker) and dist/icons/ +// (the install icons, which live with the dashboard). +import { cpSync, mkdirSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const dist = join(here, "dist"); +rmSync(dist, { recursive: true, force: true }); +mkdirSync(join(dist, "console"), { recursive: true }); +mkdirSync(join(dist, "icons"), { recursive: true }); +for (const name of ["index.html", "app.js", "app.css", "icon.svg", "sw.js"]) { + cpSync(join(here, "..", "public", name), join(dist, "console", name)); +} +for (const name of ["icon-192.png", "icon-512.png", "icon-maskable-512.png", "apple-touch-icon.png"]) { + cpSync(join(here, "..", "..", "aggregator", "src", "assets", "icons", name), join(dist, "icons", name)); +} +console.log(`built ${dist}`); diff --git a/pm-stack/console/edge/package-lock.json b/pm-stack/console/edge/package-lock.json new file mode 100644 index 0000000000..caa1372ff5 --- /dev/null +++ b/pm-stack/console/edge/package-lock.json @@ -0,0 +1,1544 @@ +{ + "name": "pm-console-edge", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pm-console-edge", + "version": "0.1.0", + "devDependencies": { + "wrangler": "4.147.0" + } + }, + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz", + "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261001.1.tgz", + "integrity": "sha512-4cgSgDf28JSw/P5Dj5GCS59hzVqS5XnmGAWNkvYHLI6ODU9idGaMMNEuhJXDkEG/lsABmlVlnCgsdh2VbKWepw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261001.1.tgz", + "integrity": "sha512-8ulAWruEVouNmEIsQsy9WSSCS9zkLu93W2MTwp5esiFyoPp05BNSVFIFsYSPi1pkFmBBd7fsnwMpbLkaJLaVPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261001.1.tgz", + "integrity": "sha512-kZbTZJGrhsMOdqZ2BIybjaBRLZjYsRLWj7mcNw/6Y3hodOhp5MrNzcz4iWGwNVWwyIV+7Pl+/LX5VcgnRqdHOg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261001.1.tgz", + "integrity": "sha512-oOk3Zj6k/8oP0FJgZBWDn7+BqbsqIMEMaV95pulHPVbwVu4wYoLfQq2hp0vkbCNsCFLqZb7cqixXdrwD54ZIow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261001.1.tgz", + "integrity": "sha512-uRxm5W4VyBkoSaoP1BfOuH0873tE+vxsknF4sab6/5YIRvIAufChq3QDp+zlAn67PuGPGcn7W8QraA0t4ucmOQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.4.tgz", + "integrity": "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.4.tgz", + "integrity": "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.4.tgz", + "integrity": "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.3.tgz", + "integrity": "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.3.tgz", + "integrity": "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.3.tgz", + "integrity": "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.3.tgz", + "integrity": "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.3.tgz", + "integrity": "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.3.tgz", + "integrity": "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.3.tgz", + "integrity": "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.3.tgz", + "integrity": "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.3.tgz", + "integrity": "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.3.tgz", + "integrity": "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.4.tgz", + "integrity": "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.4.tgz", + "integrity": "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.4.tgz", + "integrity": "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.4.tgz", + "integrity": "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.4.tgz", + "integrity": "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.3" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.4.tgz", + "integrity": "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.4.tgz", + "integrity": "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.4.tgz", + "integrity": "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.3" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.4.tgz", + "integrity": "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.4.tgz", + "integrity": "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.4" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.4.tgz", + "integrity": "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.4.tgz", + "integrity": "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.4.tgz", + "integrity": "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@poppinss/colors": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", + "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^4.1.5" + } + }, + "node_modules/@poppinss/dumper": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz", + "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@sindresorhus/is": "^7.0.2", + "supports-color": "^10.0.0" + } + }, + "node_modules/@poppinss/exception": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz", + "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/is": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", + "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@speed-highlight/core": { + "version": "1.2.24", + "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz", + "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/error-stack-parser-es": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", + "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/miniflare": { + "version": "5.20261001.0-alpha", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261001.0-alpha.tgz", + "integrity": "sha512-GaimS5mSIOMyvd16ga+e1/QkI8cmp3z35QPHFex0DktqNQf2RVZQwMPQXdyoUreUiFP/0Gpe2MoQInTyMAD5xA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.4", + "undici": "7.29.1", + "workerd": "1.20261001.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/path-to-regexp": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", + "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz", + "integrity": "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.4", + "@img/sharp-darwin-x64": "0.35.4", + "@img/sharp-freebsd-wasm32": "0.35.4", + "@img/sharp-libvips-darwin-arm64": "1.3.3", + "@img/sharp-libvips-darwin-x64": "1.3.3", + "@img/sharp-libvips-linux-arm": "1.3.3", + "@img/sharp-libvips-linux-arm64": "1.3.3", + "@img/sharp-libvips-linux-ppc64": "1.3.3", + "@img/sharp-libvips-linux-riscv64": "1.3.3", + "@img/sharp-libvips-linux-s390x": "1.3.3", + "@img/sharp-libvips-linux-x64": "1.3.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", + "@img/sharp-libvips-linuxmusl-x64": "1.3.3", + "@img/sharp-linux-arm": "0.35.4", + "@img/sharp-linux-arm64": "0.35.4", + "@img/sharp-linux-ppc64": "0.35.4", + "@img/sharp-linux-riscv64": "0.35.4", + "@img/sharp-linux-s390x": "0.35.4", + "@img/sharp-linux-x64": "0.35.4", + "@img/sharp-linuxmusl-arm64": "0.35.4", + "@img/sharp-linuxmusl-x64": "0.35.4", + "@img/sharp-webcontainers-wasm32": "0.35.4", + "@img/sharp-win32-arm64": "0.35.4", + "@img/sharp-win32-ia32": "0.35.4", + "@img/sharp-win32-x64": "0.35.4" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/undici": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.1.tgz", + "integrity": "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/unenv": { + "version": "2.0.0-rc.24", + "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz", + "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3" + } + }, + "node_modules/workerd": { + "version": "1.20261001.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261001.1.tgz", + "integrity": "sha512-d/SIYHFO0PT/wiFZg8in4NpRIxYuFwslX1HdylOtWkBIIUmSpkGFhK820cV84XACFylwJ48xuRoWW/8DWDPsPQ==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261001.1", + "@cloudflare/workerd-darwin-arm64": "1.20261001.1", + "@cloudflare/workerd-linux-64": "1.20261001.1", + "@cloudflare/workerd-linux-arm64": "1.20261001.1", + "@cloudflare/workerd-windows-64": "1.20261001.1" + } + }, + "node_modules/wrangler": { + "version": "4.147.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.147.0.tgz", + "integrity": "sha512-pQYRoiq8PTAxphaG69z8+GC1DkSGd19EDZehQ8zxjo/Ko3mRB6Qs1mTrd8ZuKAarLklIjTqr1lUdCK9r4q2hUg==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.2", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.1", + "miniflare": "5.20261001.0-alpha", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261001.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.0.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261001.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + } + } +} diff --git a/pm-stack/console/edge/package.json b/pm-stack/console/edge/package.json new file mode 100644 index 0000000000..ce2460ad0a --- /dev/null +++ b/pm-stack/console/edge/package.json @@ -0,0 +1,15 @@ +{ + "name": "pm-console-edge", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "The Cloudflare Worker that serves the PM app in front of the host.", + "scripts": { + "build": "node build.mjs", + "check": "node build.mjs && wrangler deploy --dry-run --outdir .wrangler/dry", + "dev": "node build.mjs && wrangler dev --port 8799" + }, + "devDependencies": { + "wrangler": "4.147.0" + } +} diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts new file mode 100644 index 0000000000..0cb0816ad5 --- /dev/null +++ b/pm-stack/console/edge/src/edge.ts @@ -0,0 +1,671 @@ +// The app, served from the edge. +// +// A Cloudflare Worker sits in front of the public hostname. This is the +// part of it that holds state (it runs in one Durable Object): it checks +// who is calling, serves the app's state from the copy the host last +// reported, runs the actions that need nothing from the host, holds the +// ones the owner takes while the host cannot be reached, sends +// notifications, and answers a linked phone's widget. +// +// The host is still the machine with the fleet's tools on it. When it is +// reachable, an action that needs it is relayed to it at once and its +// answer comes straight back. When it is not, the app still opens, shows +// the state as of the host's last report with the time beside it, and +// keeps working for everything that is safe to do late. +// +// Nothing here trusts where a request came from. The owner is whoever +// presents a sign-in token that verifies; the host is whoever signs with +// the key the host itself published through its tunnel; a phone is +// whoever holds a token this service issued. +import { type Action, ownActions } from "../../src/actions.ts"; +import { AuthError, type Identity, identify } from "../../src/auth.ts"; +import { Devices, Limiter } from "../../src/devices.ts"; +import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; +import { + type EdgeConfig, + edgeConfig, + HELD_FOR_MS, + type Held, + HOLDABLE, + keyId, + type PublicKey, + publicKey, + SYNC_SKEW_MS, + type SyncRequest, + type SyncResponse, + type SyncSection, + verify, +} from "../../src/edge-proto.ts"; +import { OpError } from "../../src/errors.ts"; +import { + assetLinks, + BASE, + deviceLink, + deviceSummary, + docResponse, + json, + manifest, + type Phones, + sameSiteWrite, +} from "../../src/http.ts"; +import { Notifier } from "../../src/notify.ts"; +import { Push } from "../../src/push.ts"; +import type { Store } from "../../src/store.ts"; + +/** The edge's own storage: small values by key. */ +export interface KV { + get(key: string): Promise; + put(key: string, value: unknown): Promise; + delete(key: string): Promise; +} + +/** How long each section may go unreported before the app says the + * state is old: the host's own interval for it, and room for a sync. */ +const SECTIONS: Record = { + board: 30_000, + sessions: 45_000, + census: 120_000, + asks: 45_000, + questionCount: 45_000, + questions: 45_000, + prs: 90_000, + priorities: 180_000, + agents: 75_000, + services: 45_000, + more: 2 * 60 * 60_000, +}; +/** Sections the notifier and a phone's widget are built from. */ +const WATCHED = ["board", "asks", "census", "sessions", "questionCount", "services"]; +/** One stored value holds at most this many characters of a section. */ +const CHUNK = 600_000; +const SYNC_LIMIT = 8 * 1024 * 1024; +const ACT_LIMIT = 256 * 1024; +const HELD_MAX = 100; +const ACTS_KEPT = 30; +const AUDIT_KEPT = 300; +/** "Someone is looking" lasts this long after the last read of a document. */ +const WATCHING_MS = 90_000; +/** The host is reported silent after this long without a sync. */ +export const SILENT_MS = 10 * 60_000; +const KEY_FETCH_EVERY_MS = 30_000; +const STATIC: Record = { + "app.js": "text/javascript; charset=utf-8", + "app.css": "text/css; charset=utf-8", + "icon.svg": "image/svg+xml", + "sw.js": "text/javascript; charset=utf-8", +}; +const ICONS = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; + +interface Mirror { + at: number; + hash: string; + data: unknown; +} + +/** What the stateless part of the Worker must do with a request this + * part has checked: serve a file of the app, or pass the request to the + * host. Anything else is an ordinary response. */ +export function next(what: "asset" | "relay" | "key", detail: Record): Response { + return new Response(JSON.stringify(detail), { + status: 200, + headers: { "content-type": "application/json", "x-pm-next": what }, + }); +} + +const kvStore = (kv: KV, key: string): Store => ({ + read: async () => ((await kv.get(key)) as string | undefined) ?? null, + write: (text) => kv.put(key, text), +}); + +export interface EdgeOptions { + kv: KV; + now?: () => number; + /** Reaches the sign-in issuer's keys and the push services. */ + fetchImpl?: typeof fetch; + /** Ask to be woken at a time: the check for a silent host. */ + setAlarm?: (at: number) => Promise; +} + +export class Edge { + private kv: KV; + private now: () => number; + private fetchImpl: typeof fetch; + private setAlarm: (at: number) => Promise; + private cfg: EdgeConfig | null | undefined; + private mirrors = new Map(); + private held: Held[] | null = null; + private ownActs: Act[] | null = null; + private hostActs: Act[] = []; + private lastDocAt = 0; + private lastKeyFetch = 0; + private hostSeen: number | null = null; + 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 sure = 0; + private unsure = 0; + readonly docs: Docs; + readonly push: Push; + readonly phones: Phones; + private notifier: Notifier; + private table: Record; + + constructor(options: EdgeOptions) { + this.kv = options.kv; + this.now = options.now ?? Date.now; + this.fetchImpl = options.fetchImpl ?? fetch; + this.setAlarm = options.setAlarm ?? (async () => {}); + this.docs = new Docs( + Object.fromEntries( + Object.entries(SECTIONS).map(([name, ttlMs]) => [ + name, + { + ttlMs, + 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); + }, + }, + ]), + ), + this.now, + ); + 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"}`, + (url, init) => this.fetchImpl(url, init as RequestInit), + this.now, + ); + const devices = new Devices(kvStore(this.kv, "devices"), this.now); + this.phones = { + devices, + link: new Limiter(30, 60_000, this.now), + refused: new Limiter(60, 60_000, this.now), + }; + this.notifier = new Notifier(this.docs, this.push, kvStore(this.kv, "seen")); + this.table = ownActions(this.push, devices); + } + + // ---- what is kept ------------------------------------------------------ + + private async config(): Promise { + if (this.cfg === undefined) this.cfg = edgeConfig(await this.kv.get("cfg")); + return this.cfg; + } + + private async mirror(name: string): Promise { + const cached = this.mirrors.get(name); + if (cached !== undefined) return cached; + await this.ready(); + const meta = (await this.kv.get(`m:${name}`)) as { at: number; hash: string; chunks: number } | undefined; + let found: Mirror | null = null; + if (meta) { + const parts: string[] = []; + for (let i = 0; i < meta.chunks; i++) parts.push(String((await this.kv.get(`m:${name}:${i}`)) ?? "")); + try { + // As current as the host last said it was, which may be later + // than when the copy itself was sent. + const at = Math.max(meta.at, this.confirmed[name]?.hash === meta.hash ? this.confirmed[name].at : 0); + found = { at, hash: meta.hash, data: JSON.parse(parts.join("")) }; + } catch { + found = null; // a copy that cannot be read is no copy: the host is asked for it again + } + } + this.mirrors.set(name, found); + return found; + } + + private async putMirror(section: SyncSection): Promise { + const text = JSON.stringify(section.data); + const chunks = Math.max(1, Math.ceil(text.length / CHUNK)); + const before = (await this.kv.get(`m:${section.name}`)) as { chunks: number } | undefined; + for (let i = 0; i < chunks; i++) + await this.kv.put(`m:${section.name}:${i}`, text.slice(i * CHUNK, (i + 1) * CHUNK)); + for (let i = chunks; i < (before?.chunks ?? 0); i++) await this.kv.delete(`m:${section.name}:${i}`); + await this.kv.put(`m:${section.name}`, { at: section.at, hash: section.hash, chunks }); + this.mirrors.set(section.name, { at: section.at, hash: section.hash, data: section.data }); + } + + /** Sections from the host, taken in; returns the names that changed. */ + private async take(sections: unknown): Promise { + const names: string[] = []; + if (!Array.isArray(sections)) return names; + for (const raw of sections as SyncSection[]) { + if (!raw || typeof raw.name !== "string" || !Object.hasOwn(SECTIONS, raw.name)) continue; + if (typeof raw.at !== "number" || typeof raw.hash !== "string" || raw.data === undefined) continue; + const have = await this.mirror(raw.name); + // An older read never replaces a newer one. + if (have && have.at > raw.at) continue; + await this.putMirror({ name: raw.name, at: Math.min(raw.at, this.now()), hash: raw.hash, data: raw.data }); + names.push(raw.name); + } + if (names.length > 0) await this.docs.touch(names); + return names; + } + + private async heldList(): Promise { + if (this.held === null) this.held = ((await this.kv.get("held")) as Held[] | undefined) ?? []; + return this.held; + } + + private async saveHeld(): Promise { + await this.kv.put("held", this.held ?? []); + this.docs.extra("edge", { held: (this.held ?? []).length }); + } + + /** What the owner did lately: this side's own record (what it ran or + * is holding) together with the host's, newest first. */ + private async showActs(): Promise { + if (this.ownActs === null) this.ownActs = ((await this.kv.get("acts")) as Act[] | undefined) ?? []; + const merged = [...this.ownActs, ...this.hostActs.filter((h) => !this.ownActs?.some((o) => o.id === h.id))]; + merged.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0)); + this.docs.restoreActs(merged); + } + + private async logAct(act: Act): Promise { + if (this.ownActs === null) this.ownActs = ((await this.kv.get("acts")) as Act[] | undefined) ?? []; + this.ownActs = [act, ...this.ownActs.filter((a) => a.id !== act.id)].slice(0, ACTS_KEPT); + await this.kv.put("acts", this.ownActs); + await this.showActs(); + } + + private async dropAct(id: string): Promise { + if (this.ownActs === null) this.ownActs = ((await this.kv.get("acts")) as Act[] | undefined) ?? []; + this.ownActs = this.ownActs.filter((a) => a.id !== id); + await this.kv.put("acts", this.ownActs); + await this.showActs(); + } + + private async audit(entry: Record): Promise { + const log = ((await this.kv.get("audit")) as Record[] | undefined) ?? []; + log.push(entry); + await this.kv.put("audit", log.slice(-AUDIT_KEPT)); + } + + private async ready(): Promise { + // After a restart: the held count and the record of what was done + // are read back before the first document is built. + if (this.held === null) { + await this.heldList(); + this.docs.extra("edge", { held: (this.held ?? []).length }); + } + 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 } + | undefined; + this.hostSeen = host?.seen ?? 0; + this.hostSeq = host?.seq ?? 0; + this.confirmed = host?.confirmed ?? {}; + } + } + + // ---- the host's report ------------------------------------------------- + + /** The host's public key, given by the stateless part after it asked + * the host through the tunnel. */ + private async enroll(req: Request): Promise { + const key = publicKey(((await req.json().catch(() => null)) as { key?: unknown } | null)?.key); + if (!key) return json({ error: "not a key" }, 400); + await this.kv.put("key", { kid: await keyId(key), jwk: key }); + return json({ ok: true }); + } + + private async sync(req: Request): Promise { + if (Number(req.headers.get("content-length") ?? "0") > SYNC_LIMIT) return json({ error: "too large" }, 413); + const body = new Uint8Array(await req.arrayBuffer()); + if (body.byteLength > SYNC_LIMIT) return json({ error: "too large" }, 413); + const kid = req.headers.get("x-pm-key") ?? ""; + const key = (await this.kv.get("key")) as { kid: string; jwk: PublicKey } | undefined; + const now = this.now(); + if (!key || key.kid !== kid) { + // A key this side has not seen: ask the host for its key, but not + // on every stranger's request. + if (req.headers.get("x-pm-key-fetched") === "1" || now - this.lastKeyFetch < KEY_FETCH_EVERY_MS) { + return json({ error: "this is not signed with the host's key" }, 401); + } + this.lastKeyFetch = now; + return next("key", {}); + } + if (!(await verify(key.jwk, body, req.headers.get("x-pm-signature") ?? ""))) { + return json({ error: "this is not signed with the host's key" }, 401); + } + let msg: SyncRequest; + try { + msg = JSON.parse(new TextDecoder().decode(body)) as SyncRequest; + } catch { + return json({ error: "body: expected JSON" }, 400); + } + if (msg?.v !== 1 || typeof msg.at !== "number") return json({ error: "not a sync this side understands" }, 400); + if (Math.abs(msg.at - now) > SYNC_SKEW_MS) return json({ error: "clock", now }, 409); + await this.ready(); + const last = this.hostSeq ?? 0; + if (msg.at <= last) return json({ error: "replay", last }, 409); + const cfg = edgeConfig(msg.config); + if (!cfg) return json({ error: "config: not one this side can use" }, 400); + if (JSON.stringify(cfg) !== JSON.stringify(await this.config())) { + 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[] = []; + 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 copy = await this.mirror(name); + if (copy && copy.hash === theirs.hash && this.confirmed[name].at > copy.at) { + copy.at = this.confirmed[name].at; + if (!changed.includes(name)) fresher.push(name); + } + } + if (fresher.length > 0) await this.docs.touch(fresher); + if (Array.isArray((msg as { acts?: unknown }).acts)) { + this.hostActs = ((msg as { acts?: Act[] }).acts ?? []).slice(0, ACTS_KEPT); + await this.showActs(); + } + + // What became of the held actions the host was given. + const held = await this.heldList(); + let settled = false; + for (const ack of Array.isArray(msg.acks) ? msg.acks : []) { + const at = held.findIndex((h) => h.id === ack?.id); + if (at < 0) continue; + const [done] = held.splice(at, 1); + settled = true; + if (ack.ok) + await this.dropAct(done.id); // the host's own record shows it done + else { + await this.logAct({ + id: done.id, + kind: done.kind, + at: done.at, + by: done.who, + status: "failed", + note: `Sent late, and the laptop could not do it: ${String(ack.error ?? "no reason given").slice(0, 160)}`, + }); + } + } + // What has waited too long is dropped, and said to have been. + for (const old of held.filter((h) => now - Date.parse(h.at) > HELD_FOR_MS)) { + held.splice(held.indexOf(old), 1); + settled = true; + await this.logAct({ + id: old.id, + kind: old.kind, + at: old.at, + by: old.who, + status: "failed", + note: "Not sent: the laptop was out of reach for more than a day.", + }); + } + if (settled) await this.saveHeld(); + + // The host is back, if it had been reported silent. + const wasSilent = (await this.kv.get("silent")) === true; + // One value, written once a report: when the host last reported, the + // time its report carried (which the next must exceed), and how + // current it says each section is. + this.hostSeen = now; + this.hostSeq = msg.at; + await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed }); + if (wasSilent) { + await this.kv.delete("silent"); + await this.push + .send("trouble", { title: "The laptop is back", body: "It is reporting again.", url: "/console/", tag: "host" }) + .catch(() => {}); + } + await this.setAlarm(now + SILENT_MS + 1000); + if (changed.some((n) => WATCHED.includes(n))) { + await this.notifier.tick().catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`)); + } + + // What the host has and this side has lost (its storage was reset). + const want: string[] = []; + for (const name of Object.keys(SECTIONS)) { + if (typeof msg.have?.[name]?.hash === "string" && !(await this.mirror(name))) want.push(name); + } + const answer: SyncResponse = { + ok: true, + watching: now - this.lastDocAt < WATCHING_MS, + notify: (await this.push.status()).devices > 0 || (await this.phones.devices.list()).length > 0, + want, + commands: held, + }; + return json(answer); + } + + /** Woken some time after the last sync: if there has been none since, + * the owner is told once that the host has gone quiet. */ + async alarm(): Promise { + await this.ready(); + const now = this.now(); + if (!this.hostSeen || now - this.hostSeen < SILENT_MS) return; + if ((await this.kv.get("silent")) === true) return; + await this.kv.put("silent", true); + await this.push + .send("trouble", { + title: "The laptop has gone quiet", + body: "It has not reported for ten minutes. The app still opens; what you do is held until it is back.", + url: "/console/", + tag: "host", + }) + .catch(() => {}); + } + + // ---- requests ---------------------------------------------------------- + + async fetch(req: Request): Promise { + const url = new URL(req.url); + const path = url.pathname; + const method = req.method; + + // From the stateless part of this Worker only: it never passes a + // request from outside to a path under /internal/. + if (path.startsWith("/internal/")) { + if (method !== "POST") return json({ error: "not found" }, 404); + if (path === "/internal/key") return this.enroll(req); + if (path === "/internal/hold") return this.hold(req); + if (path === "/internal/relayed") return this.relayed(req); + return json({ error: "not found" }, 404); + } + + const cfg = await this.config(); + // Public: nothing here says anything about the fleet. + if (path === `${BASE}/health` && method === "GET") { + await this.ready(); + return json({ + ok: true, + edge: true, + configured: cfg !== null, + hostSeen: this.hostSeen || null, + // Since this object last started: requests it answered as the + // owner's, and requests it left to the host to judge. + answered: this.sure, + deferred: this.unsure, + }); + } + if (path === "/manifest.webmanifest" && method === "GET") return manifest(); + if (ICONS.test(path) && (method === "GET" || method === "HEAD")) return next("asset", { path, type: "image/png" }); + if (path === `${BASE}/edge/sync` && method === "POST") return this.sync(req); + // Before the host's first report this side knows no owner: it stays + // out of the way, and the host answers as it did before. + if (cfg === null) return next("relay", { mode: "page" }); + if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(cfg)); + // Not behind the sign-in, and checked here instead: a linked phone. + if (path === `${BASE}/device/link` && method === "POST") { + return deviceLink(req, this.phones, (entry) => this.audit(entry)); + } + if (path === `${BASE}/device/summary` && method === "GET") return deviceSummary(req, this.docs, this.phones); + + // This side answers only when it is sure of the owner. When it is + // not, it does not refuse: it passes the request to the host, which + // decides as it always has. So a mistake here can cost the speed of + // the edge, never the owner's way in, and a stranger gets from the + // host exactly what a stranger got before. + let who: Identity; + try { + who = await identify(req, cfg, { peer: null, fetchImpl: this.fetchImpl as never, now: this.now() }); + this.sure++; + } catch (error) { + if (!(error instanceof AuthError)) throw error; + this.unsure++; + return next("relay", { mode: "page" }); + } + const by = who.email ?? who.certName ?? who.sub ?? who.via; + const ours = path === BASE || path.startsWith(`${BASE}/`); + if (!ours) { + // The front door is the app; every other page is the host's. + if (method === "GET" && path === "/" && url.search === "") return Response.redirect(`${url.origin}${BASE}/`, 302); + return next("relay", { mode: "page" }); + } + + const rest = path.slice(BASE.length).replace(/^\/+/, ""); + if (method === "GET" && rest === "") { + if (path === BASE) return Response.redirect(`${url.origin}${BASE}/`, 308); + return next("asset", { path: `${BASE}/index.html`, type: "text/html; charset=utf-8" }); + } + if (method === "GET" && Object.hasOwn(STATIC, rest)) { + return next("asset", { path: `${BASE}/${rest}`, type: STATIC[rest] }); + } + if (!rest.startsWith("api/")) return next("relay", { mode: "live" }); + + const seg = rest.slice(4).split("/"); + await this.ready(); + try { + if (method === "GET") { + if (seg.length === 1 && seg[0] === "me") { + return json({ + ...who, + repo: cfg.repo, + queue: cfg.queue, + androidApp: cfg.androidApp, + androidPackage: cfg.androidPackage, + edge: true, + }); + } + if (seg.length === 2 && seg[0] === "doc" && DOC_NAMES.includes(seg[1] as DocName)) { + this.lastDocAt = this.now(); + const res = docResponse(req, await this.docs.doc(seg[1] as DocName)); + // When the host last reported, beside the document rather than + // in it: it changes with every report and the content does not. + const headers = new Headers(res.headers); + headers.set("X-Host-Seen", String(this.hostSeen ?? 0)); + return new Response(res.body, { status: res.status, headers }); + } + if (seg.length === 1 && seg[0] === "push") return json(await this.push.status()); + if (seg.length === 1 && seg[0] === "devices") return json(await this.phones.devices.list()); + // Everything else is read from the host as it is now. + return next("relay", { mode: "live" }); + } + if (method !== "POST") return json({ error: "method not allowed" }, 405); + if (!sameSiteWrite(req)) return json({ error: "this request did not come from the console" }, 403); + if (!(seg.length === 1 && seg[0] === "act")) return next("relay", { mode: "live" }); + if (Number(req.headers.get("content-length") ?? "0") > ACT_LIMIT) return json({ error: "too large" }, 413); + let body: { kind?: unknown; args?: unknown }; + try { + const text = await req.text(); + if (text.length > ACT_LIMIT) return json({ error: "too large" }, 413); + body = JSON.parse(text); + if (body === null || typeof body !== "object" || Array.isArray(body)) throw new Error("not an object"); + } catch { + return json({ error: "body: expected a JSON object" }, 400); + } + const kind = typeof body.kind === "string" ? body.kind : ""; + const args = body.args ?? {}; + if (args === null || typeof args !== "object" || Array.isArray(args)) { + return json({ error: "args: expected an object" }, 400); + } + 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) }); + } + return await this.own(kind, args as Record, by, who.via); + } catch (error) { + if (error instanceof OpError) return json({ error: error.message }, error.status); + console.error(`pm-edge: ${method} ${path}: ${(error as Error).message}`); + return json({ error: "the edge could not do that" }, 500); + } + } + + /** An action this side runs itself, recorded before and after. */ + private async own(kind: string, args: Record, by: string, via: string): Promise { + const action = this.table[kind]; + const base = { at: new Date(this.now()).toISOString(), who: by, via, action: kind, args: action.audit(args) }; + await this.audit({ ...base, phase: "start" }); + const entry = { id: crypto.randomUUID(), kind, at: base.at, by, note: "" }; + try { + const result = await action.run(args); + await this.audit({ ...base, phase: "done", ok: true }); + await this.logAct({ ...entry, status: "done" }); + // A device has just subscribed: take stock now, so that it is told + // of what changes from here on and not of what was already there. + if (kind === "push.on") await this.notifier.tick().catch(() => {}); + return json({ ok: true, result }); + } catch (error) { + await this.audit({ ...base, phase: "done", ok: false, error: (error as Error).message }); + await this.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + throw error; + } + } + + /** The host could not be reached: keep the action for it, if it is one + * that may be done late. */ + private async hold(req: Request): Promise { + const body = (await req.json().catch(() => null)) as { + kind?: unknown; + args?: unknown; + who?: unknown; + } | null; + const kind = typeof body?.kind === "string" ? body.kind : ""; + 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." }, + 503, + ); + } + await this.ready(); + const held = await this.heldList(); + if (held.length >= HELD_MAX) { + return json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, 503); + } + const item: Held = { + id: crypto.randomUUID(), + kind, + args: args as Record, + who: String(body?.who ?? "owner"), + at: new Date(this.now()).toISOString(), + }; + held.push(item); + await this.saveHeld(); + await this.audit({ at: item.at, who: item.who, via: "edge", action: kind, phase: "held", id: item.id }); + await this.logAct({ + id: item.id, + kind, + at: item.at, + by: item.who, + status: "running", + note: "Held: the laptop cannot be reached. It will be sent when it is back.", + }); + return json({ ok: true, held: true, result: null }); + } + + /** After the host did a relayed action: the sections it read again and + * its record of what was done, so the next document already shows it. */ + private async relayed(req: Request): Promise { + const body = (await req.json().catch(() => null)) as { sections?: unknown; acts?: unknown } | null; + await this.ready(); + const changed = await this.take(body?.sections); + if (Array.isArray(body?.acts)) { + this.hostActs = (body.acts as Act[]).slice(0, ACTS_KEPT); + await this.showActs(); + } + return json({ ok: true, changed }); + } +} diff --git a/pm-stack/console/edge/src/entry.ts b/pm-stack/console/edge/src/entry.ts new file mode 100644 index 0000000000..09c4b64b87 --- /dev/null +++ b/pm-stack/console/edge/src/entry.ts @@ -0,0 +1,166 @@ +// What the Worker does with a request, with nothing of the platform in +// it: the object that has the state, the app's files and the host are +// handed in. worker.ts wires the real ones; the tests wire stand-ins. +// +// Every request goes to the state first, which checks who is calling. +// Its answer is either the response, or word of what to do next: serve a +// file of the app, fetch the host's key, or pass the request to the host +// behind the tunnel. If the host cannot be reached, an action that may +// be done late is handed back to the state to hold. +import { SECURITY } from "../../src/http.ts"; + +export interface Io { + /** The object with the state (edge.ts). */ + state: (request: Request) => Promise; + /** A file of the app, by path. */ + asset: (path: string) => Promise; + /** The host behind the hostname's route. `ms` is how long it has to + * start answering. Null when it could not be reached. */ + host: (request: Request, ms: number) => Promise; + /** The hostname this Worker is routed on. Only there is the host + * behind it; anywhere else only the public paths answer. */ + publicHost: string; + /** What is deployed, for the health check. */ + version: string | null; + /** Work that may finish after the response has gone. */ + later: (work: Promise) => void; + now: () => number; +} + +/** How long the host is given: a read, an action (the longest is a 60 + * second unit operation), a page. */ +export const READ_MS = 25_000; +export const ACT_MS = 75_000; +export const PAGE_MS = 60_000; +const POKE_EVERY_MS = 20_000; +/** When the host was last told that someone is looking. */ +let poked = 0; + +/** For tests: forget when the host was last told. */ +export function forgetPoke(): void { + poked = 0; +} + +function unreachablePage(): Response { + const page = ` +PM + +

The laptop cannot be reached right now

+

This page comes from it. The app itself does not: it still opens, shows the state as of the laptop's last report, and holds what you do until it is back.

+

Open the app

`; + return new Response(page, { + status: 503, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + "Retry-After": "30", + // The one inline style on this page is its own. + ...SECURITY, + "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'", + }, + }); +} + +const offline = (message: string) => + new Response(JSON.stringify({ error: message }), { + status: 503, + headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, + }); + +const withHeader = (request: Request, name: string, value: string): Request => { + const headers = new Headers(request.headers); + headers.set(name, value); + return new Request(request, { headers }); +}; + +export async function route(request: Request, io: Io): Promise { + const url = new URL(request.url); + const routed = url.hostname === io.publicHost; + const tell = (path: string, body: unknown) => + io.state( + new Request(`https://pm.internal${path}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + + // A path that is this Worker's own business with its state is never + // taken from outside: it is the host's, like any path not known here. + if (url.pathname.startsWith("/internal/")) { + if (!routed) return new Response("not found", { status: 404, headers: SECURITY }); + return (await io.host(request, PAGE_MS)) ?? unreachablePage(); + } + 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 }), { + headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, + }); + } + + const forHost = request.clone(); + let res = await io.state(request); + let what = res.headers.get("x-pm-next"); + + // The host's key is not known yet, or has changed: ask the host for it + // through the tunnel, which only the host can answer, then let the + // state look at the same report again. + if (what === "key") { + if (!routed) return offline("this address has no host behind it"); + const keyRes = await io.host(new Request(`${url.origin}/console/edge/key`), READ_MS); + const key = keyRes?.ok ? ((await keyRes.json().catch(() => null)) as { key?: unknown } | null)?.key : null; + if (!key) return offline("the host did not give its key"); + await tell("/internal/key", { key }); + res = await io.state(withHeader(forHost, "x-pm-key-fetched", "1")); + what = res.headers.get("x-pm-next"); + } + if (what === null) { + // Someone is reading the app's state, which is served from this + // side's copy. Tell the host in the background, by asking it the + // same thing: that is what makes it read everything again and report. + if (routed && request.method === "GET" && url.pathname.startsWith("/console/api/doc/")) { + const now = io.now(); + if (now - poked > POKE_EVERY_MS) { + poked = now; + io.later(io.host(forHost, READ_MS).then((r) => r?.body?.cancel())); + } + } + return res; + } + const detail = (await res.json()) as Record; + + if (what === "asset") { + const file = await io.asset(String(detail.path)); + if (!file.ok) return new Response("not found", { status: 404, headers: SECURITY }); + return new Response(request.method === "HEAD" ? null : file.body, { + headers: { "Content-Type": String(detail.type), "Cache-Control": "no-cache", ...SECURITY }, + }); + } + + // Everything below is for the host. Away from the routed hostname + // there is no host. + 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); + 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. + if (!(answer.headers.get("content-type") ?? "").startsWith("application/json")) return answer; + const body = (await answer.json().catch(() => null)) as Record | null; + if (body === null) return offline("the host's answer could not be read"); + const { sections, acts, ...rest } = body; + if (sections !== undefined || acts !== undefined) await tell("/internal/relayed", { sections, acts }); + const headers = new Headers(answer.headers); + headers.delete("content-length"); + headers.delete("content-encoding"); + return new Response(JSON.stringify(rest), { status: answer.status, headers }); + } + if (detail.mode === "live") { + return ( + (await io.host(forHost, READ_MS)) ?? + offline("The laptop cannot be reached, and this is read from it as it is now.") + ); + } + return (await io.host(forHost, PAGE_MS)) ?? unreachablePage(); +} diff --git a/pm-stack/console/edge/src/worker.ts b/pm-stack/console/edge/src/worker.ts new file mode 100644 index 0000000000..934517fe6a --- /dev/null +++ b/pm-stack/console/edge/src/worker.ts @@ -0,0 +1,89 @@ +// The Worker in front of the public hostname. +// +// It hands every request to entry.ts, which decides, and gives it the +// three things only a Worker on the hostname's own route has: the object +// that holds the state, the app's files, and the host behind the tunnel. +// +// If anything here throws, the request goes to the host exactly as it +// did before this Worker existed. The worst this layer can do is add +// nothing. +import { DurableObject } from "cloudflare:workers"; +import { Edge } from "./edge.ts"; +import { route } from "./entry.ts"; + +interface Env { + PM: DurableObjectNamespace; + ASSETS: { fetch(request: Request): Promise }; + PUBLIC_HOST: string; + VERSION?: string; + /** Local development only: where the host is, when it is not simply + * behind this hostname's route. Never set where this is deployed. */ + HOST_ORIGIN?: string; +} + +/** The object with the state. */ +export class PmEdge extends DurableObject { + private edge: Edge; + + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env); + this.edge = new Edge({ + kv: { + get: (key) => ctx.storage.get(key), + put: (key, value) => ctx.storage.put(key, value), + delete: async (key) => { + await ctx.storage.delete(key); + }, + }, + setAlarm: (at) => ctx.storage.setAlarm(at), + }); + } + + fetch(request: Request): Promise { + return this.edge.fetch(request); + } + + alarm(): Promise { + return this.edge.alarm(); + } +} + +/** The host answered, as opposed to something in front of it saying it + * could not be reached. The host marks every response it writes. */ +function fromHost(res: Response): boolean { + return res.headers.get("x-pm-console") === "1" || res.status < 500; +} + +/** Ask the host. `ms` is how long it has to start answering; a stream it + * then keeps open (the dashboard's live pages) is left to run. */ +async function host(request: Request, ms: number, origin?: string): Promise { + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), ms); + try { + // On the hostname's own route, fetching the request is asking the host. + const url = new URL(request.url); + const target = origin ? new Request(`${origin}${url.pathname}${url.search}`, request) : request; + const res = await fetch(new Request(target, { redirect: "manual", signal: abort.signal })); + return fromHost(res) ? res : null; + } catch { + return null; + } finally { + clearTimeout(timer); + } +} + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + ctx.passThroughOnException(); + const stub = env.PM.get(env.PM.idFromName("pm")); + return route(request, { + state: (r) => stub.fetch(r), + asset: (path) => env.ASSETS.fetch(new Request(`https://assets.internal${path}`)), + host: (r, ms) => host(r, ms, env.HOST_ORIGIN), + publicHost: env.PUBLIC_HOST, + version: env.VERSION ?? null, + later: (work) => ctx.waitUntil(work), + now: Date.now, + }); + }, +}; diff --git a/pm-stack/console/edge/wrangler.jsonc b/pm-stack/console/edge/wrangler.jsonc new file mode 100644 index 0000000000..9465a33ecf --- /dev/null +++ b/pm-stack/console/edge/wrangler.jsonc @@ -0,0 +1,35 @@ +{ + // The Worker in front of pm.security.cab: the app, its state, + // notifications and the phone widget, served from Cloudflare. + // + // Deployed by the pm-console-edge-deploy workflow (wrangler deploy). + // It has no route here on purpose: scripts/expose.py on the host puts + // the hostname's route on it once it answers its health check, and can + // take the route away again, which is the whole rollback. + "name": "pm-console-edge", + "main": "src/worker.ts", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat"], + // The workers.dev address answers the health check and the public + // files only: every other path needs the owner's sign-in token, which + // is only issued for the routed hostname. + "workers_dev": true, + "preview_urls": false, + "observability": { "enabled": true }, + "vars": { "PUBLIC_HOST": "pm.security.cab" }, + // The app's files, put together by build.mjs. Every request reaches + // the Worker first; it serves a file only after checking who asks. + "assets": { + "directory": "./dist", + "binding": "ASSETS", + "run_worker_first": true, + "html_handling": "none", + "not_found_handling": "none" + }, + // One object holds the state: the copy of what the host last + // reported, what is held for it, notification subscriptions and keys, + // linked phones. No secrets are configured: every key it uses it made + // itself, or was published by the host. + "durable_objects": { "bindings": [{ "name": "PM", "class_name": "PmEdge" }] }, + "migrations": [{ "tag": "v1", "new_sqlite_classes": ["PmEdge"] }] +} diff --git a/pm-stack/console/install.sh b/pm-stack/console/install.sh index ed2ae0425a..89c71c3e3f 100755 --- a/pm-stack/console/install.sh +++ b/pm-stack/console/install.sh @@ -31,15 +31,16 @@ if [ ! -f "$STATE/.env" ]; then printf 'PM_CONSOLE_PORT=4872\nPM_CONSOLE_OWNER_EMAILS=\n' >"$STATE/.env" fi install -m 644 "$UNIT_SRC" "$UNIT_DST" -# The timer keeps the public address as declared, and turns Google -# sign-in on by itself once its two secrets exist. -for unit in pm-console-expose.service pm-console-expose.timer; do +# One timer keeps the public address as declared, and turns Google +# sign-in on by itself once its two secrets exist. The other puts merged +# console code into service, so a merge needs nobody at this machine. +for unit in pm-console-expose.service pm-console-expose.timer pm-console-redeploy.service pm-console-redeploy.timer; do install -m 644 "$(dirname "$SRC")/systemd/$unit" "$(dirname "$UNIT_DST")/$unit" done systemctl --user daemon-reload systemctl --user enable pm-console.service >/dev/null systemctl --user restart pm-console.service -systemctl --user enable --now pm-console-expose.timer >/dev/null +systemctl --user enable --now pm-console-expose.timer pm-console-redeploy.timer >/dev/null # systemd strips one pair of quotes from an EnvironmentFile value, so # PM_CONSOLE_PORT="4872" is a valid line: read it the same way. diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 96e6bb7ff1..f06866e45e 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -154,6 +154,8 @@ async function loadDoc(name) { throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); } if (res.headers.get("x-as-of")) asOf[name] = Number(res.headers.get("x-as-of")); + // Served from the edge: when the laptop behind it last reported. + if (res.headers.get("x-host-seen")) hostSeen = Number(res.headers.get("x-host-seen")) || null; if (res.status === 304) return false; if (!res.ok) { if (res.status === 401 || res.status === 403) signedOut = true; @@ -161,17 +163,43 @@ async function loadDoc(name) { } docs[name] = await res.json(); etags[name] = res.headers.get("etag"); + if (name === "questions") withoutAnswered(docs[name]); return true; } +/** Questions answered on this device that the list may still show for a + * while: the answer is on its way, or held until the laptop is back. */ +const answeredHere = new Set(); +const questionKey = (q) => `${q.set}|${q.ledger}|${q.qid}`; + +function withoutAnswered(doc) { + const q = doc?.questions; + if (!q?.open) return; + const present = new Set(q.open.map(questionKey)); + // Gone from the list: the answer arrived, and there is nothing to hide. + for (const key of answeredHere) if (!present.has(key)) answeredHere.delete(key); + if (answeredHere.size === 0) return; + q.open = q.open.filter((x) => !answeredHere.has(questionKey(x))); + q.total = q.open.length; +} + +/** When the laptop behind the edge last reported, or null when the app + * is not served from an edge. */ +let hostSeen = null; +/** How far behind the laptop may be before the app says so. */ +const HOST_QUIET_MS = 3 * 60_000; +const HELD_NOTE = "Held: the laptop cannot be reached. It will be sent when it is back."; + /** Run one action, say how it went, and draw what changed. */ async function act(kind, args, done, button) { if (button) button.disabled = true; try { - const { result } = await api("act", { kind, args }); - toast(typeof done === "function" ? done(result) : done); + const { result, held } = await api("act", { kind, args }); + // Held is not done: the caller is told nothing happened yet, and the + // owner is told where it is waiting. + toast(held ? HELD_NOTE : typeof done === "function" ? done(result) : done); await refresh(true); - return result; + return held ? null : result; } catch (error) { toast(error.message, true); if (button) button.disabled = false; @@ -203,6 +231,28 @@ function taskCard(t, extra) { function notices(doc) { const out = []; + // Served from the edge with the laptop out of reach: say how old this + // is, and that working on is fine. + if (doc === docs.core && hostSeen && Date.now() - hostSeen > HOST_QUIET_MS) { + out.push( + h( + "div", + { class: "card flag" }, + h("h3", {}, "The laptop is out of reach"), + h( + "p", + { class: "meta" }, + `It last reported ${ago(new Date(hostSeen).toISOString())}; this is the state as of then. You can keep working: what is safe to do late is held and sent when it is back.`, + ), + ), + ); + } + if (doc === docs.core && doc?.edge?.held > 0) { + const n = doc.edge.held; + out.push( + h("div", { class: "card flag" }, h("p", { class: "meta" }, `${n} ${n === 1 ? "thing" : "things"} you did ${n === 1 ? "is" : "are"} waiting for the laptop. See “What you did” below.`)), + ); + } for (const [name, s] of Object.entries(doc?.health || {})) { if (!s.ok && s.error) { out.push( @@ -400,8 +450,12 @@ function flushPending() { async function sendAnswer(kind, args, key) { try { - const { result } = await api("act", { kind, args }); + const { result, held } = await api("act", { kind, args }); if (result?.refused?.length) toast(`Not recorded: ${result.refused[0].why}`, true); + else { + answeredHere.add(key); + if (held) toast(HELD_NOTE); + } picks.delete(key); if (docs.questions?.questions) { const open = docs.questions.questions.open.filter((q) => `${q.set}|${q.ledger}|${q.qid}` !== key); @@ -1274,6 +1328,9 @@ function drawFresh() { freshEl.textContent = signedOut ? "signed out" : age === null ? "" : age < 45 ? "live" : `as of ${ago(new Date(t).toISOString())}`; } +/** How many quick looks have been taken since the state was last fresh. */ +let catchUp = 0; + /** Draw the current section from what is already loaded. Only the latest * call may draw, so a slow section never lands on top of a newer one. */ async function draw() { @@ -1306,6 +1363,15 @@ async function refresh(force) { try { changed = await loadDoc("core"); if (extra) changed = (await loadDoc(extra)) || changed; + // An old copy means the laptop has just been told someone is + // looking: look again shortly, a few times, instead of waiting out + // the full interval. + const old = asOf.core && Date.now() - asOf.core > 60_000; + if (!old) catchUp = 0; + else if (catchUp < 4) { + catchUp++; + setTimeout(() => document.visibilityState === "visible" && refresh(false), 4_000); + } } catch (error) { if (!docs.core) view.replaceChildren(card(h("h3", {}, "Could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => location.reload() }, "Reload")))); } diff --git a/pm-stack/console/redeploy.sh b/pm-stack/console/redeploy.sh new file mode 100755 index 0000000000..6c852e8bc1 --- /dev/null +++ b/pm-stack/console/redeploy.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# redeploy.sh — put merged console code into service on the host. +# +# pm-console-redeploy.timer runs this every minute. It compares the +# console's code in the checkout (which pm-git-sync keeps at main) with +# the code that was last put into service. When they differ it first +# starts the new code in a self-check that listens on nothing, with the +# service's own settings; only if that passes does it run install.sh, +# which restarts the service. Code that does not start is left out of +# service, the old code keeps running, and this unit fails, which the +# console's Services screen and its notifications show. It is tried +# again only when the checkout moves to different code. +# +# Usage: bash redeploy.sh +set -euo pipefail + +if [ "$#" -ne 0 ]; then + echo "usage: bash redeploy.sh (it takes no arguments)" >&2 + exit 2 +fi + +cd "$(dirname "$0")" +SRC="$PWD" +REPO="$(git -C "$SRC" rev-parse --show-toplevel)" +STATE="$HOME/.local/state/pm-console" +BUN="${PM_CONSOLE_BUN:-/run/current-system/sw/bin/bun}" +UNITS=(pm-console.service pm-console-expose.service pm-console-expose.timer pm-console-redeploy.service pm-console-redeploy.timer) + +# What is in the checkout: the console's tree, and the units it runs +# under. A checkout that is part-way through an update (files that do +# not match its commit yet) is left for the next run. +paths=(pm-stack/console) +for unit in "${UNITS[@]}"; do paths+=("pm-stack/systemd/$unit"); done +if ! git -C "$REPO" diff --quiet HEAD -- "${paths[@]}"; then + exit 0 +fi +want="$(for path in "${paths[@]}"; do git -C "$REPO" rev-parse "HEAD:$path"; done | tr '\n' ' ')" +have="$(cat "$STATE/deployed" 2>/dev/null || true)" +if [ "$want" = "$have" ]; then + exit 0 +fi +if [ "$want" = "$(cat "$STATE/deploy-failed" 2>/dev/null || true)" ]; then + echo "redeploy: this code did not pass its self-check (see $STATE/redeploy.log); the code in service is unchanged" >&2 + exit 1 +fi + +mkdir -p "$STATE" +# The service's own settings, one KEY=value a line, passed as they are. +settings=() +if [ -f "$STATE/.env" ]; then + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in + '' | '#'* | ';'*) continue ;; + *=*) settings+=("$line") ;; + esac + done <"$STATE/.env" +fi +if ! (cd "$SRC" && env "${settings[@]}" "$BUN" run src/server.ts --check) >"$STATE/redeploy.log" 2>&1; then + printf '%s' "$want" >"$STATE/deploy-failed" + echo "redeploy: the new code does not start; the code in service is unchanged:" >&2 + tail -n 20 "$STATE/redeploy.log" >&2 + exit 1 +fi + +bash "$SRC/install.sh" +printf '%s' "$want" >"$STATE/deployed" +rm -f "$STATE/deploy-failed" +echo "redeploy: $(git -C "$REPO" rev-parse --short HEAD) is in service" diff --git a/pm-stack/console/scripts/demo-state.ts b/pm-stack/console/scripts/demo-state.ts new file mode 100644 index 0000000000..18e6bfc8f3 --- /dev/null +++ b/pm-stack/console/scripts/demo-state.ts @@ -0,0 +1,382 @@ +// A made-up host, to look at the interface without a fleet: the real +// server code answers, only the sources are canned, and every action +// succeeds. demo.ts serves it directly; edge-demo.ts puts the edge in +// front of it. +import { actions as realActions } from "../src/actions.ts"; +import { readConfig } from "../src/config.ts"; +import { Devices, Limiter } from "../src/devices.ts"; +import { Docs } from "../src/docs.ts"; +import { fileStore } from "../src/file-store.ts"; +import { Ops } from "../src/ops.ts"; +import { Push } from "../src/push.ts"; +import type { Deps } from "../src/server.ts"; + +const iso = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString().slice(0, 19); +const task = (id: number, title: string, extra: Record) => ({ + id, + title, + priority: 30, + status: "queued", + attempts: 1, + claimed: "", + lease: "", + created: iso(300), + worker: null, + lane: null, + model: null, + kind: "small_fix", + issue: 9000 + id, + pr: null, + step: "", + goal: "The fix lands with a test that fails without it", + url: `https://github.com/developing-today/code/issues/${9000 + id}`, + ...extra, +}); +const question = (set: string, n: number, extra: Record = {}) => ({ + set, + setTitle: `Pending questions — ${set}`, + created: iso(60 * 24 * n), + ledger: `ledger-${set}-${n}`, + item: `PM-stack S${n} attachments (#1003${n}): where do attachments live`, + links: [`https://github.com/developing-today/code/issues/1003${n}`], + qid: `q${n}`, + q: `For S${n} attachments and multimedia, build new storage, or reuse a mechanism outside pm-stack that you name?`, + context: "Attachments today are pasted links. The dashboard has no storage of its own, and three pages want one.", + detail: + "Building new keeps the stack self-contained. Reusing means one fewer store to run, but ties the release to another project.", + multi: false, + recommended: ["opt-1"], + options: [ + { id: "opt-1", label: "Build new attachment storage", tags: ["recommended", "simpler"] }, + { id: "opt-2", label: "Reuse a mechanism outside pm-stack (name it in your answer)", tags: [] }, + { id: "opt-3", label: "Build new now; migrate storage refs later", tags: ["reversible"] }, + ], + ...extra, +}); + +const state = { + board: { + counts: { claimed: 3, queued: 4, blocked: 474, parked: 58 }, + now: [ + task(1, "Fix #9075: session state — session id in env and a resume path", { + status: "claimed", + claimed: iso(14), + worker: "repo-worker-code", + lane: "oc-code-02", + model: "workhorse", + attempts: 8, + step: "Write the failing test for resume after a crash, then wire the env var through the launcher.", + }), + task(2, "Implement mcpx Roc script support after the Python parity gate", { + status: "claimed", + claimed: iso(41), + worker: "repo-worker-code", + lane: "code-h", + priority: 20, + step: "Resume only when a compatible docs build is available.", + }), + task(3, "Fix #2723 phase 3: PendingHold post and void lifecycle", { + status: "claimed", + claimed: iso(3), + worker: "repo-worker-code", + lane: "code-j", + goal: "Posting and voiding a hold are covered by the ledger property tests", + }), + ], + next: [ + task(4, "Owner prompt developing-today/code#12501: make the join-at-admission slice the top priority", { + priority: 10, + kind: "triage", + }), + task(5, "Triage developing-today/code#12416: link from the dashboard to the console", { + priority: 30, + kind: "triage", + }), + task(6, "Merge-watch developing-today/code#12240: recheck fix PR for issue #12230", { + priority: 30, + kind: "pr_shepherd", + }), + task(7, "Fix #11350: toolchain file drift between crates", { priority: 50 }), + ], + blockedWhy: [ + { why: "waits on #9106 (open, all PRs merged)", n: 212 }, + { why: "no reason recorded", n: 140 }, + { why: '{"kind":"time","until":"2026-11-19T14:02:00Z"}', n: 4 }, + ], + }, + sessions: { + moving: [ + { + id: "s1", + title: "F12.11 binary frames: fuzz the decoder", + agent: "build", + model: "gpt-5.2-codex", + where: "git/code-j", + last: iso(1), + tools: 2, + messages: 141, + }, + { + id: "s2", + title: "Triage sweep: opencode", + agent: "triage", + model: "workhorse", + where: "git/opencode", + last: iso(6), + tools: 0, + messages: 37, + }, + ], + waiting: [ + { + id: "porkbun", + title: "Porkbun: log into the main account and enter the password in the staged modal", + ref: "gh:developing-today/code#902", + why: "", + }, + ], + }, + census: { + at: iso(1), + complete: true, + hands: [ + { + ref: "developing-today/code#12417", + title: "Google sign-in for pm.security.cab: create the OAuth client", + url: "https://github.com/developing-today/code/issues/12417", + pr: false, + updated: iso(50), + kind: "interactive-login", + action: + "Create a Google OAuth web client with the redirect URI in the issue and save its ID and secret in Bitwarden.", + }, + { + ref: "developing-today/code#1080", + title: "epic(cluster): hardware inventory and first-node selection", + url: "https://github.com/developing-today/code/issues/1080", + pr: false, + updated: iso(60 * 24 * 9), + kind: "physical", + action: "Power on one Threadripper host and make its BMC reachable to the worker.", + }, + ], + reviews: [ + { + ref: "developing-today/code#24", + title: "Dependency Dashboard", + url: "https://github.com/developing-today/code/issues/24", + pr: false, + updated: iso(60 * 30), + }, + ], + other: [ + { + ref: "developing-today/code#1086", + title: "epic(cluster): TALM and Talos bootstrap", + url: "https://github.com/developing-today/code/issues/1086", + pr: false, + updated: iso(60 * 24 * 20), + why: "", + }, + ], + }, + asks: [ + { + issue: 12501, + url: "https://github.com/developing-today/code/issues/12501", + text: "Make the join-at-admission slice the top priority and tell me what is in its way.", + created: iso(30), + updated: iso(4), + status: "answered", + worker: null, + replies: [ + { + you: false, + at: iso(4), + text: "Done. #12279 is ranked expedite and its task is first in the queue. In its way: #12230 (36 test files in no registry row) fails the lint the slice's PR will run. I queued that ahead of it.", + }, + ], + }, + { + issue: 12499, + url: "https://github.com/developing-today/code/issues/12499", + text: "What is blocked and why? One paragraph.", + created: iso(200), + updated: iso(180), + status: "done", + worker: null, + replies: [ + { + you: false, + at: iso(180), + text: "474 tasks are blocked. 212 wait on #9106, which is open although every PR for it is merged; closing it frees them.", + }, + ], + }, + { + issue: 12502, + url: "https://github.com/developing-today/code/issues/12502", + text: "Add a dark and light theme switch to the app.", + created: iso(2), + updated: iso(2), + status: "queued", + worker: null, + replies: [], + }, + ], + questionCount: { total: 6, sets: 2 }, + questions: { + total: 6, + sets: 2, + open: [ + question("2026-11-17", 7), + question("2026-11-17", 8, { + q: "Which checks must pass before a batch merges?", + multi: true, + recommended: ["opt-1", "opt-3"], + options: [ + { id: "opt-1", label: "Unit tests of the crates the batch touches", tags: ["recommended"] }, + { id: "opt-2", label: "The whole workspace", tags: ["safer"] }, + { id: "opt-3", label: "The module reach check", tags: ["recommended"] }, + ], + }), + question("2026-11-17", 9, { recommended: [], context: "", detail: "" }), + question("2026-11-16", 4), + question("2026-11-16", 5), + question("2026-11-16", 6), + ], + }, + prs: [ + { + number: 12240, + title: "ci(id): register the 36 unwired suites", + draft: false, + url: "https://github.com/developing-today/code/pull/12240", + created: iso(60 * 20), + author: "dezren39", + branch: "task/suite-registry", + }, + { + number: 12241, + title: "feat(id): F12.11 binary frames, encoder", + draft: false, + url: "https://github.com/developing-today/code/pull/12241", + created: iso(60 * 19), + author: "dezren39", + branch: "task/f12-11-frames", + }, + { + number: 12390, + title: "wip: talos bootstrap notes", + draft: true, + url: "https://github.com/developing-today/code/pull/12390", + created: iso(60 * 3), + author: "dezren39", + branch: "wip/talos", + }, + ], + priorities: { + truncated: false, + issues: [ + { + number: 4000, + title: "id: Phase 12 exit", + url: "https://github.com/developing-today/code/issues/4000", + updated: iso(90), + comments: 14, + labels: ["expedite"], + rank: "expedite", + order: 0, + }, + { + number: 12279, + title: "id: join at admission (slice 3)", + url: "https://github.com/developing-today/code/issues/12279", + updated: iso(300), + comments: 2, + labels: ["now"], + rank: "now", + order: 2, + }, + ], + }, + agents: [ + { name: "conductor", groups: ["opencode"], last_seen: iso(2), unread_commands: 0, unread_messages: 1 }, + { name: "muse", groups: ["research"], last_seen: iso(400), unread_commands: 2, unread_messages: 0 }, + ], + services: [ + { unit: "pm-aggregator.service", load: "loaded", active: "active", sub: "running", description: "PM dashboard" }, + { + unit: "opencode-go-seating-guard.service", + load: "loaded", + active: "failed", + sub: "failed", + description: "OpenCode Go seating guard", + }, + { + unit: "queue-broker.service", + load: "loaded", + active: "active", + sub: "running", + description: "Repo queue broker", + }, + ], + more: [ + { + group: "Overview", + pages: [ + { + title: "Overview", + route: "/?dashboard", + blurb: "The stack front door: needs-you, projects, quotas and health at a glance.", + }, + { title: "Today", route: "/today", blurb: "What changed today." }, + ], + }, + { group: "Work", pages: [{ title: "Roadmap", route: "/roadmap", blurb: "Phases and what is in each." }] }, + ], +}; + +const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" }); +const docs = new Docs( + Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), +); +const done = (result: unknown) => ({ run: async () => result, touch: [] as string[], audit: () => ({}) }); +// Linking a phone is the real thing, kept in a file under /tmp. +const devices = new Devices(fileStore("/tmp/pm-console-demo-devices.json")); +const phones = { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }; +const real = realActions( + new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), + undefined as never, + undefined, + devices, +); +const table = new Proxy({} as Record>, { + get: (_t, kind) => + typeof kind === "string" && kind.startsWith("device.") + ? real[kind] + : done( + kind === "ask.send" + ? { issue: 12503, queued: true } + : kind === "questions.accept" + ? { applied: 2, refused: [] } + : { ok: true }, + ), + has: () => true, + getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }), +}); + +/** The made-up host: canned state, and actions that all succeed. */ +export const demoDeps: Deps = { + cfg, + ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), + docs, + phones, + push: new Push(fileStore("/tmp/pm-console-demo-push.json"), "mailto:you@example.com", async () => ({ + status: 201, + })), + actions: table, + identify: async () => ({ via: "demo", email: "you@example.com" }), + audit: async () => {}, +}; +export { docs as demoDocs }; diff --git a/pm-stack/console/scripts/demo.ts b/pm-stack/console/scripts/demo.ts index 20dd48cf56..c2faf5a81b 100644 --- a/pm-stack/console/scripts/demo.ts +++ b/pm-stack/console/scripts/demo.ts @@ -1,371 +1,10 @@ -// Run the interface against canned state, to look at it without a fleet. +// The app with made-up state, for looking at it in a browser: // -// bun run scripts/demo.ts [port] then open http://127.0.0.1:/console/ -// -// The real server code answers; only the sources are canned, and every -// action succeeds and is listed under "What you did". -import { actions as realActions } from "../src/actions.ts"; -import { readConfig } from "../src/config.ts"; -import { Devices, Limiter } from "../src/devices.ts"; -import { Docs } from "../src/docs.ts"; -import { Ops } from "../src/ops.ts"; -import { Push } from "../src/push.ts"; +// bun run scripts/demo.ts [port] the host alone (default 4899) +// bun run scripts/edge-demo.ts [port] the same host behind the edge import { handle } from "../src/server.ts"; +import { demoDeps } from "./demo-state.ts"; -const iso = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString().slice(0, 19); -const task = (id: number, title: string, extra: Record) => ({ - id, - title, - priority: 30, - status: "queued", - attempts: 1, - claimed: "", - lease: "", - created: iso(300), - worker: null, - lane: null, - model: null, - kind: "small_fix", - issue: 9000 + id, - pr: null, - step: "", - goal: "The fix lands with a test that fails without it", - url: `https://github.com/developing-today/code/issues/${9000 + id}`, - ...extra, -}); -const question = (set: string, n: number, extra: Record = {}) => ({ - set, - setTitle: `Pending questions — ${set}`, - created: iso(60 * 24 * n), - ledger: `ledger-${set}-${n}`, - item: `PM-stack S${n} attachments (#1003${n}): where do attachments live`, - links: [`https://github.com/developing-today/code/issues/1003${n}`], - qid: `q${n}`, - q: `For S${n} attachments and multimedia, build new storage, or reuse a mechanism outside pm-stack that you name?`, - context: "Attachments today are pasted links. The dashboard has no storage of its own, and three pages want one.", - detail: - "Building new keeps the stack self-contained. Reusing means one fewer store to run, but ties the release to another project.", - multi: false, - recommended: ["opt-1"], - options: [ - { id: "opt-1", label: "Build new attachment storage", tags: ["recommended", "simpler"] }, - { id: "opt-2", label: "Reuse a mechanism outside pm-stack (name it in your answer)", tags: [] }, - { id: "opt-3", label: "Build new now; migrate storage refs later", tags: ["reversible"] }, - ], - ...extra, -}); - -const state = { - board: { - counts: { claimed: 3, queued: 4, blocked: 474, parked: 58 }, - now: [ - task(1, "Fix #9075: session state — session id in env and a resume path", { - status: "claimed", - claimed: iso(14), - worker: "repo-worker-code", - lane: "oc-code-02", - model: "workhorse", - attempts: 8, - step: "Write the failing test for resume after a crash, then wire the env var through the launcher.", - }), - task(2, "Implement mcpx Roc script support after the Python parity gate", { - status: "claimed", - claimed: iso(41), - worker: "repo-worker-code", - lane: "code-h", - priority: 20, - step: "Resume only when a compatible docs build is available.", - }), - task(3, "Fix #2723 phase 3: PendingHold post and void lifecycle", { - status: "claimed", - claimed: iso(3), - worker: "repo-worker-code", - lane: "code-j", - goal: "Posting and voiding a hold are covered by the ledger property tests", - }), - ], - next: [ - task(4, "Owner prompt developing-today/code#12501: make the join-at-admission slice the top priority", { - priority: 10, - kind: "triage", - }), - task(5, "Triage developing-today/code#12416: link from the dashboard to the console", { - priority: 30, - kind: "triage", - }), - task(6, "Merge-watch developing-today/code#12240: recheck fix PR for issue #12230", { - priority: 30, - kind: "pr_shepherd", - }), - task(7, "Fix #11350: toolchain file drift between crates", { priority: 50 }), - ], - blockedWhy: [ - { why: "waits on #9106 (open, all PRs merged)", n: 212 }, - { why: "no reason recorded", n: 140 }, - { why: '{"kind":"time","until":"2026-11-19T14:02:00Z"}', n: 4 }, - ], - }, - sessions: { - moving: [ - { - id: "s1", - title: "F12.11 binary frames: fuzz the decoder", - agent: "build", - model: "gpt-5.2-codex", - where: "git/code-j", - last: iso(1), - tools: 2, - messages: 141, - }, - { - id: "s2", - title: "Triage sweep: opencode", - agent: "triage", - model: "workhorse", - where: "git/opencode", - last: iso(6), - tools: 0, - messages: 37, - }, - ], - waiting: [ - { - id: "porkbun", - title: "Porkbun: log into the main account and enter the password in the staged modal", - ref: "gh:developing-today/code#902", - why: "", - }, - ], - }, - census: { - at: iso(1), - complete: true, - hands: [ - { - ref: "developing-today/code#12417", - title: "Google sign-in for pm.security.cab: create the OAuth client", - url: "https://github.com/developing-today/code/issues/12417", - pr: false, - updated: iso(50), - kind: "interactive-login", - action: - "Create a Google OAuth web client with the redirect URI in the issue and save its ID and secret in Bitwarden.", - }, - { - ref: "developing-today/code#1080", - title: "epic(cluster): hardware inventory and first-node selection", - url: "https://github.com/developing-today/code/issues/1080", - pr: false, - updated: iso(60 * 24 * 9), - kind: "physical", - action: "Power on one Threadripper host and make its BMC reachable to the worker.", - }, - ], - reviews: [ - { - ref: "developing-today/code#24", - title: "Dependency Dashboard", - url: "https://github.com/developing-today/code/issues/24", - pr: false, - updated: iso(60 * 30), - }, - ], - other: [ - { - ref: "developing-today/code#1086", - title: "epic(cluster): TALM and Talos bootstrap", - url: "https://github.com/developing-today/code/issues/1086", - pr: false, - updated: iso(60 * 24 * 20), - why: "", - }, - ], - }, - asks: [ - { - issue: 12501, - url: "https://github.com/developing-today/code/issues/12501", - text: "Make the join-at-admission slice the top priority and tell me what is in its way.", - created: iso(30), - updated: iso(4), - status: "answered", - worker: null, - replies: [ - { - you: false, - at: iso(4), - text: "Done. #12279 is ranked expedite and its task is first in the queue. In its way: #12230 (36 test files in no registry row) fails the lint the slice's PR will run. I queued that ahead of it.", - }, - ], - }, - { - issue: 12499, - url: "https://github.com/developing-today/code/issues/12499", - text: "What is blocked and why? One paragraph.", - created: iso(200), - updated: iso(180), - status: "done", - worker: null, - replies: [ - { - you: false, - at: iso(180), - text: "474 tasks are blocked. 212 wait on #9106, which is open although every PR for it is merged; closing it frees them.", - }, - ], - }, - { - issue: 12502, - url: "https://github.com/developing-today/code/issues/12502", - text: "Add a dark and light theme switch to the app.", - created: iso(2), - updated: iso(2), - status: "queued", - worker: null, - replies: [], - }, - ], - questionCount: { total: 6, sets: 2 }, - questions: { - total: 6, - sets: 2, - open: [ - question("2026-11-17", 7), - question("2026-11-17", 8, { - q: "Which checks must pass before a batch merges?", - multi: true, - recommended: ["opt-1", "opt-3"], - options: [ - { id: "opt-1", label: "Unit tests of the crates the batch touches", tags: ["recommended"] }, - { id: "opt-2", label: "The whole workspace", tags: ["safer"] }, - { id: "opt-3", label: "The module reach check", tags: ["recommended"] }, - ], - }), - question("2026-11-17", 9, { recommended: [], context: "", detail: "" }), - question("2026-11-16", 4), - question("2026-11-16", 5), - question("2026-11-16", 6), - ], - }, - prs: [ - { - number: 12240, - title: "ci(id): register the 36 unwired suites", - draft: false, - url: "https://github.com/developing-today/code/pull/12240", - created: iso(60 * 20), - author: "dezren39", - branch: "task/suite-registry", - }, - { - number: 12241, - title: "feat(id): F12.11 binary frames, encoder", - draft: false, - url: "https://github.com/developing-today/code/pull/12241", - created: iso(60 * 19), - author: "dezren39", - branch: "task/f12-11-frames", - }, - { - number: 12390, - title: "wip: talos bootstrap notes", - draft: true, - url: "https://github.com/developing-today/code/pull/12390", - created: iso(60 * 3), - author: "dezren39", - branch: "wip/talos", - }, - ], - priorities: { - truncated: false, - issues: [ - { - number: 4000, - title: "id: Phase 12 exit", - url: "https://github.com/developing-today/code/issues/4000", - updated: iso(90), - comments: 14, - labels: ["expedite"], - rank: "expedite", - order: 0, - }, - { - number: 12279, - title: "id: join at admission (slice 3)", - url: "https://github.com/developing-today/code/issues/12279", - updated: iso(300), - comments: 2, - labels: ["now"], - rank: "now", - order: 2, - }, - ], - }, - agents: [ - { name: "conductor", groups: ["opencode"], last_seen: iso(2), unread_commands: 0, unread_messages: 1 }, - { name: "muse", groups: ["research"], last_seen: iso(400), unread_commands: 2, unread_messages: 0 }, - ], - services: [ - { unit: "pm-aggregator.service", load: "loaded", active: "active", sub: "running", description: "PM dashboard" }, - { - unit: "opencode-go-seating-guard.service", - load: "loaded", - active: "failed", - sub: "failed", - description: "OpenCode Go seating guard", - }, - { - unit: "queue-broker.service", - load: "loaded", - active: "active", - sub: "running", - description: "Repo queue broker", - }, - ], - more: [ - { - group: "Overview", - pages: [ - { - title: "Overview", - route: "/?dashboard", - blurb: "The stack front door: needs-you, projects, quotas and health at a glance.", - }, - { title: "Today", route: "/today", blurb: "What changed today." }, - ], - }, - { group: "Work", pages: [{ title: "Roadmap", route: "/roadmap", blurb: "Phases and what is in each." }] }, - ], -}; - -const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" }); -const docs = new Docs( - Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), -); -const done = (result: unknown) => ({ run: async () => result, touch: [] as string[], audit: () => ({}) }); -// Linking a phone is the real thing, kept in a file under /tmp. -const devices = new Devices("/tmp/pm-console-demo-devices.json"); -const phones = { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }; -const real = realActions( - new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), - undefined as never, - undefined, - devices, -); -const table = new Proxy({} as Record>, { - get: (_t, kind) => - typeof kind === "string" && kind.startsWith("device.") - ? real[kind] - : done( - kind === "ask.send" - ? { issue: 12503, queued: true } - : kind === "questions.accept" - ? { applied: 2, refused: [] } - : { ok: true }, - ), - has: () => true, - getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }), -}); const extra = process.argv.slice(2); if (extra.length > 1 || (extra[0] !== undefined && !/^[1-9][0-9]{1,4}$/.test(extra[0]))) { console.error("usage: bun run scripts/demo.ts [port]"); @@ -375,16 +14,6 @@ const port = Number(extra[0] ?? 4899); Bun.serve({ hostname: "127.0.0.1", port, - fetch: (req) => - handle(req, { - cfg, - ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), - docs, - phones, - push: new Push("/tmp/pm-console-demo-push.json", "mailto:you@example.com", async () => ({ status: 201 })), - actions: table, - identify: async () => ({ via: "demo", email: "you@example.com" }), - audit: async () => {}, - }), + fetch: (req) => handle(req, demoDeps), }); console.log(`demo: http://127.0.0.1:${port}/console/`); diff --git a/pm-stack/console/scripts/edge-demo.ts b/pm-stack/console/scripts/edge-demo.ts new file mode 100644 index 0000000000..ba74e751b8 --- /dev/null +++ b/pm-stack/console/scripts/edge-demo.ts @@ -0,0 +1,153 @@ +// The app as it is served from the edge, on this machine, for a browser. +// +// bun run scripts/edge-demo.ts [port] then open http://127.0.0.1:/ +// +// The Worker's real routing and state answer the browser, with the +// made-up host of demo.ts behind them and the host's real link reporting +// to the edge. Stand-ins: the platform's storage (a map), the sign-in (a +// key made here; the first visit sets its token as a cookie), and push +// services (accepted and dropped). +// +// /__demo/host/down the host stops answering and reporting +// /__demo/host/up and comes back +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { Edge } from "../edge/src/edge.ts"; +import { type Io, route } from "../edge/src/entry.ts"; +import { heldRunner, handle, marked } from "../src/server.ts"; +import { memoryStore } from "../src/store.ts"; +import { EdgeLink } from "../src/sync.ts"; +import { demoDeps, demoDocs } from "./demo-state.ts"; + +const extra = process.argv.slice(2); +if (extra.length > 1 || (extra[0] !== undefined && !/^[1-9][0-9]{1,4}$/.test(extra[0]))) { + console.error("usage: bun run scripts/edge-demo.ts [port]"); + process.exit(2); +} +const port = Number(extra[0] ?? 4897); +const HOSTNAME = "127.0.0.1"; +const OWNER = "you@example.com"; +const ISSUER = { + name: "demo-sign-in", + issuer: "https://demo.invalid", + jwksUri: "https://demo.invalid/keys", + audience: "demo", + source: "access" as const, +}; + +// A sign-in issuer made here. +const pair = (await crypto.subtle.generateKey( + { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + true, + ["sign", "verify"], +)) as CryptoKeyPair; +const jwk = { ...(await crypto.subtle.exportKey("jwk", pair.publicKey)), kid: "demo" }; +const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); +async function token(): Promise { + const now = Math.floor(Date.now() / 1000); + const signed = `${part({ alg: "RS256", kid: "demo" })}.${part({ iss: ISSUER.issuer, aud: [ISSUER.audience], exp: now + 86_400, iat: now, email: OWNER })}`; + const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(signed)); + return `${signed}.${Buffer.from(sig).toString("base64url")}`; +} + +const stored = new Map(); +const edge = new Edge({ + kv: { + get: async (key) => structuredClone(stored.get(key)), + put: async (key, value) => { + stored.set(key, structuredClone(value)); + }, + delete: async (key) => { + stored.delete(key); + }, + }, + fetchImpl: (async (url: string) => + String(url) === ISSUER.jwksUri ? Response.json({ keys: [jwk] }) : new Response(null, { status: 201 })) as never, +}); + +const net = { hostUp: true }; +const publicDir = join(import.meta.dir, "..", "public"); +const io: Io = { + state: (r) => edge.fetch(r), + asset: async (path) => { + try { + const name = path.startsWith("/console/") ? path.slice("/console/".length) : ""; + return name ? new Response(readFileSync(join(publicDir, name))) : new Response("", { status: 404 }); + } catch { + return new Response("", { status: 404 }); + } + }, + // The made-up host trusts every caller, as demo.ts does; here it is + // only ever reached through the edge. + host: async (r) => (net.hostUp ? marked(await handle(r, demoDeps)) : null), + publicHost: HOSTNAME, + version: "demo", + later: (work) => void work.catch(() => {}), + now: Date.now, +}; + +const link = new EdgeLink({ + url: `http://${HOSTNAME}:${port}`, + keys: memoryStore(), + done: memoryStore(), + docs: demoDocs, + config: async () => ({ + owners: [OWNER], + certNames: [], + issuers: [ISSUER], + repo: demoDeps.cfg.repo, + queue: demoDeps.cfg.queue, + androidPackage: demoDeps.cfg.androidPackage, + androidFingerprints: [], + androidApp: false, + }), + run: heldRunner(demoDeps), + fetchImpl: (async (url: string, init: RequestInit) => { + if (!net.hostUp) throw new Error("the host is down"); + return route(new Request(url, init), io); + }) as never, + log: (line) => console.log(`host: ${line}`), +}); +demoDeps.link = link; +await demoDocs.touch([ + "board", + "sessions", + "census", + "asks", + "questionCount", + "questions", + "prs", + "priorities", + "agents", + "services", + "more", +]); +await link.once(); +setInterval(() => void link.turn().catch(() => {}), 2_000); + +Bun.serve({ + hostname: HOSTNAME, + port, + fetch: async (req) => { + const url = new URL(req.url); + if (url.pathname === "/__demo/host/down" || url.pathname === "/__demo/host/up") { + net.hostUp = url.pathname.endsWith("/up"); + return new Response(`host ${net.hostUp ? "up" : "down"}\n`); + } + // The first visit signs the browser in. + if ( + !(req.headers.get("cookie") ?? "").includes("CF_Authorization=") && + req.headers.get("sec-fetch-dest") === "document" + ) { + return new Response(null, { + status: 302, + headers: { + location: url.pathname + url.search, + "set-cookie": `CF_Authorization=${await token()}; Path=/; HttpOnly; SameSite=Lax`, + }, + }); + } + return route(req, io); + }, +}); +console.log(`edge demo: http://${HOSTNAME}:${port}/`); diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts new file mode 100644 index 0000000000..b500515146 --- /dev/null +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -0,0 +1,205 @@ +// A run of the edge in the real Worker runtime, on this machine. +// +// cd edge && node build.mjs && npx wrangler dev --port 8799 \ +// --var PUBLIC_HOST:localhost --var HOST_ORIGIN:http://127.0.0.1:4898 --var VERSION:smoke +// bun run scripts/edge-smoke.ts (in another shell) +// +// It starts a host on port 4898 with made-up state and this repo's real +// handler and link, then checks what can be checked without a sign-in +// issuer: the Worker starts, serves its public files, takes the host's +// signed report (fetching the host's key through the "tunnel"), keeps a +// section too large for one stored value, leaves an unsigned caller to +// the host, and answers a phone that is not linked. +import { identify } from "../src/auth.ts"; +import { readConfig } from "../src/config.ts"; +import { Devices, Limiter } from "../src/devices.ts"; +import { Docs } from "../src/docs.ts"; +import { Ops } from "../src/ops.ts"; +import { type Deps, handle, heldRunner, marked } from "../src/server.ts"; +import { memoryStore } from "../src/store.ts"; +import { EdgeLink } from "../src/sync.ts"; + +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 = [ + { + name: "cloudflare-access", + issuer: "https://smoke.cloudflareaccess.com", + jwksUri: "https://smoke.cloudflareaccess.com/cdn-cgi/access/certs", + audience: "smoke", + source: "access", + }, +]; +const big = { open: Array.from({ length: 5000 }, (_, i) => ({ qid: `q${i}`, question: "Why? ".repeat(80) })) }; +const data: Record = { + board: { counts: { claimed: 2, queued: 1 }, now: [{ id: 1, title: "Smoke task" }], next: [], blocked: [] }, + sessions: { moving: [], waiting: [] }, + census: { hands: [], reviews: [], other: [] }, + asks: [], + questionCount: { total: 5000, sets: 1 }, + questions: big, + prs: [], + priorities: { issues: [], truncated: false }, + agents: [], + services: [], + more: [], +}; +const docs = new Docs( + Object.fromEntries(Object.keys(data).map((n) => [n, { ttlMs: 10_000, load: async () => data[n] }])), +); +const deps: Deps = { + cfg, + ops: new Ops(cfg, async () => ({ code: 0, stdout: "{}", stderr: "" })), + docs, + actions: {}, + phones: { devices: new Devices(memoryStore()), link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }, + identify: (req, peer) => identify(req, cfg, { peer }), + audit: async () => {}, +}; +const link = new EdgeLink({ + url: EDGE, + keys: memoryStore(), + done: memoryStore(), + docs, + config: async () => ({ + owners: cfg.owners, + certNames: [], + issuers: cfg.issuers, + repo: cfg.repo, + queue: cfg.queue, + androidPackage: cfg.androidPackage, + androidFingerprints: [], + androidApp: false, + }), + run: heldRunner(deps), + log: (line) => console.log(` host: ${line}`), +}); +deps.link = link; +const seen: string[] = []; +const server = Bun.serve({ + hostname: "127.0.0.1", + port: 4898, + fetch: async (req, srv) => { + seen.push(`${req.method} ${new URL(req.url).pathname}`); + // Everything that arrives here came through the Worker, as it does + // through the tunnel: never a caller on this machine. (Deployed, the + // edge's own headers say so; here the address has to.) + void srv; + return marked(await handle(req, deps, "203.0.113.9")); + }, +}); + +let failed = 0; +const check = (name: string, ok: boolean, detail = "") => { + if (!ok) failed++; + console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? `: ${detail}` : ""}`); +}; +const get = (path: string, headers: Record = {}) => + fetch(`${EDGE}${path}`, { headers, redirect: "manual" }); + +try { + const before = (await (await get("/console/health")).json()) as Record; + check( + "the Worker answers its health check", + before.ok === true && before.edge === true && before.version === "smoke", + JSON.stringify(before), + ); + const manifest = await get("/manifest.webmanifest"); + check( + "the install manifest is served", + manifest.status === 200 && ((await manifest.json()) as { start_url: string }).start_url === "/console/", + ); + const icon = await get("/icons/icon-192.png"); + const bytes = new Uint8Array(await icon.arrayBuffer()); + check( + "an icon is served from the app's files", + icon.status === 200 && icon.headers.get("content-type") === "image/png" && bytes[1] === 0x50, + `${bytes.length} bytes`, + ); + + await docs.touch(Object.keys(data)); + const first = await link.once(); + check( + "the host's signed report is accepted", + first?.ok === true, + JSON.stringify({ watching: first?.watching, notify: first?.notify, want: first?.want }), + ); + check( + "the edge asked the host for its key, once", + seen.filter((s) => s === "GET /console/edge/key").length === 1, + seen.join(", "), + ); + const after = (await (await get("/console/health")).json()) as Record; + check( + "the edge now knows the owner and has seen the host", + after.configured === true && typeof after.hostSeen === "number", + JSON.stringify(after), + ); + const second = await link.once(); + check( + "a second report is accepted and nothing is asked for again", + second?.ok === true && (second?.want ?? []).length === 0, + ); + check( + "the large section went in pieces", + JSON.stringify(big).length > 1_500_000, + `${JSON.stringify(big).length} characters`, + ); + + seen.length = 0; + const stranger = await get("/console/api/doc/core"); + check( + "a caller with no sign-in is left to the host, which refuses", + stranger.status === 401 && stranger.headers.get("x-pm-console") === "1", + `${stranger.status}; host saw ${seen.join(", ")}`, + ); + const page = await get("/console/"); + check("so is the app's page", page.status === 401 && !(await page.text()).includes("Smoke task")); + const forged = await fetch(`${EDGE}/console/edge/sync`, { + method: "POST", + body: "{}", + headers: { "x-pm-key": "nope", "x-pm-signature": "AAAA" }, + }); + check("an unsigned report is refused", forged.status === 401, String(forged.status)); + const inside = await fetch(`${EDGE}/internal/hold`, { + method: "POST", + body: JSON.stringify({ kind: "ask.send", args: {} }), + headers: { "content-type": "application/json" }, + }); + check( + "an /internal path from outside never reaches the state", + inside.headers.get("x-pm-console") === "1", + String(inside.status), + ); + const phone = await get("/console/device/summary", { authorization: `Bearer ${"x".repeat(43)}` }); + check( + "a phone that is not linked is told so by the edge", + phone.status === 401 && ((await phone.json()) as { unlinked?: boolean }).unlinked === true, + ); + const linkTry = await fetch(`${EDGE}/console/device/link`, { + method: "POST", + body: JSON.stringify({ verifier: "v".repeat(43) }), + }); + check("a link nobody approved is refused", linkTry.status === 404); + // The host goes away: the edge says so itself, and says nothing else. + server.stop(true); + const gone = await get("/attention"); + check( + "with the host gone, a page of the host's is a plain notice", + gone.status === 503 && (await gone.text()).includes("Open the app"), + ); + const closed = await get("/console/api/doc/core"); + check( + "and a caller with no sign-in still learns nothing", + closed.status === 503 && !(await closed.text()).includes("Smoke task"), + ); + const still = (await (await get("/console/health")).json()) as Record; + check("the edge itself is still up", still.ok === true && Number(still.deferred) >= 3, JSON.stringify(still)); +} catch (error) { + failed++; + console.log(`FAIL the run stopped: ${(error as Error).message}`); +} finally { + server.stop(true); +} +console.log(failed === 0 ? "all checks passed" : `${failed} check(s) failed`); +process.exit(failed === 0 ? 0 : 1); diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 2773ef7899..2ef78780b0 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -14,26 +14,35 @@ the owner's address. Sign-in methods are the one-time PIN, plus Google when the secrets `google.access-sso.client-id` and `google.access-sso.client-secret` exist. -2. Four paths bypass sign-in at the edge. Three are files a phone +2. Five paths bypass sign-in at the edge. Three are files a phone fetches before anyone has signed in: the asset-links file, the install manifest and its icons. The fourth, /console/device, is where the Android app's home-screen widget presents a token of its own to - read a short summary. The console serves exactly those files to an - unsigned caller, checks that token itself, and answers nothing else. + read a short summary. The fifth, /console/edge, is where this host + reports to the edge Worker, signed with the host's own key. The + console serves exactly those files to an unsigned caller, checks that + token and that signature itself, and answers nothing else. 3. The console's environment file names the Access issuer and the owner, and the console is running with it. 4. The tunnel routes the hostname to the console. 5. DNS points the hostname at the tunnel. +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. -The gate comes first and the route last, so the origin is never +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 up with its sign-in settings, the run stops before the route. Every secret is read by name through `fleet secrets get` and stays in memory. Nothing printed is a secret. -Usage: expose.py [--check] [--host pm.security.cab] [--owner EMAIL] - --check report what would change and exit 1 if anything would. +Usage: expose.py [--check] [--edge on|off] [--host pm.security.cab] [--owner EMAIL] + --check report what would change and exit 1 if anything would. + --edge off take the hostname off the edge Worker; remembered by later + runs (the timer's included) until --edge on. """ from __future__ import annotations @@ -64,7 +73,12 @@ "/manifest.webmanifest", "/icons", "/console/device", + "/console/edge", ) +# The Worker that serves the app from the edge (pm-stack/console/edge). +# It is deployed from the repository; this script only decides whether +# the hostname's traffic goes through it. +WORKER = "pm-console-edge" GOOGLE_ID = "google.access-sso.client-id" GOOGLE_SECRET = "google.access-sso.client-secret" @@ -153,6 +167,72 @@ def plain(rule: dict) -> dict: ) +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: + 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.""" + marker = state / "edge" + if choice is not None: + state.mkdir(parents=True, exist_ok=True, mode=0o700) + marker.write_text(choice + "\n") + 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.""" + 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) + + +def ensure_edge_route(cf: Cloudflare, zone: str, host: str, wanted: bool) -> None: + """The hostname's traffic goes through the edge Worker, or does not. + A route on this hostname that names another Worker is not this + script's, and stops the run.""" + pattern = f"{host}/*" + routes = [ + r + for r in cf.get(f"/zones/{zone}/workers/routes") + if r.get("pattern", "").split("/")[0] == host + ] + foreign = [ + r for r in routes if r.get("pattern") != pattern or r.get("script") != WORKER + ] + if foreign: + raise SystemExit( + f"workers: {host} already has a route that is not {WORKER}'s; not touching it" + ) + if wanted and not routes: + cf.change( + f"workers: route {pattern} through {WORKER}", + "POST", + f"/zones/{zone}/workers/routes", + {"pattern": pattern, "script": WORKER}, + ) + if not wanted: + for route in routes: + cf.change( + f"workers: take {pattern} off {WORKER}", + "DELETE", + f"/zones/{zone}/workers/routes/{route['id']}", + None, + ) + + def find_zone(cf: Cloudflare, host: str) -> str: """The zone that holds the host: the longest suffix of the name that is a zone in this account. The last two labels are not always it @@ -362,13 +442,14 @@ def console_up(origin: str, seconds: int = 20) -> bool: def ensure_console( path: pathlib.Path, - wanted: dict[str, str], + wanted: dict[str, str | None], origin: str, check: bool, changes: list[str], ) -> None: - """The console runs with the sign-in settings. Raises, so nothing is - routed, if it cannot be brought up with them.""" + """The console runs with the sign-in settings. A value of None means + the setting must be absent. Raises, so nothing is routed, if the + console cannot be brought up with them.""" have = env_values(path) stale = [k for k, v in wanted.items() if have.get(k) != v] if stale: @@ -388,7 +469,8 @@ def ensure_console( kept = [line for line in lines if line.split("=", 1)[0].strip() not in wanted] path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) path.write_text( - "\n".join(kept + [f"{k}={v}" for k, v in wanted.items()]) + "\n" + "\n".join(kept + [f"{k}={v}" for k, v in wanted.items() if v is not None]) + + "\n" ) path.chmod(0o600) done = subprocess.run( @@ -412,6 +494,12 @@ def main() -> int: parser.add_argument("--check", action="store_true") parser.add_argument("--host", default="pm.security.cab") parser.add_argument("--owner", default="drewrypope@gmail.com") + parser.add_argument( + "--edge", + choices=["on", "off"], + help="send the hostname through the edge Worker, or straight to this host; " + "the choice is kept for later runs (default: on, once the Worker answers)", + ) args = parser.parse_args() token = secret("cloudflare.api-token-account-wide") @@ -432,6 +520,15 @@ def main() -> int: zone, dns_needed = dns_plan(cf, args.host, tunnel) env = pathlib.Path.home() / ".local/state/pm-console/.env" 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): + edge = False + print( + f"note: the edge Worker {WORKER} is not deployed or does not answer; " + "the hostname goes straight to this host" + ) # Order matters. The sign-in gate is put in place first and the route # last, so the origin is never reachable without the gate in front. @@ -466,6 +563,9 @@ def main() -> int: "PM_CONSOLE_ACCESS_TEAM_DOMAIN": team, "PM_CONSOLE_ACCESS_AUD": aud, "PM_CONSOLE_OWNER_EMAILS": args.owner, + # Where this host reports to the edge; absent, it reports + # to nobody. + "PM_CONSOLE_EDGE_URL": f"https://{args.host}" if edge else None, }, console, args.check, @@ -474,6 +574,9 @@ def main() -> int: if aud or args.check: ensure_routes(cf, account, args.host, tunnel, tunnel_config, console) ensure_dns(cf, args.host, tunnel, zone, dns_needed) + # Last: by now the host is up, knows where the edge is, and is + # reachable behind the hostname the Worker will sit on. + ensure_edge_route(cf, zone, args.host, edge) else: raise SystemExit( "the Access application has no audience tag; not routing the hostname" diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 1966f7e22a..a178267d48 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -38,6 +38,9 @@ def __init__(self, check=False): self.dns = [] self.zones = {"security.cab": "zone"} self.order = [] + # Workers routes on the zone, and whether the edge Worker answers. + self.routes = [] + self.worker_up = True def call(self, method, path, body=None): path, _, query = path.partition("?") @@ -85,6 +88,14 @@ def call(self, method, path, body=None): elif path == "/zones": name = query.partition("name=")[2] result = [{"id": self.zones[name]}] if name in self.zones else [] + elif path.endswith("/workers/subdomain"): + result = {"subdomain": "acct"} + elif "/workers/routes" in path: + if method == "POST": + self.routes.append({"id": f"route-{len(self.routes)}", **body}) + elif method == "DELETE": + self.routes = [r for r in self.routes if r["id"] != path.split("/")[-1]] + result = self.routes elif path.endswith("/dns_records"): if method == "POST": self.dns.append({**body, "zone": path.split("/")[2]}) @@ -131,6 +142,16 @@ 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(sys, "argv", argv), mock.patch("builtins.print"), ): @@ -235,9 +256,11 @@ def test_check_reports_and_changes_nothing(self): "/manifest.webmanifest", "/icons", "/console/device", + "/console/edge", ), ) - self.assertEqual(len(account.changes), len(expose.PUBLIC_PATHS) + 4) + # ... and the hostname's route through the edge Worker. + self.assertEqual(len(account.changes), len(expose.PUBLIC_PATHS) + 5) self.assertFalse( (pathlib.Path(self.home) / ".local/state/pm-console/.env").exists() ) @@ -396,6 +419,97 @@ def test_the_record_goes_in_the_zone_that_holds_the_name(self): run(account, self.home, "--host", host) self.assertEqual(account.order, []) + def env(self): + return expose.env_values( + pathlib.Path(self.home) / ".local/state/pm-console/.env" + ) + + def test_the_hostname_goes_through_the_edge_last_and_only_once_it_answers(self): + # The Worker is not deployed yet: nothing about the edge is set up. + account = Account() + account.worker_up = False + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.routes, []) + self.assertNotIn("PM_CONSOLE_EDGE_URL", self.env()) + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + # It answers: the host is told where to report, then the route goes in, last of all. + account.worker_up = True + account.order.clear() + machine = Machine() + self.assertEqual(run(account, self.home, machine=machine), 0) + self.assertEqual( + account.routes, + [{"id": "route-0", "pattern": f"{HOST}/*", "script": expose.WORKER}], + ) + self.assertEqual(self.env()["PM_CONSOLE_EDGE_URL"], f"https://{HOST}") + self.assertIn("restart", machine.commands) + self.assertEqual(account.order, ["POST /zones/zone/workers/routes"]) + self.assertEqual( + account.changes, + [ + "console environment: PM_CONSOLE_EDGE_URL", + f"workers: route {HOST}/* through {expose.WORKER}", + ], + ) + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + + def test_a_console_that_does_not_come_up_is_never_put_behind_the_edge(self): + account = Account() + with self.assertRaises(SystemExit): + run(account, self.home, machine=Machine(comes_up=False)) + self.assertEqual(account.routes, []) + + def test_edge_off_is_remembered_and_edge_on_brings_it_back(self): + account = Account() + run(account, self.home) + self.assertEqual(len(account.routes), 1) + self.assertEqual(run(account, self.home, "--edge", "off"), 0) + self.assertEqual(account.routes, []) + self.assertNotIn("PM_CONSOLE_EDGE_URL", self.env()) + # The sign-in settings are still there: only the edge's went. + self.assertEqual(self.env()["PM_CONSOLE_OWNER_EMAILS"], "drewrypope@gmail.com") + # A later run with no flag (the timer's) keeps it off. + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + self.assertEqual(account.routes, []) + self.assertEqual(run(account, self.home, "--edge", "on"), 0) + self.assertEqual( + [(r["pattern"], r["script"]) for r in account.routes], + [(f"{HOST}/*", expose.WORKER)], + ) + self.assertEqual(self.env()["PM_CONSOLE_EDGE_URL"], f"https://{HOST}") + + def test_another_workers_route_on_the_hostname_is_left_alone(self): + for foreign in ( + {"id": "x", "pattern": f"{HOST}/*", "script": "someone-elses"}, + {"id": "y", "pattern": f"{HOST}/api/*", "script": expose.WORKER}, + ): + account = Account() + account.routes = [dict(foreign)] + with self.assertRaises(SystemExit) as stopped: + run(account, self.home) + self.assertIn("not touching it", str(stopped.exception)) + self.assertEqual(account.routes, [foreign]) + self.assertFalse(any("workers/routes" in c for c in account.order)) + # A route for a different hostname in the same zone is nobody's business here. + account = Account() + account.routes = [ + {"id": "z", "pattern": "bridge.security.cab/*", "script": "message-bridge"} + ] + self.assertEqual(run(account, self.home), 0) + self.assertEqual(len(account.routes), 2) + + def test_check_never_records_an_edge_choice(self): + account = Account() + run(account, self.home) + self.assertEqual(run(account, self.home, "--check", "--edge", "off"), 0) + self.assertFalse( + (pathlib.Path(self.home) / ".local/state/pm-console/edge").exists() + ) + self.assertEqual(len(account.routes), 1) + if __name__ == "__main__": unittest.main() diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index 32cc7c455a..ad6f61be29 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -6,12 +6,13 @@ // owner typed. import type { Devices } from "./devices.ts"; import type { Docs } from "./docs.ts"; -import { OpError, type Ops } from "./ops.ts"; +import { OpError } from "./errors.ts"; +import type { Ops } from "./ops.ts"; import type { Push } from "./push.ts"; import type { Work } from "./work.ts"; type Args = Record; -interface Action { +export interface Action { run: (args: Args) => Promise; /** Sections to read again afterwards. */ touch: string[]; @@ -30,7 +31,10 @@ const asked = async (p: Promise): Promise => throw error instanceof OpError ? error : new OpError(400, error.message); }); -export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): Record { +/** The actions that need nothing from the host: this device's + * notifications, and phones linked to read the summary. They are the + * ones the edge runs itself. */ +export function ownActions(push?: Push, devices?: Devices): Record { // A phone linked to read the summary its home-screen widget shows. const phones: Record = devices ? { @@ -56,9 +60,12 @@ export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): R }, } : {}; + return { ...notify, ...phones }; +} + +export function actions(ops: Ops, work: Work, push?: Push, devices?: Devices): Record { return { - ...notify, - ...phones, + ...ownActions(push, devices), "ask.send": { run: (a) => work.ask(a), touch: ["asks", "board"], audit: () => ({}) }, "ask.reply": { run: (a) => work.askReply(a), touch: ["asks", "board"], audit: ids("issue") }, "ask.close": { run: (a) => work.askClose(a), touch: ["asks"], audit: ids("issue") }, diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts index e8178d5fe7..df67eeb583 100644 --- a/pm-stack/console/src/config.ts +++ b/pm-stack/console/src/config.ts @@ -54,6 +54,13 @@ export interface Config { androidApk: string; /** Where linked phones are kept (hashes of their tokens, never the tokens). */ devicesFile: string; + /** The public address the edge answers on (https, no path), or null + * when this host is not behind one and reports to nobody. */ + edgeUrl: string | null; + /** This host's key pair for signing what it reports to the edge. */ + edgeKeyFile: string; + /** What became of each action the edge held for this host. */ + edgeDoneFile: string; /** The dashboard's decision-set store: the questions waiting on the * owner, and the per-set tokens that authorise an answer. */ decisionsFile: string; @@ -195,6 +202,31 @@ export function readConfig( dashboardUrl = parsed.origin; } + let edgeUrl: string | null = env.PM_CONSOLE_EDGE_URL ?? null; + if (edgeUrl === "") edgeUrl = null; + if (edgeUrl !== null) { + let parsed: URL | null = null; + try { + parsed = new URL(edgeUrl); + } catch { + // reported below + } + if ( + !parsed || + parsed.protocol !== "https:" || + parsed.pathname !== "/" || + parsed.search !== "" || + parsed.hash !== "" || + parsed.username !== "" || + parsed.password !== "" + ) { + throw new ConfigError( + `PM_CONSOLE_EDGE_URL: expected https:// with no path, got ${JSON.stringify(edgeUrl)}`, + ); + } + edgeUrl = parsed.origin; + } + return { port: port(env, "PM_CONSOLE_PORT", 4872), bind, @@ -221,6 +253,9 @@ export function readConfig( androidFingerprints: fingerprints, androidApk: env.PM_CONSOLE_ANDROID_APK ?? `${home}/.local/state/pm-console/android/pm-console.apk`, devicesFile: env.PM_CONSOLE_DEVICES_FILE ?? `${home}/.local/state/pm-console/devices.json`, + edgeUrl, + edgeKeyFile: env.PM_CONSOLE_EDGE_KEY_FILE ?? `${home}/.local/state/pm-console/edge-key.json`, + edgeDoneFile: env.PM_CONSOLE_EDGE_DONE_FILE ?? `${home}/.local/state/pm-console/edge-done.json`, decisionsFile: env.PM_CONSOLE_DECISIONS_FILE ?? `${home}/.local/state/pm-aggregator/decisions.json`, promptLabel: env.PM_CONSOLE_PROMPT_LABEL ?? "owner/prompt", needsRepos: list(env, "PM_CONSOLE_NEEDS_REPOS", [ diff --git a/pm-stack/console/src/devices.ts b/pm-stack/console/src/devices.ts index 837204dea6..4bf997e2a3 100644 --- a/pm-stack/console/src/devices.ts +++ b/pm-stack/console/src/devices.ts @@ -10,9 +10,8 @@ // the phone then presents the verifier, which only it knows, and is // given its token. The store keeps hashes of tokens, never the tokens. import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; -import { dirname } from "node:path"; -import { OpError } from "./ops.ts"; +import { OpError } from "./errors.ts"; +import type { Store as Kept } from "./store.ts"; export interface Device { id: string; @@ -80,10 +79,9 @@ export class Limiter { export class Devices { private store: Store | null = null; - private writing: Promise = Promise.resolve(); constructor( - private file: string, + private kept: Kept, private now: () => number = Date.now, private random: (bytes: number) => Buffer = randomBytes, ) {} @@ -92,25 +90,17 @@ export class Devices { if (this.store) return this.store; let store: Store = { devices: [], pending: [] }; try { - const parsed = JSON.parse(await readFile(this.file, "utf8")); + const parsed = JSON.parse((await this.kept.read()) ?? ""); if (parsed && Array.isArray(parsed.devices) && Array.isArray(parsed.pending)) store = parsed; } catch { - // no file yet, or one that cannot be read: start with no devices + // nothing kept yet, or something that cannot be read: start with no devices } this.store ??= store; return this.store; } - /** Written whole to a new file and moved into place, one write at a time. */ private save(): Promise { - const next = this.writing.then(async () => { - await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); - const tmp = `${this.file}.${process.pid}.tmp`; - await writeFile(tmp, JSON.stringify(this.store), { mode: 0o600 }); - await rename(tmp, this.file); - }); - this.writing = next.catch(() => {}); - return next; + return this.kept.write(JSON.stringify(this.store)); } /** The owner, signed in, approves a phone that is asking to be linked. */ diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index 131a2ef6a0..3ae9936d35 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -31,6 +31,15 @@ interface Section { loading: Promise | null; } +/** Data that carries the time it was really read: a copy of a section + * that somewhere else read (the host reporting to the edge). */ +export class Stamped { + constructor( + public data: unknown, + public at: number, + ) {} +} + export interface Act { id: string; kind: string; @@ -55,6 +64,8 @@ export class Docs { private sections = new Map(); private asked = 0; private acts: Act[] = []; + /** Small values that travel in the core document beside its sections. */ + private extras: Record = {}; private timer: ReturnType | null = null; constructor( @@ -79,10 +90,13 @@ export class Docs { if (s.loading) return s.loading; s.loading = (async () => { try { - s.data = await s.load(); + const loaded = await s.load(); + const now = this.now(); + // 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.goodAt = this.now(); } catch (error) { s.ok = false; s.error = (error as Error).message.slice(0, 300); @@ -162,6 +176,45 @@ export class Docs { this.acts = [act, ...this.acts.filter((a) => a.id !== act.id)].slice(0, ACTS_KEPT); } + /** What the owner did lately, newest first; and a way to put it back + * after a restart of whatever holds this. */ + recentActs(): Act[] { + return this.acts; + } + + restoreActs(acts: Act[]): void { + this.acts = acts.slice(0, ACTS_KEPT); + } + + /** Set, or with undefined remove, a value carried in the core document. */ + extra(name: string, value: unknown): void { + if (value === undefined) delete this.extras[name]; + else this.extras[name] = value; + } + + /** Someone is looking, though not through this process: keep reading. */ + keepAlive(): void { + this.asked = this.now(); + } + + /** Whether anyone has asked for a document lately. */ + watched(): boolean { + return this.now() - this.asked <= WATCH_MS; + } + + /** 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 }[] = []; + 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 }); + } + return out; + } + /** The document, at once. Only a section that has never been read is * waited for, and only so long. `asOf` is now when every section has * been read within its own interval, and earlier by however far the @@ -190,7 +243,7 @@ export class Docs { health[n] = { ok: s.ok, error: s.error }; } out.health = health; - if (name === "core") out.acts = this.acts; + if (name === "core") Object.assign(out, this.extras, { acts: this.acts }); // The tag covers the content and not the times it was read, so a // document that has not changed costs the phone nothing. The read // times travel beside it. diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts new file mode 100644 index 0000000000..b47101e256 --- /dev/null +++ b/pm-stack/console/src/edge-proto.ts @@ -0,0 +1,201 @@ +// What the host and the edge say to each other. +// +// The app is served from the edge (a Cloudflare Worker in front of the +// public hostname). The host stays what it is, the machine with the +// fleet's tools on it, and reports to the edge: +// +// host -> edge POST /console/edge/sync, signed with the host's own +// key: the sections of state that changed, and what +// became of anything the edge was holding for it +// edge -> host in the answer: whether anyone is looking, and the +// actions the owner took while the host could not be +// reached +// +// The host's key pair is made on the host and never leaves it. The edge +// learns the public half by asking the host through the tunnel, which +// only the host can answer, so there is no shared secret to keep +// anywhere. A sync is refused unless its signature verifies, its time is +// near the edge's own clock, and that time is later than the last sync +// accepted. +import type { Issuer } from "./config.ts"; + +/** What the edge needs to know to recognise the owner. It comes from the + * host in every sync, so there is one place it is set. */ +export interface EdgeConfig { + owners: string[]; + certNames: string[]; + issuers: Issuer[]; + repo: string; + queue: string; + androidPackage: string; + androidFingerprints: string[]; + /** Whether the host has a signed Android build to hand out. */ + androidApp: boolean; +} + +export interface SyncSection { + name: string; + /** When the host read it, in milliseconds. */ + at: number; + /** A fingerprint of the data: how each side tells it has not changed. */ + hash: string; + data: unknown; +} + +export interface SyncRequest { + v: 1; + /** Milliseconds, later than every sync before it. */ + at: number; + 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; + /** What became of the held actions the host was given. */ + acks: { id: string; ok: boolean; error?: string }[]; +} + +/** An action the owner took while the host could not be reached. */ +export interface Held { + id: string; + kind: string; + args: Record; + /** Who took it, as the edge verified them. */ + who: string; + at: string; +} + +export interface SyncResponse { + ok: true; + /** Someone has the app open: keep every section fresh. */ + watching: boolean; + /** A device takes notifications or a phone is linked: keep the + * sections those are built from fresh even with nobody looking. */ + notify: boolean; + /** Sections the edge lacks and wants sent whole. */ + want: string[]; + commands: Held[]; +} + +/** Actions that may be done late, when the host is back. The rest act on + * something that may have changed by then (a merge, a unit, a task's + * state), so they are refused while the host cannot be reached. */ +export const HOLDABLE = new Set([ + "ask.send", + "ask.reply", + "ask.close", + "question.answer", + "question.defer", + "questions.accept", + "hands.done", + "need.comment", + "issue.comment", + "issue.rank", + "task.move", + "message.send", +]); +/** A held action older than this is dropped, and said to have been. */ +export const HELD_FOR_MS = 24 * 60 * 60_000; +/** A sync whose time is further than this from the edge's clock is refused. */ +export const SYNC_SKEW_MS = 2 * 60_000; + +const SIGN = { name: "ECDSA", hash: "SHA-256" } as const; +const CURVE = { name: "ECDSA", namedCurve: "P-256" } as const; + +const b64u = (bytes: ArrayBuffer | Uint8Array): string => { + let bin = ""; + for (const b of new Uint8Array(bytes as ArrayBuffer)) bin += String.fromCharCode(b); + return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +}; +const unb64u = (text: string): Uint8Array => { + if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url"); + const bin = atob(text.replace(/-/g, "+").replace(/_/g, "/")); + return Uint8Array.from(bin, (c) => c.charCodeAt(0)); +}; + +/** The public half of a key, with only the fields that define it. */ +export interface PublicKey { + kty: "EC"; + crv: "P-256"; + x: string; + y: string; +} + +export function publicKey(value: unknown): PublicKey | null { + const v = value as Record | null; + if (!v || v.kty !== "EC" || v.crv !== "P-256") return null; + if (typeof v.x !== "string" || typeof v.y !== "string") return null; + if (!/^[A-Za-z0-9_-]{43}$/.test(v.x) || !/^[A-Za-z0-9_-]{43}$/.test(v.y)) return null; + return { kty: "EC", crv: "P-256", x: v.x, y: v.y }; +} + +/** A short name for a public key: the start of its SHA-256. */ +export async function keyId(key: PublicKey): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${key.x}.${key.y}`)); + return b64u(digest).slice(0, 16); +} + +export async function newKeyPair(): Promise<{ publicJwk: PublicKey; privateJwk: JsonWebKey }> { + const pair = (await crypto.subtle.generateKey(CURVE, true, ["sign", "verify"])) as CryptoKeyPair; + const pub = publicKey(await crypto.subtle.exportKey("jwk", pair.publicKey)); + if (!pub) throw new Error("the platform made a key this cannot read"); + return { publicJwk: pub, privateJwk: await crypto.subtle.exportKey("jwk", pair.privateKey) }; +} + +export async function sign(privateJwk: JsonWebKey, body: Uint8Array): Promise { + const key = await crypto.subtle.importKey("jwk", privateJwk, CURVE, false, ["sign"]); + return b64u(await crypto.subtle.sign(SIGN, key, body)); +} + +export async function verify(key: PublicKey, body: Uint8Array, signature: string): Promise { + let sig: Uint8Array; + try { + sig = unb64u(signature); + } catch { + return false; + } + if (sig.length !== 64) return false; + const imported = await crypto.subtle.importKey("jwk", key, CURVE, false, ["verify"]); + return crypto.subtle.verify(SIGN, imported, sig, body); +} + +const strings = (value: unknown): value is string[] => + Array.isArray(value) && value.every((v) => typeof v === "string"); + +/** The config a sync carries, checked: the edge decides who the owner is + * from this, so a malformed one is refused whole. */ +export function edgeConfig(value: unknown): EdgeConfig | null { + const v = value as Record | null; + if (!v || !strings(v.owners) || !strings(v.certNames) || !strings(v.androidFingerprints)) return null; + if (!Array.isArray(v.issuers)) return null; + const issuers: Issuer[] = []; + for (const raw of v.issuers as Record[]) { + if (!raw || typeof raw !== "object") return null; + for (const key of ["name", "issuer", "jwksUri", "audience"]) { + if (typeof raw[key] !== "string" || raw[key] === "") return null; + } + if (!/^https:\/\//.test(raw.issuer as string) || !/^https:\/\//.test(raw.jwksUri as string)) return null; + if (raw.source !== "access" && raw.source !== "bearer") return null; + issuers.push({ + name: raw.name as string, + issuer: raw.issuer as string, + jwksUri: raw.jwksUri as string, + audience: raw.audience as string, + source: raw.source, + }); + } + if (typeof v.repo !== "string" || typeof v.queue !== "string" || typeof v.androidPackage !== "string") return null; + return { + owners: v.owners.map((o) => o.toLowerCase()), + certNames: v.certNames, + issuers, + repo: v.repo, + queue: v.queue, + androidPackage: v.androidPackage, + androidFingerprints: v.androidFingerprints, + androidApp: v.androidApp === true, + }; +} diff --git a/pm-stack/console/src/errors.ts b/pm-stack/console/src/errors.ts new file mode 100644 index 0000000000..6a1f8dea14 --- /dev/null +++ b/pm-stack/console/src/errors.ts @@ -0,0 +1,11 @@ +// A refusal with the HTTP status it should travel as. It has a module of +// its own so that code which runs at the edge can raise one without +// pulling in the host's process-running code. +export class OpError extends Error { + constructor( + public status: 400 | 404 | 409 | 502 | 503, + message: string, + ) { + super(message); + } +} diff --git a/pm-stack/console/src/file-store.ts b/pm-stack/console/src/file-store.ts new file mode 100644 index 0000000000..c6a557f29c --- /dev/null +++ b/pm-stack/console/src/file-store.ts @@ -0,0 +1,30 @@ +// A Store that is a file on this machine: private to the user, and +// written whole to a new file that is then moved into place, so a crash +// never leaves half of it. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { Store } from "./store.ts"; + +export function fileStore(path: string): Store { + let writing: Promise = Promise.resolve(); + return { + read: async () => { + try { + return await readFile(path, "utf8"); + } catch { + return null; // no file yet + } + }, + // One write at a time, in the order asked. + write: (text) => { + const next = writing.then(async () => { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const tmp = `${path}.${process.pid}.tmp`; + await writeFile(tmp, text, { mode: 0o600 }); + await rename(tmp, path); + }); + writing = next.catch(() => {}); + return next; + }, + }; +} diff --git a/pm-stack/console/src/http.ts b/pm-stack/console/src/http.ts new file mode 100644 index 0000000000..d1bb3438a0 --- /dev/null +++ b/pm-stack/console/src/http.ts @@ -0,0 +1,174 @@ +// The pieces of the HTTP surface that are the same wherever the app is +// served from: this host, or the edge in front of it. +import type { Config } from "./config.ts"; +import { type Devices, type Limiter, summary } from "./devices.ts"; +import type { Docs } from "./docs.ts"; + +export const BASE = "/console"; + +/** The install manifest of the app at this origin. The home-screen icon + * opens the app, and a long press offers its four primary screens. */ +export const MANIFEST = { + name: "PM", + short_name: "PM", + description: "What the fleet is doing, what is next, what needs you, and a place to say what you want.", + start_url: "/console/", + scope: "/", + display: "standalone", + background_color: "#0b0f14", + theme_color: "#11161d", + icons: [ + { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, + { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, + { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], + shortcuts: [ + { name: "Ask the fleet", short_name: "Ask", url: "/console/#ask" }, + { name: "Needs me", short_name: "Needs me", url: "/console/#needs" }, + { name: "In progress", short_name: "Now", url: "/console/#now" }, + { name: "Queued next", short_name: "Next", url: "/console/#next" }, + ], +}; +export const SECURITY = { + "Content-Security-Policy": + "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "same-origin", +}; + +export function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, + }); +} + +/** The install manifest, as a response. */ +export function manifest(): Response { + return new Response(JSON.stringify(MANIFEST), { + headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-cache", ...SECURITY }, + }); +} + +/** The Digital Asset Links statement that lets the Android app open + * this origin full screen. Public by design: Android fetches it. */ +export function assetLinks(cfg: Pick): unknown[] { + if (cfg.androidFingerprints.length === 0) return []; + return [ + { + relation: ["delegate_permission/common.handle_all_urls"], + target: { + namespace: "android_app", + package_name: cfg.androidPackage, + sha256_cert_fingerprints: cfg.androidFingerprints, + }, + }, + ]; +} + +export interface Phones { + devices: Devices; + /** Tries at linking, and reads refused for a wrong token. */ + link: Limiter; + refused: Limiter; +} + +/** Sections the summary is built from, and how long a phone waits for + * them to be read again. */ +const SUMMARY_SECTIONS = ["board", "sessions", "census", "asks", "questionCount"]; +/** Under the five seconds the phone gives a read. */ +const SUMMARY_WAIT_MS = 3_500; +const DEVICE_BODY_LIMIT = 1024; + +/** A phone presents the verifier for a link the owner approved. */ +export async function deviceLink( + req: Request, + phones: Phones, + audit: (entry: Record) => Promise, +): Promise { + if (!phones.link.allow()) return json({ error: "too many tries: wait a minute" }, 429); + if (Number(req.headers.get("content-length") ?? "0") > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); + let verifier: unknown; + try { + const text = await req.text(); + if (text.length > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); + verifier = (JSON.parse(text) as { verifier?: unknown } | null)?.verifier; + } catch { + return json({ error: "body: expected a JSON object" }, 400); + } + const linked = await phones.devices.link(verifier); + if (!linked) return json({ error: "not approved" }, 404); + await audit({ + at: new Date().toISOString(), + who: `device:${linked.id}`, + via: "device", + action: "device.link", + phase: "done", + ok: true, + }).catch((error) => console.error(`pm-console: audit: ${(error as Error).message}`)); + return json(linked); +} + +/** A linked phone reads the counts and the top line of each list. */ +export async function deviceSummary(req: Request, docs: Docs, phones: Phones): Promise { + const header = req.headers.get("authorization") ?? ""; + const device = header.startsWith("Bearer ") ? await phones.devices.check(header.slice(7)) : null; + if (!device) { + // Wrong tokens are counted; a linked phone is never slowed by them. + if (!phones.refused.allow()) return json({ error: "too many tries: wait a minute" }, 429); + // `unlinked` tells the app to forget its token; a refusal from + // anything else in front of this service does not carry it. + return json({ error: "this phone is not linked", unlinked: true }, 401); + } + const { data, at, missing } = await docs.current(SUMMARY_SECTIONS, SUMMARY_WAIT_MS); + // Before the queue has been read once there is nothing true to show: + // the phone keeps what it has and asks again. + if (missing.includes("board")) return json({ error: "not ready yet" }, 503); + return json(summary(data, at)); +} + +/** A write must come from this site. A browser sends Origin on every + * cross-site write and Sec-Fetch-Site on every request, and the sign-in + * cookie alone must not be enough for another site to act as the owner. */ +export function crossSiteWrite(req: Request): boolean { + if (req.method === "GET" || req.method === "HEAD") return false; + if (req.headers.get("sec-fetch-site") === "cross-site") return true; + const origin = req.headers.get("origin"); + if (origin === null) return false; + try { + return new URL(origin).host !== (req.headers.get("host") ?? ""); + } catch { + return true; + } +} + +/** A state-changing request must be one this page made: a custom header + * a cross-site form cannot set, and an Origin that is this host. */ +export function sameSiteWrite(req: Request): boolean { + if (req.headers.get("x-pm-console") !== "1") return false; + const origin = req.headers.get("origin"); + if (origin === null) return true; + try { + return new URL(origin).host === (req.headers.get("host") ?? ""); + } catch { + return false; + } +} + +/** One of the three state documents, as a response: the tag for "you + * already have this", and beside it the time the state was read. */ +export function docResponse( + req: Request, + doc: { etag: string; body: string; asOf: number }, + shrink?: (req: Request, bytes: Uint8Array, headers: Headers) => Response | null, +): Response { + const headers = new Headers({ + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-cache", + ETag: doc.etag, + "X-As-Of": String(doc.asOf), + ...SECURITY, + }); + if (req.headers.get("if-none-match") === doc.etag) return new Response(null, { status: 304, headers }); + return shrink?.(req, new TextEncoder().encode(doc.body), headers) ?? new Response(doc.body, { headers }); +} diff --git a/pm-stack/console/src/notify.ts b/pm-stack/console/src/notify.ts index 0a42981d6b..474a5cc119 100644 --- a/pm-stack/console/src/notify.ts +++ b/pm-stack/console/src/notify.ts @@ -5,10 +5,9 @@ // one of his prompts, something new needs his hands, new questions // arrived, a unit failed. The first pass only takes stock, so turning // notifications on never sets off a flood about things already there. -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; -import { dirname } from "node:path"; import type { Docs } from "./docs.ts"; import type { Class, Push } from "./push.ts"; +import type { Store } from "./store.ts"; export interface Seen { primed: boolean; @@ -120,13 +119,13 @@ export class Notifier { constructor( private docs: Docs, private push: Push, - private file: string, + private store: Store, ) {} private async load(): Promise { if (this.seen) return this.seen; try { - this.seen = { ...NOTHING_SEEN, ...(JSON.parse(await readFile(this.file, "utf8")) as Seen) }; + this.seen = { ...NOTHING_SEEN, ...(JSON.parse((await this.store.read()) ?? "") as Seen) }; } catch { this.seen = NOTHING_SEEN; } @@ -143,11 +142,10 @@ export class Notifier { const now = Object.fromEntries(WATCHED.map((n) => [n, this.docs.good(n)])) as State; const { messages, seen } = changes(await this.load(), now); for (const m of messages) await this.push.send(m.cls, m); + // Written down only when it differs: most passes find nothing new. + const before = JSON.stringify(this.seen); this.seen = seen; - await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); - const tmp = `${this.file}.tmp-${process.pid}`; - await writeFile(tmp, JSON.stringify(seen), { mode: 0o600 }); - await rename(tmp, this.file); + if (JSON.stringify(seen) !== before) await this.store.write(JSON.stringify(seen)); return messages.length; } finally { this.busy = false; diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 59751a99cb..abc7d4f4bd 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -8,6 +8,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Config } from "./config.ts"; +import { OpError } from "./errors.ts"; export interface RunResult { code: number; @@ -23,14 +24,7 @@ export type Row = Record; /** Queue priorities, most urgent first (the queue's design scale). */ export const PRIORITY_SCALE = [10, 20, 30, 40, 50, 70, 90] as const; -export class OpError extends Error { - constructor( - public status: 400 | 404 | 409 | 502, - message: string, - ) { - super(message); - } -} +export { OpError }; export const realRun: Run = async (argv, opts = {}) => { const proc = Bun.spawn(argv, { diff --git a/pm-stack/console/src/push.ts b/pm-stack/console/src/push.ts index 3686f318b8..70c6789dc6 100644 --- a/pm-stack/console/src/push.ts +++ b/pm-stack/console/src/push.ts @@ -5,9 +5,8 @@ // (RFC 8291, aes128gcm), and the request is signed with this server's // own key pair so the push service knows who is sending (RFC 8292, // VAPID). The key pair is made here on first use and kept in this -// service's state directory; nobody ever handles it. -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; -import { dirname } from "node:path"; +// service's own store; nobody ever handles it. +import type { Store } from "./store.ts"; const enc = new TextEncoder(); const b64u = (bytes: Uint8Array | ArrayBuffer) => Buffer.from(bytes as ArrayBuffer).toString("base64url"); @@ -109,8 +108,10 @@ export class Push { private signer: CryptoKey | null = null; constructor( - private file: string, - private subject: string, + private store: Store, + /** The contact a push service is given; a function when it is only + * known later. */ + private subject: string | (() => string), private post: Poster = (url, init) => fetch(url, init as RequestInit), private now: () => number = Date.now, ) {} @@ -118,7 +119,7 @@ export class Push { private async load(): Promise { if (this.state) return this.state; try { - this.state = JSON.parse(await readFile(this.file, "utf8")) as PushFile; + this.state = JSON.parse((await this.store.read()) ?? "") as PushFile; } catch { this.state = { vapid: null, subscriptions: [], off: [] }; } @@ -138,10 +139,7 @@ export class Push { private async save(): Promise { if (!this.state) return; - await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); - const tmp = `${this.file}.tmp-${process.pid}`; - await writeFile(tmp, JSON.stringify(this.state), { mode: 0o600 }); - await rename(tmp, this.file); + await this.store.write(JSON.stringify(this.state)); } /** What the page needs to subscribe, and what is switched on. */ @@ -195,7 +193,7 @@ export class Push { JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(this.now() / 1000) + 12 * 3600, - sub: this.subject, + sub: typeof this.subject === "function" ? this.subject() : this.subject, }), ), ); diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index af2c203424..02b6d42a46 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -13,16 +13,31 @@ import { mkdirSync, readFileSync } from "node:fs"; import { appendFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { actions, perform } from "./actions.ts"; +import { HOLDABLE, type Held } from "./edge-proto.ts"; import { AuthError, type Identity, identify } from "./auth.ts"; import { type Config, readConfig } from "./config.ts"; -import { Devices, Limiter, summary } from "./devices.ts"; +import { Devices, Limiter } from "./devices.ts"; import { DOC_NAMES, type DocName, Docs } from "./docs.ts"; +import { fileStore } from "./file-store.ts"; +import { + assetLinks, + BASE, + crossSiteWrite, + deviceLink, + deviceSummary, + docResponse, + json, + manifest, + type Phones, + SECURITY, + sameSiteWrite, +} from "./http.ts"; import { Notifier } from "./notify.ts"; import { OpError, Ops } from "./ops.ts"; import { Push } from "./push.ts"; +import { EdgeLink } from "./sync.ts"; import { Work } from "./work.ts"; -const BASE = "/console"; const PUBLIC_DIR = join(import.meta.dir, "..", "public"); const STATIC = new Map([ ["app.js", "text/javascript; charset=utf-8"], @@ -31,36 +46,7 @@ const STATIC = new Map([ ["sw.js", "text/javascript; charset=utf-8"], ]); -/** The install manifest of the app at this origin. The home-screen icon - * opens the app, and a long press offers its four primary screens. */ -const MANIFEST = { - name: "PM", - short_name: "PM", - description: "What the fleet is doing, what is next, what needs you, and a place to say what you want.", - start_url: "/console/", - scope: "/", - display: "standalone", - background_color: "#0b0f14", - theme_color: "#11161d", - icons: [ - { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, - { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, - { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, - ], - shortcuts: [ - { name: "Ask the fleet", short_name: "Ask", url: "/console/#ask" }, - { name: "Needs me", short_name: "Needs me", url: "/console/#needs" }, - { name: "In progress", short_name: "Now", url: "/console/#now" }, - { name: "Queued next", short_name: "Next", url: "/console/#next" }, - ], -}; const APK_NAME = "pm-console.apk"; -const SECURITY = { - "Content-Security-Policy": - "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "same-origin", -}; /** 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$/; @@ -84,13 +70,6 @@ const UPSTREAM_BODY_LIMIT = 16 * 1024 * 1024; * while the action carried on. Bun's limit is 255. */ const IDLE_TIMEOUT_SECONDS = 120; -function json(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body), { - status, - headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, - }); -} - // The page's four files, read once: nothing on the request path touches // the disk synchronously after the first hit. const fileCache = new Map(); @@ -103,21 +82,7 @@ function file(name: string, type: string): Response { return new Response(bytes, { headers: { "Content-Type": type, "Cache-Control": "no-cache", ...SECURITY } }); } -/** The Digital Asset Links statement that lets the Android app open - * this origin full screen. Public by design: Android fetches it. */ -export function assetLinks(cfg: Pick): unknown[] { - if (cfg.androidFingerprints.length === 0) return []; - return [ - { - relation: ["delegate_permission/common.handle_all_urls"], - target: { - namespace: "android_app", - package_name: cfg.androidPackage, - sha256_cert_fingerprints: cfg.androidFingerprints, - }, - }, - ]; -} +export { assetLinks, type Phones }; export interface Deps { cfg: Config; @@ -136,65 +101,8 @@ export interface Deps { * paths they use: those paths are reachable without sign-in, so they * exist only when their limits do. */ phones?: Phones; -} - -export interface Phones { - devices: Devices; - /** Tries at linking, and reads refused for a wrong token. */ - link: Limiter; - refused: Limiter; -} - -/** Sections the summary is built from, and how long a phone waits for - * them to be read again. */ -const SUMMARY_SECTIONS = ["board", "sessions", "census", "asks", "questionCount"]; -/** Under the five seconds the phone gives a read. */ -const SUMMARY_WAIT_MS = 3_500; -const DEVICE_BODY_LIMIT = 1024; - -/** A phone presents the verifier for a link the owner approved. */ -async function deviceLink(req: Request, deps: Deps, phones: Phones): Promise { - if (!phones.link.allow()) return json({ error: "too many tries: wait a minute" }, 429); - if (Number(req.headers.get("content-length") ?? "0") > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); - let verifier: unknown; - try { - const text = await req.text(); - if (text.length > DEVICE_BODY_LIMIT) return json({ error: "too large" }, 413); - verifier = (JSON.parse(text) as { verifier?: unknown } | null)?.verifier; - } catch { - return json({ error: "body: expected a JSON object" }, 400); - } - const linked = await phones.devices.link(verifier); - if (!linked) return json({ error: "not approved" }, 404); - await deps - .audit({ - at: new Date().toISOString(), - who: `device:${linked.id}`, - via: "device", - action: "device.link", - phase: "done", - ok: true, - }) - .catch((error) => console.error(`pm-console: audit: ${(error as Error).message}`)); - return json(linked); -} - -/** A linked phone reads the counts and the top line of each list. */ -async function deviceSummary(req: Request, docs: Docs, phones: Phones): Promise { - const header = req.headers.get("authorization") ?? ""; - const device = header.startsWith("Bearer ") ? await phones.devices.check(header.slice(7)) : null; - if (!device) { - // Wrong tokens are counted; a linked phone is never slowed by them. - if (!phones.refused.allow()) return json({ error: "too many tries: wait a minute" }, 429); - // `unlinked` tells the app to forget its token; a refusal from - // anything else in front of this service does not carry it. - return json({ error: "this phone is not linked", unlinked: true }, 401); - } - const { data, at, missing } = await docs.current(SUMMARY_SECTIONS, SUMMARY_WAIT_MS); - // Before the queue has been read once there is nothing true to show: - // the phone keeps what it has and asks again. - if (missing.includes("board")) return json({ error: "not ready yet" }, 503); - return json(summary(data, at)); + /** This host's link to the edge, when the app is served from one. */ + link?: Pick; } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -213,21 +121,6 @@ function gzipped(req: Request, bytes: Uint8Array, headers: Headers): Response | return new Response(Bun.gzipSync(bytes), { headers }); } -/** A write must come from this site. A browser sends Origin on every - * cross-site write and Sec-Fetch-Site on every request, and the sign-in - * cookie alone must not be enough for another site to act as the owner. */ -function crossSiteWrite(req: Request): boolean { - if (req.method === "GET" || req.method === "HEAD") return false; - if (req.headers.get("sec-fetch-site") === "cross-site") return true; - const origin = req.headers.get("origin"); - if (origin === null) return false; - try { - return new URL(origin).host !== (req.headers.get("host") ?? ""); - } catch { - return true; - } -} - /** Pass one request to the dashboard and its answer back. `open` is for * the public files: nothing the caller sent goes with it. */ async function toDashboard(req: Request, url: URL, deps: Deps, open: boolean): Promise { @@ -283,19 +176,6 @@ async function toDashboard(req: Request, url: URL, deps: Deps, open: boolean): P return new Response(req.method === "HEAD" ? null : res.body, { status: res.status, headers: out }); } -/** A state-changing request must be one this page made: a custom header - * a cross-site form cannot set, and an Origin that is this host. */ -function sameSiteWrite(req: Request): boolean { - if (req.headers.get("x-pm-console") !== "1") return false; - const origin = req.headers.get("origin"); - if (origin === null) return true; - try { - return new URL(origin).host === (req.headers.get("host") ?? ""); - } catch { - return false; - } -} - export async function handle(req: Request, deps: Deps, peer: string | null = null): Promise { const url = new URL(req.url); const path = url.pathname; @@ -304,16 +184,15 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul // Public, unauthenticated: nothing here says anything about the fleet. if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(deps.cfg)); if (path === `${BASE}/health` && method === "GET") return json({ ok: true }); - if (path === "/manifest.webmanifest" && method === "GET") { - return new Response(JSON.stringify(MANIFEST), { - headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-cache", ...SECURITY }, - }); - } + if (path === "/manifest.webmanifest" && method === "GET") return manifest(); // Not behind the sign-in, and checked here instead: a linked phone. if (deps.phones && deps.docs) { - if (path === `${BASE}/device/link` && method === "POST") return deviceLink(req, deps, deps.phones); + if (path === `${BASE}/device/link` && method === "POST") return deviceLink(req, deps.phones, deps.audit); if (path === `${BASE}/device/summary` && method === "GET") return deviceSummary(req, deps.docs, deps.phones); } + // The public half of this host's key: the edge asks for it through the + // tunnel to check that a report really is from this host. + if (deps.link && path === `${BASE}/edge/key` && method === "GET") return json({ key: await deps.link.publicKey() }); const ours = path === BASE || path.startsWith(`${BASE}/`); if (!ours) { if (deps.cfg.dashboardUrl === null) return json({ error: "not found" }, 404); @@ -399,16 +278,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } } if (seg.length === 2 && seg[0] === "doc" && deps.docs && DOC_NAMES.includes(seg[1] as DocName)) { - const doc = await deps.docs.doc(seg[1] as DocName); - const headers = new Headers({ - "Content-Type": "application/json; charset=utf-8", - "Cache-Control": "no-cache", - ETag: doc.etag, - "X-As-Of": String(doc.asOf), - ...SECURITY, - }); - if (req.headers.get("if-none-match") === doc.etag) return new Response(null, { status: 304, headers }); - return gzipped(req, new TextEncoder().encode(doc.body), headers) ?? new Response(doc.body, { headers }); + return docResponse(req, await deps.docs.doc(seg[1] as DocName), gzipped); } if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status()); if (seg.length === 1 && seg[0] === "devices" && deps.phones) return json(await deps.phones.devices.list()); @@ -443,6 +313,8 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul name: string, args: Record, work: () => Promise, + /** More to say in the answer when the action worked. */ + extra?: () => Record, ): Promise => { const base = { at: new Date().toISOString(), @@ -464,7 +336,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul try { const result = await work(); await done({ ok: true }); - return json({ ok: true, result }); + return json({ ok: true, result, ...extra?.() }); } catch (error) { await done({ ok: false, error: (error as Error).message }); throw error; @@ -486,17 +358,32 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul by: who.email ?? who.certName ?? who.sub ?? who.via, note: "", }; - return await act(kind || "unknown", kept, async () => { - docs.logAct({ ...entry, status: "running" }); - try { - const result = await perform(table, docs, kind, args); - docs.logAct({ ...entry, status: "done" }); - return result; - } catch (error) { - docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); - throw error; - } - }); + // Relayed by the edge: the answer also carries the sections this + // action read again and the record of what was done, so the edge's + // copy shows the change without waiting for the next report. + const forEdge = + req.headers.get("x-pm-edge") === "1" && Object.hasOwn(table, kind) + ? () => ({ + sections: docs.snapshot().filter((s) => table[kind].touch.includes(s.name)), + acts: docs.recentActs(), + }) + : undefined; + return await act( + kind || "unknown", + kept, + async () => { + docs.logAct({ ...entry, status: "running" }); + try { + const result = await perform(table, docs, kind, args); + docs.logAct({ ...entry, status: "done" }); + return result; + } catch (error) { + docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + throw error; + } + }, + forEdge, + ); } if (seg.length === 3 && seg[0] === "queue") { return await act(`queue.${seg[2]}`, { task: seg[1], reason: body.reason }, () => @@ -585,17 +472,65 @@ export async function morePages(): Promise< } } +/** Runs an action the edge held while this host could not be reached, + * recorded like any other. Only the actions that may be done late. */ +export function heldRunner(deps: Pick): (held: Held) => Promise { + return async (held) => { + const { docs, actions: table } = deps; + if (!docs || !table) throw new Error("this host takes no actions"); + if (!HOLDABLE.has(held.kind) || !Object.hasOwn(table, held.kind)) { + throw new Error("this is not an action that may be done late"); + } + const base = { + at: new Date().toISOString(), + who: held.who, + via: "edge-held", + action: held.kind, + args: table[held.kind].audit(held.args), + held: { id: held.id, at: held.at }, + }; + // As with any action: one that cannot be recorded is not taken. + await deps.audit({ ...base, phase: "start" }); + const entry = { id: held.id, kind: held.kind, at: held.at, by: held.who }; + const done = (more: Record) => + deps + .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); + docs.logAct({ ...entry, status: "done", note: "Sent late: held while the laptop could not be reached." }); + await done({ ok: true }); + } catch (error) { + const message = (error as Error).message; + docs.logAct({ ...entry, status: "failed", note: `Sent late, and it failed: ${message.slice(0, 160)}` }); + await done({ ok: false, error: message }); + throw error; + } + }; +} + +/** Every response this service writes is marked, so the edge in front + * can tell "the host answered, with an error" from "the host could not + * be reached". */ +export function marked(res: Response): Response { + const headers = new Headers(res.headers); + headers.set("X-PM-Console", "1"); + return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); +} + if (import.meta.main) { + // `--check` builds everything this service needs and stops before + // listening: what a redeploy runs to learn that new code starts. + const check = process.argv.includes("--check"); const cfg = readConfig(); const ops = new Ops(cfg); mkdirSync(dirname(cfg.auditFile), { recursive: true, mode: 0o700 }); const work = new Work(ops); const docs = new Docs(loaders(ops, work, await morePages())); - docs.start(); const state = dirname(cfg.auditFile); - const push = new Push(join(state, "push.json"), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`); - new Notifier(docs, push, join(state, "notified.json")).start(); - const devices = new Devices(cfg.devicesFile); + const push = new Push(fileStore(join(state, "push.json")), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`); + const notifier = new Notifier(docs, push, fileStore(join(state, "notified.json"))); + const devices = new Devices(fileStore(cfg.devicesFile)); const deps: Deps = { cfg, ops, @@ -607,13 +542,43 @@ if (import.meta.main) { identify: (req, peer) => identify(req, cfg, { peer }), audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }), }; + // Behind an edge: report to it, and run what it held for this host. + const link = cfg.edgeUrl + ? new EdgeLink({ + url: cfg.edgeUrl, + keys: fileStore(cfg.edgeKeyFile), + done: fileStore(cfg.edgeDoneFile), + docs, + config: async () => ({ + owners: cfg.owners, + certNames: cfg.certNames, + issuers: cfg.issuers, + repo: cfg.repo, + queue: cfg.queue, + androidPackage: cfg.androidPackage, + androidFingerprints: cfg.androidFingerprints, + androidApp: await Bun.file(cfg.androidApk).exists(), + }), + run: heldRunner(deps), + }) + : null; + if (link) deps.link = link; + if (check) { + const health = await handle(new Request(`http://127.0.0.1:${cfg.port}${BASE}/health`), deps, "127.0.0.1"); + if (health.status !== 200) throw new Error(`self-check: health answered ${health.status}`); + console.log("pm-console: check passed"); + process.exit(0); + } + docs.start(); + notifier.start(); + link?.start(); const server = Bun.serve({ hostname: cfg.bind, port: cfg.port, idleTimeout: IDLE_TIMEOUT_SECONDS, - fetch: (req, srv) => handle(req, deps, srv.requestIP(req)?.address ?? null), + fetch: async (req, srv) => marked(await handle(req, deps, srv.requestIP(req)?.address ?? null)), }); console.log( - `pm-console listening on http://${server.hostname}:${server.port}${BASE}/ — owners: ${cfg.owners.length}, issuers: ${cfg.issuers.map((i) => i.name).join(", ") || "none (edge requests are refused)"}, dashboard: ${cfg.dashboardUrl ?? "not fronted"}`, + `pm-console listening on http://${server.hostname}:${server.port}${BASE}/ — owners: ${cfg.owners.length}, issuers: ${cfg.issuers.map((i) => i.name).join(", ") || "none (edge requests are refused)"}, dashboard: ${cfg.dashboardUrl ?? "not fronted"}, edge: ${cfg.edgeUrl ?? "none"}`, ); } diff --git a/pm-stack/console/src/store.ts b/pm-stack/console/src/store.ts new file mode 100644 index 0000000000..5de5c6a0d1 --- /dev/null +++ b/pm-stack/console/src/store.ts @@ -0,0 +1,24 @@ +// Where a small piece of state is kept between runs. +// +// The same classes (notifications, linked phones) run in two places: on +// the host, where state is a file, and at the edge, where it is the +// edge's own storage. They are given one of these and do not know which. + +/** One JSON text, read whole and written whole. */ +export interface Store { + /** The text last written, or null when nothing has been. */ + read(): Promise; + write(text: string): Promise; +} + +/** Kept in memory: for tests, and for state that need not outlive the process. */ +export function memoryStore(initial: string | null = null): Store & { text: () => string | null } { + let text = initial; + return { + read: async () => text, + write: async (next) => { + text = next; + }, + text: () => text, + }; +} diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts new file mode 100644 index 0000000000..ac589ddf55 --- /dev/null +++ b/pm-stack/console/src/sync.ts @@ -0,0 +1,248 @@ +// The host's side of its link to the edge. +// +// The app is served from the edge. This reports the host's state to it +// (only the sections that changed), learns from the answer whether +// anyone is looking, and runs the actions the owner took while the host +// could not be reached. See edge-proto.ts for what travels and why it +// can be trusted. +// +// A held action is run at most once. Its id is written down before it +// starts; if the host dies part-way, the action is reported as +// interrupted instead of being run a second time. +import type { Docs } from "./docs.ts"; +import { + type EdgeConfig, + type Held, + HOLDABLE, + keyId, + newKeyPair, + type PublicKey, + publicKey, + type SyncRequest, + type SyncResponse, + sign, +} from "./edge-proto.ts"; +import type { Store } from "./store.ts"; + +/** Sections kept fresh for notifications and a phone's widget when + * nobody has the app open. */ +const WATCHED = ["board", "asks", "census", "sessions", "questionCount", "services"]; +const FAST_MS = 5_000; +const IDLE_MS = 30_000; +const WATCHED_EVERY_MS = 60_000; +const SYNC_TIMEOUT_MS = 20_000; +const DONE_KEPT = 300; + +type Fate = "started" | { ok: boolean; error?: string }; + +export interface LinkOptions { + /** The public address the edge answers on, e.g. https://pm.example. */ + url: string; + /** The host's key pair. Made on first use; the private half stays here. */ + keys: Store; + /** What became of each held action, so none is run twice. */ + done: Store; + docs: Docs; + config: () => Promise; + /** Run one held action; throws if it could not be done. */ + run: (held: Held) => Promise; + fetchImpl?: typeof fetch; + now?: () => number; + log?: (line: string) => void; +} + +export class EdgeLink { + private pair: { publicJwk: PublicKey; privateJwk: JsonWebKey; kid: string } | null = null; + private fates: Map | null = null; + /** What the edge is known to have, by fingerprint. */ + private sent = new Map(); + private want = new Set(); + private acks: { id: string; ok: boolean; error?: string }[] = []; + private lastAt = 0; + private watchedAt = 0; + private timer: ReturnType | null = null; + private busy = false; + private now: () => number; + private fetchImpl: typeof fetch; + private log: (line: string) => void; + /** The last answer from the edge, or null while it cannot be reached. */ + last: SyncResponse | null = null; + + constructor(private o: LinkOptions) { + this.now = o.now ?? Date.now; + this.fetchImpl = o.fetchImpl ?? fetch; + this.log = o.log ?? ((line) => console.error(`pm-console: edge: ${line}`)); + } + + private async keys() { + if (this.pair) return this.pair; + let stored: { publicJwk?: unknown; privateJwk?: JsonWebKey } | null = null; + try { + stored = JSON.parse((await this.o.keys.read()) ?? "null"); + } catch { + stored = null; + } + let pub = publicKey(stored?.publicJwk); + let priv = stored?.privateJwk; + if (!pub || !priv) { + const made = await newKeyPair(); + pub = made.publicJwk; + priv = made.privateJwk; + await this.o.keys.write(JSON.stringify(made)); + } + this.pair = { publicJwk: pub, privateJwk: priv, kid: await keyId(pub) }; + return this.pair; + } + + /** The public half, for the edge to fetch through the tunnel. */ + async publicKey(): Promise { + return (await this.keys()).publicJwk; + } + + private async fate(): Promise> { + if (this.fates) return this.fates; + try { + this.fates = new Map(Object.entries(JSON.parse((await this.o.done.read()) ?? "{}") as Record)); + } catch { + this.fates = new Map(); + } + return this.fates; + } + + private async record(id: string, fate: Fate): Promise { + const fates = await this.fate(); + fates.delete(id); + fates.set(id, fate); + while (fates.size > DONE_KEPT) fates.delete(fates.keys().next().value as string); + await this.o.done.write(JSON.stringify(Object.fromEntries(fates))); + } + + /** 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; + const seen = (await this.fate()).get(held.id); + if (seen === "started") { + // The host stopped while this was running. Whether it happened is + // not known, and running it again could do it twice. + const fate = { ok: false, error: "the host restarted while doing this; check whether it happened" }; + await this.record(held.id, fate); + this.acks.push({ id: held.id, ...fate }); + return; + } + if (seen) { + this.acks.push({ id: held.id, ...seen }); // the edge missed the first answer + return; + } + let fate: { ok: boolean; error?: string }; + if (!HOLDABLE.has(held.kind)) { + fate = { ok: false, error: "this is not an action that may be done late" }; + } else { + await this.record(held.id, "started"); + try { + await this.o.run(held); + fate = { ok: true }; + } catch (error) { + fate = { ok: false, error: (error as Error).message.slice(0, 300) }; + } + } + await this.record(held.id, fate); + this.acks.push({ id: held.id, ...fate }); + } + + /** One report to the edge. Returns its answer, or null if it could not + * be reached or refused the report; nothing is lost either way. */ + async once(): Promise { + if (this.busy) return this.last; + this.busy = true; + try { + const pair = await this.keys(); + const snapshot = this.o.docs.snapshot(); + const sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); + const acks = [...this.acks]; + const at = Math.max(this.now(), this.lastAt + 1); + const message: SyncRequest & { acts: unknown } = { + v: 1, + at, + config: await this.o.config(), + sections, + have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at }])), + acks, + acts: this.o.docs.recentActs(), + }; + const body = new TextEncoder().encode(JSON.stringify(message)); + let res: Response; + try { + res = await this.fetchImpl(`${this.o.url}/console/edge/sync`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-pm-key": pair.kid, + "x-pm-signature": await sign(pair.privateJwk, body), + }, + body, + redirect: "manual", + signal: AbortSignal.timeout(SYNC_TIMEOUT_MS), + }); + } catch (error) { + if (this.last) this.log(`cannot reach the edge: ${(error as Error).message}`); + this.last = null; + return null; + } + this.lastAt = at; + const answer = (await res.json().catch(() => null)) as (SyncResponse & { error?: string; last?: number }) | null; + if (!res.ok || answer?.ok !== true) { + // "replay" means the edge has seen a later time than this clock + // gives (it ran backwards): step past it. + if (res.status === 409 && typeof answer?.last === "number") this.lastAt = Math.max(this.lastAt, answer.last); + if (this.last) this.log(`the edge refused the report: http ${res.status} ${answer?.error ?? ""}`); + this.last = null; + return null; + } + if (!this.last) this.log("reporting to the edge"); + for (const s of sections) this.sent.set(s.name, s.hash); + this.acks = this.acks.filter((a) => !acks.includes(a)); + this.want = new Set(answer.want ?? []); + this.last = answer; + for (const held of answer.commands ?? []) await this.take(held); + return answer; + } finally { + this.busy = false; + } + } + + /** One turn of the loop: keep fresh what someone needs, report, and + * say how long to wait before the next turn. */ + async turn(): Promise { + const now = this.now(); + if (this.last?.watching) this.o.docs.keepAlive(); + else if (this.last?.notify && now - this.watchedAt >= WATCHED_EVERY_MS) { + this.watchedAt = now; + // Read again what is stale, without waiting for it and without + // counting as someone looking. + void this.o.docs.current(WATCHED, 0); + } + const answer = await this.once(); + // Something was done or is wanted: say so at once. + if (this.acks.length > 0 || this.want.size > 0) return 500; + return answer?.watching || this.o.docs.watched() ? FAST_MS : IDLE_MS; + } + + start(): void { + if (this.timer) return; + const loop = async () => { + let wait = IDLE_MS; + try { + wait = await this.turn(); + } catch (error) { + this.log((error as Error).message); + } + this.timer = setTimeout(loop, wait); + }; + this.timer = setTimeout(loop, 1_000); + } + + stop(): void { + if (this.timer) clearTimeout(this.timer); + this.timer = null; + } +} diff --git a/pm-stack/console/test/devices.test.ts b/pm-stack/console/test/devices.test.ts index 6663015610..e1cedf5e34 100644 --- a/pm-stack/console/test/devices.test.ts +++ b/pm-stack/console/test/devices.test.ts @@ -16,6 +16,7 @@ import { AuthError } from "../src/auth.ts"; import { readConfig } from "../src/config.ts"; import { challengeOf, Devices, Limiter, summary } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; +import { fileStore } from "../src/file-store.ts"; import { OpError, Ops } from "../src/ops.ts"; import { type Deps, handle } from "../src/server.ts"; import { Work } from "../src/work.ts"; @@ -31,8 +32,8 @@ function store(now = { t: 1_800_000_000_000 }) { return { now, file, - devices: new Devices(file, () => now.t), - again: () => new Devices(file, () => now.t), + devices: new Devices(fileStore(file), () => now.t), + again: () => new Devices(fileStore(file), () => now.t), bytes: () => readFileSync(file, "utf8"), done: () => rmSync(dir, { recursive: true, force: true }), }; diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts new file mode 100644 index 0000000000..3e817c27d9 --- /dev/null +++ b/pm-stack/console/test/edge.test.ts @@ -0,0 +1,989 @@ +// The app served from the edge, with the host behind it. +// +// Nothing here is mocked at the seam under test. A request goes through +// the Worker's real routing (entry.ts) to the real state (edge.ts), and +// when it is the host's it goes on to the host's real handler +// (server.ts), whose own link (sync.ts) reports back through the same +// routing. The stand-ins are at the outside: the platform's storage (a +// map), the sign-in issuer (a key made here that signs real tokens), the +// push service (a list), and the host's sources (plain objects). +// +// Oracles: what the host holds is compared with what the edge serves; +// "run once" is counted on the host; a signature is made here with a key +// the edge was never given; stored values are measured in the map. +import { beforeEach, describe, expect, test } from "bun:test"; +import { Edge, type KV, SILENT_MS } from "../edge/src/edge.ts"; +import { forgetPoke, type Io, route } from "../edge/src/entry.ts"; +import type { Action } from "../src/actions.ts"; +import { clearJwksCache, identify } from "../src/auth.ts"; +import { readConfig } from "../src/config.ts"; +import { Devices, Limiter } from "../src/devices.ts"; +import { Docs } from "../src/docs.ts"; +import { type EdgeConfig, keyId, newKeyPair, sign } from "../src/edge-proto.ts"; +import { OpError } from "../src/errors.ts"; +import { Ops } from "../src/ops.ts"; +import { type Deps, handle, heldRunner, marked } from "../src/server.ts"; +import { memoryStore } from "../src/store.ts"; +import { EdgeLink } from "../src/sync.ts"; +import { browser, signer } from "./support.ts"; + +const HOST = "pm.example"; +const OWNER = "owner@example.com"; +const ISSUER = { + name: "cloudflare-access", + issuer: "https://team.cloudflareaccess.com", + jwksUri: "https://team.cloudflareaccess.com/cdn-cgi/access/certs", + audience: "aud-1", + source: "access" as const, +}; +const START = Date.parse("2026-11-22T12:00:00Z"); +const SECTION_NAMES = [ + "board", + "sessions", + "census", + "asks", + "questionCount", + "questions", + "prs", + "priorities", + "agents", + "services", + "more", +]; + +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 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 }); + return { status: 201 }; + } + throw new Error(`unexpected fetch ${u}`); + }; + + // ---- the edge ---------------------------------------------------------- + const stored = new Map(); + /** Every key written to the edge's storage, in order. */ + const puts: string[] = []; + const kv: KV = { + get: async (key) => structuredClone(stored.get(key)), + put: async (key, value) => { + puts.push(key); + stored.set(key, structuredClone(value)); + }, + delete: async (key) => { + stored.delete(key); + }, + }; + const alarm = { at: 0 }; + const makeEdge = () => + new Edge({ + kv, + now: clock, + fetchImpl: outward as never, + setAlarm: async (at) => { + alarm.at = at; + }, + }); + const edge = { now: makeEdge() }; + + // ---- the host ---------------------------------------------------------- + const cfg = readConfig({ HOME: "/h", PM_CONSOLE_OWNER_EMAILS: OWNER }); + cfg.issuers = [ISSUER]; + const data: Record = { + board: { counts: { claimed: 1, queued: 2 }, now: [{ id: 1, title: "First task" }], next: [], blocked: [] }, + sessions: { moving: [], waiting: [] }, + census: { hands: [], reviews: [], other: [] }, + asks: [] as unknown[], + questionCount: { total: 0, sets: 0 }, + questions: { open: [] }, + prs: [], + priorities: { issues: [], truncated: false }, + agents: [], + services: [] as unknown[], + more: [], + }; + const hostDocs = new Docs( + Object.fromEntries( + SECTION_NAMES.map((name) => [name, { ttlMs: 10_000, load: async () => structuredClone(data[name]) }]), + ), + clock, + ); + const ran: { kind: string; args: Record }[] = []; + const table: Record = { + "ask.send": { + run: async (a) => { + ran.push({ kind: "ask.send", args: a }); + const issue = 100 + ran.length; + (data.asks as unknown[]).unshift({ + issue, + text: a.text, + status: "queued", + replies: [], + updated: new Date(now.t).toISOString(), + }); + return { issue }; + }, + touch: ["asks"], + audit: () => ({}), + }, + "issue.comment": { + run: async (a) => { + ran.push({ kind: "issue.comment", args: a }); + if (a.issue === 13) throw new OpError(404, "no such issue"); + return { commented: a.issue }; + }, + touch: [], + audit: (a) => ({ issue: a.issue }), + }, + "pr.merge": { + run: async (a) => { + ran.push({ kind: "pr.merge", args: a }); + return { merged: a.pr }; + }, + touch: ["prs"], + audit: (a) => ({ pr: a.pr }), + }, + }; + const audited: Record[] = []; + const hostDeps: Deps = { + cfg, + ops: new Ops(cfg, async () => ({ code: 0, stdout: "{}", stderr: "" })), + docs: hostDocs, + actions: table, + phones: { devices: new Devices(memoryStore()), link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }, + identify: (req, peer) => identify(req, cfg, { peer, fetchImpl: outward as never, now: clock() }), + audit: async (entry) => { + audited.push(entry); + }, + }; + const net = { hostUp: true, edgeUp: true }; + const hostSaw: string[] = []; + const edgeConfig: EdgeConfig = { + owners: [OWNER], + certNames: [], + issuers: [ISSUER], + repo: cfg.repo, + queue: cfg.queue, + androidPackage: cfg.androidPackage, + androidFingerprints: [], + androidApp: true, + }; + + // ---- the Worker's routing, with the two wired together ----------------- + const later: Promise[] = []; + const files = new Map([ + ["/console/index.html", "PM"], + ["/console/app.js", "// app"], + ["/icons/icon-192.png", "PNG"], + ]); + const io: Io = { + state: (r) => edge.now.fetch(r), + asset: async (path) => (files.has(path) ? new Response(files.get(path)) : new Response("", { status: 404 })), + host: async (r) => { + 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")); + }, + publicHost: HOST, + version: "test", + later: (work) => later.push(work), + now: clock, + }; + const keys = memoryStore(); + const done = memoryStore(); + const makeLink = () => + new EdgeLink({ + url: `https://${HOST}`, + keys, + done, + docs: hostDocs, + config: async () => edgeConfig, + run: heldRunner(hostDeps), + fetchImpl: (async (url: string, init: RequestInit) => { + if (!net.edgeUp) throw new Error("no route to the edge"); + return route( + new Request(url, { ...init, headers: { ...(init.headers as Record), "cf-ray": "1" } }), + io, + ); + }) as never, + now: clock, + log: () => {}, + }); + const link = { now: makeLink() }; + hostDeps.link = { publicKey: () => link.now.publicKey() }; + + const token = (claims: Record = {}) => + access.sign({ + iss: ISSUER.issuer, + aud: [ISSUER.audience], + exp: now.t / 1000 + 600, + iat: now.t / 1000 - 5, + sub: "u1", + email: OWNER, + ...claims, + }); + /** A request from the owner's browser, as it reaches the Worker, with + * a sign-in token good at this moment unless another is given. */ + const browse = async ( + path: string, + init: { + method?: string; + body?: unknown; + token?: string | null; + host?: string; + headers?: Record; + } = {}, + ) => + route( + new Request(`https://${init.host ?? HOST}${path}`, { + method: init.method ?? (init.body === undefined ? "GET" : "POST"), + body: init.body === undefined ? undefined : JSON.stringify(init.body), + headers: { + "cf-ray": "1", + ...(init.token === null ? {} : { "cf-access-jwt-assertion": init.token ?? (await token()) }), + ...(init.body === undefined ? {} : { "content-type": "application/json", "x-pm-console": "1" }), + ...init.headers, + }, + }), + io, + ); + const act = (kind: string, args: Record = {}) => + browse("/console/api/act", { body: { kind, args } }); + const core = async () => { + const res = await browse("/console/api/doc/core"); + return { res, doc: (await res.json()) as Record }; + }; + /** Load every section on the host, as the host does while someone looks. */ + const hostReads = () => hostDocs.touch(SECTION_NAMES); + return { + now, + edge, + makeEdge, + stored, + puts, + keys, + done, + alarm, + pushes, + hostDocs, + hostDeps, + data, + ran, + audited, + net, + hostSaw, + io, + link, + makeLink, + later, + token, + browse, + act, + core, + hostReads, + table, + access, + edgeConfig, + }; +} + +beforeEach(() => { + clearJwksCache(); + forgetPoke(); +}); + +describe("before the host's first report", () => { + test("the edge stays out of the way: the host answers everything, as before", async () => { + const w = await setup(); + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health).toEqual({ + ok: true, + edge: true, + configured: false, + hostSeen: null, + answered: 0, + deferred: 0, + version: "test", + }); + // The owner's page is the host's own, reached through the edge. + const page = await w.browse("/console/api/me"); + expect(page.headers.get("x-pm-console")).toBe("1"); + expect(((await page.json()) as { email: string; edge?: boolean }).edge).toBeUndefined(); + // And the host still refuses a stranger itself. + expect((await w.browse("/console/api/me", { token: null })).status).toBe(401); + expect(w.hostSaw).toEqual(["GET /console/api/me", "GET /console/api/me"]); + }); + + test("the first report teaches the edge the host's key and who the owner is", async () => { + const w = await setup(); + await w.hostReads(); + const answer = await w.link.now.once(); + expect(answer).toMatchObject({ ok: true, watching: false, notify: false, want: [], commands: [] }); + // The key came from the host itself, through the tunnel. + expect(w.hostSaw).toEqual(["GET /console/edge/key"]); + const kept = w.stored.get("key") as { kid: string; jwk: Record }; + expect(kept.jwk).toEqual(await w.link.now.publicKey()); + expect(JSON.stringify([...w.stored.entries()])).not.toContain('"d":'); // never a private key + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health).toMatchObject({ configured: true, hostSeen: START }); + // A second report needs no key fetch and sends nothing that has not changed. + w.now.t += 5_000; + w.puts.length = 0; + await w.link.now.once(); + expect(w.hostSaw).toEqual(["GET /console/edge/key"]); + expect(w.puts.filter((k) => k.startsWith("m:"))).toEqual([]); + // One section changes: that one is sent, and only that one. + (w.data.board as { counts: { queued: number } }).counts.queued = 9; + w.now.t += 11_000; + await w.hostReads(); + await w.link.now.once(); + expect(w.puts.filter((k) => k.startsWith("m:"))).toEqual(["m:board:0", "m:board"]); + }); +}); + +describe("the owner, at the edge", () => { + test("the app and its state come from the edge, and only for a verified owner", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.hostSaw.length = 0; + + const page = await w.browse("/console/"); + expect(page.status).toBe(200); + expect(await page.text()).toContain("PM"); + expect(page.headers.get("content-security-policy")).toContain("default-src 'self'"); + expect((await w.browse("/console/app.js")).headers.get("content-type")).toBe("text/javascript; charset=utf-8"); + expect((await w.browse("/console")).status).toBe(308); + const home = await w.browse("/"); + expect([home.status, home.headers.get("location")]).toEqual([302, `https://${HOST}/console/`]); + + const { res, doc } = await w.core(); + expect(res.status).toBe(200); + // Exactly what the host holds, with the time the host read it. + expect(doc.board).toEqual(w.data.board); + expect(doc.asks).toEqual([]); + expect(Number(res.headers.get("x-as-of"))).toBe(START); + expect(Number(res.headers.get("x-host-seen"))).toBe(START); + expect(doc.edge).toEqual({ held: 0 }); + // Unchanged: the tag says so and nothing is sent again. + const again = await w.browse("/console/api/doc/core", { + headers: { "if-none-match": res.headers.get("etag") as string }, + }); + expect(again.status).toBe(304); + expect(await (await w.browse("/console/api/me")).json()).toMatchObject({ + email: OWNER, + edge: true, + androidApp: true, + }); + // None of that asked the host for the page or its state (only the + // one background word that someone is looking). + await Promise.all(w.later); + expect(w.hostSaw).toEqual(["GET /console/api/doc/core"]); + + // Not surely the owner: the edge says nothing itself and leaves it + // to the host, which refuses as it always has. + w.hostSaw.length = 0; + const strangers = [ + null, + "junk", + await w.token({ email: "someone@else.example" }), + await w.token({ aud: ["another-app"] }), + await w.token({ exp: w.now.t / 1000 - 3600 }), + await (await signer("k1")).sign({ + iss: ISSUER.issuer, + aud: [ISSUER.audience], + exp: w.now.t / 1000 + 600, + email: OWNER, + }), + ]; + const paths = ["/console/", "/console/app.js", "/console/api/doc/core", "/console/api/me", "/", "/attention"]; + for (const bad of strangers) { + for (const path of paths) { + const refused = await w.browse(path, { token: bad }); + expect([401, 403]).toContain(refused.status); + expect(refused.headers.get("x-pm-console")).toBe("1"); // the host's own refusal + expect(await refused.text()).not.toContain("First task"); + } + } + expect(w.hostSaw).toHaveLength(strangers.length * paths.length); + // With the host out of reach there is nobody to judge: nothing is said at all. + w.net.hostUp = false; + for (const bad of strangers) { + for (const path of paths) { + const closed = await w.browse(path, { token: bad }); + expect(closed.status).toBe(503); + expect(await closed.text()).not.toContain("First task"); + } + } + const health = (await (await w.browse("/console/health", { token: null })).json()) as { + answered: number; + deferred: number; + }; + expect(health.deferred).toBe(strangers.length * paths.length * 2); + expect(health.answered).toBeGreaterThan(0); + }); + + test("the state is as old as the host's last report, and says so", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + // The host goes on reporting: the document stays current. + for (let i = 0; i < 3; i++) { + w.now.t += 5_000; + (w.data.board as { counts: { queued: number } }).counts.queued++; + await w.hostReads(); + await w.link.now.once(); + } + let { res, doc } = await w.core(); + expect(doc.board.counts.queued).toBe(5); + expect(Number(res.headers.get("x-as-of"))).toBe(w.now.t); + // What counts is when the host read the state, not when it was + // reported: a read at one time, reported seven seconds later. + w.now.t += 11_000; + await w.hostReads(); + const read = w.now.t; + w.now.t += 7_000; + await w.link.now.once(); + const last = w.now.t; + // The host goes quiet for an hour: same state, and its age is plain, + // however many times it is asked for. + w.net.edgeUp = false; + w.now.t += 60 * 60_000; + for (let asked = 0; asked < 3; asked++) { + ({ res, doc } = await w.core()); + expect(doc.board.counts.queued).toBe(5); + expect(Number(res.headers.get("x-as-of"))).toBe(read + 30_000); // the board may be 30 seconds unreported + expect(Number(res.headers.get("x-host-seen"))).toBe(last); + w.now.t += 1_000; + } + // The edge restarts: its copy is exactly as current as the host last said, no more and no less. + w.edge.now = w.makeEdge(); + ({ res } = await w.core()); + expect(Number(res.headers.get("x-as-of"))).toBe(read + 30_000); + expect(Number(res.headers.get("x-host-seen"))).toBe(last); + }); + + 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) })) }; + w.data.questions = big; + await w.hostReads(); + await w.link.now.once(); + const pieces = [...w.stored.entries()].filter(([k]) => k.startsWith("m:questions:")); + expect(pieces.length).toBeGreaterThan(2); + for (const [, value] of pieces) expect((value as string).length).toBeLessThanOrEqual(600_000); + // A new object with the same storage: nothing in memory. + w.edge.now = w.makeEdge(); + const res = await w.browse("/console/api/doc/questions"); + expect(((await res.json()) as { questions: unknown }).questions).toEqual(big); + // A shorter one leaves no stale piece behind. + w.data.questions = { open: [] }; + w.now.t += 11_000; + await w.hostReads(); + await w.link.now.once(); + expect([...w.stored.keys()].filter((k) => k.startsWith("m:questions:"))).toEqual(["m:questions:0"]); + }); + + test("opening the app tells the host that someone is looking, and not on every read", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.hostSaw.length = 0; + await w.core(); + await w.core(); + await Promise.all(w.later); + expect(w.hostSaw).toEqual(["GET /console/api/doc/core"]); + // The host now knows, and the edge says so too. + expect(w.hostDocs.watched()).toBe(true); + w.now.t += 1_000; + expect((await w.link.now.once())?.watching).toBe(true); + w.now.t += 21_000; + await w.core(); + await Promise.all(w.later); + expect(w.hostSaw).toHaveLength(2); + // Nobody reads for a while: not watching. + w.now.t += 91_000; + expect((await w.link.now.once())?.watching).toBe(false); + }); +}); + +describe("actions", () => { + test("with the host in reach, an action is done there at once and the edge's copy already shows it", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const res = await w.act("ask.send", { text: "What is blocking the queue?" }); + expect(res.status).toBe(200); + // The owner gets the result and nothing of the edge's housekeeping. + expect(await res.json()).toEqual({ ok: true, result: { issue: 101 } }); + expect(w.ran).toEqual([{ kind: "ask.send", args: { text: "What is blocking the queue?" } }]); + // No report has been made since, and the document has the new prompt and the record of the action. + const { doc } = await w.core(); + expect(doc.asks.map((a: { issue: number }) => a.issue)).toEqual([101]); + expect(doc.acts.map((a: { kind: string; status: string }) => [a.kind, a.status])).toEqual([["ask.send", "done"]]); + // The host recorded it as the owner's, through the sign-in. + expect(w.audited.filter((e) => e.phase === "done")).toEqual([ + expect.objectContaining({ who: OWNER, via: "cloudflare-access", action: "ask.send", ok: true }), + ]); + // A refusal by the host is the host's answer, not "unreachable". + const refused = await w.act("issue.comment", { issue: 13, text: "x" }); + expect([refused.status, await refused.json()]).toEqual([404, { error: "no such issue" }]); + expect((w.stored.get("held") as unknown[] | undefined) ?? []).toEqual([]); + }); + + test("with the host out of reach, what may be done late is held, done once when it is back, and the rest is refused", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + w.net.edgeUp = false; + + const held = await w.act("ask.send", { text: "Do this when you are back" }); + expect(await held.json()).toEqual({ ok: true, held: true, result: null }); + // 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(w.ran).toEqual([]); + // The app says what is waiting. + let { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 1 }); + expect(doc.acts[0]).toMatchObject({ kind: "ask.send", status: "running", by: OWNER }); + expect(doc.acts[0].note).toMatch(/^Held/); + // Reads that are the host's own say why they cannot be had. + const live = await w.browse("/console/api/prs/7"); + expect([live.status, ((await live.json()) as { error: string }).error]).toEqual([ + 503, + "The laptop cannot be reached, and this is read from it as it is now.", + ]); + const pageRes = await w.browse("/attention"); + expect(pageRes.status).toBe(503); + expect(await pageRes.text()).toContain("Open the app"); + // The edge restarts while the host is away: nothing held is lost. + w.edge.now = w.makeEdge(); + expect((await w.core()).doc.edge).toEqual({ held: 1 }); + + // The host is back. Its report brings the held action down, it runs + // it, and the next report says so. + w.net.hostUp = true; + w.net.edgeUp = true; + w.now.t += 60_000; + const first = await w.link.now.once(); + expect(first?.commands.map((c) => c.kind)).toEqual(["ask.send"]); + expect(w.ran).toEqual([{ kind: "ask.send", args: { text: "Do this when you are back" } }]); + // The host restarts before its answer reaches the edge (what it had + // to say was only in memory). The edge offers the action again; the + // host finds it written down as done, does not run it again, and + // says so. + w.link.now = w.makeLink(); + w.hostDeps.link = { publicKey: () => w.link.now.publicKey() }; + 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; + const second = await w.link.now.once(); + expect(second?.commands).toEqual([]); + expect(w.ran).toHaveLength(1); + ({ doc } = await w.core()); + expect(doc.edge).toEqual({ held: 0 }); + expect(doc.asks.map((a: { text: string }) => a.text)).toEqual(["Do this when you are back"]); + // One record of it, the host's, saying it was sent late. + expect(doc.acts.filter((a: { kind: string }) => a.kind === "ask.send")).toEqual([ + expect.objectContaining({ status: "done", by: OWNER, note: expect.stringMatching(/^Sent late/) }), + ]); + expect(w.audited.filter((e) => e.via === "edge-held").map((e) => [e.phase, e.who, e.action])).toEqual([ + ["start", OWNER, "ask.send"], + ["done", OWNER, "ask.send"], + ]); + }); + + test("a held action the host cannot do is reported failed, and one it was interrupted in is not tried again", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + await w.act("issue.comment", { issue: 13, text: "late" }); + await w.act("issue.comment", { issue: 14, text: "late too" }); + w.net.hostUp = true; + // The host dies after writing down that it started the second one: + // stand in for that by marking it started before the report. + const ids = (w.stored.get("held") as { id: string }[]).map((h) => h.id); + const done = { [ids[1]]: "started" }; + w.link.now = new EdgeLink({ + url: `https://${HOST}`, + keys: memoryStore( + JSON.stringify(await (async () => ({ publicJwk: await w.link.now.publicKey(), privateJwk: null }))()), + ), + done: memoryStore(JSON.stringify(done)), + docs: w.hostDocs, + config: async () => w.edgeConfig, + run: heldRunner(w.hostDeps), + fetchImpl: (async (url: string, init: RequestInit) => + route( + new Request(url, { ...init, headers: { ...(init.headers as Record), "cf-ray": "1" } }), + w.io, + )) as never, + now: () => w.now.t, + log: () => {}, + }); + w.hostDeps.link = { publicKey: () => w.link.now.publicKey() }; + w.now.t += 31_000; // past the wait before a changed key is fetched again + await w.link.now.once(); + w.now.t += 1_000; + await w.link.now.once(); + // The first was tried once and failed; the second was never run. + expect(w.ran).toEqual([{ kind: "issue.comment", args: { issue: 13, text: "late" } }]); + const { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 0 }); + const notes = doc.acts + .filter((a: { status: string }) => a.status === "failed") + .map((a: { note: string }) => a.note); + expect(notes).toHaveLength(2); + expect(notes.join(" | ")).toMatch(/no such issue/); + expect(notes.join(" | ")).toMatch(/restarted while doing this/); + }); + + test("a held action is dropped after a day, and said to have been", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + await w.act("ask.send", { text: "too late" }); + w.net.hostUp = true; + w.now.t += 24 * 60 * 60_000 + 1; + const answer = await w.link.now.once(); + expect(answer?.commands).toEqual([]); + expect(w.ran).toEqual([]); + const { doc } = await w.core(); + expect(doc.edge).toEqual({ held: 0 }); + expect(doc.acts[0]).toMatchObject({ + kind: "ask.send", + status: "failed", + note: expect.stringMatching(/more than a day/), + }); + }); + + test("a write must come from the app's own page, and no more than a hundred wait", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const foreign = await w.browse("/console/api/act", { + body: { kind: "ask.send", args: {} }, + headers: { origin: "https://evil.example" }, + }); + expect(foreign.status).toBe(403); + const noHeader = await route( + new Request(`https://${HOST}/console/api/act`, { + method: "POST", + body: "{}", + headers: { "cf-access-jwt-assertion": await w.token(), "cf-ray": "1" }, + }), + w.io, + ); + expect(noHeader.status).toBe(403); + expect((await w.act("ask.send", [] as never)).status).toBe(400); + // The same for an action the edge runs itself: refused here, and nothing subscribed. + const phone = await browser(); + const crossSite = await w.browse("/console/api/act", { + body: { kind: "push.on", args: { subscription: phone.subscription, label: "x" } }, + headers: { origin: "https://evil.example" }, + }); + expect(crossSite.status).toBe(403); + expect(((await (await w.browse("/console/api/push")).json()) as { devices: number }).devices).toBe(0); + w.net.hostUp = false; + for (let i = 0; i < 100; i++) expect((await w.act("ask.send", { text: `n${i}` })).status).toBe(200); + const full = await w.act("ask.send", { text: "one too many" }); + expect(full.status).toBe(503); + expect((w.stored.get("held") as unknown[]).length).toBe(100); + }); +}); + +describe("the host's report is the host's", () => { + const report = async ( + w: Awaited>, + change: (msg: Record) => void, + sig?: (body: Uint8Array) => Promise, + kid?: string, + ) => { + const msg: Record = { v: 1, at: w.now.t, config: w.edgeConfig, sections: [], have: {}, acks: [] }; + change(msg); + const body = new TextEncoder().encode(JSON.stringify(msg)); + const pub = await w.link.now.publicKey(); + return route( + new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body, + headers: { + "x-pm-key": kid ?? (await keyId(pub)), + "x-pm-signature": sig ? await sig(body) : "AAAA", + "cf-ray": "1", + }, + }), + w.io, + ); + }; + + test("a report not signed by the host changes nothing", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const before = JSON.stringify([...w.stored.entries()]); + const forged = { owners: ["attacker@example.com"] }; + // No signature worth the name. + expect((await report(w, (m) => Object.assign(m.config as object, forged))).status).toBe(401); + // A real signature, by a key that is not the host's, under the host's key name. + const stranger = await newKeyPair(); + const bySomeoneElse = (body: Uint8Array) => sign(stranger.privateJwk, body); + w.now.t += 1_000; + expect((await report(w, (m) => Object.assign(m.config as object, forged), bySomeoneElse)).status).toBe(401); + // The same under its own key name: the edge asks the host for its key, gets the host's, and refuses. + w.hostSaw.length = 0; + w.now.t += 31_000; + const own = await report( + w, + (m) => Object.assign(m.config as object, forged), + bySomeoneElse, + await keyId(stranger.publicJwk), + ); + expect(own.status).toBe(401); + expect(w.hostSaw).toEqual(["GET /console/edge/key"]); + // And it cannot make the edge ask the host again and again. + w.now.t += 1_000; + expect((await report(w, () => {}, bySomeoneElse, await keyId(stranger.publicJwk))).status).toBe(401); + expect(w.hostSaw).toEqual(["GET /console/edge/key"]); + expect(JSON.stringify([...w.stored.entries()])).toBe(before); + // The owner is still the owner, and the forged one is nobody. + expect((await w.browse("/console/api/me")).status).toBe(200); + expect( + (await w.browse("/console/api/me", { token: await w.token({ email: "attacker@example.com" }) })).status, + ).toBe(403); + }); + + test("an old report, a replayed one and a malformed one are refused", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + // The host's own private key is not reachable from here, so a second + // link over the same key store plays the host. + const captured: { url: string; init: RequestInit }[] = []; + const tap = w.makeLink(); + (tap as unknown as { fetchImpl: unknown }).fetchImpl = async (url: string, init: RequestInit) => { + captured.push({ url, init }); + return route( + new Request(url, { ...init, headers: { ...(init.headers as Record), "cf-ray": "1" } }), + w.io, + ); + }; + w.now.t += 5_000; + expect(await tap.once()).not.toBeNull(); + const again = () => + route( + new Request(captured[0].url, { + ...captured[0].init, + headers: { ...(captured[0].init.headers as Record), "cf-ray": "1" }, + }), + w.io, + ); + // Sent again, byte for byte: refused. + const replay = await again(); + expect([replay.status, ((await replay.json()) as { error: string }).error]).toEqual([409, "replay"]); + // Kept and sent an hour later: refused for its age. + w.now.t += 60 * 60_000; + const stale = await again(); + expect([stale.status, ((await stale.json()) as { error: string }).error]).toEqual([409, "clock"]); + // Too large to be a report. + const huge = await route( + new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body: "x", + headers: { "content-length": String(9 * 1024 * 1024), "cf-ray": "1" }, + }), + w.io, + ); + expect(huge.status).toBe(413); + }); + + test("a report from the host with settings the edge cannot use is refused whole", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const kept = JSON.parse(w.keys.text() as string) as { privateJwk: JsonWebKey }; + const signed = async (config: unknown) => { + w.now.t += 1_000; + const body = new TextEncoder().encode( + JSON.stringify({ v: 1, at: w.now.t, config, sections: [], have: {}, acks: [] }), + ); + return route( + new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body, + headers: { + "x-pm-key": await keyId(await w.link.now.publicKey()), + "x-pm-signature": await sign(kept.privateJwk, body), + "cf-ray": "1", + }, + }), + w.io, + ); + }; + const before = JSON.stringify(w.stored.get("cfg")); + for (const bad of [ + { ...w.edgeConfig, issuers: [{ ...ISSUER, jwksUri: "http://team.cloudflareaccess.com/certs" }] }, // keys over plain http + { ...w.edgeConfig, issuers: [{ ...ISSUER, issuer: "http://team.cloudflareaccess.com" }] }, + { ...w.edgeConfig, issuers: [{ ...ISSUER, source: "cookie" }] }, + { ...w.edgeConfig, owners: OWNER }, // not a list + { ...w.edgeConfig, issuers: "none" }, + null, + ]) { + expect((await signed(bad)).status).toBe(400); + } + expect(JSON.stringify(w.stored.get("cfg"))).toBe(before); + // The same key signing a well-formed one is accepted: the refusals above were about the settings. + expect((await signed(w.edgeConfig)).status).toBe(200); + }); + + test("the host itself will not run late what may not be done late", async () => { + const w = await setup(); + const runHeld = heldRunner(w.hostDeps); + const at = new Date(w.now.t).toISOString(); + await expect(runHeld({ id: "x1", kind: "pr.merge", args: { pr: 7 }, who: OWNER, at })).rejects.toThrow( + /may be done late/, + ); + await expect(runHeld({ id: "x2", kind: "no.such.action", args: {}, who: OWNER, at })).rejects.toThrow( + /may be done late/, + ); + expect(w.ran).toEqual([]); + expect(w.audited).toEqual([]); + // One that may: run, and recorded before and after as the owner's, late. + await runHeld({ id: "x3", kind: "ask.send", args: { text: "late" }, who: OWNER, at }); + expect(w.ran).toEqual([{ kind: "ask.send", args: { text: "late" } }]); + expect(w.audited.map((e) => [e.phase, e.via, e.who])).toEqual([ + ["start", "edge-held", OWNER], + ["done", "edge-held", OWNER], + ]); + }); + + test("an address that is not the routed hostname has no host behind it", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.hostSaw.length = 0; + const elsewhere = "pm-console-edge.example.workers.dev"; + expect((await w.browse("/console/health", { host: elsewhere, token: null })).status).toBe(200); + expect((await w.browse("/manifest.webmanifest", { host: elsewhere, token: null })).status).toBe(200); + expect((await w.browse("/icons/icon-192.png", { host: elsewhere, token: null })).status).toBe(200); + expect((await w.browse("/attention", { host: elsewhere })).status).toBe(503); + expect((await w.browse("/internal/hold", { host: elsewhere, body: { kind: "ask.send", args: {} } })).status).toBe( + 404, + ); + expect(w.hostSaw).toEqual([]); + // On the routed hostname an /internal path is the host's, never the state's. + const inside = await w.browse("/internal/hold", { + body: { kind: "ask.send", args: { text: "x" }, who: "attacker" }, + }); + expect(inside.headers.get("x-pm-console")).toBe("1"); + expect(w.hostSaw).toEqual(["POST /internal/hold"]); + expect((w.stored.get("held") as unknown[] | undefined) ?? []).toEqual([]); + }); +}); + +describe("notifications and phones, from the edge", () => { + test("a subscribed device is told of a reply, and once that the host has gone quiet and that it is back", async () => { + const w = await setup(); + const phone = await browser(); + (w.data.asks as unknown[]).push({ + issue: 5, + title: "Q", + status: "working", + replies: [], + updated: "2026-11-22T11:00:00Z", + }); + await w.hostReads(); + await w.link.now.once(); + // Subscribing is the edge's own: the host is not asked. + w.hostSaw.length = 0; + expect((await w.act("push.on", { subscription: phone.subscription, label: "Pocket" })).status).toBe(200); + expect(w.hostSaw).toEqual([]); + expect(((await (await w.browse("/console/api/push")).json()) as { devices: number }).devices).toBe(1); + // The host is told to keep the sections notifications need fresh. + w.now.t += 1_000; + expect((await w.link.now.once())?.notify).toBe(true); + // The first pass only takes stock; then the fleet answers. + w.data.asks = [ + { + issue: 5, + title: "Q", + status: "answered", + replies: [{ you: false, at: "2026-11-22T12:00:30Z", text: "Here is why." }], + updated: "2026-11-22T12:00:30Z", + }, + ]; + w.now.t += 11_000; + await w.hostReads(); + 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 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); + w.now.t = w.alarm.at; + await w.edge.now.alarm(); + await w.edge.now.alarm(); + expect(w.pushes).toHaveLength(2); + expect(JSON.parse(await phone.open(w.pushes[1].body)).title).toBe("The laptop has gone quiet"); + // An alarm that fires while the host is reporting says nothing. + w.now.t += 1_000; + await w.link.now.once(); + expect(JSON.parse(await phone.open(w.pushes[2].body)).title).toBe("The laptop is back"); + w.now.t += 60_000; + await w.edge.now.alarm(); + expect(w.pushes).toHaveLength(3); + }); + + test("a phone is linked at the edge and reads its summary there, host or no host", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const verifier = "v".repeat(43); + const challenge = Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))).toString( + "base64url", + ); + w.hostSaw.length = 0; + w.net.hostUp = false; + expect((await w.act("device.approve", { challenge, name: "Pocket" })).status).toBe(200); + const linked = await route( + new Request(`https://${HOST}/console/device/link`, { method: "POST", body: JSON.stringify({ verifier }) }), + w.io, + ); + const { token } = (await linked.json()) as { token: string }; + const read = await route( + new Request(`https://${HOST}/console/device/summary`, { headers: { authorization: `Bearer ${token}` } }), + w.io, + ); + expect(read.status).toBe(200); + expect(await read.json()).toMatchObject({ + now: { count: 1, top: [{ title: "First task", step: "" }] }, + next: { count: 2 }, + }); + expect(await (await w.browse("/console/api/devices")).json()).toEqual([ + expect.objectContaining({ name: "Pocket" }), + ]); + // Linked phones live at the edge and survive its restart; the token is not in its storage. + expect(JSON.stringify([...w.stored.entries()])).not.toContain(token); + w.edge.now = w.makeEdge(); + const after = await route( + new Request(`https://${HOST}/console/device/summary`, { headers: { authorization: `Bearer ${token}` } }), + w.io, + ); + expect(after.status).toBe(200); + expect(w.hostSaw).toEqual([]); + }); +}); diff --git a/pm-stack/console/test/push.test.ts b/pm-stack/console/test/push.test.ts index 68943184ce..9ad9685f7c 100644 --- a/pm-stack/console/test/push.test.ts +++ b/pm-stack/console/test/push.test.ts @@ -10,64 +10,10 @@ import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; 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"; - -const b64u = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url"); -const raw = (s: string) => new Uint8Array(Buffer.from(s, "base64url")); - -async function browser(host = "fcm.googleapis.com") { - const pair = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ - "deriveBits", - ])) as CryptoKeyPair; - const auth = crypto.getRandomValues(new Uint8Array(16)); - const p256dh = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); - const hkdf = async (salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, n: number) => - new Uint8Array( - await crypto.subtle.deriveBits( - { name: "HKDF", hash: "SHA-256", salt, info }, - await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]), - n * 8, - ), - ); - const cat = (...p: Uint8Array[]) => new Uint8Array(p.flatMap((x) => [...x])); - const t = new TextEncoder(); - return { - subscription: { endpoint: `https://${host}/fcm/send/abc123`, keys: { p256dh: b64u(p256dh), auth: b64u(auth) } }, - /** RFC 8291 section 3.4 and RFC 8188: what a user agent does with the body. */ - async open(body: Uint8Array): Promise { - const salt = body.slice(0, 16); - const rs = new DataView(body.buffer, body.byteOffset).getUint32(16); - const idlen = body[20]; - const sender = body.slice(21, 21 + idlen); - const sealed = body.slice(21 + idlen); - expect(rs).toBe(4096); - expect(idlen).toBe(65); - const shared = new Uint8Array( - await crypto.subtle.deriveBits( - { - name: "ECDH", - public: await crypto.subtle.importKey("raw", sender, { name: "ECDH", namedCurve: "P-256" }, false, []), - }, - pair.privateKey, - 256, - ), - ); - const ikm = await hkdf(auth, shared, cat(t.encode("WebPush: info\0"), p256dh, sender), 32); - const cek = await hkdf(salt, ikm, t.encode("Content-Encoding: aes128gcm\0"), 16); - const nonce = await hkdf(salt, ikm, t.encode("Content-Encoding: nonce\0"), 12); - const plain = new Uint8Array( - await crypto.subtle.decrypt( - { name: "AES-GCM", iv: nonce }, - await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]), - sealed, - ), - ); - expect(plain[plain.length - 1]).toBe(2); // the last-record delimiter - return new TextDecoder().decode(plain.slice(0, -1)); - }, - }; -} +import { b64u, browser, raw } from "./support.ts"; describe("the message a phone receives", () => { test("only the subscribed browser can read it, and each one is sealed afresh", async () => { @@ -93,7 +39,7 @@ describe("the message a phone receives", () => { const posts: { url: string; headers: Record; body: Uint8Array }[] = []; const NOW = 1_800_000_000_000; const push = new Push( - join(dir, "push.json"), + fileStore(join(dir, "push.json")), "mailto:owner@example.com", async (url, init) => (posts.push({ url, headers: init.headers, body: init.body }), { status: 201 }), () => NOW, @@ -142,7 +88,9 @@ describe("the message a phone receives", () => { ).toBe(true); } // The key pair and the devices survive a restart; the file is private. - const again = new Push(join(dir, "push.json"), "mailto:owner@example.com", async () => ({ status: 201 })); + 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); expect((await again.status()).key).toBe(status.key); expect(JSON.parse(readFileSync(join(dir, "push.json"), "utf8")).vapid.privateJwk.d.length).toBeGreaterThan(20); @@ -159,7 +107,7 @@ describe("the message a phone receives", () => { let answer = (url: string) => (url === a.subscription.endpoint ? 410 : 201); let posts = 0; const push = new Push( - join(dir, "push.json"), + fileStore(join(dir, "push.json")), "mailto:o@example.com", async (url) => (posts++, { status: answer(url) }), ); @@ -209,7 +157,7 @@ describe("the message a phone receives", () => { const dir = mkdtempSync(join(tmpdir(), "pm-push-")); try { await expect( - new Push(join(dir, "p.json"), "mailto:o@example.com").subscribe( + new Push(fileStore(join(dir, "p.json")), "mailto:o@example.com").subscribe( { ...good, endpoint: "https://127.0.0.1/x" }, "", ), @@ -316,18 +264,18 @@ describe("when a notification is owed", () => { const sent: string[] = []; const b = await browser(); const push = new Push( - join(dir, "push.json"), + fileStore(join(dir, "push.json")), "mailto:o@example.com", async (_u, init) => (sent.push(JSON.parse(await b.open(init.body)).title), { status: 201 }), ); - const notifier = new Notifier(docs, push, join(dir, "notified.json")); + const notifier = new Notifier(docs, push, fileStore(join(dir, "notified.json"))); expect(await notifier.tick()).toBe(0); // no device: nothing is read, nothing is sent await push.subscribe(b.subscription, "phone"); expect(await notifier.tick()).toBe(0); // first pass: take stock now = state({ questionCount: { total: 361 } }); expect(await notifier.tick()).toBe(1); expect(sent).toEqual(["1 new question for you"]); - const restarted = new Notifier(docs, push, join(dir, "notified.json")); + const restarted = new Notifier(docs, push, fileStore(join(dir, "notified.json"))); expect(await restarted.tick()).toBe(0); expect(sent.length).toBe(1); } finally { diff --git a/pm-stack/console/test/redeploy.test.ts b/pm-stack/console/test/redeploy.test.ts new file mode 100644 index 0000000000..73c0b9b5eb --- /dev/null +++ b/pm-stack/console/test/redeploy.test.ts @@ -0,0 +1,182 @@ +// redeploy.sh, run for real against a small checkout made here. +// +// The script under test is this repository's own file, copied into a +// throwaway git repository shaped like the real one. Two things are +// stand-ins: the program that starts the console's self-check (a script +// that records what it was given and passes or fails as told) and +// install.sh (a script that records that it ran). Everything else, git +// included, is the real thing. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const SCRIPT = join(import.meta.dir, "..", "redeploy.sh"); +const UNITS = [ + "pm-console.service", + "pm-console-expose.service", + "pm-console-expose.timer", + "pm-console-redeploy.service", + "pm-console-redeploy.timer", +]; + +let dir: string; +let repo: string; +let home: string; +let log: string; + +function sh(cwd: string, ...argv: string[]) { + const done = Bun.spawnSync(argv, { cwd, env: { ...process.env, HOME: home, GIT_CONFIG_GLOBAL: "/dev/null" } }); + return { code: done.exitCode, out: done.stdout.toString(), err: done.stderr.toString() }; +} + +function git(...args: string[]) { + const done = sh( + repo, + "git", + "-c", + "user.name=t", + "-c", + "user.email=t@example.com", + "-c", + "commit.gpgsign=false", + ...args, + ); + if (done.code !== 0) throw new Error(`git ${args.join(" ")}: ${done.err}`); + return done.out.trim(); +} + +function run(env: Record = {}) { + const done = Bun.spawnSync(["bash", join(repo, "pm-stack/console/redeploy.sh")], { + cwd: dir, + env: { + ...process.env, + HOME: home, + GIT_CONFIG_GLOBAL: "/dev/null", + PM_CONSOLE_BUN: join(dir, "fake-bun"), + CHECK: "pass", + ...env, + }, + }); + return { code: done.exitCode, out: done.stdout.toString(), err: done.stderr.toString() }; +} + +const events = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean) : []); +const state = (name: string) => { + const path = join(home, ".local/state/pm-console", name); + return existsSync(path) ? readFileSync(path, "utf8") : null; +}; + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "pm-redeploy-")); + repo = join(dir, "repo"); + home = join(dir, "home"); + log = join(dir, "events.log"); + mkdirSync(join(repo, "pm-stack/console/src"), { recursive: true }); + mkdirSync(join(repo, "pm-stack/systemd"), { recursive: true }); + mkdirSync(join(home, ".local/state/pm-console"), { recursive: true }); + cpSync(SCRIPT, join(repo, "pm-stack/console/redeploy.sh")); + writeFileSync(join(repo, "pm-stack/console/install.sh"), `echo "install" >>"${log}"\n`); + writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// v1\n"); + for (const unit of UNITS) writeFileSync(join(repo, "pm-stack/systemd", unit), "[Unit]\n"); + // The stand-in for bun: records its arguments, the directory it ran + // 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`, + ); + 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"); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-q", "-m", "one"); +}); + +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe("redeploy.sh", () => { + test("new code is checked with the service's own settings, then put into service, once", () => { + const first = run(); + 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(state("deployed")).not.toBeNull(); + // Nothing has changed: nothing is checked or installed again. + expect(run().code).toBe(0); + expect(events()).toHaveLength(2); + }); + + test("a change to the console or to one of its units is new code; a change elsewhere is not", () => { + run(); + writeFileSync(join(repo, "README.md"), "elsewhere\n"); + mkdirSync(join(repo, "pm-stack/aggregator"), { recursive: true }); + writeFileSync(join(repo, "pm-stack/aggregator/x.ts"), "x\n"); + writeFileSync(join(repo, "pm-stack/systemd/pm-other.service"), "[Unit]\n"); + git("add", "-A"); + git("commit", "-q", "-m", "elsewhere"); + run(); + expect(events()).toHaveLength(2); + writeFileSync(join(repo, "pm-stack/systemd/pm-console.service"), "[Unit]\nDescription=changed\n"); + git("commit", "-q", "-am", "unit"); + run(); + expect(events()).toHaveLength(4); + writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// v2\n"); + git("commit", "-q", "-am", "code"); + run(); + expect(events()).toHaveLength(6); + }); + + test("code that does not start is never put into service, and is not tried again until the code changes", () => { + run(); + const inService = state("deployed"); + writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// broken\n"); + git("commit", "-q", "-am", "broken"); + const bad = run({ CHECK: "fail" }); + expect(bad.code).toBe(1); + expect(bad.err).toContain("the code in service is unchanged"); + expect(bad.err).toContain("boom: cannot start"); + expect(events().filter((e) => e === "install")).toHaveLength(1); + expect(state("deployed")).toBe(inService); + // The next minute: still failed, and the check is not run again. + const again = run({ CHECK: "fail" }); + expect(again.code).toBe(1); + expect(events().filter((e) => e.startsWith("check"))).toHaveLength(2); + // Even if it would pass now: the same code is the same verdict. + expect(run({ CHECK: "pass" }).code).toBe(1); + // A fix arrives: checked, installed, and the failure is forgotten. + writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// fixed\n"); + git("commit", "-q", "-am", "fixed"); + expect(run().code).toBe(0); + expect(events().filter((e) => e === "install")).toHaveLength(2); + expect(state("deploy-failed")).toBeNull(); + expect(state("deployed")).not.toBe(inService); + }); + + test("a checkout part-way through an update is left for the next run", () => { + run(); + // A file changed on disk that its commit does not have yet. + writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// half written\n"); + const mid = run(); + expect(mid.code).toBe(0); + expect(events()).toHaveLength(2); + }); + + test("an install that fails leaves the code marked as not in service", () => { + writeFileSync(join(repo, "pm-stack/console/install.sh"), `echo "install" >>"${log}"\nexit 1\n`); + git("commit", "-q", "-am", "install fails"); + expect(run().code).toBe(1); + expect(state("deployed")).toBeNull(); + // It is tried again, since the code itself passed its check. + expect(run().code).toBe(1); + expect(events().filter((e) => e === "install")).toHaveLength(2); + }); + + test("it takes no arguments", () => { + const done = Bun.spawnSync(["bash", join(repo, "pm-stack/console/redeploy.sh"), "--force"], { + env: { ...process.env, HOME: home }, + }); + expect(done.exitCode).toBe(2); + expect(events()).toEqual([]); + }); +}); diff --git a/pm-stack/console/test/support.ts b/pm-stack/console/test/support.ts new file mode 100644 index 0000000000..182dd4fcf8 --- /dev/null +++ b/pm-stack/console/test/support.ts @@ -0,0 +1,83 @@ +// Stand-ins the tests share: a browser that can open a push message, +// and a sign-in issuer that mints tokens. +import { expect } from "bun:test"; + +export const b64u = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url"); +export const raw = (s: string) => new Uint8Array(Buffer.from(s, "base64url")); + +export async function browser(host = "fcm.googleapis.com") { + const pair = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ + "deriveBits", + ])) as CryptoKeyPair; + const auth = crypto.getRandomValues(new Uint8Array(16)); + const p256dh = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); + const hkdf = async (salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, n: number) => + new Uint8Array( + await crypto.subtle.deriveBits( + { name: "HKDF", hash: "SHA-256", salt, info }, + await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]), + n * 8, + ), + ); + const cat = (...p: Uint8Array[]) => new Uint8Array(p.flatMap((x) => [...x])); + const t = new TextEncoder(); + return { + subscription: { endpoint: `https://${host}/fcm/send/abc123`, keys: { p256dh: b64u(p256dh), auth: b64u(auth) } }, + /** RFC 8291 section 3.4 and RFC 8188: what a user agent does with the body. */ + async open(body: Uint8Array): Promise { + const salt = body.slice(0, 16); + const rs = new DataView(body.buffer, body.byteOffset).getUint32(16); + const idlen = body[20]; + const sender = body.slice(21, 21 + idlen); + const sealed = body.slice(21 + idlen); + expect(rs).toBe(4096); + expect(idlen).toBe(65); + const shared = new Uint8Array( + await crypto.subtle.deriveBits( + { + name: "ECDH", + public: await crypto.subtle.importKey("raw", sender, { name: "ECDH", namedCurve: "P-256" }, false, []), + }, + pair.privateKey, + 256, + ), + ); + const ikm = await hkdf(auth, shared, cat(t.encode("WebPush: info\0"), p256dh, sender), 32); + const cek = await hkdf(salt, ikm, t.encode("Content-Encoding: aes128gcm\0"), 16); + const nonce = await hkdf(salt, ikm, t.encode("Content-Encoding: nonce\0"), 12); + const plain = new Uint8Array( + await crypto.subtle.decrypt( + { name: "AES-GCM", iv: nonce }, + await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]), + sealed, + ), + ); + expect(plain[plain.length - 1]).toBe(2); // the last-record delimiter + return new TextDecoder().decode(plain.slice(0, -1)); + }, + }; +} + +export interface Signer { + jwk: JsonWebKey & { kid: string }; + sign(claims: Record): Promise; +} + +/** An issuer's signing key (RS256), and tokens signed with it. */ +export async function signer(kid: string): Promise { + const pair = (await crypto.subtle.generateKey( + { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + true, + ["sign", "verify"], + )) as CryptoKeyPair; + const jwk = { ...(await crypto.subtle.exportKey("jwk", pair.publicKey)), kid }; + const part = (value: unknown) => b64u(new TextEncoder().encode(JSON.stringify(value))); + return { + jwk, + async sign(claims) { + const signed = `${part({ alg: "RS256", kid, typ: "JWT" })}.${part(claims)}`; + const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(signed)); + return `${signed}.${b64u(sig)}`; + }, + }; +} diff --git a/pm-stack/systemd/pm-console-redeploy.service b/pm-stack/systemd/pm-console-redeploy.service new file mode 100644 index 0000000000..82af79efe4 --- /dev/null +++ b/pm-stack/systemd/pm-console-redeploy.service @@ -0,0 +1,13 @@ +[Unit] +Description=PM console — put merged console code into service, if it starts (pm-stack) +Documentation=https://github.com/developing-today/code/tree/main/pm-stack/console +After=network-online.target + +[Service] +Type=oneshot +# Does nothing unless the checkout holds console code that is not the +# code in service. New code is started in a self-check first; code that +# does not start is never put into service. +ExecStart=/run/current-system/sw/bin/bash %h/git/code/pm-stack/console/redeploy.sh +Environment=PATH=%h/.local/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin:/usr/bin:/bin +TimeoutStartSec=300 diff --git a/pm-stack/systemd/pm-console-redeploy.timer b/pm-stack/systemd/pm-console-redeploy.timer new file mode 100644 index 0000000000..a0f43dbf1d --- /dev/null +++ b/pm-stack/systemd/pm-console-redeploy.timer @@ -0,0 +1,10 @@ +[Unit] +Description=PM console — look every minute for merged console code to put into service (pm-stack) + +[Timer] +OnBootSec=2min +OnUnitActiveSec=1min +AccuracySec=10s + +[Install] +WantedBy=timers.target From 87d57c4ad1fde1d0ac733a7f1e9cf76f1d147077 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:15:51 -0600 Subject: [PATCH 2/2] docs(fleet): register the console's redeploy timer, its report loop and the edge's alarm Same pass as the code that adds them (#12505): the laptop timer that puts merged console code into service, the console's report to the edge, and the Durable Object alarm that notices a silent laptop. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- doc/fleet-schedule-registry.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 60edcad260..00aba3ba7d 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -256,7 +256,7 @@ Execution route/pool is recorded separately from work scope: the repo-health que | `aea12c82-c5af-4e5a-9b66-f8e360f87177` | Queue lane (scheduled) - code | `*/40 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | not recorded | not recorded | not recorded | not recorded | 2026-11-03 | | `f1b4a33b-14d5-4a69-9ad6-d221e42e3ac9` | Opencode lane claimant/executor - #3026 | `*/10 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | opencode-route / workhorse | not recorded | not recorded | not recorded | 2026-11-03 | -### 2b. Laptop systemd user timers (45 listed: 41 enabled, 1 installed-but-disabled; 4 Nix-configured pending deployment) +### 2b. Laptop systemd user timers (46 listed: 42 enabled, 1 installed-but-disabled; 4 Nix-configured pending deployment) The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitActiveUSec` spec, read live from `systemctl --user show`. Specs are recorded **complete** — the full effective calendar expression, date **and** time components (e.g. `*-*-* *:*:00`); never truncate a spec to a date-only prefix, because a bare `*-*-*` normalizes to daily at midnight and misstates the cadence (issue #5313). Prompt/brief pointer is the unit file in `~/.config/systemd/user/` (or its Nix store target for linked units). Installed-but-disabled timer units ARE listed in this table and marked `(disabled)` after the unit name: the registry inventories what is installed on the laptop, not only what is currently scheduled, so a disabled unit stays visible until it is uninstalled (reconciled 2026-11-04, issue #5661). @@ -296,6 +296,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `pm-dashboard-backup.timer` | `OnCalendar=*-*-* 04:30:00` | `pm-dashboard-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-digest-daily.timer` | `OnCalendar=*-*-* 07:00:00` | `pm-digest-daily.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-console-expose.timer` | `OnUnitActiveUSec=15min,OnBootUSec=5min` | `pm-console-expose.service` | laptop (user systemd; code#12452; runs `pm-stack/console/scripts/expose.py`: keeps the public address as declared, turns Google sign-in on once its secrets exist) | not recorded | not recorded | 2026-11-22 | 2026-11-22 | +| `pm-console-redeploy.timer` | `OnUnitActiveUSec=1min,OnBootUSec=2min` | `pm-console-redeploy.service` | laptop (user systemd; code#12505; runs `pm-stack/console/redeploy.sh`: puts merged console code into service after a self-check, and leaves out code that does not start) | not recorded | not recorded | 2026-11-22 | 2026-11-22 | | `pm-digest-weekly.timer` | `OnCalendar=Mon *-*-* 07:05:00` | `pm-digest-weekly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-git-sync.timer` | `OnUnitActiveUSec=30s,OnBootUSec=30s` | `pm-git-sync.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-host-health.timer` | `OnCalendar=*-*-* *:00/5:00,OnBootUSec=1min` | `pm-host-health.service` | laptop (user systemd; code#10141) | not recorded | not recorded | 2026-11-14 | 2026-11-14 | @@ -375,7 +376,7 @@ registered. The primary user's repos are maintained by git's own per-user launchd agents, which `git maintenance start` installs outside Nix; they are not recorded here until a review reads them on the Mac. -## Surface 6 — PM-stack process intervals (3 entries) +## Surface 6 — PM-stack process intervals (4 entries) Recurring loops owned by PM-stack processes (aggregator, console). These are not external scheduler surfaces; this inventory records timers that run only @@ -386,16 +387,20 @@ while the service is alive. | SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 | | Console state refresh | developing-today/code | every 5 seconds | live console process only | PR #12452 | `pm-stack/console/src/docs.ts` (`Docs.start`) | not recorded | Reads only while the app was opened in the last 10 minutes; remove if state is no longer served from memory | 2026-11-22 | 2026-11-22 | | Console notifier | developing-today/code | every 60 seconds | live console process only | PR #12452 | `pm-stack/console/src/notify.ts` (`Notifier.start`) | not recorded | Reads only while a device is subscribed; remove if notifications move to another sender | 2026-11-22 | 2026-11-22 | +| Console report to the edge | developing-today/code | 5 to 30 seconds | live console process only | PR #12505 | `pm-stack/console/src/sync.ts` (`EdgeLink.start`) | not recorded | Runs only when PM_CONSOLE_EDGE_URL is set; remove if the app is no longer served from the edge | 2026-11-22 | 2026-11-22 | -## Surface 7 — Cloudflare Worker cron triggers (1 entry) +## Surface 7 — Cloudflare Worker cron triggers (2 entries) Cron triggers on Cloudflare Workers in this account, from each Worker's `wrangler.jsonc` (`triggers.crons`) and deployed from the flake. They run on Cloudflare, off every fleet host. Cadence is the trigger's cron expression in UTC. The row was read from the repo and confirmed against the Worker's live schedule (Cloudflare `workers/scripts//schedules`) -on 2026-11-19. +on 2026-11-19. The second row is a Durable Object alarm: it is set by +the Worker's code, so it appears in no `wrangler.jsonc` and in no +schedules listing. | name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review | | --------------------------------------------- | --------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | --------------------------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------- | ----------- | | `queue-transport-alert` (Worker cron trigger) | developing-today/code | `*/10 * * * *` (every 10 min UTC) | enabled; probes the repo-queue broker `/healthz` through Cloudflare Access; files or comments on one `Queue transport incident:` issue, pushes to Telegram, enqueues a triage task on recovery, never closes | issue #6369 | `pkgs/queue-transport-alert/worker/` (`wrangler.jsonc`, `src/`) | Workers free-tier requests; one probe per tick | Remove the trigger if the probe misfires (repeated false alerts) or the broker route is retired | 2026-11-19 | 2026-11-19 | +| pm-console-edge silent-host alarm | developing-today/code | 10 minutes after each host report | Durable Object alarm, re-armed by every report from the laptop, so it fires only when the laptop has been silent for ten minutes | PR #12505 | `pm-stack/console/edge/src/edge.ts` (`Edge.alarm`) | one notification a silence | Goes with the Worker; `expose.py --edge off` takes the hostname off it | 2026-11-22 | 2026-11-22 |