Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,61 @@ Not checked before going live: the owner's real sign-in token at the
edge. The edge counts requests it answered as the owner's and requests
it left to the laptop (`/console/health`), so the first real visit shows
which happened.

## 2026-11-22T11:50Z Update: going live, and the first review

Two things stopped the first go-live, and neither was in the design.

- The laptop's checkout had stopped following `main` two hours earlier.
A system rebuild had left an empty marker commit on the local `main`,
and the sync only ever fast-forwards, so it stood still, 28 commits
behind, and nothing merged since had been deployed. The marker was
kept under the tag `rebuild-marker/amd-569` and `main` was moved to
`origin/main` (nothing was discarded: the commit was empty and the
tree was clean). The sync still cannot do this by itself; that is a
separate change to `pm-git-sync`.
- The setup script judged the Worker "not deployed" while it was
answering. Its health check went out under Python's default client
name, which Cloudflare refuses with a 403; `curl` from the same
machine got the answer. The check now names its program (and nothing
else), asks three times before believing a failure, and is covered by
a test that looks at the request actually made.

What the first review found, and what was done:

- **An action could run twice.** If the laptop did a relayed action and
its answer was lost on the way back, the edge held the action under a
new name and the laptop ran it again at the next report. An action is
now named at the edge before it goes anywhere; the laptop writes the
name down before starting and the outcome after; a held action
offered under a name the laptop knows is answered from that record,
and one still running is left to finish. Tested with the answer lost
after the work, and with the edge giving up while the work was still
going.
- **A source the laptop could no longer read looked healthy at the
edge.** The laptop keeps its last good copy, so the data and its
fingerprint do not change; the report now says of every section
whether its latest read failed and why, and the edge shows that with
the copy, across its own restarts.
- **A late answer the dashboard refused was logged as done.** It is now
logged as not recorded, with the reason.
- **Notifications after the move.** A browser's subscription is made
for one sender's key, and the edge has its own. The app now checks, on
opening, whether the sender still holds this device and under which
key, and makes the subscription again or hands it over again without
asking (the owner already said yes on that device). The sender tells
the app which devices it holds by a short mark of each address, never
the address. Until a device next opens the app, the laptop goes on
sending to it. Phones linked for the widget are not carried across an
edge on/off change yet: one linked on one side has to be linked again
on the other.
- **The setup script**: `--check --edge off` now previews that choice
instead of ignoring it; a Worker built for another hostname is not
given this one (the Worker says which it is built for); the redeploy
check reads quoted settings the way the service does; the build and
the smoke check refuse arguments they do not take.

