12345import { afterEach, describe, expect, it, vi } from "vitest";6import {7 GENERATION_UNKNOWN,8 browserGenerationIo,9 hasLegacyTrustState,10 LEGACY_ACTIVE,11 REPAIRING,12 RESET_CONFIRMED,13 RESET_REQUIRED,14 V2_ACTIVE,15 V2_ANCHOR,16 assertSyncAllowed,17 confirmSecureReset,18 decodeGeneration,19 encodeGeneration,20 enterResetRequired,21 isPostReset,22 mintDecision,23 onDirectV2PairingEstablished,24 resolveGeneration,25 GENERATION_KEY,26 type ResetResult,27 type SyncGeneration,28 type SyncGenerationBlob,29 type SyncGenerationIo,30} from "./sync-generation";3132class CrashAt extends Error {}3334class FakeGenerationIo implements SyncGenerationIo {35 blob: unknown = null;36 pairedDevices = false;37 revocations = false;38 archivedIssuers = false;39 pendingHolders = false;40 legacyRouteMaterial = false;4142 43 failWrites = false;44 failArchive = false;45 failClear = false;46 failIdentity = false;4748 49 crashAt: string | null = null;5051 archiveRef: string | null = null;52 archiveCount = 0;53 cleared = false;54 identityMints = 0;55 deviceId = "anchor-device";5657 58 readonly calls: string[] = [];5960 get record(): SyncGeneration | null {61 return decodeGeneration(this.blob)?.active ?? null;62 }6364 async readBlob(): Promise<unknown> {65 return this.blob;66 }6768 async writeBlob(blob: SyncGenerationBlob): Promise<boolean> {69 if (this.failWrites) return false;70 this.blob = JSON.parse(encodeGeneration(blob)) as unknown;71 return true;72 }7374 async hasPairedDevices(): Promise<boolean> {75 return this.pairedDevices;76 }7778 async hasArchivedIssuers(): Promise<boolean> {79 return this.archivedIssuers;80 }8182 async hasRevocations(): Promise<boolean> {83 return this.revocations;84 }8586 async hasPendingHolders(): Promise<boolean> {87 return this.pendingHolders;88 }8990 async hasLegacyRouteMaterial(): Promise<boolean> {91 return this.legacyRouteMaterial;92 }9394 async archiveLegacyState(generation: number): Promise<string | null> {95 if (this.failArchive) return null;96 this.archiveCount += 1;97 this.archiveRef = `peach_sync_archive_g${generation}_v1`;98 this.calls.push(`archive:${generation}`);99 return this.archiveRef;100 }101102 async clearLegacyTrustState(): Promise<boolean> {103 if (this.failClear) return false;104 this.cleared = true;105 this.pairedDevices = false;106 this.revocations = false;107 this.archivedIssuers = false;108 this.pendingHolders = false;109 this.legacyRouteMaterial = false;110 this.calls.push("clear");111 return true;112 }113114 async ensureV2Identity(): Promise<boolean> {115 if (this.failIdentity) return false;116 this.identityMints += 1;117 this.calls.push("identity");118 return true;119 }120121 async getDeviceId(): Promise<string> {122 return this.deviceId;123 }124125 reset(nowMs = 1_000): Promise<ResetResult> {126 return confirmSecureReset(this, {127 nowMs,128 checkpoint: (name) => {129 if (name === this.crashAt) throw new CrashAt(name);130 },131 });132 }133}134135const CHECKPOINTS = [136 "before-confirmed",137 "before-archive",138 "after-archive",139 "before-clear",140 "after-clear",141 "before-identity",142 "after-identity",143 "before-generation-write",144 "after-generation-write",145];146147describe("sync generation — derived state", () => {148 it("derives V2_ACTIVE at generation 2 for a fresh install, and persists it", async () => {149 const io = new FakeGenerationIo();150 const record = await resolveGeneration(io, 1_000);151 expect(record.state).toBe(V2_ACTIVE);152 expect(record.generation).toBe(2);153 expect(io.record).toEqual(record);154 });155156 it("derives LEGACY_ACTIVE at generation 1 when any trust state is present", async () => {157 const io = new FakeGenerationIo();158 io.pairedDevices = true;159 const record = await resolveGeneration(io, 1_000);160 expect(record.state).toBe(LEGACY_ACTIVE);161 expect(record.generation).toBe(1);162 });163164 it("resolves an unreadable record to UNKNOWN rather than to a generation", async () => {165 const io = new FakeGenerationIo();166 io.blob = "{ not json";167 expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN);168 expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");169 });170171 it("refuses a record of another schema instead of misreading it", async () => {172 173 174 const io = new FakeGenerationIo();175 io.blob = {176 schemaVersion: 99,177 active: { schemaVersion: 99, generation: 7, state: V2_ACTIVE, createdAt: 1 },178 };179 expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");180 });181182 it("refuses an unrecognised state instead of guessing", async () => {183 const io = new FakeGenerationIo();184 io.blob = {185 schemaVersion: 1,186 active: { schemaVersion: 1, generation: 1, state: "WOBBLING", createdAt: 1 },187 };188 expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");189 });190191 it("does not trust a derived record that could not be persisted", async () => {192 const io = new FakeGenerationIo();193 io.pairedDevices = true;194 io.failWrites = true;195 expect((await resolveGeneration(io, 1_000)).state).toBe(GENERATION_UNKNOWN);196 expect(await assertSyncAllowed(io, 1_000)).toBe("sync_generation_unknown");197 });198});199200describe("sync generation — create-on-miss refusal (§11.5)", () => {201 it("refuses to mint over every class of trust state", async () => {202 const classes: Array<[string, (io: FakeGenerationIo) => void]> = [203 ["paired device", (io) => (io.pairedDevices = true)],204 ["revocation", (io) => (io.revocations = true)],205 ["archived issuer", (io) => (io.archivedIssuers = true)],206 ["pending holder", (io) => (io.pendingHolders = true)],207 ["legacy route material", (io) => (io.legacyRouteMaterial = true)],208 ];209 for (const [label, configure] of classes) {210 const io = new FakeGenerationIo();211 configure(io);212 expect(await mintDecision(io, 1_000), label).toBe("REFUSE_RESET_REQUIRED");213 expect(io.record?.state, label).toBe(RESET_REQUIRED);214 expect(io.identityMints, label).toBe(0);215 expect(await assertSyncAllowed(io, 1_000), label).toBe("reset_required");216 }217 });218219 it("mints only on a genuinely fresh installation", async () => {220 const io = new FakeGenerationIo();221 expect(await mintDecision(io, 1_000)).toBe("MINT");222 expect(io.record).toBeNull();223 });224});225226describe("sync generation — the reset", () => {227 it("archives, clears, mints, then flips the pointer — in that order", async () => {228 const io = new FakeGenerationIo();229 io.pairedDevices = true;230 io.revocations = true;231232 expect(await io.reset()).toBe("V2_ANCHOR");233 expect(io.calls).toEqual(["archive:1", "clear", "identity"]);234 expect(io.record).toMatchObject({235 state: V2_ANCHOR,236 generation: 2,237 anchorDeviceId: "anchor-device",238 legacyArchiveRef: "peach_sync_archive_g1_v1",239 });240 expect(io.cleared).toBe(true);241 });242243 it("does not retire the v2 generation or mint twice when repeated", async () => {244 const io = new FakeGenerationIo();245 io.pairedDevices = true;246 await io.reset();247 const firstArchive = io.record?.legacyArchiveRef;248249 expect(await io.reset()).toBe("reset_not_completed");250 expect(io.record?.legacyArchiveRef).toBe(firstArchive);251 expect(io.identityMints).toBe(1);252 });253254 it("stays in RESET_CONFIRMED and reports the failure when a step fails", async () => {255 for (const configure of [256 (io: FakeGenerationIo) => (io.failArchive = true),257 (io: FakeGenerationIo) => (io.failClear = true),258 (io: FakeGenerationIo) => (io.failIdentity = true),259 (io: FakeGenerationIo) => (io.failWrites = true),260 ]) {261 const io = new FakeGenerationIo();262 io.pairedDevices = true;263 configure(io);264 expect(await io.reset()).toBe("reset_not_completed");265 expect(io.record?.state === RESET_CONFIRMED || io.record === null).toBe(true);266 }267 });268});269270describe("sync generation — crash injection (§11.8)", () => {271 it("leaves the archive durable and the retry reaches V2_ANCHOR from any crash point", async () => {272 for (const name of CHECKPOINTS) {273 const io = new FakeGenerationIo();274 io.pairedDevices = true;275 io.crashAt = name;276277 await expect(io.reset()).rejects.toThrow(CrashAt);278279 280 const state = io.record?.state;281 expect([LEGACY_ACTIVE, RESET_CONFIRMED, V2_ANCHOR], name).toContain(state);282 283 expect(io.cleared && io.archiveCount === 0, `${name} cleared without an archive`).toBe(false);284285 io.crashAt = null;286 await io.reset();287 expect(io.record?.state, `retry after ${name}`).toBe(V2_ANCHOR);288 expect(io.record?.generation, `retry after ${name}`).toBe(2);289 expect(io.archiveRef).not.toBeNull();290 }291 });292293 it("blocks sync before the pointer flip and allows it after", async () => {294 const before = new FakeGenerationIo();295 before.pairedDevices = true;296 before.crashAt = "before-generation-write";297 await expect(before.reset()).rejects.toThrow(CrashAt);298 expect(before.record?.state).toBe(RESET_CONFIRMED);299 expect(await assertSyncAllowed(before, 1_000)).toBe("reset_required");300301 const after = new FakeGenerationIo();302 after.pairedDevices = true;303 after.crashAt = "after-generation-write";304 await expect(after.reset()).rejects.toThrow(CrashAt);305 expect(after.record?.state).toBe(V2_ANCHOR);306 expect(await assertSyncAllowed(after, 1_000)).toBe("allowed");307 expect(after.archiveRef).not.toBeNull();308 expect(after.identityMints).toBe(1);309 });310311 it("loses nothing when the crash lands after the archive but before the clear", async () => {312 const io = new FakeGenerationIo();313 io.pairedDevices = true;314 io.revocations = true;315 io.crashAt = "before-clear";316317 await expect(io.reset()).rejects.toThrow(CrashAt);318319 expect(io.archiveCount).toBe(1);320 expect(io.cleared).toBe(false);321 expect(io.pairedDevices).toBe(true);322 });323});324325describe("sync generation — the sync gate (§7)", () => {326 it("allows a legacy device to sync before it resets", async () => {327 const io = new FakeGenerationIo();328 io.pairedDevices = true;329 expect(await assertSyncAllowed(io, 1_000)).toBe("allowed");330 expect(await isPostReset(io, 1_000)).toBe(false);331 });332333 it("allows a device that has already reset to sync and pair again", async () => {334 const io = new FakeGenerationIo();335 io.pairedDevices = true;336 await io.reset();337 expect(await assertSyncAllowed(io, 1_000)).toBe("allowed");338 expect(await isPostReset(io, 1_000)).toBe(true);339 });340341 it("blocks sync from RESET_REQUIRED and never walks a reset device backwards", async () => {342 const legacy = new FakeGenerationIo();343 legacy.pairedDevices = true;344 await enterResetRequired(legacy, 1_000);345 expect(await assertSyncAllowed(legacy, 1_000)).toBe("reset_required");346347 const reset = new FakeGenerationIo();348 reset.pairedDevices = true;349 await reset.reset();350 await enterResetRequired(reset, 2_000);351 expect(reset.record?.state).toBe(V2_ANCHOR);352 });353});354355describe("sync generation — repair progression (§11.3)", () => {356 it("is REPAIRING until a direct peer exists, then V2_ACTIVE", async () => {357 const io = new FakeGenerationIo();358 io.pairedDevices = true;359 await io.reset();360361 await onDirectV2PairingEstablished(io, false, 2_000);362 expect(io.record?.state).toBe(REPAIRING);363 expect(await isPostReset(io, 2_000)).toBe(true);364365 await onDirectV2PairingEstablished(io, true, 3_000);366 expect(io.record?.state).toBe(V2_ACTIVE);367 });368369 it("never disturbs a device that never reset", async () => {370 const io = new FakeGenerationIo();371 io.pairedDevices = true;372 await onDirectV2PairingEstablished(io, true, 2_000);373 expect(io.record?.state).toBe(LEGACY_ACTIVE);374 });375});376377describe("sync generation — §15.4: the reset retires a generation, it does not rotate the root", () => {378 it("reaches storage only through archive, clear and identity, in that order", async () => {379 const io = new FakeGenerationIo();380 io.pairedDevices = true;381 io.revocations = true;382 io.legacyRouteMaterial = true;383384 expect(await io.reset()).toBe("V2_ANCHOR");385386 387 388 389 390 expect(io.calls).toEqual(["archive:1", "clear", "identity"]);391 expect(io.record?.legacyArchiveRef).toBe("peach_sync_archive_g1_v1");392 expect(io.record?.generation).toBe(2);393 });394});395396397describe("verification issuer archive reset", () => {398 afterEach(() => vi.unstubAllGlobals());399 it("refuses corrupt archive trust without persisting a new generation", async () => {400 const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");401 const set = vi.fn();402 vi.stubGlobal("chrome", { storage: { local: {403 get: async () => ({ [REVOCATION_ISSUERS_KEY]: "corrupt" }), set,404 } } });405 await expect(hasLegacyTrustState(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");406 await expect(resolveGeneration(browserGenerationIo)).rejects.toThrow("trust_data_corrupted");407 expect(set).not.toHaveBeenCalled();408 });409410 it("counts archive-only trust, copies it into rollback history and verifies its removal", async () => {411 const { REVOCATION_ISSUERS_KEY } = await import("./paired-devices");412 const archive = [{ deviceId: "removed", longTermPublicKeyHex: "a".repeat(64), signingPublicKeys: ["b".repeat(64)] }];413 const stored: Record<string, unknown> = { [REVOCATION_ISSUERS_KEY]: archive };414 let refuseRemoval = true;415 const area = {416 async get(keys: string | string[]) {417 return Object.fromEntries((Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]]));418 },419 async set(values: Record<string, unknown>) { Object.assign(stored, values); },420 async remove(keys: string | string[]) {421 for (const key of Array.isArray(keys) ? keys : [keys]) {422 if (key !== REVOCATION_ISSUERS_KEY || !refuseRemoval) delete stored[key];423 }424 },425 };426 vi.stubGlobal("chrome", { storage: { local: area, session: area } });427 expect(await hasLegacyTrustState(browserGenerationIo)).toBe(true);428 const ref = await browserGenerationIo.archiveLegacyState(1);429 expect(ref).not.toBeNull();430 expect(JSON.parse((stored[ref!] as { snapshotJson: string }).snapshotJson)).toMatchObject({ revocationIssuers: archive });431 expect(await browserGenerationIo.clearLegacyTrustState()).toBe(false);432 refuseRemoval = false;433 expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);434 expect(stored[REVOCATION_ISSUERS_KEY]).toBeUndefined();435 expect(await hasLegacyTrustState(browserGenerationIo)).toBe(false);436 });437});438439440describe("production reset archive durability", () => {441 const ref = "peach_sync_archive_g1_v1";442 const trustKeys = [443 "peach_paired_devices_v3", "peach_device_revocations_v1", "peach_revocation_issuers_v1",444 "peach_pending_adoption_holder_v1", "peach_pending_adoption_identity_v2", "peach_pair_secrets_v1",445 ];446447 function storage() {448 const stored: Record<string, unknown> = {449 [GENERATION_KEY]: encodeGeneration({ schemaVersion: 1, active: {450 schemaVersion: 1, generation: 1, state: LEGACY_ACTIVE, createdAt: 100,451 } }),452 [trustKeys[0]]: [{ deviceId: "peer", nested: { retained: null } }],453 [trustKeys[1]]: [{ deviceId: "removed", signatureHex: "original" }],454 [trustKeys[2]]: [{ deviceId: "issuer", signingPublicKeys: ["original-key"] }],455 [trustKeys[3]]: { deviceId: "pending" },456 [trustKeys[4]]: { deviceId: "identity" },457 [trustKeys[5]]: { route: "original" },458 };459 const area = {460 get: vi.fn(async (keys: string | string[]) => structuredClone(Object.fromEntries(461 (Array.isArray(keys) ? keys : [keys]).map((key) => [key, stored[key]]),462 ))),463 set: vi.fn(async (values: Record<string, unknown>) => { Object.assign(stored, structuredClone(values)); }),464 remove: vi.fn(async (keys: string | string[]) => {465 for (const key of Array.isArray(keys) ? keys : [keys]) delete stored[key];466 }),467 };468 const sessionStored: Record<string, unknown> = { peach_pair_secrets_session: { route: "session-only" } };469 const session = {470 get: vi.fn(async (key: string) => ({ [key]: sessionStored[key] })),471 set: vi.fn(async (values: Record<string, unknown>) => { Object.assign(sessionStored, structuredClone(values)); }),472 remove: vi.fn(async (key: string) => { delete sessionStored[key]; }),473 };474 vi.stubGlobal("chrome", { storage: { local: area, session } });475 vi.spyOn(browserGenerationIo, "ensureV2Identity").mockResolvedValue(true);476 vi.spyOn(browserGenerationIo, "getDeviceId").mockResolvedValue("new-identity");477 return { stored, area, sessionStored };478 }479480 afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });481482 it.each(["after-clear", "after-identity", "before-generation-write"])("reuses the complete original archive after a crash at %s", async (point) => {483 const { stored, area } = storage();484 const original = structuredClone(stored);485 await expect(confirmSecureReset(browserGenerationIo, { nowMs: 200, checkpoint(name) {486 if (name === point) throw new CrashAt(name);487 } })).rejects.toThrow(CrashAt);488 const first = structuredClone(stored[ref]) as { snapshotJson: string };489 expect(JSON.parse(first.snapshotJson)).toEqual({490 pairedDevices: original[trustKeys[0]], revocations: original[trustKeys[1]],491 revocationIssuers: original[trustKeys[2]], pendingHolder: original[trustKeys[3]],492 pendingIdentity: original[trustKeys[4]], pairSecrets: original[trustKeys[5]],493 });494 expect(await assertSyncAllowed(browserGenerationIo)).toBe("reset_required");495 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 300 })).toBe("V2_ANCHOR");496 expect(stored[ref]).toEqual(first);497 expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(1);498 });499500 it("accepts reordered envelope keys on readback and reuse", async () => {501 const { stored, area } = storage();502 const get = area.get.getMockImplementation()!;503 area.get.mockImplementation(async (keys) => {504 const result = await get(keys);505 if (result[ref] && typeof result[ref] === "object") {506 result[ref] = Object.fromEntries(Object.entries(result[ref] as object).reverse());507 }508 return result;509 });510 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);511 const first = structuredClone(stored[ref]);512 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);513 expect(stored[ref]).toEqual(first);514 expect(area.set).toHaveBeenCalledTimes(1);515 });516517 it.each(["payload", "missing-field", "metadata", "valid-alternate-metadata"])("blocks clear when archive readback changes %s", async (change) => {518 const { area } = storage();519 const set = area.set.getMockImplementation()!;520 area.set.mockImplementation(async (values) => {521 const copied = structuredClone(values);522 const archive = copied[ref] as Record<string, unknown> | undefined;523 if (archive) {524 if (change === "payload") archive.snapshotJson = '{"pairedDevices":null}';525 if (change === "missing-field") delete archive.snapshotJson;526 if (change === "metadata" || change === "valid-alternate-metadata") archive.archivedAt = Number(archive.archivedAt) + 1;527 if (change === "valid-alternate-metadata") {528 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([529 "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation, archive.archivedAt, archive.snapshotJson,530 ])));531 archive.completionSha256Hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");532 }533 }534 await set(copied);535 });536 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required");537 expect(area.remove).not.toHaveBeenCalled();538 });539540 it.each([null, {}, { schemaVersion: 1, generation: 1, pairedDevices: ["original"] }, "corrupt"])("preserves and refuses an existing unmarked archive %j", async (archive) => {541 const { stored, area } = storage();542 stored[ref] = archive;543 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required");544 expect(stored[ref]).toEqual(archive);545 expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0);546 expect(area.remove).not.toHaveBeenCalled();547 });548549 it("detects valid JSON payload edits when reusing an archive", async () => {550 const { stored, area } = storage();551 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);552 const archive = stored[ref] as { snapshotJson: string };553 const snapshot = JSON.parse(archive.snapshotJson);554 snapshot.pairedDevices = null;555 archive.snapshotJson = JSON.stringify(snapshot);556 const damaged = structuredClone(archive);557 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required");558 expect(stored[ref]).toEqual(damaged);559 expect(area.remove).not.toHaveBeenCalled();560 });561562 it.each(["read", "write"])("leaves trust intact after first archive %s failure and permits retry", async (failure) => {563 const { stored, area } = storage();564 const original = structuredClone(stored);565 if (failure === "read") {566 const get = area.get.getMockImplementation()!;567 area.get.mockImplementationOnce(async (keys) => {568 if (keys === ref) throw new Error("read failed");569 return get(keys);570 });571 } else area.set.mockRejectedValueOnce(new Error("write failed"));572 expect(await browserGenerationIo.archiveLegacyState(1)).toBeNull();573 expect(stored).toEqual(original);574 expect(area.remove).not.toHaveBeenCalled();575 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);576 });577578 it("keeps the original snapshot after a failed readback and later trust clearing", async () => {579 const { stored, area } = storage();580 const get = area.get.getMockImplementation()!;581 let archiveReads = 0;582 area.get.mockImplementation(async (keys) => {583 if (keys === ref && ++archiveReads === 2) throw new Error("readback failed");584 return get(keys);585 });586 expect(await browserGenerationIo.archiveLegacyState(1)).toBeNull();587 const original = structuredClone(stored[ref]);588 for (const key of trustKeys) delete stored[key];589 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);590 expect(stored[ref]).toEqual(original);591 expect(area.set).toHaveBeenCalledTimes(1);592 });593594 it.each(["missing", "extra", "array", "invalid-json"])("refuses a completed snapshot with %s fields", async (damage) => {595 const { stored, area } = storage();596 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);597 const archive = stored[ref] as {598 schemaVersion: number; generation: number; archivedAt: number; snapshotJson: string; completionSha256Hex: string;599 };600 const snapshot = JSON.parse(archive.snapshotJson);601 if (damage === "missing") delete snapshot.pairSecrets;602 if (damage === "extra") snapshot.extra = null;603 archive.snapshotJson = damage === "invalid-json" ? "{" : JSON.stringify(damage === "array" ? [] : snapshot);604 const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([605 "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation, archive.archivedAt, archive.snapshotJson,606 ])));607 archive.completionSha256Hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");608 const original = structuredClone(archive);609 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_archive_review_required");610 expect(stored[ref]).toEqual(original);611 expect(area.remove).not.toHaveBeenCalled();612 });613614 it.each([false, true])("reuses complete schema1 archives with cleared trust=%s without rewriting", async (cleared) => {615 const { stored, area } = storage();616 const fields = ["pairedDevices", "revocations", "revocationIssuers", "pendingHolder", "pendingIdentity", "pairSecrets"];617 const archive = { schemaVersion: 1, generation: 1, archivedAt: 123,618 ...Object.fromEntries(fields.map((field, index) => [field, structuredClone(stored[trustKeys[index]])])),619 };620 stored[ref] = structuredClone(archive);621 if (cleared) for (const key of trustKeys) delete stored[key];622 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR");623 expect(stored[ref]).toEqual(archive);624 expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0);625 });626627 it("reuses the complete pre-issuer schema1 shape without fabricating archive fields", async () => {628 const { stored, area } = storage();629 const archive = { schemaVersion: 1, generation: 1, archivedAt: 123,630 pairedDevices: stored[trustKeys[0]], revocations: stored[trustKeys[1]], pendingHolder: stored[trustKeys[3]],631 pendingIdentity: stored[trustKeys[4]], pairSecrets: stored[trustKeys[5]],632 };633 stored[ref] = structuredClone(archive);634 delete stored[trustKeys[2]];635 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR");636 expect(stored[ref]).toEqual(archive);637 expect(area.set.mock.calls.filter(([values]) => ref in values)).toHaveLength(0);638 });639640 it("blocks a retry that would clear trust added after a failed clear", async () => {641 const { stored, area } = storage();642 area.remove.mockRejectedValueOnce(new Error("clear failed"));643 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("reset_not_completed");644 const firstArchive = structuredClone(stored[ref]);645 stored[trustKeys[0]] = [{ deviceId: "new-peer" }];646 stored[trustKeys[5]] = { route: "new-route" };647 const changedTrust = structuredClone(stored);648 area.remove.mockClear();649 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 300 })).toBe("reset_archive_review_required");650 expect(area.remove).not.toHaveBeenCalled();651 for (const key of trustKeys) expect(stored[key]).toEqual(changedTrust[key]);652 expect(stored[ref]).toEqual(firstArchive);653 });654655 it("reuses equal nested trust despite object key order and normalized empty fields", async () => {656 const { stored } = storage();657 stored[trustKeys[0]] = [{ deviceId: "peer", metadata: { a: null, b: "value" } }];658 stored[trustKeys[3]] = null;659 stored[trustKeys[4]] = [];660 stored[trustKeys[5]] = {};661 expect(await browserGenerationIo.archiveLegacyState(1)).toBe(ref);662 stored[trustKeys[0]] = [{ metadata: { b: "value", a: null }, deviceId: "peer" }];663 delete stored[trustKeys[3]];664 stored[trustKeys[4]] = {};665 stored[trustKeys[5]] = [];666 expect(await confirmSecureReset(browserGenerationIo, { nowMs: 200 })).toBe("V2_ANCHOR");667 });668669 it("joins concurrent same-IO attempts and releases a rejected attempt for retry", async () => {670 const io = new FakeGenerationIo();671 io.pairedDevices = true;672 let release!: () => void;673 const blocked = new Promise<void>((resolve) => { release = resolve; });674 const archive = vi.spyOn(io, "archiveLegacyState").mockImplementationOnce(async () => {675 await blocked;676 throw new Error("archive failed");677 });678 const first = confirmSecureReset(io, { nowMs: 100 });679 const joined = confirmSecureReset(io, { nowMs: 101 });680 const results = Promise.allSettled([first, joined]);681 release();682 expect((await results).map((result) => result.status)).toEqual(["rejected", "rejected"]);683 expect(archive).toHaveBeenCalledTimes(1);684 expect(await confirmSecureReset(io, { nowMs: 200 })).toBe("V2_ANCHOR");685 expect(io.identityMints).toBe(1);686 });687688 it("joins successful concurrent production resets without a second clear or identity mint", async () => {689 const { area, stored, sessionStored } = storage();690 const ensureIdentity = vi.mocked(browserGenerationIo.ensureV2Identity);691 expect(await Promise.all([692 confirmSecureReset(browserGenerationIo, { nowMs: 200 }),693 confirmSecureReset(browserGenerationIo, { nowMs: 201 }),694 ])).toEqual(["V2_ANCHOR", "V2_ANCHOR"]);695 expect(area.remove.mock.calls.filter(([keys]) => Array.isArray(keys))).toHaveLength(1);696 expect(ensureIdentity).toHaveBeenCalledTimes(1);697 expect(sessionStored.peach_pair_secrets_session).toBeUndefined();698 expect(stored.peach_pair_secrets_session).toBeUndefined();699 });700});