diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 08bc19fbe0..e2d695e334 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -552,6 +552,7 @@ export class Edge { this.confirmed[name] = { hash: theirs.hash, at: Math.min(theirs.at, now), error }; } const changed = await this.take(msg.sections); + await this.phones.devices.mergeLinks(msg.phones); // 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[] = []; @@ -642,6 +643,7 @@ export class Edge { notify: (await this.push.status()).devices > 0 || (await this.phones.devices.list()).length > 0, want, commands: held, + phones: await this.phones.devices.links(), }; return json(answer); } diff --git a/pm-stack/console/scripts/edge-demo.ts b/pm-stack/console/scripts/edge-demo.ts index 2b91012c41..51b14840ae 100644 --- a/pm-stack/console/scripts/edge-demo.ts +++ b/pm-stack/console/scripts/edge-demo.ts @@ -91,6 +91,7 @@ const link = new EdgeLink({ keys: memoryStore(), done: memoryStore(), docs: demoDocs, + phones: demoDeps.phones!.devices, config: async () => ({ owners: [OWNER], certNames: [], diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index 61e7dd7d99..97ed224fbe 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -65,6 +65,7 @@ const link = new EdgeLink({ keys: memoryStore(), done: memoryStore(), docs, + phones: deps.phones!.devices, config: async () => ({ owners: cfg.owners, certNames: [], diff --git a/pm-stack/console/src/devices.ts b/pm-stack/console/src/devices.ts index 4bf997e2a3..a41aa1189f 100644 --- a/pm-stack/console/src/devices.ts +++ b/pm-stack/console/src/devices.ts @@ -31,6 +31,13 @@ interface Pending { interface Store { devices: Device[]; pending: Pending[]; + removed: { hash: string; at: string }[]; +} + +/** Only identity metadata crosses the signed host/edge sync boundary. */ +export interface DeviceLinks { + devices: Pick[]; + removed: { hash: string; at: string }[]; } const CHALLENGE = /^[A-Za-z0-9_-]{43}$/; @@ -88,10 +95,12 @@ export class Devices { private async load(): Promise { if (this.store) return this.store; - let store: Store = { devices: [], pending: [] }; + let store: Store = { devices: [], pending: [], removed: [] }; try { const parsed = JSON.parse((await this.kept.read()) ?? ""); - if (parsed && Array.isArray(parsed.devices) && Array.isArray(parsed.pending)) store = parsed; + if (parsed && Array.isArray(parsed.devices) && Array.isArray(parsed.pending)) { + store = { devices: parsed.devices, pending: parsed.pending, removed: Array.isArray(parsed.removed) ? parsed.removed : [] }; + } } catch { // nothing kept yet, or something that cannot be read: start with no devices } @@ -177,9 +186,55 @@ export class Devices { const device = store.devices.find((d) => d.id === id); if (!device) throw new OpError(404, "that phone is not linked"); store.devices = store.devices.filter((d) => d !== device); + store.removed = [...store.removed.filter((r) => r.hash !== device.hash), { hash: device.hash, at: new Date(this.now()).toISOString() }]; await this.save(); return { removed: device.name }; } + + /** Hash-only snapshot for the signed sync protocol; pending verifiers and + * token values are deliberately not part of this shape. */ + async links(): Promise { + const store = await this.load(); + return { + devices: store.devices.map(({ id, name, hash, createdAt, seenAt }) => ({ id, name, hash, createdAt, seenAt })), + removed: store.removed.map(({ hash, at }) => ({ hash, at })), + }; + } + + /** Merge another endpoint's hash-only state. A removal wins for the same + * token hash regardless of timestamps: endpoints may have skewed clocks, + * and a fresh link always has a different token hash. */ + async mergeLinks(value: unknown): Promise { + if (!value || typeof value !== "object") return; + const incoming = value as Partial; + if (!Array.isArray(incoming.devices) || !Array.isArray(incoming.removed)) return; + const validDate = (s: unknown): s is string => typeof s === "string" && Number.isFinite(Date.parse(s)); + const store = await this.load(); + for (const raw of incoming.removed) { + if (!raw || typeof raw.hash !== "string" || !/^[0-9a-f]{64}$/.test(raw.hash) || !validDate(raw.at)) continue; + const previous = store.removed.find((r) => r.hash === raw.hash); + if (!previous || Date.parse(raw.at) > Date.parse(previous.at)) { + store.removed = [...store.removed.filter((r) => r.hash !== raw.hash), { hash: raw.hash, at: raw.at }]; + } + } + for (const raw of incoming.devices) { + if ( + !raw || typeof raw.id !== "string" || raw.id.length > 32 || typeof raw.name !== "string" || raw.name.length > 60 || + typeof raw.hash !== "string" || !/^[0-9a-f]{64}$/.test(raw.hash) || !validDate(raw.createdAt) || + (raw.seenAt !== null && !validDate(raw.seenAt)) + ) continue; + const removed = store.removed.find((r) => r.hash === raw.hash); + if (removed) continue; + const current = store.devices.find((d) => d.hash === raw.hash); + if (!current) store.devices.push({ ...raw }); + else { + current.seenAt = !current.seenAt ? raw.seenAt : !raw.seenAt ? current.seenAt : + Date.parse(raw.seenAt) > Date.parse(current.seenAt) ? raw.seenAt : current.seenAt; + } + } + store.devices = store.devices.filter((d) => !store.removed.some((r) => r.hash === d.hash)); + await this.save(); + } } const clip = (text: unknown, max: number): string => { diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 706c10ab8f..a230c11e61 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -68,6 +68,13 @@ export interface SyncRequest { have: Record; /** What became of the held actions the host was given. */ acks: { id: string; ok: boolean; error?: string }[]; + /** Linked-phone hashes and metadata only; never phone tokens. */ + phones: PhoneLinks; +} + +export interface PhoneLinks { + devices: { id: string; name: string; hash: string; createdAt: string; seenAt: string | null }[]; + removed: { hash: string; at: string }[]; } /** An action the owner took while the host could not be reached. */ @@ -90,6 +97,8 @@ export interface SyncResponse { /** Sections the edge lacks and wants sent whole. */ want: string[]; commands: Held[]; + /** The edge's merged phone-link state, containing hashes only. */ + phones: PhoneLinks; } /** Actions that may be done late, when the host is back. The rest act on diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 8ae9a814ca..0dba99f657 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -574,6 +574,7 @@ if (import.meta.main) { keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), docs, + phones: devices, config: async () => ({ owners: cfg.owners, certNames: cfg.certNames, diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 5627bccd41..13029a8bd1 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -17,6 +17,7 @@ import { keyId, newKeyPair, type PublicKey, + type PhoneLinks, publicKey, type SyncRequest, type SyncResponse, @@ -43,6 +44,7 @@ export interface LinkOptions { /** What became of each held action, so none is run twice. */ done: Store; docs: Docs; + phones: { links(): Promise; mergeLinks(value: unknown): Promise }; config: () => Promise; /** Run one held action; throws if it could not be done. */ run: (held: Held) => Promise; @@ -188,6 +190,7 @@ export class EdgeLink { sections, have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), acks, + phones: await this.o.phones.links(), acts: this.o.docs.recentActs(), }; const body = new TextEncoder().encode(JSON.stringify(message)); @@ -224,6 +227,7 @@ export class EdgeLink { this.acks = this.acks.filter((a) => !acks.includes(a)); this.want = new Set(answer.want ?? []); this.last = answer; + await this.o.phones.mergeLinks(answer.phones); for (const held of answer.commands ?? []) await this.take(held); return answer; } finally { diff --git a/pm-stack/console/test/devices.test.ts b/pm-stack/console/test/devices.test.ts index 41ea9a64c7..021e7aad0c 100644 --- a/pm-stack/console/test/devices.test.ts +++ b/pm-stack/console/test/devices.test.ts @@ -39,6 +39,17 @@ function store(now = { t: 1_800_000_000_000 }) { }; } +function memoryDevices(now: () => number) { + let contents: string | null = null; + const kept = { + read: async () => contents, + write: async (value: string) => { + contents = value; + }, + }; + return new Devices(kept, now); +} + describe("linking a phone", () => { test("the challenge is the SHA-256 of the verifier", () => { expect(challengeOf(VERIFIER)).toBe(hashOf(VERIFIER)); @@ -119,6 +130,82 @@ describe("linking a phone", () => { } }); + test("phone-link sync merges hashes and propagates owner removals without transmitting tokens", async () => { + const owner = store(); + const other = store(); + try { + await owner.devices.approve({ challenge: hashOf(VERIFIER), name: "Pocket" }); + const linked = await owner.devices.link(VERIFIER); + const token = linked!.token; + const snapshot = await owner.devices.links(); + expect(JSON.stringify(snapshot)).not.toContain(token); + expect(snapshot.devices).toEqual([ + expect.objectContaining({ id: linked!.id, name: "Pocket", hash: expect.any(String) }), + ]); + await other.devices.mergeLinks(snapshot); + expect((await other.devices.check(token))?.name).toBe("Pocket"); + + await owner.devices.remove({ id: linked!.id }); + await other.devices.mergeLinks(await owner.devices.links()); + expect(await other.devices.check(token)).toBeNull(); + // A stale pre-removal report cannot resurrect an owner-removed phone. + await other.devices.mergeLinks(snapshot); + expect(await other.devices.check(token)).toBeNull(); + } finally { + owner.done(); + other.done(); + } + }); + + test("property: generated link/remove histories never resurrect a removed token", async () => { + // Deterministic LCG: generated independent endpoint clocks and delivery + // orders make this reproducible while exploring many replication histories. + let seed = 0x12528; + const next = () => { + seed = (Math.imul(seed, 1_664_525) + 1_013_904_223) >>> 0; + return seed; + }; + + for (let history = 0; history < 250; history++) { + const base = 1_800_000_000_000 + history * 10_000; + const skew = next() % (2 * 60_000 + 1); + const hostNow = { t: base + skew }; + const edgeNow = { t: base - (120_000 - skew) }; + const host = memoryDevices(() => hostNow.t); + const edge = memoryDevices(() => edgeNow.t); + const verifier = String(history).padStart(3, "0").repeat(15).slice(0, 43); + + await host.approve({ challenge: hashOf(verifier), name: "Generated phone" }); + const linked = await host.link(verifier); + expect(linked).not.toBeNull(); + const staleLink = await host.links(); + await edge.mergeLinks(staleLink); + + // The edge's removal timestamp can be earlier than the host-created + // link timestamp by almost the full supported two-minute sync skew. + await edge.remove({ id: (await edge.list())[0].id }); + const removal = await edge.links(); + if (next() & 1) await host.mergeLinks(staleLink); + await host.mergeLinks(removal); + expect((await host.links()).devices.some((device) => device.hash === staleLink.devices[0].hash)).toBe(false); + + // Replaying any previously captured link snapshot cannot restore it. + await host.mergeLinks(staleLink); + expect((await host.links()).devices.some((device) => device.hash === staleLink.devices[0].hash)).toBe(false); + expect(await host.check(linked!.token)).toBeNull(); + } + }); + + test("malformed link snapshots are ignored", async () => { + const s = store(); + try { + await s.devices.mergeLinks({ devices: [{ id: "bad", hash: "raw-token", name: "x", createdAt: "y", seenAt: null }], removed: "bad" }); + expect(await s.devices.links()).toEqual({ devices: [], removed: [] }); + } finally { + s.done(); + } + }); + test("no more than eight phones, and no more than four requests waiting", async () => { const s = store(); try { diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 718f3bbd56..75a9188f2e 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -570,6 +570,7 @@ async function setup(options: { direct?: boolean } = {}) { keys, done, docs: hostDocs, + phones: hostDeps.phones!.devices, config: async () => edgeConfig, run: heldRunner(hostDeps), fetchImpl: (async (url: string, init: RequestInit) => { @@ -1042,6 +1043,7 @@ describe("actions", () => { ), done: memoryStore(JSON.stringify(done)), docs: w.hostDocs, + phones: w.hostDeps.phones!.devices, config: async () => w.edgeConfig, run: heldRunner(w.hostDeps), fetchImpl: (async (url: string, init: RequestInit) => @@ -1508,7 +1510,11 @@ describe("notifications and phones, from the edge", () => { new Request(`https://${HOST}/console/device/link`, { method: "POST", body: JSON.stringify({ verifier }) }), w.io, ); - const { token } = (await linked.json()) as { token: string }; + const { token, id } = (await linked.json()) as { token: string; id: string }; + // Phone identity crosses only the signed sync as a hash; the host can + // validate the token locally after an edge/host endpoint switch. + await w.link.now.once(); + expect((await w.hostDeps.phones!.devices.check(token))?.name).toBe("Pocket"); const read = await route( new Request(`https://${HOST}/console/device/summary`, { headers: { authorization: `Bearer ${token}` } }), w.io, @@ -1521,6 +1527,7 @@ describe("notifications and phones, from the edge", () => { expect(await (await w.browse("/console/api/devices")).json()).toEqual([ expect.objectContaining({ name: "Pocket" }), ]); + expect(JSON.stringify(await w.hostDeps.phones!.devices.links())).not.toContain(token); // 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(); @@ -1530,6 +1537,29 @@ describe("notifications and phones, from the edge", () => { ); expect(after.status).toBe(200); expect(w.hostSaw).toEqual([]); + await w.act("device.remove", { id }); + await w.link.now.once(); + expect(await w.hostDeps.phones!.devices.check(token)).toBeNull(); + }); + + test("a host-linked phone survives the edge cutover and an owner removal reaches both stores", async () => { + const w = await setup(); + await w.hostReads(); + const verifier = "h".repeat(43); + const challenge = Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))).toString( + "base64url", + ); + await w.hostDeps.phones!.devices.approve({ challenge, name: "Host phone" }); + const linked = await w.hostDeps.phones!.devices.link(verifier); + expect(linked).not.toBeNull(); + await w.link.now.once(); + expect((await w.edge.now.phones.devices.check(linked!.token))?.name).toBe("Host phone"); + expect(JSON.stringify(await w.edge.now.phones.devices.links())).not.toContain(linked!.token); + + await w.hostDeps.phones!.devices.remove({ id: linked!.id }); + await w.link.now.once(); + expect(await w.edge.now.phones.devices.check(linked!.token)).toBeNull(); + expect(await w.hostDeps.phones!.devices.check(linked!.token)).toBeNull(); }); });