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
2 changes: 2 additions & 0 deletions pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [];
Expand Down Expand Up @@ -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);
}
Expand Down
1 change: 1 addition & 0 deletions pm-stack/console/scripts/edge-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ const link = new EdgeLink({
keys: memoryStore(),
done: memoryStore(),
docs: demoDocs,
phones: demoDeps.phones!.devices,
config: async () => ({
owners: [OWNER],
certNames: [],
Expand Down
1 change: 1 addition & 0 deletions pm-stack/console/scripts/edge-smoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const link = new EdgeLink({
keys: memoryStore(),
done: memoryStore(),
docs,
phones: deps.phones!.devices,
config: async () => ({
owners: cfg.owners,
certNames: [],
Expand Down
59 changes: 57 additions & 2 deletions pm-stack/console/src/devices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Device, "id" | "name" | "hash" | "createdAt" | "seenAt">[];
removed: { hash: string; at: string }[];
}

const CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
Expand Down Expand Up @@ -88,10 +95,12 @@ export class Devices {

private async load(): Promise<Store> {
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
}
Expand Down Expand Up @@ -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<DeviceLinks> {
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<void> {
if (!value || typeof value !== "object") return;
const incoming = value as Partial<DeviceLinks>;
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 => {
Expand Down
9 changes: 9 additions & 0 deletions pm-stack/console/src/edge-proto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ export interface SyncRequest {
have: Record<string, { hash: string; at: number; error?: string | null }>;
/** 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. */
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions pm-stack/console/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/console/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
keyId,
newKeyPair,
type PublicKey,
type PhoneLinks,
publicKey,
type SyncRequest,
type SyncResponse,
Expand All @@ -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<PhoneLinks>; mergeLinks(value: unknown): Promise<void> };
config: () => Promise<EdgeConfig>;
/** Run one held action; throws if it could not be done. */
run: (held: Held) => Promise<void>;
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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 {
Expand Down
87 changes: 87 additions & 0 deletions pm-stack/console/test/devices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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 {
Comment thread
dezren39 marked this conversation as resolved.
Resolved
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 {
Expand Down
32 changes: 31 additions & 1 deletion pm-stack/console/test/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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,
Expand All @@ -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();
Expand All @@ -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();
});
});

Expand Down