09f15de8221f

persist manual-summon recall in encrypted vault state (v5.3.29)

time
2026-11-22 22:55 UTC · 5 days ago
machine
Junes-MacBook-Pro.local
agent
gpt-5.6-sol
session
remediate interim audit findings
parent
42639fcaf96f
7 files manifest.firefox.json+1 −1manifest.json+1 −1package.json+1 −1src/background/messages.manual-summon-recall.test.ts+1038 −0src/background/messages.test.ts+2 −0src/background/messages.ts+8 −15src/background/vault.ts+429 −7
manifest.firefox.json+1 −1
@@ -1,7 +1,7 @@11 {22   "manifest_version": 3,33   "name": "Peach Password Manager",4-  "version": "5.3.28",4+  "version": "5.3.29",55   "description": "Zero-knowledge password manager",66   "browser_specific_settings": {77     "gecko": {

view file

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.28",5+  "version": "5.3.29",66   "description": "Zero-knowledge password manager",77   "action": {88     "default_popup": "src/popup/index.html",

view file

package.json+1 −1
@@ -1,6 +1,6 @@11 {22   "name": "peach",3-  "version": "5.3.28",3+  "version": "5.3.29",44   "description": "Zero-knowledge password manager",55   "license": "GPL-3.0-only",66   "type": "module",

view file

src/background/messages.manual-summon-recall.test.ts+1038 −0
@@ -0,0 +1,1038 @@1+/**2+ * PB-26-952: manual-summon recall must survive a settings reload and a cold3+ * service-worker restart, and must not sit in plaintext or leak between the4+ * real and decoy vaults.5+ *6+ * These tests drive the owning boundary: RECORD_MANUAL_SUMMON in, GET_SETTINGS7+ * out. Nothing here asserts against vault.ts internals except the storage key8+ * the design fixes.9+ */10+11+import { beforeEach, describe, expect, it, vi } from "vitest";12+13+import type { Message, MessageResponse, ManualSummonRecord } from "../shared/types";14+import { decrypt } from "./aes";15+16+type StorageShape = Record<string, unknown>;17+type MessageListener = (18+  msg: unknown,19+  sender: chrome.runtime.MessageSender,20+  sendResponse: (response: MessageResponse) => void,21+) => boolean;22+23+const RECALL_KEY = "peach_manual_summon_recall_v1";24+const SLOT_A = "peach_vault_a";25+const SLOT_B = "peach_vault_b";26+const SETTINGS_KEY = "peach_settings";27+const RECALL_REAL_AAD = "manual_summon_recall_v1";28+const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";29+const PASSWORD = "correct-pass-12345";30+const DURESS_PASSWORD = "duress-pass-98765";31+32+const EXTENSION_SENDER = {33+  id: "peach-extension",34+  url: "chrome-extension://peach-extension/popup.html",35+} as chrome.runtime.MessageSender;36+37+function pageSender(origin: string): chrome.runtime.MessageSender {38+  return {39+    id: "peach-extension",40+    url: `${origin}/login`,41+    origin,42+    tab: { id: 1 },43+    frameId: 0,44+  } as chrome.runtime.MessageSender;45+}46+47+function deferred(): { promise: Promise<void>; resolve: () => void } {48+  let resolve!: () => void;49+  const promise = new Promise<void>((done) => {50+    resolve = done;51+  });52+  return { promise, resolve };53+}54+55+function ownRecord(response: MessageResponse, domain: string): ManualSummonRecord | undefined {56+  const data = response.data as57+    | { manualSummonDomains?: Record<string, ManualSummonRecord> }58+    | undefined;59+  return data?.manualSummonDomains?.[domain];60+}61+62+describe("PB-26-952: encrypted manual-summon recall", () => {63+  let storage: StorageShape;64+  let sessionStorage: StorageShape;65+  let listener: MessageListener;66+  let recallWriteHook: ((next: StorageShape) => Promise<void>) | null = null;67+  /** Fires before a read that includes the recall key; used to hold a write. */68+  let recallReadHook: (() => Promise<void>) | null = null;69+  /** Fires before a read of peach_settings; used to hold an unlock in flight. */70+  let settingsReadHook: (() => Promise<void>) | null = null;71+  /** Fires during a vault slot write, before the write reaches storage. */72+  let slotWriteHook: ((slot: string) => void) | null = null;73+74+  /** Chrome drops `undefined` properties on write; mirror that here. */75+  function chromeStore(value: unknown): unknown {76+    if (Array.isArray(value)) return value.map(chromeStore);77+    if (value && typeof value === "object") {78+      const out: StorageShape = {};79+      for (const [key, nested] of Object.entries(value as StorageShape)) {80+        if (nested === undefined) continue;81+        out[key] = chromeStore(nested);82+      }83+      return out;84+    }85+    return value;86+  }87+88+  function storeWrite(target: StorageShape, next: StorageShape): void {89+    for (const [key, value] of Object.entries(next)) {90+      if (value === undefined) continue;91+      target[key] = chromeStore(value);92+    }93+  }94+95+  /**96+   * Hold the next WebCrypto decrypt. `decrypt` imports the key before awaiting,97+   * so a held decrypt still succeeds after the key is zeroed or replaced.98+   */99+  function holdNextDecrypt(): { started: Promise<void>; release: () => void } {100+    const started = deferred();101+    const release = deferred();102+    const realDecrypt = crypto.subtle.decrypt.bind(crypto.subtle);103+    let hold = true;104+    vi.spyOn(crypto.subtle, "decrypt").mockImplementation(async (algorithm, key, data) => {105+      if (!hold) return realDecrypt(algorithm, key, data);106+      hold = false;107+      started.resolve();108+      await release.promise;109+      return realDecrypt(algorithm, key, data);110+    });111+    return { started: started.promise, release: release.resolve };112+  }113+114+  function readsKey(key: string | string[] | undefined, target: string): boolean {115+    if (!key) return false;116+    return Array.isArray(key) ? key.includes(target) : key === target;117+  }118+119+  /**120+   * True when the member cannot be opened with 32 zero bytes. A recall write121+   * that is sealed after its key was zeroed in place passes this check the122+   * wrong way, so every stored member must reject the zero key.123+   */124+  async function opensUnderZeroKey(member: unknown): Promise<boolean> {125+    const sealed = member as { nonce: string; ciphertext: string; tag: string };126+    try {127+      await decrypt(128+        new Uint8Array(32),129+        sealed.nonce,130+        sealed.ciphertext,131+        sealed.tag,132+        RECALL_REAL_AAD,133+      );134+      return true;135+    } catch {136+      return false;137+    }138+  }139+140+  beforeEach(() => {141+    vi.restoreAllMocks();142+    vi.resetModules();143+    vi.useRealTimers();144+    storage = {};145+    sessionStorage = {};146+    recallWriteHook = null;147+    recallReadHook = null;148+    settingsReadHook = null;149+    slotWriteHook = null;150+    vi.stubGlobal("fetch", vi.fn(async () => {151+      throw new Error("network disabled in tests");152+    }));153+    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);154+155+    const chromeMock = {156+      runtime: {157+        id: "peach-extension",158+        getURL: (path: string) => `chrome-extension://peach-extension/${path}`,159+        onMessage: {160+          addListener: vi.fn((fn: MessageListener) => {161+            listener = fn;162+          }),163+        },164+        sendMessage: vi.fn(async () => ({ ok: true })),165+      },166+      tabs: {167+        query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {168+          if (typeof callback === "function") {169+            callback([{ id: 1 }]);170+            return;171+          }172+          return Promise.resolve([{ id: 1 }]);173+        }),174+        sendMessage: vi.fn(async () => ({ ok: true })),175+      },176+      storage: {177+        local: {178+          get: vi.fn(async (key?: string | string[]) => {179+            if (readsKey(key, RECALL_KEY) && recallReadHook) await recallReadHook();180+            if (readsKey(key, SETTINGS_KEY) && settingsReadHook) await settingsReadHook();181+            if (!key) return storage;182+            if (typeof key === "string") return { [key]: storage[key] };183+            return key.reduce<Record<string, unknown>>((result, entry) => {184+              result[entry] = storage[entry];185+              return result;186+            }, {});187+          }),188+          set: vi.fn(async (next: Record<string, unknown>) => {189+            if (slotWriteHook) {190+              for (const slot of [SLOT_A, SLOT_B]) {191+                if (slot in next) slotWriteHook(slot);192+              }193+            }194+            if (recallWriteHook && RECALL_KEY in next) await recallWriteHook(next);195+            storeWrite(storage, next);196+          }),197+          remove: vi.fn(async (keys: string | string[]) => {198+            for (const key of Array.isArray(keys) ? keys : [keys]) delete storage[key];199+          }),200+          clear: vi.fn(async () => {201+            for (const key of Object.keys(storage)) delete storage[key];202+          }),203+        },204+        session: {205+          get: vi.fn(async (key?: string | string[]) => {206+            if (!key) return sessionStorage;207+            if (typeof key === "string") return { [key]: sessionStorage[key] };208+            return key.reduce<Record<string, unknown>>((result, entry) => {209+              result[entry] = sessionStorage[entry];210+              return result;211+            }, {});212+          }),213+          set: vi.fn(async (next: Record<string, unknown>) => {214+            storeWrite(sessionStorage, next);215+          }),216+          remove: vi.fn(async (keys: string | string[]) => {217+            for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];218+          }),219+          clear: vi.fn(async () => {220+            for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];221+          }),222+        },223+      },224+      alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } },225+      idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },226+      scripting: { executeScript: vi.fn(async () => []) },227+    } as unknown as typeof chrome;228+229+    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;230+  });231+232+  async function setup() {233+    const messages = await import("./messages");234+    messages.setupMessageHandler();235+    const vault = await import("./vault");236+    await vault.ensureSettingsLoaded();237+    return vault;238+  }239+240+  async function dispatch(241+    message: Message,242+    sender: chrome.runtime.MessageSender = EXTENSION_SENDER,243+  ): Promise<MessageResponse> {244+    return await new Promise<MessageResponse>((resolve) => {245+      const keepChannelOpen = listener(message, sender, (response) => resolve(response));246+      expect(keepChannelOpen).toBe(true);247+    });248+  }249+250+  async function createUnlockedVault(password = PASSWORD): Promise<void> {251+    await expect(dispatch({ type: "CREATE_VAULT", payload: { password } })).resolves.toMatchObject({252+      ok: true,253+    });254+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });255+    await expect(dispatch({ type: "UNLOCK", payload: { password } })).resolves.toMatchObject({256+      ok: true,257+    });258+  }259+260+  /** Simulate an MV3 worker restart: fresh module state over the same storage. */261+  async function coldStart(): Promise<typeof import("./vault") | null> {262+    await Promise.resolve();263+    vi.resetModules();264+    const messages = await import("./messages");265+    const vault = await import("./vault");266+    const restored = await vault.restoreFromSession();267+    messages.setupMessageHandler();268+    return restored ? vault : null;269+  }270+271+  it("keeps two summon records across settings loads and a cold restart", async () => {272+    await setup();273+    await createUnlockedVault();274+275+    await expect(dispatch(276+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },277+      pageSender("https://login.example.com"),278+    )).resolves.toEqual({ ok: true });279+    await expect(dispatch(280+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "other.example" } },281+      pageSender("https://other.example"),282+    )).resolves.toEqual({ ok: true });283+284+    // An ordinary settings read reloads peach_settings from disk.285+    const first = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));286+    expect(ownRecord(first, "example.com")).toEqual({287+      firstSummonedAt: expect.any(Number),288+      summonCount: 1,289+      lastSummonedAt: expect.any(Number),290+    });291+    expect(ownRecord(first, "other.example")).toBeUndefined();292+293+    // The lazy content script asks again; nothing may be cleared by the reload.294+    await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({ ok: true });295+296+    expect(await coldStart()).not.toBeNull();297+298+    for (const [domain, origin] of [299+      ["example.com", "https://login.example.com"],300+      ["other.example", "https://other.example"],301+    ] as const) {302+      const response = await dispatch({ type: "GET_SETTINGS" }, pageSender(origin));303+      const record = ownRecord(response, domain);304+      expect(record).toBeDefined();305+      // Aggression is derived from this count; zero is the PB-26-952 bug.306+      expect(record?.summonCount).toBeGreaterThan(0);307+    }308+    // No plaintext domain ledger survives in peach_settings.309+    expect(storage.peach_settings).not.toHaveProperty("manualSummonDomains");310+    expect(storage.peach_settings).not.toHaveProperty("manualSummonSalt");311+  });312+313+  it("rejects a write while locked", async () => {314+    await setup();315+    await createUnlockedVault();316+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });317+318+    await expect(dispatch(319+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },320+      pageSender("https://login.example.com"),321+    )).resolves.toEqual({ ok: false, error: "vault_locked" });322+    expect(storage[RECALL_KEY]).toBeUndefined();323+  });324+325+  it("keeps real and decoy recall isolated in both directions", async () => {326+    const vault = await setup();327+    await expect(dispatch({ type: "CREATE_VAULT", payload: { password: PASSWORD } })).resolves.toMatchObject({ ok: true });328+    await vault.setupDuress(DURESS_PASSWORD);329+330+    await expect(dispatch(331+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },332+      pageSender("https://real-site.com"),333+    )).resolves.toEqual({ ok: true });334+    const stored = storage[RECALL_KEY] as { real?: unknown; decoy?: unknown };335+    expect(stored.real).toBeDefined();336+    expect(stored.decoy).toBeUndefined();337+    const realMember = structuredClone(stored.real);338+339+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });340+    await expect(dispatch({ type: "UNLOCK", payload: { password: DURESS_PASSWORD } })).resolves.toMatchObject({ ok: true });341+342+    // The decoy session must not see the real vault's recall.343+    const decoyLookalike = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://real-site.com"));344+    expect(ownRecord(decoyLookalike, "real-site.com")).toBeUndefined();345+346+    await expect(dispatch(347+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "decoy-site.com" } },348+      pageSender("https://decoy-site.com"),349+    )).resolves.toEqual({ ok: true });350+    const afterDecoyWrite = storage[RECALL_KEY] as { real?: unknown; decoy?: unknown };351+    // Writing the decoy member leaves the real ciphertext byte-identical.352+    expect(afterDecoyWrite.real).toEqual(realMember);353+    expect(afterDecoyWrite.decoy).toBeDefined();354+    const decoyMember = structuredClone(afterDecoyWrite.decoy);355+356+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });357+    await expect(dispatch({ type: "UNLOCK", payload: { password: PASSWORD } })).resolves.toMatchObject({ ok: true });358+359+    const realOwn = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://real-site.com"));360+    expect(ownRecord(realOwn, "real-site.com")).toMatchObject({ summonCount: 1 });361+    const realLookalike = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://decoy-site.com"));362+    expect(ownRecord(realLookalike, "decoy-site.com")).toBeUndefined();363+364+    await expect(dispatch(365+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },366+      pageSender("https://real-site.com"),367+    )).resolves.toEqual({ ok: true });368+    // Writing the real member leaves the decoy ciphertext byte-identical.369+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toEqual(decoyMember);370+  });371+372+  it("clears recall when the vault is destroyed", async () => {373+    await setup();374+    await createUnlockedVault();375+    await dispatch(376+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },377+      pageSender("https://login.example.com"),378+    );379+    expect(storage[RECALL_KEY]).toBeDefined();380+381+    await expect(dispatch({ type: "DESTROY_VAULT" })).resolves.toMatchObject({ ok: true });382+383+    expect(storage[RECALL_KEY]).toBeUndefined();384+    const after = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));385+    expect(ownRecord(after, "example.com")).toBeUndefined();386+  });387+388+  it("rolls back the in-memory record when persistence fails", async () => {389+    await setup();390+    await createUnlockedVault();391+    await expect(dispatch(392+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "kept.com" } },393+      pageSender("https://kept.com"),394+    )).resolves.toEqual({ ok: true });395+    const storedBefore = structuredClone(storage[RECALL_KEY]);396+397+    recallWriteHook = async () => {398+      throw new Error("storage unavailable");399+    };400+    const failed = await dispatch(401+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "dropped.com" } },402+      pageSender("https://dropped.com"),403+    );404+    expect(failed.ok).toBe(false);405+    recallWriteHook = null;406+407+    expect(storage[RECALL_KEY]).toEqual(storedBefore);408+    const kept = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://kept.com"));409+    expect(ownRecord(kept, "kept.com")).toMatchObject({ summonCount: 1 });410+    const dropped = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://dropped.com"));411+    expect(ownRecord(dropped, "dropped.com")).toBeUndefined();412+  });413+414+  it("reports success for a write committed before a lock and publishes nothing after it", async () => {415+    await setup();416+    await createUnlockedVault();417+418+    const started = deferred();419+    const release = deferred();420+    recallWriteHook = async () => {421+      started.resolve();422+      await release.promise;423+    };424+    const pending = dispatch(425+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },426+      pageSender("https://login.example.com"),427+    );428+    await started.promise;429+430+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });431+    release.resolve();432+    recallWriteHook = null;433+434+    // The ciphertext is already committed, so the summon must not report a435+    // failure the user would retry; it must also publish nothing to the locked436+    // session.437+    await expect(pending).resolves.toEqual({ ok: true });438+    expect(storage[RECALL_KEY]).toBeDefined();439+    const afterLock = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));440+    expect(ownRecord(afterLock, "example.com")).toBeUndefined();441+442+    await expect(dispatch({ type: "UNLOCK", payload: { password: PASSWORD } })).resolves.toMatchObject({ ok: true });443+    const reopened = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));444+    expect(ownRecord(reopened, "example.com")).toMatchObject({ summonCount: 1 });445+  });446+447+  it("stops a write that crossed a lock before encrypt and leaves storage untouched", async () => {448+    await setup();449+    await createUnlockedVault();450+    await dispatch(451+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "kept.com" } },452+      pageSender("https://kept.com"),453+    );454+    const storedBefore = structuredClone(storage[RECALL_KEY]);455+456+    const started = deferred();457+    const release = deferred();458+    recallReadHook = async () => {459+      recallReadHook = null;460+      started.resolve();461+      await release.promise;462+    };463+    const pending = dispatch(464+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "crossed.com" } },465+      pageSender("https://crossed.com"),466+    );467+    await started.promise;468+469+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });470+    release.resolve();471+472+    await expect(pending).resolves.toEqual({ ok: false, error: "vault_locked" });473+    expect(storage[RECALL_KEY]).toEqual(storedBefore);474+  });475+476+  it("publishes no record when the lock lands during the recall decrypt", async () => {477+    await setup();478+    await createUnlockedVault();479+    await dispatch(480+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "kept.com" } },481+      pageSender("https://kept.com"),482+    );483+    const storedBefore = structuredClone(storage[RECALL_KEY]);484+485+    const decryptHold = holdNextDecrypt();486+    const pending = dispatch(487+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "crossed.com" } },488+      pageSender("https://crossed.com"),489+    );490+    await decryptHold.started;491+492+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });493+    decryptHold.release();494+495+    await expect(pending).resolves.toEqual({ ok: false, error: "vault_locked" });496+    // A late assignment would republish the real records while locked.497+    const afterLock = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://kept.com"));498+    expect(ownRecord(afterLock, "kept.com")).toBeUndefined();499+    expect(storage[RECALL_KEY]).toEqual(storedBefore);500+  });501+502+  it("re-keys a deferred record when the root key rotates without a zero-key window", async () => {503+    await setup();504+    await createUnlockedVault();505+506+    const started = deferred();507+    const release = deferred();508+    recallReadHook = async () => {509+      recallReadHook = null;510+      started.resolve();511+      await release.promise;512+    };513+    const sealed: unknown[] = [];514+    recallWriteHook = async (next) => {515+      const member = (next[RECALL_KEY] as { real?: unknown } | undefined)?.real;516+      if (member) sealed.push(structuredClone(member));517+    };518+519+    const pending = dispatch(520+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },521+      pageSender("https://login.example.com"),522+    );523+    await started.promise;524+525+    // Let rotation reach its in-memory swap while the write is still queued, so526+    // any zeroing of the live root happens before this write encrypts.527+    const rotatedPastSlotA = deferred();528+    slotWriteHook = (slot) => {529+      if (slot !== SLOT_A) return;530+      slotWriteHook = null;531+      setTimeout(() => rotatedPastSlotA.resolve(), 0);532+    };533+    const rotation = dispatch({534+      type: "ROTATE_SYNC_IDENTITY",535+      payload: { password: PASSWORD },536+    });537+    await rotatedPastSlotA.promise;538+    release.resolve();539+540+    await expect(pending).resolves.toEqual({ ok: true });541+    await expect(rotation).resolves.toMatchObject({ ok: true });542+    recallWriteHook = null;543+544+    // No member may ever be sealed under an all-zero key, even transiently.545+    expect(sealed.length).toBeGreaterThan(0);546+    for (const member of sealed) {547+      await expect(opensUnderZeroKey(member)).resolves.toBe(false);548+    }549+550+    // The retired root can no longer open the member; restoring the session551+    // derives the new root and must still find the deferred record.552+    expect(await coldStart()).not.toBeNull();553+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));554+    expect(ownRecord(response, "example.com")).toMatchObject({ summonCount: 1 });555+  });556+557+  it("keeps recall across a master password change", async () => {558+    await setup();559+    await createUnlockedVault();560+    await dispatch(561+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "example.com" } },562+      pageSender("https://login.example.com"),563+    );564+565+    await expect(dispatch({566+      type: "CHANGE_PASSWORD",567+      payload: { currentPassword: PASSWORD, newPassword: "rotated-pass-67890" },568+    })).resolves.toMatchObject({ ok: true });569+570+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));571+    expect(ownRecord(response, "example.com")).toMatchObject({ summonCount: 1 });572+573+    expect(await coldStart()).not.toBeNull();574+    const afterRestart = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://login.example.com"));575+    expect(ownRecord(afterRestart, "example.com")).toMatchObject({ summonCount: 1 });576+  });577+578+  it("reloads recall after a PIN unlock", async () => {579+    await setup();580+    await createUnlockedVault();581+    await expect(dispatch({582+      type: "SETUP_PIN",583+      payload: { currentPassword: PASSWORD, pin: "4816" },584+    })).resolves.toMatchObject({ ok: true });585+    await dispatch(586+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "pin.com" } },587+      pageSender("https://pin.com"),588+    );589+590+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });591+    await expect(dispatch({592+      type: "UNLOCK_WITH_PIN",593+      payload: { pin: "4816" },594+    })).resolves.toMatchObject({ ok: true });595+596+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://pin.com"));597+    expect(ownRecord(response, "pin.com")).toMatchObject({ summonCount: 1 });598+  });599+600+  it("reloads recall after a Codex restore", async () => {601+    const vault = await setup();602+    await createUnlockedVault();603+    await dispatch(604+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "codex.com" } },605+      pageSender("https://codex.com"),606+    );607+608+    await expect(vault.unlockFromCodex({609+      slotA: JSON.stringify(storage[SLOT_A]),610+      slotB: JSON.stringify(storage[SLOT_B]),611+      timestamp: Date.now(),612+      masterPassphrase: PASSWORD,613+    })).resolves.toMatchObject({ ok: true });614+615+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://codex.com"));616+    expect(ownRecord(response, "codex.com")).toMatchObject({ summonCount: 1 });617+  });618+619+  it("reloads recall after word recovery", async () => {620+    const vault = await setup();621+    await createUnlockedVault();622+    await dispatch(623+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "recovered.com" } },624+      pageSender("https://recovered.com"),625+    );626+    const words = await vault.getRecoveryWords();627+628+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });629+    await expect(dispatch({630+      type: "RECOVER_WITH_WORDS",631+      payload: { words, newPassword: "recovered-pass-123" },632+    })).resolves.toMatchObject({ ok: true });633+634+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://recovered.com"));635+    expect(ownRecord(response, "recovered.com")).toMatchObject({ summonCount: 1 });636+  });637+638+  it("clears a member that another root sealed when an adopted vault replaces it", async () => {639+    await setup();640+    // A member from any earlier vault is unreadable under the adopted root, so641+    // creation must remove it rather than leave it behind.642+    storage[RECALL_KEY] = { v: 1, real: { nonce: "00", ciphertext: "00", tag: "00" } };643+644+    await expect(dispatch({645+      type: "CREATE_VAULT_FROM_ROOT_KEY",646+      payload: { password: PASSWORD, rootKeyHex: "42".repeat(32) },647+    })).resolves.toMatchObject({ ok: true });648+    expect(storage[RECALL_KEY]).toBeUndefined();649+650+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });651+    await expect(dispatch({652+      type: "UNLOCK",653+      payload: { password: PASSWORD },654+    })).resolves.toMatchObject({ ok: true });655+    await dispatch(656+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "adopted.com" } },657+      pageSender("https://adopted.com"),658+    );659+660+    expect(await coldStart()).not.toBeNull();661+    const response = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://adopted.com"));662+    expect(ownRecord(response, "adopted.com")).toMatchObject({ summonCount: 1 });663+  });664+665+  it("clears the decoy member when an adopted duress slot replaces it", async () => {666+    const vault = await setup();667+    await createUnlockedVault();668+    await dispatch(669+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },670+      pageSender("https://real-site.com"),671+    );672+    await vault.setupDuress(DURESS_PASSWORD);673+    const adoptedSlotB = JSON.stringify(storage[SLOT_B]);674+    const realMember = structuredClone((storage[RECALL_KEY] as { real?: unknown }).real);675+    expect(realMember).toBeDefined();676+677+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });678+    await expect(dispatch({679+      type: "UNLOCK",680+      payload: { password: DURESS_PASSWORD },681+    })).resolves.toMatchObject({ ok: true });682+    await dispatch(683+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "decoy-site.com" } },684+      pageSender("https://decoy-site.com"),685+    );686+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeDefined();687+688+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });689+    await expect(dispatch({690+      type: "UNLOCK",691+      payload: { password: PASSWORD },692+    })).resolves.toMatchObject({ ok: true });693+    await vault.installAdoptedDuressSlot(adoptedSlotB);694+695+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeUndefined();696+    expect((storage[RECALL_KEY] as { real?: unknown }).real).toEqual(realMember);697+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });698+    await expect(dispatch({699+      type: "UNLOCK",700+      payload: { password: DURESS_PASSWORD },701+    })).resolves.toMatchObject({ ok: true });702+    const decoyView = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://decoy-site.com"));703+    expect(ownRecord(decoyView, "decoy-site.com")).toBeUndefined();704+  });705+706+  it("clears the decoy member when duress is re-configured or disabled", async () => {707+    const vault = await setup();708+    await createUnlockedVault();709+    await dispatch(710+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },711+      pageSender("https://real-site.com"),712+    );713+    await vault.setupDuress(DURESS_PASSWORD);714+    const realMember = structuredClone((storage[RECALL_KEY] as { real?: unknown }).real);715+716+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });717+    await expect(dispatch({718+      type: "UNLOCK",719+      payload: { password: DURESS_PASSWORD },720+    })).resolves.toMatchObject({ ok: true });721+    await dispatch(722+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "decoy-site.com" } },723+      pageSender("https://decoy-site.com"),724+    );725+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeDefined();726+727+    // Re-configuring duress replaces slot B, so its member must go too.728+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });729+    await expect(dispatch({730+      type: "UNLOCK",731+      payload: { password: PASSWORD },732+    })).resolves.toMatchObject({ ok: true });733+    await vault.setupDuress("second-duress-pass");734+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeUndefined();735+    expect((storage[RECALL_KEY] as { real?: unknown }).real).toEqual(realMember);736+737+    // A fresh decoy member must also go when duress is disabled.738+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });739+    await expect(dispatch({740+      type: "UNLOCK",741+      payload: { password: "second-duress-pass" },742+    })).resolves.toMatchObject({ ok: true });743+    await dispatch(744+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "second-decoy.com" } },745+      pageSender("https://second-decoy.com"),746+    );747+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });748+    await expect(dispatch({749+      type: "UNLOCK",750+      payload: { password: PASSWORD },751+    })).resolves.toMatchObject({ ok: true });752+    await vault.disableDuress();753+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeUndefined();754+    expect((storage[RECALL_KEY] as { real?: unknown }).real).toEqual(realMember);755+  });756+757+  it("seals nothing from a real session into the decoy member on a switch without a lock", async () => {758+    const vault = await setup();759+    await expect(dispatch({760+      type: "CREATE_VAULT",761+      payload: { password: PASSWORD },762+    })).resolves.toMatchObject({ ok: true });763+    await vault.setupDuress(DURESS_PASSWORD);764+    await dispatch(765+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },766+      pageSender("https://real-site.com"),767+    );768+    const realMember = structuredClone((storage[RECALL_KEY] as { real?: unknown }).real);769+770+    // Hold the decoy unlock after it published its key and mode but before it771+    // reloads recall, then let the page write: the real session's records must772+    // be gone from memory by then.773+    const paused = deferred();774+    const release = deferred();775+    settingsReadHook = async () => {776+      settingsReadHook = null;777+      paused.resolve();778+      await release.promise;779+    };780+    const unlocking = dispatch({ type: "UNLOCK", payload: { password: DURESS_PASSWORD } });781+    await paused.promise;782+783+    await expect(dispatch(784+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "decoy-site.com" } },785+      pageSender("https://decoy-site.com"),786+    )).resolves.toEqual({ ok: true });787+    release.resolve();788+    await expect(unlocking).resolves.toMatchObject({ ok: true });789+790+    const decoyLookalike = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://real-site.com"));791+    expect(ownRecord(decoyLookalike, "real-site.com")).toBeUndefined();792+    const decoyOwn = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://decoy-site.com"));793+    expect(ownRecord(decoyOwn, "decoy-site.com")).toMatchObject({ summonCount: 1 });794+    expect((storage[RECALL_KEY] as { real?: unknown }).real).toEqual(realMember);795+  });796+797+  it("rejects a cross-mode ciphertext copy because the AAD binds the position", async () => {798+    const vault = await setup();799+    await expect(dispatch({800+      type: "CREATE_VAULT",801+      payload: { password: PASSWORD },802+    })).resolves.toMatchObject({ ok: true });803+    await vault.setupDuress(DURESS_PASSWORD);804+    await dispatch(805+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },806+      pageSender("https://real-site.com"),807+    );808+    const member = structuredClone(809+      (storage[RECALL_KEY] as { real: { nonce: string; ciphertext: string; tag: string } }).real,810+    );811+    const rootKeyHex = vault.getRootKeyHex();812+    expect(rootKeyHex).not.toBeNull();813+    const rootKey = Uint8Array.from(rootKeyHex!.match(/../g)!, (byte) => Number.parseInt(byte, 16));814+815+    // Same key, wrong position: the decoy AAD must refuse the real member.816+    await expect(decrypt(817+      rootKey, member.nonce, member.ciphertext, member.tag, RECALL_DECOY_AAD,818+    )).rejects.toThrow();819+    await expect(decrypt(820+      rootKey, member.nonce, member.ciphertext, member.tag, RECALL_REAL_AAD,821+    )).resolves.toContain("real-site.com");822+823+    // Copied into the decoy position, a decoy unlock must fail closed.824+    storage[RECALL_KEY] = { v: 1, real: member, decoy: member };825+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });826+    await expect(dispatch({827+      type: "UNLOCK",828+      payload: { password: DURESS_PASSWORD },829+    })).resolves.toMatchObject({ ok: true });830+    const decoyView = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://real-site.com"));831+    expect(ownRecord(decoyView, "real-site.com")).toBeUndefined();832+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toEqual(member);833+  });834+835+  it("clamps the counter", async () => {836+    await setup();837+    await createUnlockedVault();838+839+    for (let i = 0; i < 3; i++) {840+      await dispatch(841+        { type: "RECORD_MANUAL_SUMMON", payload: { domain: "clamp.com" } },842+        pageSender("https://clamp.com"),843+      );844+    }845+    const clamped = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://clamp.com"));846+    expect(ownRecord(clamped, "clamp.com")).toMatchObject({ summonCount: 2 });847+  });848+849+  it("caps stored records by recency, not by insertion order", async () => {850+    await setup();851+    await createUnlockedVault();852+853+    // Step the clock so every record carries a distinct lastSummonedAt; equal854+    // timestamps would let Map order decide and the test could not tell855+    // recency from insertion order.856+    let clock = Date.now();857+    vi.spyOn(Date, "now").mockImplementation(() => clock);858+    const summon = async (domain: string): Promise<void> => {859+      clock += 1_000;860+      await expect(dispatch(861+        { type: "RECORD_MANUAL_SUMMON", payload: { domain } },862+        pageSender(`https://${domain}`),863+      )).resolves.toEqual({ ok: true });864+    };865+866+    // "early.com" is inserted first and summoned again last, so recency and867+    // insertion order disagree about which record should survive.868+    await summon("early.com");869+    for (let i = 0; i < 255; i++) await summon(`site${i}.com`);870+    await summon("early.com");871+    await summon("site255.com");872+873+    const early = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://early.com"));874+    expect(ownRecord(early, "early.com")).toMatchObject({ summonCount: 2 });875+    // 257 distinct records, so exactly one is evicted: the least recently876+    // summoned, not the first inserted.877+    const dropped = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://site0.com"));878+    expect(ownRecord(dropped, "site0.com")).toBeUndefined();879+    const kept = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://site1.com"));880+    expect(ownRecord(kept, "site1.com")).toMatchObject({ summonCount: 1 });881+    const newest = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://site255.com"));882+    expect(ownRecord(newest, "site255.com")).toMatchObject({ summonCount: 1 });883+  });884+885+  it("adopts valid legacy plaintext recall only after unlock and a successful write", async () => {886+    await setup();887+    const now = Date.now();888+    storage.peach_settings = {889+      theme: "dark",890+      manualSummonSalt: "deadbeef",891+      manualSummonDomains: {892+        "legacy.com": { firstSummonedAt: now - 5_000, summonCount: 7, lastSummonedAt: now - 1_000 },893+        "future.com": { firstSummonedAt: now, summonCount: 1, lastSummonedAt: now + 86_400_000 },894+        "negative.com": { firstSummonedAt: -1, summonCount: 1, lastSummonedAt: 0 },895+        "broken.com": { firstSummonedAt: now, summonCount: "2", lastSummonedAt: now },896+      },897+    };898+    await createUnlockedVault();899+900+    const settings = storage.peach_settings as Record<string, unknown>;901+    expect(settings).not.toHaveProperty("manualSummonDomains");902+    expect(settings).not.toHaveProperty("manualSummonSalt");903+    expect(settings.theme).toBe("dark");904+    expect(storage[RECALL_KEY]).toBeDefined();905+906+    const adopted = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://legacy.com"));907+    expect(ownRecord(adopted, "legacy.com")).toEqual({908+      firstSummonedAt: now - 5_000,909+      summonCount: 2,910+      lastSummonedAt: now - 1_000,911+    });912+    for (const domain of ["future.com", "negative.com", "broken.com"]) {913+      const rejected = await dispatch({ type: "GET_SETTINGS" }, pageSender(`https://${domain}`));914+      expect(ownRecord(rejected, domain)).toBeUndefined();915+    }916+917+    // Adoption does not rely on in-memory settings after a restart. This asserts918+    // against the module instance that exists after the restart, not the one919+    // that was already unlocked before it.920+    const restarted = await coldStart();921+    expect(restarted?.isUnlocked()).toBe(true);922+    const afterRestart = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://legacy.com"));923+    expect(ownRecord(afterRestart, "legacy.com")).toMatchObject({ summonCount: 2 });924+  });925+926+  it("does not resurrect the decoy member when a duress change interleaves a real write", async () => {927+    const vault = await setup();928+    await createUnlockedVault();929+    await vault.setupDuress(DURESS_PASSWORD);930+    await dispatch(931+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "real-site.com" } },932+      pageSender("https://real-site.com"),933+    );934+935+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });936+    await expect(dispatch({937+      type: "UNLOCK",938+      payload: { password: DURESS_PASSWORD },939+    })).resolves.toMatchObject({ ok: true });940+    await dispatch(941+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "decoy-site.com" } },942+      pageSender("https://decoy-site.com"),943+    );944+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeDefined();945+946+    await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });947+    await expect(dispatch({948+      type: "UNLOCK",949+      payload: { password: PASSWORD },950+    })).resolves.toMatchObject({ ok: true });951+952+    // Hold a real write between its read and its write, then let a duress change953+    // clear the decoy member: the clear must not be undone by the queued write.954+    const decryptHold = holdNextDecrypt();955+    const pending = dispatch(956+      { type: "RECORD_MANUAL_SUMMON", payload: { domain: "second-real.com" } },957+      pageSender("https://second-real.com"),958+    );959+    await decryptHold.started;960+961+    const duressSlotWritten = deferred();962+    slotWriteHook = (slot) => {963+      if (slot !== SLOT_B) return;964+      slotWriteHook = null;965+      setTimeout(() => duressSlotWritten.resolve(), 0);966+    };967+    const reconfiguring = vault.setupDuress("third-duress-pass");968+    await duressSlotWritten.promise;969+    // Give an unserialized read-modify-write the chance to land before the970+    // queued write commits.971+    await new Promise((resolve) => setTimeout(resolve, 20));972+    decryptHold.release();973+974+    await expect(pending).resolves.toEqual({ ok: true });975+    await expect(reconfiguring).resolves.toBeUndefined();976+977+    expect((storage[RECALL_KEY] as { decoy?: unknown }).decoy).toBeUndefined();978+    expect(await coldStart()).not.toBeNull();979+    for (const domain of ["real-site.com", "second-real.com"]) {980+      const response = await dispatch({ type: "GET_SETTINGS" }, pageSender(`https://${domain}`));981+      expect(ownRecord(response, domain)).toMatchObject({ summonCount: 1 });982+    }983+  });984+985+  it("preserves legacy plaintext through an unrelated settings write until adoption", async () => {986+    await setup();987+    const now = Date.now();988+    const legacy = {989+      "legacy.com": { firstSummonedAt: now - 1_000, summonCount: 1, lastSummonedAt: now - 1_000 },990+    };991+    storage.peach_settings = {992+      theme: "dark",993+      manualSummonSalt: "deadbeef",994+      manualSummonDomains: legacy,995+    };996+997+    // A settings change while locked must neither strip the plaintext nor let a998+    // caller inject its own map in its place.999+    await expect(dispatch({1000+      type: "UPDATE_SETTINGS",1001+      payload: {1002+        clipboardClearSeconds: 20,1003+        manualSummonDomains: {1004+          "injected.com": { firstSummonedAt: 1, summonCount: 1, lastSummonedAt: 1 },1005+        },1006+      },1007+    })).resolves.toMatchObject({ ok: true });1008+    const patched = storage.peach_settings as Record<string, unknown>;1009+    expect(patched.manualSummonDomains).toEqual(legacy);1010+    expect(patched.manualSummonSalt).toBe("deadbeef");1011+    expect(patched.clipboardClearSeconds).toBe(20);1012+1013+    // Adoption alone removes it, and only after the encrypted copy committed.1014+    await createUnlockedVault();1015+    expect(storage.peach_settings).not.toHaveProperty("manualSummonDomains");1016+    expect(storage.peach_settings).not.toHaveProperty("manualSummonSalt");1017+    const adopted = await dispatch({ type: "GET_SETTINGS" }, pageSender("https://legacy.com"));1018+    expect(ownRecord(adopted, "legacy.com")).toMatchObject({ summonCount: 1 });1019+  });1020+1021+  it("keeps legacy plaintext when the encrypted write fails", async () => {1022+    await setup();1023+    const now = Date.now();1024+    storage.peach_settings = {1025+      manualSummonDomains: {1026+        "legacy.com": { firstSummonedAt: now - 1_000, summonCount: 1, lastSummonedAt: now - 1_000 },1027+      },1028+    };1029+    recallWriteHook = async () => {1030+      throw new Error("storage unavailable");1031+    };1032+1033+    await expect(dispatch({ type: "CREATE_VAULT", payload: { password: PASSWORD } })).resolves.toMatchObject({ ok: true });1034+1035+    const settings = storage.peach_settings as { manualSummonDomains?: Record<string, ManualSummonRecord> };1036+    expect(settings.manualSummonDomains).toHaveProperty("legacy.com");1037+  });1038+});

view file

src/background/messages.test.ts+2 −0
@@ -223,6 +223,8 @@223223   });224224 225225   it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {226+    const vault = await import("./vault");227+    await vault.createVault("summon-pass-12345");226228     const sender = {227229       id: "peach-extension",228230       url: "https://login.example.com/form",

view file

src/background/messages.ts+8 −15
@@ -1244,7 +1244,7 @@12441244           theme: settings.theme,12451245         };12461246         const domain = attestedSenderDomain(sender);1247-        const ownSummon = domain ? settings.manualSummonDomains?.[domain] : undefined;1247+        const ownSummon = domain ? vault.getManualSummonRecord(domain) : undefined;12481248         if (domain && ownSummon) safeSettings.manualSummonDomains = { [domain]: ownSummon };12491249         return { ok: true, data: safeSettings };12501250       }@@ -1527,22 +1527,15 @@15271527             senderDomain = null;15281528           }15291529         }1530-        if (typeof domain !== "string" || domain.length > 253 || domain !== senderDomain) {1530+        if (1531+          typeof domain !== "string" ||1532+          new TextEncoder().encode(domain).length > 253 ||1533+          domain !== senderDomain1534+        ) {15311535           return { ok: false, error: "invalid_domain" };15321536         }1533-        const settings = vault.getSettings();1534-        const existing = settings.manualSummonDomains?.[domain];1535-        const now = Date.now();1536-        await vault.updateSettings({1537-          manualSummonDomains: {1538-            ...settings.manualSummonDomains,1539-            [domain]: {1540-              firstSummonedAt: existing?.firstSummonedAt ?? now,1541-              summonCount: (existing?.summonCount ?? 0) + 1,1542-              lastSummonedAt: now,1543-            },1544-          },1545-        });1537+        if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };1538+        await vault.recordManualSummon(domain);15461539         return { ok: true };15471540       }15481541       case "DECLINE_CARD_SAVE": {

view file

src/background/vault.ts+429 −7
@@ -214,9 +214,14 @@214214   // feeds parsed external JSON here (native spread keeps __proto__ an own-215215   // property today, but Object.assign-style consumers and JSON revivers have216216   // been burned before).217+  // `manualSummonDomains`/`manualSummonSalt` are legacy plaintext recall that218+  // only the adoption path may clear; an external patch must not write them.217219   const safe = Object.fromEntries(218220     Object.entries(patch).filter(219-      ([k]) => !["__proto__", "constructor", "prototype"].includes(k),221+      ([k]) => ![222+        "__proto__", "constructor", "prototype",223+        "manualSummonDomains", "manualSummonSalt",224+      ].includes(k),220225     ),221226   ) as Partial<VaultSettings>;222227   settings = { ...settings, ...safe };@@ -389,9 +394,9 @@389394   try {390395     await chrome.storage.local.set({391396       peach_settings: {397+        // Legacy plaintext recall is carried through every settings write until398+        // adoption commits the encrypted copy and clears it explicitly.392399         ...settings,393-        manualSummonDomains: undefined,394-        manualSummonSalt: undefined,395400         cardFingerprintSalt: undefined,396401         declinedCardFingerprints: settings.declinedCardFingerprints ?? [],397402         metadataVersion: 1,@@ -415,6 +420,376 @@415420   settings = (result as { peach_settings?: VaultSettings }).peach_settings ?? {};416421 }417422 423+/** Drop the legacy plaintext recall only once its encrypted copy committed. */424+async function clearLegacyManualSummonPlaintext(): Promise<void> {425+  settings = { ...settings, manualSummonDomains: undefined, manualSummonSalt: undefined };426+  await persistSettings();427+}428+429+// ---------------------------------------------------------------------------430+// Manual-summon recall (encrypted Browser-local state)431+// ---------------------------------------------------------------------------432+433+// One storage key holds one sealed member per vault mode. The real member is434+// sealed under the vault root key so it survives password changes; slot B has435+// no root key, so the decoy member uses that session's decoy vault key. The436+// distinct AAD contexts stop one mode from opening the other's member.437+const RECALL_STORAGE = "peach_manual_summon_recall_v1";438+const RECALL_REAL_AAD = "manual_summon_recall_v1";439+const RECALL_DECOY_AAD = "manual_summon_recall_decoy_v1";440+const RECALL_MAX_RECORDS = 256;441+const RECALL_DOMAIN_MAX_BYTES = 253;442+// Summon timestamps come from the device clock; anything further ahead than443+// this is corrupt or forged data, not a real summon.444+const RECALL_MAX_CLOCK_SKEW_MS = 5 * 60_000;445+446+interface SealedRecall {447+  nonce: string;448+  ciphertext: string;449+  tag: string;450+}451+452+interface StoredRecall {453+  v: 1;454+  real?: SealedRecall;455+  decoy?: SealedRecall;456+}457+458+let manualSummonRecall = new Map<string, ManualSummonRecord>();459+let recallMutation: Promise<void> = Promise.resolve();460+461+function isValidRecallDomain(domain: unknown): domain is string {462+  return typeof domain === "string" && domain.length > 0 &&463+    new TextEncoder().encode(domain).length <= RECALL_DOMAIN_MAX_BYTES;464+}465+466+function sanitizeSummonRecord(value: unknown, now: number): ManualSummonRecord | null {467+  if (!value || typeof value !== "object") return null;468+  const record = value as Record<string, unknown>;469+  const firstSummonedAt = record.firstSummonedAt;470+  const lastSummonedAt = record.lastSummonedAt;471+  const latestAllowed = now + RECALL_MAX_CLOCK_SKEW_MS;472+  for (const timestamp of [firstSummonedAt, lastSummonedAt]) {473+    if (474+      typeof timestamp !== "number" ||475+      !Number.isSafeInteger(timestamp) ||476+      timestamp < 0 ||477+      timestamp > latestAllowed478+    ) {479+      return null;480+    }481+  }482+  if (typeof record.summonCount !== "number" || !Number.isFinite(record.summonCount)) {483+    return null;484+  }485+  return {486+    firstSummonedAt: firstSummonedAt as number,487+    lastSummonedAt: lastSummonedAt as number,488+    // Only two aggression levels exist; anything past two is the same state.489+    summonCount: Math.min(2, Math.max(1, Math.trunc(record.summonCount))),490+  };491+}492+493+function capManualSummonRecall(494+  records: Map<string, ManualSummonRecord>,495+): Map<string, ManualSummonRecord> {496+  if (records.size <= RECALL_MAX_RECORDS) return records;497+  const kept = new Map(records);498+  while (kept.size > RECALL_MAX_RECORDS) {499+    let oldestDomain: string | null = null;500+    let oldestAt = Number.POSITIVE_INFINITY;501+    for (const [domain, record] of kept) {502+      if (record.lastSummonedAt < oldestAt) {503+        oldestAt = record.lastSummonedAt;504+        oldestDomain = domain;505+      }506+    }507+    if (oldestDomain === null) break;508+    kept.delete(oldestDomain);509+  }510+  return kept;511+}512+513+function sanitizeManualSummonRecall(value: unknown): Map<string, ManualSummonRecord> {514+  const records = new Map<string, ManualSummonRecord>();515+  if (!value || typeof value !== "object" || Array.isArray(value)) return records;516+  const now = Date.now();517+  for (const [domain, raw] of Object.entries(value as Record<string, unknown>)) {518+    if (!isValidRecallDomain(domain)) continue;519+    const record = sanitizeSummonRecord(raw, now);520+    if (record) records.set(domain, record);521+  }522+  return capManualSummonRecall(records);523+}524+525+function readStoredRecall(value: unknown): StoredRecall {526+  const stored: StoredRecall = { v: 1 };527+  if (!value || typeof value !== "object" || Array.isArray(value)) return stored;528+  for (const mode of ["real", "decoy"] as const) {529+    const member = (value as Record<string, unknown>)[mode];530+    if (!member || typeof member !== "object") continue;531+    const sealed = member as Record<string, unknown>;532+    if (533+      typeof sealed.nonce === "string" &&534+      typeof sealed.ciphertext === "string" &&535+      typeof sealed.tag === "string"536+    ) {537+      stored[mode] = { nonce: sealed.nonce, ciphertext: sealed.ciphertext, tag: sealed.tag };538+    }539+  }540+  return stored;541+}542+543+function recallSealContext(): { key: Uint8Array; aad: string } | null {544+  if (vaultMode === "decoy") {545+    return derivedKey ? { key: derivedKey, aad: RECALL_DECOY_AAD } : null;546+  }547+  return rootKey ? { key: rootKey, aad: RECALL_REAL_AAD } : null;548+}549+550+function serializeRecallMutation(run: () => Promise<void>): Promise<void> {551+  const task = recallMutation.then(run, run);552+  recallMutation = task.then(() => undefined, () => undefined);553+  return task;554+}555+556+async function readStoredRecallFromDisk(): Promise<StoredRecall> {557+  const raw = await chrome.storage.local.get(RECALL_STORAGE);558+  return readStoredRecall((raw as Record<string, unknown>)[RECALL_STORAGE]);559+}560+561+// A lock zeroes the keys in place and a root rotation replaces the array, so562+// the epoch and mode alone cannot prove a captured key still holds the bytes563+// it was captured with.564+function recallSealIsCurrent(565+  epoch: number,566+  mode: "real" | "decoy",567+  sealKey: Uint8Array,568+): boolean {569+  return epoch === vaultEpoch && mode === vaultMode && recallSealContext()?.key === sealKey;570+}571+572+async function loadManualSummonRecall(): Promise<void> {573+  const epoch = vaultEpoch;574+  const mode = vaultMode;575+  const context = recallSealContext();576+  manualSummonRecall = new Map();577+  if (!context) return;578+  let stored: StoredRecall;579+  try {580+    stored = await readStoredRecallFromDisk();581+  } catch (error) {582+    console.warn("[Peach] manual-summon recall read failed:", error);583+    return;584+  }585+  if (epoch !== vaultEpoch || mode !== vaultMode) return;586+  const member = stored[mode];587+  if (!member) return;588+  try {589+    const plain = await decrypt(context.key, member.nonce, member.ciphertext, member.tag, context.aad);590+    if (epoch !== vaultEpoch || mode !== vaultMode) return;591+    manualSummonRecall = sanitizeManualSummonRecall(JSON.parse(plain));592+  } catch {593+    // Fail closed: leave the unreadable member on disk; the next successful594+    // write in this mode replaces it.595+    manualSummonRecall = new Map();596+  }597+}598+599+async function persistManualSummonRecall(): Promise<void> {600+  const epoch = vaultEpoch;601+  const mode = vaultMode;602+  const context = recallSealContext();603+  if (!derivedKey || !context) throw new Error("vault_locked");604+  const sealKey = context.key;605+  let stored: StoredRecall;606+  try {607+    stored = await readStoredRecallFromDisk();608+  } catch (error) {609+    throw mapStorageError(error);610+  }611+  // Merge the committed member first: an unlock still loading recall must not612+  // let this write drop records it has not seen yet. The merge stays local so a613+  // write that crosses a lock or a mode change publishes nothing.614+  let records = manualSummonRecall;615+  const existing = stored[mode];616+  if (existing) {617+    try {618+      const plain = await decrypt(sealKey, existing.nonce, existing.ciphertext, existing.tag, context.aad);619+      const merged = sanitizeManualSummonRecall(JSON.parse(plain));620+      for (const [domain, record] of records) merged.set(domain, record);621+      records = capManualSummonRecall(merged);622+    } catch {623+      // Fail closed on load, replace here: this session's records win.624+    }625+  }626+  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");627+  const sealed = await encrypt(628+    sealKey,629+    JSON.stringify(Object.fromEntries(records)),630+    context.aad,631+  );632+  if (!recallSealIsCurrent(epoch, mode, sealKey)) throw new Error("vault_locked");633+  // Replace only this mode's member; the other mode's ciphertext stays intact.634+  stored[mode] = sealed;635+  try {636+    await chrome.storage.local.set({ [RECALL_STORAGE]: stored });637+  } catch (error) {638+    throw mapStorageError(error);639+  }640+  // Committed: a lock that followed is not a failed summon, and the merged view641+  // is published only into the session it still belongs to.642+  if (recallSealIsCurrent(epoch, mode, sealKey)) manualSummonRecall = records;643+}644+645+/**646+ * Re-seal the real member from the retired root to the new one. Rotation calls647+ * this inside the recall queue, so no queued write can still be encrypting with648+ * the old key bytes when they are zeroed.649+ */650+async function rekeyManualSummonRecall(651+  oldRootKey: Uint8Array,652+  newRootKey: Uint8Array,653+): Promise<void> {654+  const epoch = vaultEpoch;655+  const sealIsCurrent = (): boolean =>656+    epoch === vaultEpoch && vaultMode === "real" && rootKey === oldRootKey;657+  if (!sealIsCurrent()) throw new Error("vault_locked");658+  const stored = await readStoredRecallFromDisk();659+  let records = manualSummonRecall;660+  const existing = stored.real;661+  if (existing) {662+    try {663+      const plain = await decrypt(oldRootKey, existing.nonce, existing.ciphertext, existing.tag, RECALL_REAL_AAD);664+      const merged = sanitizeManualSummonRecall(JSON.parse(plain));665+      for (const [domain, record] of records) merged.set(domain, record);666+      records = capManualSummonRecall(merged);667+    } catch {668+      // Fail closed on load, replace here: this session's records win.669+    }670+  }671+  if (!existing && records.size === 0) return;672+  if (!sealIsCurrent()) throw new Error("vault_locked");673+  stored.real = await encrypt(674+    newRootKey,675+    JSON.stringify(Object.fromEntries(records)),676+    RECALL_REAL_AAD,677+  );678+  if (!sealIsCurrent()) return;679+  await chrome.storage.local.set({ [RECALL_STORAGE]: stored });680+  if (sealIsCurrent()) manualSummonRecall = records;681+}682+683+/**684+ * Adopt recall left as plaintext in `peach_settings` by older builds. Only a685+ * successful encrypted write authorises removing the plaintext copy.686+ */687+async function adoptLegacyManualSummonRecall(): Promise<void> {688+  if (vaultMode !== "real" || !rootKey) return;689+  const legacy = sanitizeManualSummonRecall(settings.manualSummonDomains);690+  if (legacy.size === 0) return;691+  const epoch = vaultEpoch;692+  const previous = manualSummonRecall;693+  const merged = new Map(legacy);694+  for (const [domain, record] of previous) merged.set(domain, record);695+  manualSummonRecall = capManualSummonRecall(merged);696+  try {697+    await persistManualSummonRecall();698+  } catch (error) {699+    if (epoch === vaultEpoch && vaultMode === "real") manualSummonRecall = previous;700+    throw error;701+  }702+  await clearLegacyManualSummonPlaintext();703+}704+705+async function restoreManualSummonRecall(): Promise<void> {706+  try {707+    await loadSettings();708+  } catch (error) {709+    console.warn("[Peach] manual-summon recall settings read failed:", error);710+    return;711+  }712+  try {713+    await serializeRecallMutation(async () => {714+      await loadManualSummonRecall();715+      await adoptLegacyManualSummonRecall();716+    });717+  } catch (error) {718+    // Recall is a hint, never a reason to fail an unlock.719+    console.warn("[Peach] manual-summon recall migration deferred:", error);720+  }721+}722+723+async function clearStoredManualSummonRecall(mode?: "real" | "decoy"): Promise<void> {724+  if (mode === undefined) {725+    manualSummonRecall = new Map();726+    try {727+      await chrome.storage.local.remove(RECALL_STORAGE);728+    } catch (error) {729+      console.warn("[Peach] manual-summon recall cleanup failed:", error);730+    }731+    return;732+  }733+  try {734+    // Serialized with record writes: this is a read-modify-write of the shared735+    // key and must not revert the other member to stale ciphertext.736+    await serializeRecallMutation(async () => {737+      const stored = await readStoredRecallFromDisk();738+      if (!stored[mode]) return;739+      delete stored[mode];740+      if (stored.real || stored.decoy) {741+        await chrome.storage.local.set({ [RECALL_STORAGE]: stored });742+      } else {743+        await chrome.storage.local.remove(RECALL_STORAGE);744+      }745+    });746+  } catch (error) {747+    console.warn("[Peach] manual-summon recall cleanup failed:", error);748+  }749+}750+751+/** This domain's recall record, if the current mode has one. */752+export function getManualSummonRecord(domain: string): ManualSummonRecord | undefined {753+  const recalled = manualSummonRecall.get(domain);754+  if (recalled) return recalled;755+  // Pre-migration plaintext is real-vault data; a decoy session must not see it.756+  if (vaultMode !== "real" || !isValidRecallDomain(domain)) return undefined;757+  return sanitizeSummonRecord(settings.manualSummonDomains?.[domain], Date.now()) ?? undefined;758+}759+760+/** Record a manual summons for the caller's own domain and persist it. */761+export async function recordManualSummon(domain: string): Promise<void> {762+  if (!isValidRecallDomain(domain)) throw new Error("invalid_domain");763+  vaultWritesInFlight++;764+  try {765+    const run = async (): Promise<void> => {766+      if (!derivedKey || !recallSealContext()) throw new Error("vault_locked");767+      const epoch = vaultEpoch;768+      const mode = vaultMode;769+      const previous = manualSummonRecall;770+      const now = Date.now();771+      const existing = previous.get(domain);772+      const next = new Map(previous);773+      next.set(domain, {774+        firstSummonedAt: existing?.firstSummonedAt ?? now,775+        summonCount: Math.min(2, (existing?.summonCount ?? 0) + 1),776+        lastSummonedAt: now,777+      });778+      manualSummonRecall = capManualSummonRecall(next);779+      try {780+        await persistManualSummonRecall();781+      } catch (error) {782+        if (epoch === vaultEpoch && mode === vaultMode) manualSummonRecall = previous;783+        throw error;784+      }785+    };786+    // Serialize read-modify-write pairs so two quick summonses cannot lose one.787+    await serializeRecallMutation(run);788+  } finally {789+    vaultWritesInFlight--;790+  }791+}792+418793 // Fire-and-forget sync trigger after a committed vault write. A failure here419794 // must never fail the write that caused it.420795 function fireSyncTrigger(reason: "vault_change"): void {@@ -949,6 +1324,7 @@9491324     tombstones = payload.tombstones;9501325     duressConfigured = payload.duressConfigured;9511326     vaultMode = "real";1327+    manualSummonRecall = new Map();9521328     buildDomainIndexSync(entries);9531329     await saveSessionKey(derivedKey, "real", epoch);9541330     if (epoch !== vaultEpoch) throw new Error("vault_locked");@@ -958,6 +1334,8 @@9581334     if (epoch !== vaultEpoch) throw new Error("vault_locked");9591335     await clearPinUnlockStorage();9601336     if (epoch !== vaultEpoch) throw new Error("vault_locked");1337+    await restoreManualSummonRecall();1338+    if (epoch !== vaultEpoch) throw new Error("vault_locked");9611339     touchAutoLock();9621340     return { committed: true, unlocked: true };9631341   } catch (error) {@@ -1156,6 +1534,7 @@11561534         SLOT_A,11571535         SLOT_B,11581536         "peach_last_modified_at",1537+        RECALL_STORAGE,11591538       ]);11601539     } catch (err) {11611540       throw mapStorageError(err);@@ -1594,6 +1973,7 @@15941973     entries = [];15951974     tombstones = new Map();15961975     vaultMode = "real";1976+    manualSummonRecall = new Map();15971977     duressConfigured = false;15981978     buildDomainIndexSync(entries);15991979     if (previousKey) zeroKey(previousKey);@@ -1604,6 +1984,11 @@16041984       console.warn("[Peach] local identity promotion failed:", error);16051985     });16061986     if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };1987+    // A newly created vault owns a fresh root and a fresh slot B, so any1988+    // recalled member sealed under the old vault is unreachable by design.1989+    await clearStoredManualSummonRecall();1990+    await restoreManualSummonRecall();1991+    if (publishedEpoch !== vaultEpoch || !derivedKey) return { committed: true, unlocked: false };16071992     touchAutoLock();16081993     return { committed: true, unlocked: true };16091994   } catch (error) {@@ -1698,6 +2083,7 @@16982083     entries = nextEntries;16992084     tombstones = new Map();17002085     vaultMode = "real";2086+    manualSummonRecall = new Map();17012087     duressConfigured = nextDuressConfigured;17022088     buildDomainIndexSync(entries);17032089     if (previousDerivedKey && previousDerivedKey !== derivedKey) zeroKey(previousDerivedKey);@@ -1709,13 +2095,15 @@17092095     await identityHooks?.onVaultCreated(password).catch((error) => {17102096       console.warn("[Peach] local identity promotion failed:", error);17112097     });2098+    await clearStoredManualSummonRecall();2099+    await restoreManualSummonRecall();17122100 17132101     return { vaultId };17142102   } catch (error) {17152103     if (committed) {17162104       // Removal cannot use withVaultRemoval while this operation owns creationSettled.17172105       try { await lock(); }1718-      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, "peach_last_modified_at"]); }2106+      finally { await chrome.storage.local.remove([SLOT_A, SLOT_B, RECALL_STORAGE, "peach_last_modified_at"]); }17192107     }17202108     throw error;17212109   } finally {@@ -1770,6 +2158,8 @@17702158       ciphertext,17712159       tag,17722160     });2161+    // The stored decoy member belonged to the previous decoy slot.2162+    await clearStoredManualSummonRecall("decoy");17732163   } finally {17742164     zeroKey(decoyKey);17752165   }@@ -1794,6 +2184,7 @@17942184   const slotA = await loadSlot(SLOT_A);17952185   if (slotA) {17962186     await writeSlot(SLOT_B, generateNoiseBlob(slotA.ciphertext.length / 2));2187+    await clearStoredManualSummonRecall("decoy");17972188   }17982189 17992190   duressConfigured = false;@@ -1879,6 +2270,7 @@18792270     cancelBreachScan();18802271     derivedKey = keyA;18812272     vaultMode = "real";2273+    manualSummonRecall = new Map();18822274     entries = payloadA.entries;18832275     tombstones = payloadA.tombstones;18842276     duressConfigured = payloadA.duressConfigured;@@ -1940,6 +2332,8 @@19402332     }19412333     await saveSessionKey(keyA, "real", epoch);19422334     if (stale()) return false;2335+    await restoreManualSummonRecall();2336+    if (stale()) return false;19432337     return true;19442338   }19452339 @@ -1952,6 +2346,7 @@19522346     cancelBreachScan();19532347     derivedKey = keyB;19542348     vaultMode = "decoy";2349+    manualSummonRecall = new Map();19552350     decoySyncTeardownHook?.();19562351     // A duress session must not retain the real vault's root key. It gates the19572352     // recovery words, the sync identity, and the root wrap of the local device@@ -1977,6 +2372,8 @@19772372     }19782373     await saveSessionKey(keyB, "decoy", epoch);19792374     if (stale()) return false;2375+    await restoreManualSummonRecall();2376+    if (stale()) return false;19802377     return true;19812378   }19822379 @@ -2140,6 +2537,7 @@21402537   cancelBreachScan();21412538   derivedKey = key;21422539   vaultMode = entry.mode;2540+  manualSummonRecall = new Map();21432541   if (entry.mode === "decoy") decoySyncTeardownHook?.();21442542   entries = payload.entries;21452543   tombstones = payload.tombstones;@@ -2152,6 +2550,8 @@21522550     console.warn("[Peach sync] locked inbox drain failed:", error);21532551   });21542552   if (stale()) return false;2553+  await restoreManualSummonRecall();2554+  if (stale()) return false;21552555 21562556   return true;21572557 }@@ -2179,6 +2579,7 @@21792579   }21802580 21812581   entries = [];2582+  manualSummonRecall = new Map();21822583   tombstones = new Map();21832584   domainIndex = new Map();21842585   vaultMode = "real";@@ -2234,6 +2635,7 @@22342635     cancelBreachScan();22352636     derivedKey = masterKeyBytes;22362637     vaultMode = "real";2638+    manualSummonRecall = new Map();22372639     entries = payload.entries;22382640     tombstones = payload.tombstones;22392641     duressConfigured = payload.duressConfigured;@@ -2253,6 +2655,8 @@22532655     }22542656     await saveSessionKey(masterKeyBytes, "real", epoch);22552657     if (stale()) return { ok: false, error: "invalid_key" };2658+    await restoreManualSummonRecall();2659+    if (stale()) return { ok: false, error: "invalid_key" };22562660     return { ok: true, entries };22572661   } catch {22582662     if (masterKeyBytes && derivedKey !== masterKeyBytes) zeroKey(masterKeyBytes);@@ -2299,6 +2703,10 @@22992703     throw err;23002704   }23012705   await writeSlot(SLOT_B, parsed);2706+  // The adopted decoy slot replaces any local decoy the member belonged to.2707+  await clearStoredManualSummonRecall("decoy");2708+  manualSummonRecall = new Map();2709+  await restoreManualSummonRecall();23022710   } finally { vaultWritesInFlight--; }23032711 }23042712 @@ -3845,9 +4253,23 @@38454253   await writeSlot(SLOT_A, nextSlotA);38464254 38474255   // 4. Swap in memory only after disk committed.3848-  if (rotationEpoch === vaultEpoch && derivedKey) {3849-    if (rootKey) zeroKey(rootKey);3850-    rootKey = newRootKey;4256+  if (rotationEpoch === vaultEpoch && derivedKey && rootKey) {4257+    const oldRootKey = rootKey;4258+    // The old root must stay live until the recall member is re-sealed: a queued4259+    // write encrypts with the bytes it captured, so zeroing in place first would4260+    // seal it under an all-zero key. Both the re-key and the swap run inside the4261+    // recall queue so no write can interleave with either.4262+    await serializeRecallMutation(async () => {4263+      await rekeyManualSummonRecall(oldRootKey, newRootKey).catch((error) => {4264+        console.warn("[Peach] manual-summon recall re-key failed:", error);4265+      });4266+      if (rootKey === oldRootKey) {4267+        rootKey = newRootKey;4268+        zeroKey(oldRootKey);4269+      } else {4270+        zeroKey(newRootKey);4271+      }4272+    });38514273   } else {38524274     zeroKey(newRootKey);38534275   }

view file