897a841c69dc
wip: preserve reset archives pending protocol integration (v5.3.24)
- time
- 2026-11-22 02:07 UTC · 5 days ago
- machine
- Junes-MacBook-Pro.local
- agent
- gpt-6
- session
- remediate interim audit findings
- parent
- fe296aba12b8
↓ peach-browser-897a841c.tar.gzatlas at this save
files changed8 files
manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/messages.test.ts+19 −0src/background/messages.ts+7 −11src/background/sync-generation.test.ts+266 −3src/background/sync-generation.ts+133 −38src/popup/views/Settings.tsx+2 −2manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22 "manifest_version": 3,33 "name": "Peach Password Manager",4- "version": "5.3.22",4+ "version": "5.3.24",55 "description": "Zero-knowledge password manager",66 "browser_specific_settings": {77 "gecko": {manifest.json+1 −1
@@ -2,7 +2,7 @@22 "manifest_version": 3,33 "minimum_chrome_version": "116",44 "name": "Peach Password Manager",5- "version": "5.3.22",5+ "version": "5.3.24",66 "description": "Zero-knowledge password manager",77 "action": {88 "default_popup": "src/popup/index.html",package.json+1 −1
@@ -1,6 +1,6 @@11 {22 "name": "peach",3- "version": "5.3.22",3+ "version": "5.3.24",44 "description": "Zero-knowledge password manager",55 "license": "GPL-3.0-only",66 "type": "module",src/background/messages.test.ts+19 −0
@@ -2199,6 +2199,25 @@21992199 });22002200 expect(res).toMatchObject({ ok: false, error: "invalid_payload" });22012201 });2202+ it("SECURE_RESET reports archive review without clearing trust or a separate RESET_REQUIRED write", async () => {2203+ const vault = await import("./vault");2204+ await vault.createVault("correct-pass-12345");2205+ const archive = { schemaVersion: 1, generation: 1, pairedDevices: ["incomplete"] };2206+ storage.peach_sync_archive_g1_v1 = archive;2207+ storage.peach_sync_generation_v1 = JSON.stringify({ schemaVersion: 1, active: {2208+ schemaVersion: 1, generation: 1, state: "LEGACY_ACTIVE", createdAt: 100,2209+ } });2210+ const set = vi.mocked(chrome.storage.local.set);2211+ set.mockClear();2212+ const response = await dispatch({ type: "SECURE_RESET", payload: { password: "correct-pass-12345" } });2213+ expect(response).toEqual({ ok: false, error: "The saved Sync trust archive needs review before reset can continue. Peach has kept the archive and current trust unchanged. Contact Peach support before retrying." });2214+ expect(storage.peach_sync_archive_g1_v1).toEqual(archive);2215+ const states = set.mock.calls.flatMap(([values]) => {2216+ const raw = (values as StorageShape).peach_sync_generation_v1;2217+ return typeof raw === "string" ? [JSON.parse(raw).active.state] : [];2218+ });2219+ expect(states).toEqual(["RESET_CONFIRMED"]);2220+ });22022221 it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {22032222 const vault = await import("./vault");22042223 await vault.createVault("correct-pass-12345");src/background/messages.ts+7 −11
@@ -117,7 +117,6 @@117117 import {118118 browserGenerationIo,119119 confirmSecureReset,120- enterResetRequired,121120 resolveGeneration,122121 } from "./sync-generation";123122 import { isMessageSenderAllowed } from "./message-policy";@@ -1966,19 +1965,16 @@19661965 // Identity rotation needs the live vault root key. A password check is19671966 // deliberately verification-only, so establish the real session first19681967 // when Settings is opened after the vault session expired.1969- // Enter the blocking state before the reset steps: a crash after this1970- // point leaves the device refusing sync rather than mid-reset over live1971- // trust. Both are idempotent, so a retry is safe.1972- await enterResetRequired(browserGenerationIo);19731968 const result = await confirmSecureReset(browserGenerationIo, {19741969 nowMs: Date.now(),19751970 });1976- return result === "V2_ANCHOR"1977- ? { ok: true, data: await resolveGeneration(browserGenerationIo) }1978- : {1979- ok: false,1980- error: "The reset did not complete — nothing was lost, try again",1981- };1971+ if (result === "V2_ANCHOR") return { ok: true, data: await resolveGeneration(browserGenerationIo) };1972+ return {1973+ ok: false,1974+ error: result === "reset_archive_review_required"1975+ ? "The saved Sync trust archive needs review before reset can continue. Peach has kept the archive and current trust unchanged. Contact Peach support before retrying."1976+ : "The reset did not complete. Try again; if it still fails, contact Peach support.",1977+ };19821978 }19831979 19841980 case "GET_SYNC_SETTINGS": {src/background/sync-generation.test.ts+266 −3
@@ -1,7 +1,6 @@11 // The §11 secure-reset contract: the durable generation record, the six states,22 // create-on-miss refusal, archival by generation, crash recovery at every step,3-// and the sync gate. Runs entirely against an in-memory io — no Chrome, no4-// vault, no crypto.3+// and the sync gate. Storage is simulated; archive digests use native crypto.54 65 import { afterEach, describe, expect, it, vi } from "vitest";76 import {@@ -23,6 +22,7 @@2322 mintDecision,2423 onDirectV2PairingEstablished,2524 resolveGeneration,25+ GENERATION_KEY,2626 type ResetResult,2727 type SyncGeneration,2828 type SyncGenerationBlob,@@ -427,11 +427,274 @@427427 expect(await hasLegacyTrustState(browserGenerationIo)).toBe(true);428428 const ref = await browserGenerationIo.archiveLegacyState(1);429429 expect(ref).not.toBeNull();430- expect(stored[ref!] as { revocationIssuers: unknown }).toMatchObject({ revocationIssuers: archive });430+ expect(JSON.parse((stored[ref!] as { snapshotJson: string }).snapshotJson)).toMatchObject({ revocationIssuers: archive });431431 expect(await browserGenerationIo.clearLegacyTrustState()).toBe(false);432432 refuseRemoval = false;433433 expect(await browserGenerationIo.clearLegacyTrustState()).toBe(true);434434 expect(stored[REVOCATION_ISSUERS_KEY]).toBeUndefined();435435 expect(await hasLegacyTrustState(browserGenerationIo)).toBe(false);436+ });437+});438+439+440+describe("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+ ];446+447+ 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+ }479+480+ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });481+482+ 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+ });499+500+ 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+ });516+517+ 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+ });539+540+ 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+ });548+549+ 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+ });561+562+ 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+ });577+578+ 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+ });593+594+ 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+ });613+614+ 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+ });626+627+ 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+ });639+640+ 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+ });654+655+ 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+ });668+669+ 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+ });687+688+ 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();436699 });437700 });src/background/sync-generation.ts+133 −38
@@ -66,8 +66,10 @@6666 6767 export type SyncDecision = "allowed" | "reset_required" | "sync_generation_unknown";6868 69-export type ResetResult = "V2_ANCHOR" | "reset_not_completed";69+export type ResetResult = "V2_ANCHOR" | "reset_not_completed" | "reset_archive_review_required";7070 71+class ResetArchiveReviewRequiredError extends Error {}72+7173 /**7274 * The storage boundary. The trust probe is split per class so a test can assert7375 * the refusal for each one, and archival and clearing are separate steps so a@@ -183,6 +185,8 @@183185 return next;184186 }185187 188+const resetAttempts = new WeakMap<SyncGenerationIo, Promise<ResetResult>>();189+186190 /**187191 * Archive the legacy generation, mint the v2 identity, then flip the pointer —188192 * in that order, so every crash point leaves either a recoverable@@ -192,10 +196,24 @@192196 * immediately before each step that can fail; a test throws from it to inject a193197 * crash at exactly that point.194198 */195-export async function confirmSecureReset(199+export function confirmSecureReset(196200 io: SyncGenerationIo,197201 opts: { nowMs: number; checkpoint?: (name: string) => void },198202 ): Promise<ResetResult> {203+ const current = resetAttempts.get(io);204+ if (current) return current;205+ const attempt = runSecureReset(io, opts).then(206+ (result) => { resetAttempts.delete(io); return result; },207+ (error: unknown) => { resetAttempts.delete(io); throw error; },208+ );209+ resetAttempts.set(io, attempt);210+ return attempt;211+}212+213+async function runSecureReset(214+ io: SyncGenerationIo,215+ opts: { nowMs: number; checkpoint?: (name: string) => void },216+): Promise<ResetResult> {199217 const { nowMs } = opts;200218 const checkpoint = opts.checkpoint ?? (() => {});201219 const current = await resolveGeneration(io, nowMs);@@ -214,7 +232,13 @@214232 if (!(await persist({ ...current, state: RESET_CONFIRMED }))) return "reset_not_completed";215233 216234 checkpoint("before-archive");217- const archiveRef = await io.archiveLegacyState(current.generation);235+ let archiveRef: string | null;236+ try {237+ archiveRef = await io.archiveLegacyState(current.generation);238+ } catch (error) {239+ if (error instanceof ResetArchiveReviewRequiredError) return "reset_archive_review_required";240+ throw error;241+ }218242 if (!archiveRef) return "reset_not_completed";219243 checkpoint("after-archive");220244 @@ -315,6 +339,84 @@315339 return !value || typeof value !== "object" || Object.keys(value as object).length === 0;316340 }317341 342+const RESET_SNAPSHOT_FIELDS = [343+ ["pairedDevices", REGISTRY_KEY],344+ ["revocations", REVOCATIONS_KEY],345+ ["revocationIssuers", REVOCATION_ISSUERS_KEY],346+ ["pendingHolder", PENDING_ADOPTION_HOLDER_KEY],347+ ["pendingIdentity", PENDING_ADOPTION_IDENTITY_KEY],348+ ["pairSecrets", PAIR_SECRETS_KEY],349+] as const;350+351+type ResetArchive = {352+ schemaVersion: 2;353+ generation: number;354+ archivedAt: number;355+ snapshotJson: string;356+ completionSha256Hex: string;357+};358+359+async function resetArchiveDigest(archive: ResetArchive): Promise<string> {360+ const bytes = new TextEncoder().encode(JSON.stringify([361+ "peach.sync-reset-archive.v2", archive.schemaVersion, archive.generation,362+ archive.archivedAt, archive.snapshotJson,363+ ]));364+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));365+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");366+}367+368+function exactObjectKeys(value: unknown, keys: readonly string[]): value is Record<string, unknown> {369+ return value !== null && typeof value === "object" && !Array.isArray(value) &&370+ Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));371+}372+373+async function validResetArchive(value: unknown, generation: number): Promise<boolean> {374+ if (!exactObjectKeys(value, ["schemaVersion", "generation", "archivedAt", "snapshotJson", "completionSha256Hex"]) ||375+ value.schemaVersion !== 2 || value.generation !== generation ||376+ !Number.isSafeInteger(value.generation) || generation < 1 ||377+ typeof value.archivedAt !== "number" || !Number.isSafeInteger(value.archivedAt) || value.archivedAt < 0 ||378+ typeof value.snapshotJson !== "string" || typeof value.completionSha256Hex !== "string" ||379+ !/^[0-9a-f]{64}$/.test(value.completionSha256Hex)) return false;380+ let snapshot: unknown;381+ try { snapshot = JSON.parse(value.snapshotJson); } catch { return false; }382+ if (!exactObjectKeys(snapshot, RESET_SNAPSHOT_FIELDS.map(([field]) => field))) return false;383+ return await resetArchiveDigest(value as ResetArchive) === value.completionSha256Hex;384+}385+386+function resetSnapshot(stored: Record<string, unknown>): Record<string, unknown> {387+ return Object.fromEntries(RESET_SNAPSHOT_FIELDS.map(([field, key]) => [field, stored[key] ?? null]));388+}389+390+function emptyTrust(value: unknown): boolean {391+ return value === null || value === undefined ||392+ (typeof value === "object" && Object.keys(value).length === 0);393+}394+395+function equalSnapshotValue(left: unknown, right: unknown): boolean {396+ if (left === right) return true;397+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;398+ if (Array.isArray(left) || Array.isArray(right)) {399+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length &&400+ left.every((value, index) => equalSnapshotValue(value, right[index]));401+ }402+ const keys = Object.keys(left);403+ return exactObjectKeys(right, keys) && keys.every((key) =>404+ equalSnapshotValue((left as Record<string, unknown>)[key], right[key]),405+ );406+}407+408+async function archivedResetSnapshot(value: unknown, generation: number): Promise<Record<string, unknown> | null> {409+ if (await validResetArchive(value, generation)) return JSON.parse((value as ResetArchive).snapshotJson);410+ const fields = RESET_SNAPSHOT_FIELDS.map(([field]) => field);411+ const legacyKeys = ["schemaVersion", "generation", "archivedAt", ...fields];412+ const preIssuerKeys = legacyKeys.filter((field) => field !== "revocationIssuers");413+ if ((!exactObjectKeys(value, legacyKeys) && !exactObjectKeys(value, preIssuerKeys)) ||414+ value.schemaVersion !== 1 || value.generation !== generation || !Number.isSafeInteger(generation) || generation < 1 ||415+ typeof value.archivedAt !== "number" || !Number.isSafeInteger(value.archivedAt) || value.archivedAt < 0) return null;416+ // Old builds wrote one complete object but provided no content digest.417+ return Object.fromEntries(fields.map((field) => [field, value[field] ?? null]));418+}419+318420 export const browserGenerationIo: SyncGenerationIo = {319421 async readBlob() {320422 return (await chrome.storage.local.get(GENERATION_KEY))[GENERATION_KEY];@@ -359,48 +461,41 @@359461 return !emptyRecord((await chrome.storage.local.get(PAIR_SECRETS_KEY))[PAIR_SECRETS_KEY]);360462 },361463 362- /**363- * Copy the legacy trust material verbatim into an archive tagged with its364- * generation. The registry, the ledger and the pair secrets are exactly what365- * §11.4 retains; the generation is tagged both in the key and in the record,366- * so a rollback build can tell which generation it is looking at.367- */464+ /// Preserve the first complete snapshot for this generation; older builds cannot safely resume it.368465 async archiveLegacyState(generation) {369466 const ref = `peach_sync_archive_g${generation}_v1`;370467 try {371- const stored = await chrome.storage.local.get([372- REGISTRY_KEY,373- REVOCATIONS_KEY,374- REVOCATION_ISSUERS_KEY,375- PENDING_ADOPTION_HOLDER_KEY,376- PENDING_ADOPTION_IDENTITY_KEY,377- PAIR_SECRETS_KEY,378- ]);379- const archive = {380- schemaVersion: 1,468+ const existing = (await chrome.storage.local.get(ref))[ref];469+ if (existing !== undefined) {470+ const snapshot = await archivedResetSnapshot(existing, generation);471+ if (!snapshot) throw new ResetArchiveReviewRequiredError();472+ const live = resetSnapshot(await chrome.storage.local.get(RESET_SNAPSHOT_FIELDS.map(([, key]) => key)));473+ const fields = RESET_SNAPSHOT_FIELDS.map(([field]) => field);474+ const cleared = fields.every((field) => emptyTrust(live[field]));475+ const unchanged = fields.every((field) =>476+ (emptyTrust(live[field]) && emptyTrust(snapshot[field])) || equalSnapshotValue(live[field], snapshot[field]),477+ );478+ if (!cleared && !unchanged) throw new ResetArchiveReviewRequiredError();479+ return ref;480+ }481+ const stored = await chrome.storage.local.get(RESET_SNAPSHOT_FIELDS.map(([, key]) => key));482+ const snapshotJson = JSON.stringify(resetSnapshot(stored));483+ const archive: ResetArchive = {484+ schemaVersion: 2,381485 generation,382486 archivedAt: Date.now(),383- pairedDevices: stored[REGISTRY_KEY] ?? null,384- revocations: stored[REVOCATIONS_KEY] ?? null,385- revocationIssuers: stored[REVOCATION_ISSUERS_KEY] ?? null,386- pendingHolder: stored[PENDING_ADOPTION_HOLDER_KEY] ?? null,387- pendingIdentity: stored[PENDING_ADOPTION_IDENTITY_KEY] ?? null,388- pairSecrets: stored[PAIR_SECRETS_KEY] ?? null,487+ snapshotJson,488+ completionSha256Hex: "",389489 };490+ archive.completionSha256Hex = await resetArchiveDigest(archive);390491 await chrome.storage.local.set({ [ref]: archive });391- // Read back to prove the archive is durable, but compare the fields that392- // identify this write. Chrome re-encodes stored objects and does not393- // return their keys in insertion order, so comparing the serialized text394- // never matches on a real device — it failed every reset while the395- // archive had in fact been written.396- const written = (await chrome.storage.local.get(ref))[ref] as typeof archive | undefined;397- if (!written) return null;398- return written.schemaVersion === archive.schemaVersion &&399- written.generation === archive.generation &&400- written.archivedAt === archive.archivedAt401- ? ref402- : null;403- } catch {492+ const written: unknown = (await chrome.storage.local.get(ref))[ref];493+ if (!(await validResetArchive(written, generation)) || !Object.keys(archive).every((key) =>494+ (written as ResetArchive)[key as keyof ResetArchive] === archive[key as keyof ResetArchive],495+ )) throw new ResetArchiveReviewRequiredError();496+ return ref;497+ } catch (error) {498+ if (error instanceof ResetArchiveReviewRequiredError) throw error;404499 return null;405500 }406501 },src/popup/views/Settings.tsx+2 −2
@@ -168,7 +168,7 @@168168 case "RESET_REQUIRED":169169 return "Sync is stopped until the reset completes. Update Peach on every other device, then reset this one and re-pair each device.";170170 case "RESET_CONFIRMED":171- return "The reset did not finish. Nothing was lost — the old trust is archived. Try again.";171+ return "The reset did not finish, so Sync is paused. If Peach reports an archive problem, contact Peach support before retrying.";172172 case "V2_ANCHOR":173173 case "REPAIRING":174174 return "This device anchors the new Sync generation and is not re-paired yet. Pair each device again; until then it keeps its own vault and cannot sync.";@@ -363,7 +363,7 @@363363 setResetting(false);364364 setResetPassword("");365365 if (!r.ok) {366- setResetError(r.error ?? "The reset did not complete — nothing was lost, try again");366+ setResetError(r.error ?? "The reset did not complete. Check the error before retrying.");367367 await loadGeneration();368368 return;369369 }