// The §11 secure-reset contract: the durable generation record, the six states, // create-on-miss refusal, archival by generation, crash recovery at every step, // and the sync gate. Storage is simulated; archive digests use native crypto. import { afterEach, describe, expect, it, vi } from "vitest"; import { GENERATION_UNKNOWN, browserGenerationIo, hasLegacyTrustState, LEGACY_ACTIVE, REPAIRING, RESET_CONFIRMED, RESET_REQUIRED, V2_ACTIVE, V2_ANCHOR, assertSyncAllowed, confirmSecureReset, decodeGeneration, encodeGeneration, enterResetRequired, isPostReset, mintDecision, onDirectV2PairingEstablished, resolveGeneration, GENERATION_KEY, type ResetResult, type SyncGeneration, type SyncGenerationBlob, type SyncGenerationIo, } from "./sync-generation"; class CrashAt extends Error {} class FakeGenerationIo implements SyncGenerationIo { blob: unknown = null; pairedDevices = false; revocations = false; archivedIssuers = false; pendingHolders = false; legacyRouteMaterial = false; /** Storage that refuses the write, to model a generation that cannot land. */ failWrites = false; failArchive = false; failClear = false; failIdentity = false; /** Simulated process death: the checkpoint with this name throws. */ crashAt: string | null = null; archiveRef: string | null = null; archiveCount = 0; cleared = false; identityMints = 0; deviceId = "anchor-device"; /** The order the reset actually touched storage. */ readonly calls: string[] = []; get record(): SyncGeneration | null { return decodeGeneration(this.blob)?.active ?? null; } async readBlob(): Promise { return this.blob; } async writeBlob(blob: SyncGenerationBlob): Promise { if (this.failWrites) return false; this.blob = JSON.parse(encodeGeneration(blob)) as unknown; return true; } async hasPairedDevices(): Promise { return this.pairedDevices; } async hasArchivedIssuers(): Promise { return this.archivedIssuers; } async hasRevocations(): Promise { return this.revocations; } async hasPendingHolders(): Promise { return this.pendingHolders; } async hasLegacyRouteMaterial(): Promise { return this.legacyRouteMaterial; } async archiveLegacyState(generation: number): Promise { if (this.failArchive) return null; this.archiveCount += 1; this.archiveRef = `peach_sync_archive_g${generation}_v1`; this.calls.push(`archive:${generation}`); return this.archiveRef; } async clearLegacyTrustState(): Promise { if (this.failClear) return false; this.cleared = true; this.pairedDevices = false; this.revocations = false; this.archivedIssuers = false; this.pendingHolders = false; this.legacyRouteMaterial = false; this.calls.push("clear"); return true; } async ensureV2Identity(): Promise { if (this.failIdentity) return false; this.identityMints += 1; this.calls.push("identity"); return true; } async getDeviceId(): Promise { return this.deviceId; } reset(nowMs = 1_000): Promise { return confirmSecureReset(this, { nowMs, checkpoint: (name) => { if (name === this.crashAt) throw new CrashAt(name); }, }); } } const CHECKPOINTS = [ "before-confirmed", "before-archive", "after-archive", "before-clear", "after-clear", "before-identity", "after-identity", "before-generation-write", "after-generation-write", ]; describe("sync generation — derived state", () => { it("derives V2_ACTIVE at generation 2 for a fresh install, and persists it", async () => { const io = new FakeGenerationIo(); const record = await resolveGeneration(io, 1_000); expect(record.state).toBe(V2_ACTIVE); expect(record.generation).toBe(2); expect(io.record).toEqual(record); }); it("derives LEGACY_ACTIVE at generation 1 when any trust state is present", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; const record = await resolveGeneration(io, 1_000); expect(record.state).toBe(LEGACY_ACTIVE); expect(record.generation).toBe(1); }); it("resolves an unreadable record to UNKNOWN rather than to a generation", async () => { const io = new FakeGenerationIo(); io.blob = "{ not json"; expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN); expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown"); }); it("refuses a record of another schema instead of misreading it", async () => { // The rollback case: a build that does not know the generation must not // treat v2 state as legacy trust. const io = new FakeGenerationIo(); io.blob = { schemaVersion: 99, active: { schemaVersion: 99, generation: 7, state: V2_ACTIVE, createdAt: 1 }, }; expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown"); }); it("refuses an unrecognised state instead of guessing", async () => { const io = new FakeGenerationIo(); io.blob = { schemaVersion: 1, active: { schemaVersion: 1, generation: 1, state: "WOBBLING", createdAt: 1 }, }; expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown"); }); it("does not trust a derived record that could not be persisted", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; io.failWrites = true; expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN); expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown"); }); }); describe("sync generation — create-on-miss refusal (§11.5)", () => { it("refuses to mint over every class of trust state", async () => { const classes: Array<[string, (io: FakeGenerationIo) => void]> = [ ["paired device", (io) => (io.pairedDevices = true)], ["revocation", (io) => (io.revocations = true)], ["archived issuer", (io) => (io.archivedIssuers = true)], ["pending holder", (io) => (io.pendingHolders = true)], ["legacy route material", (io) => (io.legacyRouteMaterial = true)], ]; for (const [label, configure] of classes) { const io = new FakeGenerationIo(); configure(io); expect(await mintDecision(io, 1_000), label).toBe("REFUSE_RESET_REQUIRED"); expect(io.record?.state, label).toBe(RESET_REQUIRED); expect(io.identityMints, label).toBe(0); expect(await assertSyncAllowed(io, 1_000), label).toBe("reset_required"); } }); it("mints only on a genuinely fresh installation", async () => { const io = new FakeGenerationIo(); expect(await mintDecision(io, 1_000)).toBe("MINT"); expect(io.record).toBeNull(); }); }); describe("sync generation — the reset", () => { it("archives, clears, mints, then flips the pointer — in that order", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; io.revocations = true; expect(await io.reset()).toBe("V2_ANCHOR"); expect(io.calls).toEqual(["archive:1", "clear", "identity"]); expect(io.record).toMatchObject({ state: V2_ANCHOR, generation: 2, anchorDeviceId: "anchor-device", legacyArchiveRef: "peach_sync_archive_g1_v1", }); expect(io.cleared).toBe(true); }); it("does not retire the v2 generation or mint twice when repeated", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; await io.reset(); const firstArchive = io.record?.legacyArchiveRef; expect(await io.reset()).toBe("reset_not_completed"); expect(io.record?.legacyArchiveRef).toBe(firstArchive); expect(io.identityMints).toBe(1); }); it("stays in RESET_CONFIRMED and reports the failure when a step fails", async () => { for (const configure of [ (io: FakeGenerationIo) => (io.failArchive = true), (io: FakeGenerationIo) => (io.failClear = true), (io: FakeGenerationIo) => (io.failIdentity = true), (io: FakeGenerationIo) => (io.failWrites = true), ]) { const io = new FakeGenerationIo(); io.pairedDevices = true; configure(io); expect(await io.reset()).toBe("reset_not_completed"); expect(io.record?.state === RESET_CONFIRMED || io.record === null).toBe(true); } }); }); describe("sync generation — crash injection (§11.8)", () => { it("leaves the archive durable and the retry reaches V2_ANCHOR from any crash point", async () => { for (const name of CHECKPOINTS) { const io = new FakeGenerationIo(); io.pairedDevices = true; io.crashAt = name; await expect(io.reset()).rejects.toThrow(CrashAt); // Never a wrong outcome: nothing retired yet, mid-flight, or committed. const state = io.record?.state; expect([LEGACY_ACTIVE, RESET_CONFIRMED, V2_ANCHOR], name).toContain(state); // Trust is never cleared without an archive first. expect(io.cleared && io.archiveCount === 0, `${name} cleared without an archive`).toBe(false); io.crashAt = null; await io.reset(); expect(io.record?.state, `retry after ${name}`).toBe(V2_ANCHOR); expect(io.record?.generation, `retry after ${name}`).toBe(2); expect(io.archiveRef).not.toBeNull(); } }); it("blocks sync before the pointer flip and allows it after", async () => { const before = new FakeGenerationIo(); before.pairedDevices = true; before.crashAt = "before-generation-write"; await expect(before.reset()).rejects.toThrow(CrashAt); expect(before.record?.state).toBe(RESET_CONFIRMED); expect(await assertSyncAllowed(before, 1_000)).toBe("reset_required"); const after = new FakeGenerationIo(); after.pairedDevices = true; after.crashAt = "after-generation-write"; await expect(after.reset()).rejects.toThrow(CrashAt); expect(after.record?.state).toBe(V2_ANCHOR); expect(await assertSyncAllowed(after, 1_000)).toBe("allowed"); expect(after.archiveRef).not.toBeNull(); expect(after.identityMints).toBe(1); }); it("loses nothing when the crash lands after the archive but before the clear", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; io.revocations = true; io.crashAt = "before-clear"; await expect(io.reset()).rejects.toThrow(CrashAt); expect(io.archiveCount).toBe(1); expect(io.cleared).toBe(false); expect(io.pairedDevices).toBe(true); }); }); describe("sync generation — the sync gate (§7)", () => { it("allows a legacy device to sync before it resets", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; expect(await assertSyncAllowed(io, 1_000)).toBe("allowed"); expect(await isPostReset(io, 1_000)).toBe(false); }); it("allows a device that has already reset to sync and pair again", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; await io.reset(); expect(await assertSyncAllowed(io, 1_000)).toBe("allowed"); expect(await isPostReset(io, 1_000)).toBe(true); }); it("blocks sync from RESET_REQUIRED and never walks a reset device backwards", async () => { const legacy = new FakeGenerationIo(); legacy.pairedDevices = true; await enterResetRequired(legacy, 1_000); expect(await assertSyncAllowed(legacy, 1_000)).toBe("reset_required"); const reset = new FakeGenerationIo(); reset.pairedDevices = true; await reset.reset(); await enterResetRequired(reset, 2_000); expect(reset.record?.state).toBe(V2_ANCHOR); }); }); describe("sync generation — repair progression (§11.3)", () => { it("is REPAIRING until a direct peer exists, then V2_ACTIVE", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; await io.reset(); await onDirectV2PairingEstablished(io, false, 2_000); expect(io.record?.state).toBe(REPAIRING); expect(await isPostReset(io, 2_000)).toBe(true); await onDirectV2PairingEstablished(io, true, 3_000); expect(io.record?.state).toBe(V2_ACTIVE); }); it("never disturbs a device that never reset", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; await onDirectV2PairingEstablished(io, true, 2_000); expect(io.record?.state).toBe(LEGACY_ACTIVE); }); }); describe("sync generation — §15.4: the reset retires a generation, it does not rotate the root", () => { it("reaches storage only through archive, clear and identity, in that order", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; io.revocations = true; io.legacyRouteMaterial = true; expect(await io.reset()).toBe("V2_ANCHOR"); // The io is the whole surface the reset can reach. It carries no root key, // no recovery material, and no vault-id parameter, so no rotation is // possible by construction; what is worth pinning is the order that makes // the archive safe. expect(io.calls).toEqual(["archive:1", "clear", "identity"]); expect(io.record?.legacyArchiveRef).toBe("peach_sync_archive_g1_v1"); expect(io.record?.generation).toBe(2); }); }); describe("verification issuer archive reset", () => { afterEach(() => vi.unstubAllGlobals()); it("refuses corrupt archive trust without persisting a new generation", async () => { const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices"); const set = vi.fn(); vi.stubGlobal("chrome", { storage: { local: { get: async () => ({ [REVOCATION_ISSUERS_KEY]: "corrupt" }), set, } } }); await expect(hasLegacyTrustState(browserGenerationIo)).rejects.toThrow("trust_data_corrupted"); await expect(resolveGeneration(browserGenerationIo)).rejects.toThrow("trust_data_corrupted"); expect(set).not.toHaveBeenCalled(); }); it("counts archive-only trust, copies it into rollback history and verifies its removal", async () => { const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices"); const archive = [{ deviceId: "removed", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }]; const stored: Record = { [REVOCATION_ISSUERS_KEY]: archive }; let refuseRemoval = true; const area = { async get(keys: string | string[]) { return Object.fromEntries((Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]])); }, async set(values: Record) { Object.assign(stored, values); }, async remove(keys: string | string[]) { for (const key of Array.isArray(keys) ? keys : [keys]) { if (key !== REVOCATION_ISSUERS_KEY || !refuseRemoval) delete stored[key]; } }, }; vi.stubGlobal("chrome", { storage: { local: area, session: area } }); expect(await hasLegacyTrustState(browserGenerationIo)).toBe(true); const ref = await browserGenerationIo.archiveLegacyState(1); expect(ref).not.toBeNull(); expect(JSON.parse((stored[ref!] as { snapshotJson: string }).snapshotJson)).toMatchObject({ revocationIssuers: archive }); expect(await browserGenerationIo.clearLegacyTrustState()).toBe(false); refuseRemoval = false; expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true); expect(stored[REVOCATION_ISSUERS_KEY]).toBeUndefined(); expect(await hasLegacyTrustState(browserGenerationIo)).toBe(false); }); }); describe("production reset archive durability", () => { const ref = "peach_sync_archive_g1_v1"; const trustKeys = [ "peach_paired_devices_v3", "peach_device_revocations_v1", "peach_revocation_issuers_v1", "peach_pending_adoption_holder_v1", "peach_pending_adoption_identity_v2", "peach_pair_secrets_v1", ]; function storage() { const stored: Record = { [GENERATION_KEY]: encodeGeneration({ schemaVersion: 1, active: { schemaVersion: 1, generation: 1, state: LEGACY_ACTIVE, createdAt: 100, } }), [trustKeys[0]]: [{ deviceId: "peer", nested: { retained: null } }], [trustKeys[1]]: [{ deviceId: "removed", signatureHex: "original" }], [trustKeys[2]]: [{ deviceId: "issuer", signingPublicKeys: ["original-key"] }], [trustKeys[3]]: { deviceId: "pending" }, [trustKeys[4]]: { deviceId: "identity" }, [trustKeys[5]]: { route: "original" }, }; const area = { get: vi.fn(async (keys: string | string[]) => structuredClone(Object.fromEntries( (Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]]), ))), set: vi.fn(async (values: Record) => { Object.assign(stored, structuredClone(values)); }), remove: vi.fn(async (keys: string | string[]) => { for (const key of Array.isArray(keys) ? keys : [keys]) delete stored[key]; }), }; const sessionStored: Record = { peach_pair_secrets_session: { route: "session-only" } }; const session = { get: vi.fn(async (key: string) => ({ [key]: sessionStored[key] })), set: vi.fn(async (values: Record) => { Object.assign(sessionStored, structuredClone(values)); }), remove: vi.fn(async (key: string) => { delete sessionStored[key]; }), }; vi.stubGlobal("chrome", { storage: { local: area, session } }); vi.spyOn(browserGenerationIo, "ensureV2Identity").mockResolvedValue(true); vi.spyOn(browserGenerationIo, "getDeviceId").mockResolvedValue("new-identity"); return { stored, area, sessionStored }; } afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); it.each(["after-clear", "after-identity", "before-generation-write"])("reuses the complete original archive after a crash at %s", async (point) => { const { stored, area } = storage(); const original = structuredClone(stored); await expect(confirmSecureReset(browserGenerationIo, { nowMs: 200, checkpoint(name) { if (name === point) throw new CrashAt(name); } })).rejects.toThrow(CrashAt); const first = structuredClone(stored[ref]) as { snapshotJson: string }; expect(JSON.parse(first.snapshotJson)).toEqual({ pairedDevices: original[trustKeys[0]], revocations: original[trustKeys[1]], revocationIssuers: original[trustKeys[2]], pendingHolder: original[trustKeys[3]], pendingIdentity: original[trustKeys[4]], pairSecrets: original[trustKeys[5]], }); expect(await assertSyncAllowed(browserGenerationIo)).toBe("reset_required"); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 300 })).toBe("V2_ANCHOR"); expect(stored[ref]).toEqual(first); expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(1); }); it("accepts reordered envelope keys on readback and reuse", async () => { const { stored, area } = storage(); const get = area.get.getMockImplementation()!; area.get.mockImplementation(async (keys) => { const result = await get(keys); if (result[ref] && typeof result[ref] === "object") { result[ref] = Object.fromEntries(Object.entries(result[ref] as object).reverse()); } return result; }); expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); const first = structuredClone(stored[ref]); expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); expect(stored[ref]).toEqual(first); expect(area.set).toHaveBeenCalledTimes(1); }); it.each(["payload", "missing-field", "metadata", "valid-alternate-metadata"])("blocks clear when archive readback changes %s", async (change) => { const { area } = storage(); const set = area.set.getMockImplementation()!; area.set.mockImplementation(async (values) => { const copied = structuredClone(values); const archive = copied[ref] as Record | undefined; if (archive) { if (change === "payload") archive.snapshotJson = '{"pairedDevices":null}'; if (change === "missing-field") delete archive.snapshotJson; if (change === "metadata" || change === "valid-alternate-metadata") archive.archivedAt = Number(archive.archivedAt) + 1; if (change === "valid-alternate-metadata") { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([ "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation, archive.archivedAt, archive.snapshotJson, ]))); archive.completionSha256Hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); } } await set(copied); }); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required"); expect(area.remove).not.toHaveBeenCalled(); }); it.each([null, {}, { schemaVersion: 1, generation: 1, pairedDevices: ["original"] }, "corrupt"])("preserves and refuses an existing unmarked archive %j", async (archive) => { const { stored, area } = storage(); stored[ref] = archive; expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required"); expect(stored[ref]).toEqual(archive); expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0); expect(area.remove).not.toHaveBeenCalled(); }); it("detects valid JSON payload edits when reusing an archive", async () => { const { stored, area } = storage(); expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); const archive = stored[ref] as { snapshotJson: string }; const snapshot = JSON.parse(archive.snapshotJson); snapshot.pairedDevices = null; archive.snapshotJson = JSON.stringify(snapshot); const damaged = structuredClone(archive); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required"); expect(stored[ref]).toEqual(damaged); expect(area.remove).not.toHaveBeenCalled(); }); it.each(["read", "write"])("leaves trust intact after first archive %s failure and permits retry", async (failure) => { const { stored, area } = storage(); const original = structuredClone(stored); if (failure === "read") { const get = area.get.getMockImplementation()!; area.get.mockImplementationOnce(async (keys) => { if (keys === ref) throw new Error("read failed"); return get(keys); }); } else area.set.mockRejectedValueOnce(new Error("write failed")); expect(await browserGenerationIo.archiveLegacyState(1)).toBeNull(); expect(stored).toEqual(original); expect(area.remove).not.toHaveBeenCalled(); expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); }); it("keeps the original snapshot after a failed readback and later trust clearing", async () => { const { stored, area } = storage(); const get = area.get.getMockImplementation()!; let archiveReads = 0; area.get.mockImplementation(async (keys) => { if (keys === ref && ++archiveReads === 2) throw new Error("readback failed"); return get(keys); }); expect(await browserGenerationIo.archiveLegacyState(1)).toBeNull(); const original = structuredClone(stored[ref]); for (const key of trustKeys) delete stored[key]; expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); expect(stored[ref]).toEqual(original); expect(area.set).toHaveBeenCalledTimes(1); }); it.each(["missing", "extra", "array", "invalid-json"])("refuses a completed snapshot with %s fields", async (damage) => { const { stored, area } = storage(); expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); const archive = stored[ref] as { schemaVersion: number; generation: number; archivedAt: number; snapshotJson: string; completionSha256Hex: string; }; const snapshot = JSON.parse(archive.snapshotJson); if (damage === "missing") delete snapshot.pairSecrets; if (damage === "extra") snapshot.extra = null; archive.snapshotJson = damage === "invalid-json" ? "{" : JSON.stringify(damage === "array" ? [] : snapshot); const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([ "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation, archive.archivedAt, archive.snapshotJson, ]))); archive.completionSha256Hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); const original = structuredClone(archive); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required"); expect(stored[ref]).toEqual(original); expect(area.remove).not.toHaveBeenCalled(); }); it.each([false, true])("reuses complete schema1 archives with cleared trust=%s without rewriting", async (cleared) => { const { stored, area } = storage(); const fields = ["pairedDevices", "revocations", "revocationIssuers", "pendingHolder", "pendingIdentity", "pairSecrets"]; const archive = { schemaVersion: 1, generation: 1, archivedAt: 123, ...Object.fromEntries(fields.map((field, index) => [field, structuredClone(stored[trustKeys[index]])])), }; stored[ref] = structuredClone(archive); if (cleared) for (const key of trustKeys) delete stored[key]; expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR"); expect(stored[ref]).toEqual(archive); expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0); }); it("reuses the complete pre-issuer schema1 shape without fabricating archive fields", async () => { const { stored, area } = storage(); const archive = { schemaVersion: 1, generation: 1, archivedAt: 123, pairedDevices: stored[trustKeys[0]], revocations: stored[trustKeys[1]], pendingHolder: stored[trustKeys[3]], pendingIdentity: stored[trustKeys[4]], pairSecrets: stored[trustKeys[5]], }; stored[ref] = structuredClone(archive); delete stored[trustKeys[2]]; expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR"); expect(stored[ref]).toEqual(archive); expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0); }); it("blocks a retry that would clear trust added after a failed clear", async () => { const { stored, area } = storage(); area.remove.mockRejectedValueOnce(new Error("clear failed")); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_not_completed"); const firstArchive = structuredClone(stored[ref]); stored[trustKeys[0]] = [{ deviceId: "new-peer" }]; stored[trustKeys[5]] = { route: "new-route" }; const changedTrust = structuredClone(stored); area.remove.mockClear(); expect(await confirmSecureReset(browserGenerationIo, { nowMs: 300 })).toBe("reset_archive_review_required"); expect(area.remove).not.toHaveBeenCalled(); for (const key of trustKeys) expect(stored[key]).toEqual(changedTrust[key]); expect(stored[ref]).toEqual(firstArchive); }); it("reuses equal nested trust despite object key order and normalized empty fields", async () => { const { stored } = storage(); stored[trustKeys[0]] = [{ deviceId: "peer", metadata: { a: null, b: "value" } }]; stored[trustKeys[3]] = null; stored[trustKeys[4]] = []; stored[trustKeys[5]] = {}; expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref); stored[trustKeys[0]] = [{ metadata: { b: "value", a: null }, deviceId: "peer" }]; delete stored[trustKeys[3]]; stored[trustKeys[4]] = {}; stored[trustKeys[5]] = []; expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR"); }); it("joins concurrent same-IO attempts and releases a rejected attempt for retry", async () => { const io = new FakeGenerationIo(); io.pairedDevices = true; let release!: () => void; const blocked = new Promise((resolve) => { release = resolve; }); const archive = vi.spyOn(io, "archiveLegacyState").mockImplementationOnce(async () => { await blocked; throw new Error("archive failed"); }); const first = confirmSecureReset(io, { nowMs: 100 }); const joined = confirmSecureReset(io, { nowMs: 101 }); const results = Promise.allSettled([first, joined]); release(); expect((await results).map((result) => result.status)).toEqual(["rejected", "rejected"]); expect(archive).toHaveBeenCalledTimes(1); expect(await confirmSecureReset(io, { nowMs: 200 })).toBe("V2_ANCHOR"); expect(io.identityMints).toBe(1); }); it("joins successful concurrent production resets without a second clear or identity mint", async () => { const { area, stored, sessionStored } = storage(); const ensureIdentity = vi.mocked(browserGenerationIo.ensureV2Identity); expect(await Promise.all([ confirmSecureReset(browserGenerationIo, { nowMs: 200 }), confirmSecureReset(browserGenerationIo, { nowMs: 201 }), ])).toEqual(["V2_ANCHOR", "V2_ANCHOR"]); expect(area.remove.mock.calls.filter(([keys]) => Array.isArray(keys))).toHaveLength(1); expect(ensureIdentity).toHaveBeenCalledTimes(1); expect(sessionStored.peach_pair_secrets_session).toBeUndefined(); expect(stored.peach_pair_secrets_session).toBeUndefined(); }); });