One change nobody asked for: the contact handed to push services with
every notification was the owner's address. It is now the project's
page. Delivery does not depend on it, and an address has no reason to
travel to Google or Mozilla with each message.
4 changes: 4 additions & 0 deletions pm-stack/console/edge/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { cpSync, mkdirSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

if (process.argv.length > 2) {
console.error("usage: node build.mjs (it takes no arguments)");
process.exit(2);
}
const here = dirname(fileURLToPath(import.meta.url));
const dist = join(here, "dist");
rmSync(dist, { recursive: true, force: true });
Expand Down
61 changes: 45 additions & 16 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import {
sameSiteWrite,
} from "../../src/http.ts";
import { Notifier } from "../../src/notify.ts";
import { Push } from "../../src/push.ts";
import { contact, Push } from "../../src/push.ts";
import type { Store } from "../../src/store.ts";

/** The edge's own storage: small values by key. */
Expand Down Expand Up @@ -94,6 +94,7 @@ const STATIC: Record<string, string> = {
"icon.svg": "image/svg+xml",
"sw.js": "text/javascript; charset=utf-8",
};
const ACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const ICONS = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/;

interface Mirror {
Expand Down Expand Up @@ -142,7 +143,7 @@ export class Edge {
private hostSeq: number | null = null;
/** For each section, the content the host last said it has and when
* it read it: a copy with that content is current as of that read. */
private confirmed: Record<string, { hash: string; at: number }> = {};
private confirmed: Record<string, { hash: string; at: number; error: string | null }> = {};
private sure = 0;
private unsure = 0;
readonly docs: Docs;
Expand All @@ -165,7 +166,8 @@ export class Edge {
load: async () => {
const m = await this.mirror(name);
if (!m) throw new Error("the laptop has not reported this yet");
return new Stamped(m.data, m.at);
// With the laptop's own word on whether it could still read it.
return new Stamped(m.data, m.at, this.confirmed[name]?.error ?? null);
},
},
]),
Expand All @@ -174,8 +176,8 @@ export class Edge {
);
this.push = new Push(
kvStore(this.kv, "push"),
// Who a push service may write to about these messages: the owner.
() => `mailto:${this.cfg?.owners[0] ?? "owner@invalid.example"}`,
// The contact a push service is given: the project's page.
() => contact(this.cfg?.repo ?? "developing-today/code"),
(url, init) => this.fetchImpl(url, init as RequestInit),
this.now,
);
Expand Down Expand Up @@ -295,7 +297,7 @@ export class Edge {
if (this.ownActs === null) await this.showActs();
if (this.hostSeen === null) {
const host = (await this.kv.get("host")) as
| { seen: number; seq: number; confirmed?: Record<string, { hash: string; at: number }> }
| { seen: number; seq: number; confirmed?: Record<string, { hash: string; at: number; error: string | null }> }
| undefined;
this.hostSeen = host?.seen ?? 0;
this.hostSeq = host?.seq ?? 0;
Expand Down Expand Up @@ -350,16 +352,25 @@ export class Edge {
await this.kv.put("cfg", cfg);
this.cfg = cfg;
}
const changed = await this.take(msg.sections);
// A section that has not changed is not sent again, but the host
// says when it last read it: the copy here is as current as that.
const fresher: string[] = [];
// What the host says of every section it has: how current it is, and
// whether it could still read it. Taken first, so a section that
// arrives in this report is shown with its health as of this report.
const told: { name: string; healthChanged: boolean }[] = [];
for (const [name, theirs] of Object.entries(msg.have ?? {})) {
if (!Object.hasOwn(SECTIONS, name) || typeof theirs?.hash !== "string" || typeof theirs.at !== "number") continue;
this.confirmed[name] = { hash: theirs.hash, at: Math.min(theirs.at, now) };
const error = typeof theirs.error === "string" && theirs.error !== "" ? theirs.error.slice(0, 300) : null;
told.push({ name, healthChanged: (this.confirmed[name]?.error ?? null) !== error });
this.confirmed[name] = { hash: theirs.hash, at: Math.min(theirs.at, now), error };
}
const changed = await this.take(msg.sections);
// A section that has not changed is not sent again: the copy here is
// as current as the host says, and as healthy.
const fresher: string[] = [];
for (const { name, healthChanged } of told) {
const copy = await this.mirror(name);
if (copy && copy.hash === theirs.hash && this.confirmed[name].at > copy.at) {
copy.at = this.confirmed[name].at;
if (!copy || copy.hash !== this.confirmed[name].hash) continue;
if (this.confirmed[name].at > copy.at || healthChanged) {
copy.at = Math.max(copy.at, this.confirmed[name].at);
if (!changed.includes(name)) fresher.push(name);
}
}
Expand Down Expand Up @@ -583,7 +594,18 @@ export class Edge {
if (!Object.hasOwn(this.table, kind)) {
// The host's to do. The stateless part relays it, and if the
// host cannot be reached comes back to have it held.
return next("relay", { mode: "act", kind, args, who: by, holdable: HOLDABLE.has(kind) });
// It is named here, before it goes anywhere. If the host's answer
// is lost on the way back, the action is held under the same
// name, and the host, which wrote the name down before starting,
// does not do it a second time.
return next("relay", {
mode: "act",
id: crypto.randomUUID(),
kind,
args,
who: by,
holdable: HOLDABLE.has(kind),
});
}
return await this.own(kind, args as Record<string, unknown>, by, who.via);
} catch (error) {
Expand Down Expand Up @@ -618,6 +640,7 @@ export class Edge {
* that may be done late. */
private async hold(req: Request): Promise<Response> {
const body = (await req.json().catch(() => null)) as {
id?: unknown;
kind?: unknown;
args?: unknown;
who?: unknown;
Expand All @@ -626,7 +649,12 @@ export class Edge {
const args = body?.args;
if (!HOLDABLE.has(kind) || args === null || typeof args !== "object" || Array.isArray(args)) {
return json(
{ error: "The laptop cannot be reached, and this is not safe to do late. Try again when it is back." },
// No answer is not "not done": the laptop may have got it and its
// answer been lost. Nothing is kept to do later, and it says so.
{
error:
"The laptop did not answer, and this is not something to do late, so it is not kept. Check whether it happened before trying again.",
},
503,
);
}
Expand All @@ -636,7 +664,8 @@ export class Edge {
return json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, 503);
}
const item: Held = {
id: crypto.randomUUID(),
// The name it was relayed under, so the host can tell it has seen it.
id: typeof body?.id === "string" && ACT_ID.test(body.id) ? body.id : crypto.randomUUID(),
kind,
args: args as Record<string, unknown>,
who: String(body?.who ?? "owner"),
Expand Down
10 changes: 8 additions & 2 deletions pm-stack/console/edge/src/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ export async function route(request: Request, io: Io): Promise<Response> {
}
if (url.pathname === "/console/health" && request.method === "GET") {
const body = (await (await io.state(request)).json()) as Record<string, unknown>;
return new Response(JSON.stringify({ ...body, version: io.version }), {
// The hostname it is built for is said too: the host's setup script
// will not put any other hostname behind this Worker.
return new Response(JSON.stringify({ ...body, version: io.version, host: io.publicHost }), {
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY },
});
}
Expand Down Expand Up @@ -142,7 +144,11 @@ export async function route(request: Request, io: Io): Promise<Response> {
if (!routed) return offline("this address has no host behind it");

if (detail.mode === "act") {
const answer = await io.host(withHeader(forHost, "x-pm-edge", "1"), ACT_MS);
// The host is told the action's name with the action. No answer may
// mean the host never got it, or did it and the answer was lost: it
// is held under that name, and the host sorts out which.
const named = withHeader(withHeader(forHost, "x-pm-edge", "1"), "x-pm-act", String(detail.id ?? ""));
const answer = await io.host(named, ACT_MS);
if (answer === null) return tell("/internal/hold", detail);
// The host's answer says what it read again; keep that here, and
// send the owner the rest.
Expand Down
49 changes: 49 additions & 0 deletions pm-stack/console/public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,52 @@ export function deviceLabel(agent = navigator.userAgent) {
return (m ? m[1] : agent).trim().slice(0, 60);
}

/** A short mark for a push address: how this device tells whether the
* sender of notifications still has it, without the address going
* anywhere. The same as endpointMark in src/push.ts. */
export async function endpointMark(endpoint) {
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint)));
return b64url(hash).slice(0, 16);
}

function b64url(bytes) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}

/** What this device's notification subscription needs, given what the
* sender says of itself: "keep" it, hand it over "again" (the sender
* has lost it), or "renew" it (it was made for a key the sender does not
* use, as when the app moved from the laptop to the edge). `madeFor` is
* the key it was made for, or "" where the browser does not say. */
export function subscriptionState(madeFor, mark, status) {
if (!status || !status.key) return "keep";
if (madeFor && madeFor !== status.key) return "renew";
return (status.known || []).includes(mark) ? "keep" : "again";
}

/** Notifications that are on for this device stay on: nothing is asked,
* because the owner already said yes on this device. A device where
* they are off is left alone. */
async function keepSubscribed() {
if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) return;
if (Notification.permission !== "granted") return;
const reg = await navigator.serviceWorker.getRegistration("/console/");
let sub = reg ? await reg.pushManager.getSubscription() : null;
if (!sub) return;
const status = await api("push");
const key = sub.options?.applicationServerKey;
const state = subscriptionState(key ? b64url(new Uint8Array(key)) : "", await endpointMark(sub.endpoint), status);
if (state === "keep") return;
if (state === "renew") {
await sub.unsubscribe();
sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(status.key) });
}
await api("act", { kind: "push.on", args: { subscription: sub.toJSON(), label: deviceLabel() } });
}

function keyBytes(b64) {
const text = atob((b64 + "=".repeat((4 - (b64.length % 4)) % 4)).replace(/-/g, "+").replace(/_/g, "/"));
return Uint8Array.from(text, (c) => c.charCodeAt(0));
Expand Down Expand Up @@ -1409,6 +1455,9 @@ if (typeof document !== "undefined" && view) {
.catch(() => {});
// The worker shows notifications and opens the right screen when one is tapped.
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }).catch(() => {});
// And a device that has notifications on keeps getting them when the
// sender changed or lost track of it.
keepSubscribed().catch(() => {});
draw();
refresh(true);
}
14 changes: 12 additions & 2 deletions pm-stack/console/redeploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,23 @@ if [ "$want" = "$(cat "$STATE/deploy-failed" 2>/dev/null || true)" ]; then
fi

mkdir -p "$STATE"
# The service's own settings, one KEY=value a line, passed as they are.
# The service's own settings, read the way systemd reads them: one
# KEY=value a line, and one pair of quotes around a value is not part of
# the value (install.sh reads PM_CONSOLE_PORT="4872" the same way).
settings=()
if [ -f "$STATE/.env" ]; then
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
'' | '#'* | ';'*) continue ;;
*=*) settings+=("$line") ;;
*=*)
key="${line%%=*}"
value="${line#*=}"
case "$value" in
\"*\") value="${value#\"}" && value="${value%\"}" ;;
\'*\') value="${value#\'}" && value="${value%\'}" ;;
esac
settings+=("$key=$value")
;;
esac
done <"$STATE/.env"
fi
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/console/scripts/edge-smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import { type Deps, handle, heldRunner, marked } from "../src/server.ts";
import { memoryStore } from "../src/store.ts";
import { EdgeLink } from "../src/sync.ts";

if (process.argv.length > 2) {
console.error("usage: bun run scripts/edge-smoke.ts (it takes no arguments; EDGE names the Worker's address)");
process.exit(2);
}
const EDGE = process.env.EDGE ?? "http://localhost:8799";
const cfg = readConfig({ HOME: "/tmp/pm-edge-smoke", PM_CONSOLE_OWNER_EMAILS: "owner@example.com" });
cfg.issuers = [
Expand Down
Loading