1import { beforeEach, describe, expect, it, vi } from "vitest";23import { base64urlEncode, generatePasskeyKeypair } from "./passkey-crypto";4import type { Message, MessageResponse } from "../shared/types";56type StorageShape = Record<string, unknown>;78function deferred(): { promise: Promise<void>; resolve: () => void } {9 let resolve!: () => void;10 const promise = new Promise<void>((done) => {11 resolve = done;12 });13 return { promise, resolve };14}15type MessageListener = (16 msg: unknown,17 sender: chrome.runtime.MessageSender,18 sendResponse: (response: MessageResponse) => void19) => boolean;202122232425262728function asChromeStores(value: unknown): unknown {29 if (Array.isArray(value)) return value.map(asChromeStores);30 if (value && typeof value === "object") {31 const source = value as StorageShape;32 const clone: StorageShape = {};33 for (const key of Object.keys(source).sort()) clone[key] = asChromeStores(source[key]);34 return clone;35 }36 return value;37}3839function storeWrite(target: StorageShape, next: StorageShape): void {40 for (const [key, value] of Object.entries(next)) {41 if (value === undefined) continue;42 target[key] = asChromeStores(value);43 }44}4546describe("background messages", () => {47 let storage: StorageShape;48 let sessionStorage: StorageShape;49 let listener: MessageListener;50 let fetchMock: ReturnType<typeof vi.fn>;5152 beforeEach(async () => {53 vi.resetModules();54 vi.useRealTimers();55 storage = {56 peach_settings: { breachMonitoring: false },57 };58 sessionStorage = {};59 fetchMock = vi.fn(async () => ({60 ok: true,61 status: 200,62 text: async () => "",63 }));64 vi.stubGlobal("fetch", fetchMock);65 vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);6667 const tabs = [{ id: 1 }];68 const chromeMock = {69 runtime: {70 id: "peach-extension",71 getURL: (p: string) => `chrome-extension://peach-extension/${p}`,72 onMessage: {73 addListener: vi.fn((fn: MessageListener) => {74 listener = fn;75 }),76 },77 sendMessage: vi.fn(async () => ({ ok: true })),78 },79 tabs: {80 query: vi.fn((_query: unknown, callback?: (tabs: Array<{ id?: number }>) => void) => {81 if (typeof callback === "function") {82 callback(tabs);83 return;84 }85 return Promise.resolve(tabs);86 }),87 sendMessage: vi.fn(async () => ({ ok: true })),88 },89 storage: {90 local: {91 get: vi.fn(async (key?: string | string[]) => {92 if (!key) return storage;93 if (typeof key === "string") {94 return { [key]: storage[key] };95 }9697 return key.reduce<Record<string, unknown>>((result, entry) => {98 result[entry] = storage[entry];99 return result;100 }, {});101 }),102 set: vi.fn(async (next: Record<string, unknown>) => {103 storeWrite(storage, next);104 }),105 remove: vi.fn(async (keys: string | string[]) => {106 const list = Array.isArray(keys) ? keys : [keys];107 for (const key of list) {108 delete storage[key];109 }110 }),111 clear: vi.fn(async () => {112 for (const key of Object.keys(storage)) delete storage[key];113 }),114 },115 session: {116 get: vi.fn(async (key?: string | string[]) => {117 if (!key) return sessionStorage;118 if (typeof key === "string") {119 return { [key]: sessionStorage[key] };120 }121 return key.reduce<Record<string, unknown>>((result, entry) => {122 result[entry] = sessionStorage[entry];123 return result;124 }, {});125 }),126 set: vi.fn(async (next: Record<string, unknown>) => {127 storeWrite(sessionStorage, next);128 }),129 remove: vi.fn(async (keys: string | string[]) => {130 const list = Array.isArray(keys) ? keys : [keys];131 for (const key of list) {132 delete sessionStorage[key];133 }134 }),135 clear: vi.fn(async () => {136 for (const key of Object.keys(sessionStorage)) delete sessionStorage[key];137 }),138 },139 sync: {140 get: vi.fn(async (_key?: string | string[]) => ({})),141 set: vi.fn(async (_values: Record<string, unknown>) => undefined),142 remove: vi.fn(async (_keys: string | string[]) => undefined),143 clear: vi.fn(async () => undefined),144 },145 },146 alarms: {147 clear: vi.fn(),148 create: vi.fn(),149 onAlarm: { addListener: vi.fn() },150 },151 idle: {152 setDetectionInterval: vi.fn(),153 onStateChanged: { addListener: vi.fn() },154 },155 scripting: {156 executeScript: vi.fn(async () => []),157 },158 } as unknown as typeof chrome;159160 (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;161162 const messages = await import("./messages");163 messages.setupMessageHandler();164 const vault = await import("./vault");165 await vault.ensureSettingsLoaded();166 });167168 async function dispatch(169 message: Message,170 sender: chrome.runtime.MessageSender = {171 id: "peach-extension",172 url: "chrome-extension://peach-extension/popup.html",173 }174 ): Promise<MessageResponse> {175 return await new Promise<MessageResponse>((resolve) => {176 const keepChannelOpen = listener(message, sender, (response) => resolve(response));177 expect(keepChannelOpen).toBe(true);178 });179 }180181 it("PB-26-303: page GET_SETTINGS returns only theme, accent, and its own summon record", async () => {182 storage.peach_settings = {183 theme: "dark",184 accentColor: "peach",185 autoLockMinutes: 5,186 pinEnabled: true,187 manualSummonDomains: {188 "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },189 "other.example": { firstSummonedAt: 4, summonCount: 5, lastSummonedAt: 6 },190 },191 };192 const response = await dispatch(193 { type: "GET_SETTINGS" },194 {195 id: "peach-extension",196 url: "https://login.example.com/form",197 tab: { id: 1 },198 frameId: 0,199 } as chrome.runtime.MessageSender,200 );201202 expect(response).toEqual({203 ok: true,204 data: {205 theme: "dark",206 accentColor: "peach",207 manualSummonDomains: {208 "example.com": { firstSummonedAt: 1, summonCount: 2, lastSummonedAt: 3 },209 },210 },211 });212 await expect(dispatch({ type: "GET_SETTINGS" })).resolves.toMatchObject({213 ok: true,214 data: {215 autoLockMinutes: 5,216 pinEnabled: true,217 manualSummonDomains: {218 "example.com": expect.anything(),219 "other.example": expect.anything(),220 },221 },222 });223 });224225 it("RECORD_MANUAL_SUMMON binds and bounds the sender domain", async () => {226 const sender = {227 id: "peach-extension",228 url: "https://login.example.com/form",229 origin: "https://login.example.com",230 tab: { id: 1 },231 frameId: 0,232 } as chrome.runtime.MessageSender;233234 await expect(dispatch({235 type: "RECORD_MANUAL_SUMMON",236 payload: { domain: "evil.example" },237 }, sender)).resolves.toEqual({ ok: false, error: "invalid_domain" });238 await expect(dispatch({239 type: "RECORD_MANUAL_SUMMON",240 payload: { domain: "example.com" },241 }, sender)).resolves.toEqual({ ok: true });242 await expect(dispatch({243 type: "RECORD_MANUAL_SUMMON",244 payload: { domain: "a".repeat(254) },245 }, { ...sender, origin: "https://a.com", url: "https://a.com/form" })).resolves.toEqual({246 ok: false,247 error: "invalid_domain",248 });249 });250251 it("GET_ENTRIES when unlocked returns the entry array", async () => {252 const vault = await import("./vault");253 await vault.createVault("correct-pass-12345");254 await vault.addEntry({255 title: "GitHub",256 username: "june",257 password: "secret123",258 url: "https://github.com",259 });260261 await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({262 ok: true,263 data: [264 expect.objectContaining({265 title: "GitHub",266 username: "june",267 }),268 ],269 });270 });271272 it("GET_ENTRIES when locked returns a vault locked error", async () => {273 const vault = await import("./vault");274 await vault.createVault("correct-pass-12345");275 vault.lock();276277 await expect(dispatch({ type: "GET_ENTRIES" })).resolves.toMatchObject({278 ok: false,279 error: "vault_locked",280 });281 });282283 it("ADD_ENTRY with a valid payload returns the created entry", async () => {284 const vault = await import("./vault");285 await vault.createVault("correct-pass-12345");286287 const response = await dispatch({288 type: "ADD_ENTRY",289 payload: {290 title: "GitHub",291 username: "june",292 password: "secret123",293 url: "https://github.com",294 },295 });296297 expect(response).toMatchObject({298 ok: true,299 data: expect.objectContaining({300 id: expect.any(String),301 title: "GitHub",302 }),303 });304 expect(vault.getEntries()).toHaveLength(1);305 });306307 it("ADD_ENTRY when locked returns a vault locked error", async () => {308 const vault = await import("./vault");309 await vault.createVault("correct-pass-12345");310 vault.lock();311312 await expect(313 dispatch({314 type: "ADD_ENTRY",315 payload: {316 title: "GitHub",317 username: "june",318 password: "secret123",319 url: "https://github.com",320 },321 })322 ).resolves.toMatchObject({ ok: false, error: "vault_locked" });323 });324325 it("ADD_ENTRY with no password succeeds for email-only accounts", async () => {326 const vault = await import("./vault");327 await vault.createVault("correct-pass-12345");328329 await expect(330 dispatch({331 type: "ADD_ENTRY",332 payload: {333 title: "GitHub",334 username: "june",335 password: "",336 url: "https://github.com",337 },338 })339 ).resolves.toMatchObject({ ok: true });340 });341342 it("UPDATE_ENTRY updates an existing entry and returns ok", async () => {343 const vault = await import("./vault");344 await vault.createVault("correct-pass-12345");345 const entry = await vault.addEntry({346 title: "GitHub",347 username: "june",348 password: "secret123",349 url: "https://github.com",350 });351352 await expect(353 dispatch({354 type: "UPDATE_ENTRY",355 payload: { id: entry.id, patch: { password: "new-secret" } },356 })357 ).resolves.toMatchObject({ ok: true });358359 expect(vault.getEntryById(entry.id)?.password).toBe("new-secret");360 });361362 it("UPDATE_ENTRY with an empty password clears it for email-only accounts", async () => {363 const vault = await import("./vault");364 await vault.createVault("correct-pass-12345");365 const entry = await vault.addEntry({366 title: "GitHub",367 username: "june",368 password: "secret123",369 url: "https://github.com",370 });371372 await expect(373 dispatch({374 type: "UPDATE_ENTRY",375 payload: { id: entry.id, patch: { password: "" } },376 })377 ).resolves.toMatchObject({ ok: true });378379 expect(vault.getEntryById(entry.id)?.password).toBeUndefined();380 });381382 it("DELETE_ENTRY soft-deletes the target entry", async () => {383 const vault = await import("./vault");384 await vault.createVault("correct-pass-12345");385 const entry = await vault.addEntry({386 title: "GitHub",387 username: "june",388 password: "secret123",389 url: "https://github.com",390 });391392 await expect(393 dispatch({394 type: "DELETE_ENTRY",395 payload: { id: entry.id },396 })397 ).resolves.toMatchObject({ ok: true });398399 expect(vault.getEntries()).toEqual([]);400 expect(vault.getDeletedEntries()).toHaveLength(1);401 });402403 it("DELETE_ENTRY of a missing id returns an error", async () => {404 const vault = await import("./vault");405 await vault.createVault("correct-pass-12345");406407 await expect(408 dispatch({409 type: "DELETE_ENTRY",410 payload: { id: "missing" },411 })412 ).resolves.toMatchObject({ ok: false, error: "entry_not_found" });413 });414415 it("GET_ENTRY_FOR_FILL returns a safe login entry without privateKeyJwk", async () => {416 const vault = await import("./vault");417 await vault.createVault("correct-pass-12345");418 const entry = await vault.addEntry({419 title: "GitHub",420 username: "june",421 password: "secret123",422 url: "https://github.com",423 });424425 const response = await dispatch(426 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },427 { id: "peach-extension", url: "https://github.com/login" },428 );429430 expect(response).toMatchObject({431 ok: true,432 data: expect.objectContaining({433 id: entry.id,434 username: "june",435 password: "secret123",436 }),437 });438 expect((response.data as Record<string, unknown>).privateKeyJwk).toBeUndefined();439 });440441 it("GET_ENTRY_FOR_FILL when locked returns an error", async () => {442 const vault = await import("./vault");443 await vault.createVault("correct-pass-12345");444 vault.lock();445446 await expect(447 dispatch({448 type: "GET_ENTRY_FOR_FILL",449 payload: { id: "missing" },450 })451 ).resolves.toMatchObject({ ok: false, error: "vault_locked" });452 });453454 it("GET_ENTRY_FOR_FILL rejects passkey-only entries", async () => {455 const vault = await import("./vault");456 await vault.createVault("correct-pass-12345");457 const generated = await generatePasskeyKeypair(-7);458 const entry = await vault.addEntry({459 type: "login",460 title: "WebAuthn.io",461 passkey: {462 rpId: "webauthn.io",463 rpName: "WebAuthn.io",464 credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),465 publicKeyCose: base64urlEncode(generated.publicKeyCose),466 privateKeyJwk: generated.privateKeyJwk,467 userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),468 userName: "june",469 userDisplayName: "June",470 algorithm: -7,471 signCount: 0,472 aaguid: "AAAAAAAAAAAAAAAAAAAAAA",473 backupEligible: true,474 backupState: false,475 createdAt: Date.now(),476 },477 });478479 await expect(480 dispatch({481 type: "GET_ENTRY_FOR_FILL",482 payload: { id: entry.id },483 })484 ).resolves.toMatchObject({ ok: false, error: "passkey_not_fillable" });485 });486487 it("AUTOFILL_QUERY returns matched domain metadata without secrets", async () => {488 const vault = await import("./vault");489 await vault.createVault("correct-pass-12345");490 await vault.addEntry({491 title: "GitHub",492 username: "june",493 password: "secret123",494 url: "https://github.com",495 totp: "JBSWY3DPEHPK3PXP",496 });497498 const response = await dispatch({499 type: "AUTOFILL_QUERY",500 payload: { domain: "github.com" },501 });502503 expect(response).toMatchObject({504 ok: true,505 data: [506 {507 id: expect.any(String),508 title: "GitHub",509 username: "june",510 url: "https://github.com",511 hasTotp: true,512 },513 ],514 });515 expect((response.data as Array<Record<string, unknown>>)[0].password).toBeUndefined();516 expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();517 });518519 it("AUTOFILL_QUERY includeAll returns search-ready summaries for non-note, non-passkey entries", async () => {520 const vault = await import("./vault");521 await vault.createVault("correct-pass-12345");522 await vault.addEntry({523 title: "GitHub",524 username: "june",525 password: "secret123",526 url: "https://github.com",527 });528 await vault.addEntry({529 type: "note",530 title: "Secure note",531 notes: "hello",532 });533534 const response = await dispatch({535 type: "AUTOFILL_QUERY",536 payload: { domain: "github.com", includeAll: true },537 });538539 expect(response).toMatchObject({540 ok: true,541 data: [542 {543 id: expect.any(String),544 title: "GitHub",545 username: "june",546 url: "https://github.com",547 hasPasskey: false,548 },549 ],550 });551 const data = response.data as Array<Record<string, unknown>>;552 expect(data).toHaveLength(1);553 554 expect(data[0]).not.toHaveProperty("password");555 expect(data[0]).not.toHaveProperty("totp");556 });557558 it("AUTOFILL_QUERY kind=totp returns only matching entries with 2FA summaries", async () => {559 const vault = await import("./vault");560 await vault.createVault("correct-pass-12345");561 await vault.addEntry({562 title: "GitHub",563 username: "june",564 password: "secret123",565 url: "https://github.com",566 totp: "JBSWY3DPEHPK3PXP",567 });568 await vault.addEntry({569 title: "No 2FA",570 username: "person",571 password: "secret123",572 url: "https://github.com",573 });574575 const response = await dispatch({576 type: "AUTOFILL_QUERY",577 payload: { domain: "github.com", kind: "totp" },578 });579580 expect(response).toMatchObject({581 ok: true,582 data: [583 {584 id: expect.any(String),585 title: "GitHub",586 username: "june",587 url: "https://github.com",588 hasTotp: true,589 },590 ],591 });592 expect((response.data as Array<Record<string, unknown>>)[0].totp).toBeUndefined();593 expect(response.data).toHaveLength(1);594 });595596 it("RESTORE_ENTRIES replace mode restores the provided entries", async () => {597 const vault = await import("./vault");598 await vault.createVault("correct-pass-12345");599 await vault.addEntry({ title: "A", username: "", password: "one", url: "" });600601 const response = await dispatch({602 type: "RESTORE_ENTRIES",603 payload: {604 mode: "replace",605 entries: [606 {607 id: "restored-1",608 type: "login",609 title: "B",610 username: "june",611 password: "two",612 url: "https://b.test",613 createdAt: 1,614 modifiedAt: 1,615 },616 ],617 },618 });619620 expect(response).toMatchObject({ ok: true, data: { added: 1, updated: 0, skipped: 0 } });621 expect(vault.getEntries().map((entry) => entry.id)).toEqual(["restored-1"]);622 });623624 it("RESTORE_ENTRIES replace mode with an empty array returns an error", async () => {625 const vault = await import("./vault");626 await vault.createVault("correct-pass-12345");627628 await expect(629 dispatch({630 type: "RESTORE_ENTRIES",631 payload: { mode: "replace", entries: [] },632 })633 ).resolves.toMatchObject({ ok: false, error: "refuse to replace with empty entry set" });634 });635636 it("CHANGE_PASSWORD responds true for the happy path and false for a wrong current password", async () => {637 const vault = await import("./vault");638 await vault.createVault("correct-pass-12345");639640 await expect(641 dispatch({642 type: "CHANGE_PASSWORD",643 payload: {644 currentPassword: "correct-pass-12345",645 newPassword: "new-pass-67890",646 },647 })648 ).resolves.toMatchObject({ ok: true });649650 vault.lock();651 expect(await vault.unlock("new-pass-67890")).toBe(true);652653 await expect(654 dispatch({655 type: "CHANGE_PASSWORD",656 payload: {657 currentPassword: "wrong-pass",658 newPassword: "another-pass",659 },660 })661 ).resolves.toMatchObject({ ok: false, error: "incorrect_current_password" });662 });663664 it("UPDATE_SETTINGS reschedules auto-lock using the new minutes value", async () => {665 const vault = await import("./vault");666 await vault.createVault("correct-pass-12345");667668 (669 chrome.alarms.create as unknown as ReturnType<typeof vi.fn>670 ).mockClear();671 (672 chrome.idle.setDetectionInterval as unknown as ReturnType<typeof vi.fn>673 ).mockClear();674675 await expect(676 dispatch({677 type: "UPDATE_SETTINGS",678 payload: { autoLockMinutes: 30 },679 })680 ).resolves.toMatchObject({ ok: true });681682 expect(vault.getSettings().autoLockMinutes).toBe(30);683 expect(chrome.idle.setDetectionInterval).toHaveBeenLastCalledWith(1800);684 expect(chrome.alarms.create).toHaveBeenLastCalledWith("autolock", {685 delayInMinutes: 30,686 });687 });688689 it("CHECK_ALL_BREACHES updates matching entries without corrupting the vault", async () => {690 vi.useFakeTimers();691 const vault = await import("./vault");692 await vault.createVault("correct-pass-12345");693 const entry = await vault.addEntry({694 title: "GitHub",695 username: "june",696 password: "secret123",697 url: "https://github.com",698 });699 const breachSpy = vi.spyOn(vault, "checkBreach").mockResolvedValue(7);700701 const responsePromise = dispatch({ type: "CHECK_ALL_BREACHES" });702 await vi.runAllTimersAsync();703 const response = await responsePromise;704705 expect(response).toMatchObject({ ok: true, data: { [entry.id]: 7 } });706 expect(vault.getEntryById(entry.id)?.breach).toBe(7);707 breachSpy.mockRestore();708 });709710 it("rejects passkey approval from a different tab than the ceremony", async () => {711 sessionStorage.passkey_pending_301 = {712 requestId: 301,713 type: "get",714 rpId: "example.com",715 rpName: "Example",716 userName: "[email protected]",717 tabId: 7,718 origin: "https://example.com",719 };720721 await expect(722 dispatch(723 { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 301, approved: true } },724 { id: "peach-extension", tab: { id: 8 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,725 ),726 ).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });727 });728729 it("requires trusted popup approval for embedded passkey requests", async () => {730 sessionStorage.passkey_pending_302 = {731 requestId: 302, type: "get", rpId: "login.example", rpName: "Login",732 userName: "june", origin: "https://login.example", crossOrigin: true,733 };734 for (const origin of ["https://top.example", "https://login.example"]) {735 await expect(dispatch(736 { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 302, approved: true } },737 { id: "peach-extension", tab: { id: 7 }, origin, url: `${origin}/login` } as chrome.runtime.MessageSender,738 )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });739 expect(sessionStorage.passkey_pending_302).toBeDefined();740 }741 await expect(dispatch({ type: "APPROVE_PASSKEY", payload: { requestId: 302 } })).resolves.toMatchObject({ ok: true });742 expect(sessionStorage.passkey_pending_302).toBeUndefined();743 });744745 it.each([false, true])("rejects content approval without a bound toast (missing pending: %s)", async (missing) => {746 if (!missing) sessionStorage.passkey_pending_303 = {747 requestId: 303, type: "get", rpId: "example.com", rpName: "Example",748 userName: "june", origin: "https://example.com", crossOrigin: false,749 };750 await expect(dispatch(751 { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 303, approved: true } },752 { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,753 )).resolves.toMatchObject({ ok: false, error: "invalid_passkey_approval_sender" });754 if (!missing) expect(sessionStorage.passkey_pending_303).toBeDefined();755 });756757 it.each([true, false])("accepts bound same-origin toast consent: %s", async (approved) => {758 sessionStorage.passkey_pending_304 = {759 requestId: 304, type: "get", rpId: "example.com", rpName: "Example",760 userName: "june", tabId: 7, origin: "https://example.com", crossOrigin: false,761 };762 await expect(dispatch(763 { type: "PASSKEY_AUTH_RESPONSE", payload: { requestId: 304, approved } },764 { id: "peach-extension", tab: { id: 7 }, url: "https://example.com/login" } as chrome.runtime.MessageSender,765 )).resolves.toMatchObject({ ok: true });766 expect(sessionStorage.passkey_pending_304).toBeUndefined();767 });768769 it("messages from foreign or URL-less senders are rejected", async () => {770 const vault = await import("./vault");771 await vault.createVault("correct-pass-12345");772773 await expect(dispatch({ type: "GET_ENTRIES" }, { id: "other-extension" })).resolves.toMatchObject({774 ok: false,775 error: "invalid_sender",776 });777778 await expect(dispatch({ type: "GET_ENTRIES" }, {})).resolves.toMatchObject({779 ok: false,780 error: "invalid_sender",781 });782 });783784 it("LOCK and UNLOCK messages update vault state correctly", async () => {785 const vault = await import("./vault");786787 await expect(788 dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })789 ).resolves.toMatchObject({ ok: true });790 expect(vault.isUnlocked()).toBe(true);791792 await expect(dispatch({ type: "LOCK" })).resolves.toMatchObject({ ok: true });793 expect(vault.isUnlocked()).toBe(false);794795 await expect(796 dispatch({ type: "UNLOCK", payload: { password: "wrong-pass" } })797 ).resolves.toMatchObject({ ok: false });798 expect(vault.isUnlocked()).toBe(false);799800 await expect(801 dispatch({ type: "UNLOCK", payload: { password: "correct-pass-12345" } })802 ).resolves.toMatchObject({ ok: true });803 expect(vault.isUnlocked()).toBe(true);804 });805806 it("does not acknowledge LOCK until session cleanup finishes", async () => {807 await expect(808 dispatch({ type: "CREATE_VAULT", payload: { password: "correct-pass-12345" } })809 ).resolves.toMatchObject({ ok: true });810811 const removalStarted = deferred();812 const releaseRemoval = deferred();813 const remove = chrome.storage.session.remove as unknown as ReturnType<typeof vi.fn>;814 remove.mockImplementation(async (keys: string | string[]) => {815 removalStarted.resolve();816 await releaseRemoval.promise;817 for (const key of Array.isArray(keys) ? keys : [keys]) delete sessionStorage[key];818 });819820 let responded = false;821 const response = dispatch({ type: "LOCK" }).then((result) => {822 responded = true;823 return result;824 });825 await removalStarted.promise;826827 try {828 await Promise.resolve();829 expect(responded).toBe(false);830 } finally {831 releaseRemoval.resolve();832 }833834 await expect(response).resolves.toMatchObject({ ok: true });835 });836837 it("remembers the last successful unlock method", async () => {838 const vault = await import("./vault");839 const password = "correct-pass-12345";840 const popupSender = {841 id: "peach-extension",842 url: "chrome-extension://peach-extension/src/popup/index.html",843 } as chrome.runtime.MessageSender;844845 await vault.createVault(password);846 expect(await vault.setupPinUnlock(password, "1234")).toBe(true);847 vault.lock();848849 await expect(850 dispatch({ type: "UNLOCK_WITH_PIN", payload: { pin: "1234" } }, popupSender),851 ).resolves.toMatchObject({ ok: true });852 expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(true);853854 vault.lock();855 await expect(856 dispatch({ type: "UNLOCK", payload: { password } }, popupSender),857 ).resolves.toMatchObject({ ok: true });858 expect((await vault.ensureSettingsLoaded()).pinPreferred).toBe(false);859 });860861 it("FIRE_CANARY_PING sends a minimal payload to allowed HTTPS webhooks", async () => {862 const response = await dispatch({863 type: "FIRE_CANARY_PING",864 payload: {865 webhookUrl: "https://example.com/hook",866 entryTitle: "GitHub",867 trigger: "password_copied",868 },869 });870871 expect(response).toMatchObject({ ok: true });872 expect(fetchMock).toHaveBeenCalledWith(873 "https://example.com/hook",874 expect.objectContaining({875 method: "POST",876 headers: { "Content-Type": "application/json" },877 body: expect.any(String),878 })879 );880 const body = JSON.parse(fetchMock.mock.calls[0][1].body as string) as Record<string, unknown>;881 expect(body).toMatchObject({882 entry: "GitHub",883 trigger: "password_copied",884 source: "peach-extension",885 });886 });887888 it("LV-3: debounces a repeat non-test ping for the same webhook+entry", async () => {889 const payload = {890 webhookUrl: "https://example.com/hook",891 entryTitle: "GitHub",892 trigger: "autofilled" as const,893 };894 const first = await dispatch({ type: "FIRE_CANARY_PING", payload });895 expect(first).toMatchObject({ ok: true });896 expect(fetchMock).toHaveBeenCalledTimes(1);897 expect(Object.keys(storage).some((key) => key.includes("GitHub"))).toBe(false);898 expect(Object.keys(storage).some((key) => key.startsWith("canary-last-fetch:"))).toBe(true);899900 const second = await dispatch({ type: "FIRE_CANARY_PING", payload });901 expect(second).toMatchObject({ ok: true, data: { rateLimited: true } });902 expect(fetchMock).toHaveBeenCalledTimes(1); 903 });904905 it("LV-3: removes legacy plaintext rate-limit keys", async () => {906 const legacyKey = "canary-last-fetch:https://example.com/hook:GitHub";907 storage[legacyKey] = Date.now();908909 await dispatch({910 type: "FIRE_CANARY_PING",911 payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },912 });913914 expect(storage[legacyKey]).toBeUndefined();915 });916917 it("LV-3: debounce is per-entry — a different entry on the same webhook still fires", async () => {918 await dispatch({919 type: "FIRE_CANARY_PING",920 payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitHub", trigger: "autofilled" },921 });922 await dispatch({923 type: "FIRE_CANARY_PING",924 payload: { webhookUrl: "https://example.com/hook", entryTitle: "GitLab", trigger: "autofilled" },925 });926 expect(fetchMock).toHaveBeenCalledTimes(2);927 });928929 it("LV-3: test pings are exempt from the debounce", async () => {930 const payload = {931 webhookUrl: "https://example.com/hook",932 entryTitle: "GitHub",933 trigger: "test" as const,934 };935 await dispatch({ type: "FIRE_CANARY_PING", payload });936 await dispatch({ type: "FIRE_CANARY_PING", payload });937 expect(fetchMock).toHaveBeenCalledTimes(2);938 });939940 it("rejects test pings from content scripts before contacting the webhook", async () => {941 const response = await dispatch(942 {943 type: "FIRE_CANARY_PING",944 payload: {945 webhookUrl: "https://example.com/hook",946 entryTitle: "GitHub",947 trigger: "test",948 },949 },950 {951 id: "peach-extension",952 url: "https://example.com/login",953 tab: { id: 7 },954 } as chrome.runtime.MessageSender,955 );956957 expect(response).toMatchObject({ ok: false, error: "invalid_sender" });958 expect(fetchMock).not.toHaveBeenCalled();959 });960961 it("FIRE_CANARY_PING rejects insecure webhook urls", async () => {962 await expect(963 dispatch({964 type: "FIRE_CANARY_PING",965 payload: {966 webhookUrl: "http://example.com/hook",967 entryTitle: "GitHub",968 trigger: "password_copied",969 },970 })971 ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });972973 expect(fetchMock).not.toHaveBeenCalled();974 });975976 it("F3: FIRE_CANARY_PING rejects IPv4-mapped IPv6 webhooks pointing at private ranges (Codex Security 2026-08-04)", async () => {977 for (const webhookUrl of [978 "https://[::ffff:192.168.0.1]/hook",979 "https://[::ffff:c0a8:1]/hook",980 "https://[::ffff:10.0.0.1]/hook",981 "https://[::ffff:127.0.0.1]/hook",982 "https://[::ffff:169.254.1.1]/hook",983 "https://[::ffff:172.16.0.1]/hook",984 ]) {985 await expect(986 dispatch({987 type: "FIRE_CANARY_PING",988 payload: { webhookUrl, entryTitle: "GitHub", trigger: "password_copied" },989 })990 ).resolves.toMatchObject({ ok: false, error: "invalid_webhook_url" });991 }992993 expect(fetchMock).not.toHaveBeenCalled();994 });995996 it("GET_IDENTITIES when locked returns vault locked error", async () => {997 const vault = await import("./vault");998 await vault.createVault("correct-pass-12345");999 vault.lock();1000 await expect(dispatch({ type: "GET_IDENTITIES" })).resolves.toMatchObject({1001 ok: false,1002 error: "vault_locked",1003 });1004 });10051006 it("GET_IDENTITIES returns emails and usernames derived from login entries", async () => {1007 const vault = await import("./vault");1008 await vault.createVault("correct-pass-12345");1009 await vault.addEntry({ title: "Gmail", username: "[email protected]", password: "pw1", url: "https://gmail.com" });1010 await vault.addEntry({ title: "GitHub", username: "[email protected]", password: "pw2", url: "https://github.com" });1011 await vault.addEntry({ title: "Slack", username: "juni_patel", password: "pw3", url: "https://slack.com" });10121013 const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1014 expect(resp.ok).toBe(true);1015 const data = resp.data as Array<{ value: string; type: string; useCount: number }>;1016 expect(data.find((d) => d.value === "[email protected]")).toMatchObject({1017 type: "email",1018 useCount: 2,1019 });1020 expect(data.find((d) => d.value === "juni_patel")).toMatchObject({1021 type: "username",1022 useCount: 1,1023 });1024 1025 const emailIdx = data.findIndex((d) => d.value === "[email protected]");1026 const userIdx = data.findIndex((d) => d.value === "juni_patel");1027 expect(emailIdx).toBeLessThan(userIdx);1028 });10291030 it("GET_IDENTITIES deduplicates correctly — same email across 3 entries appears once with useCount 3", async () => {1031 const vault = await import("./vault");1032 await vault.createVault("correct-pass-12345");1033 for (let i = 0; i < 3; i++) {1034 await vault.addEntry({ title: `Site${i}`, username: "[email protected]", password: "pw", url: `https://site${i}.com` });1035 }10361037 const resp = await dispatch({ type: "GET_IDENTITIES" }) as { ok: boolean; data: unknown[] };1038 const data = resp.data as Array<{ value: string; useCount: number }>;1039 const hits = data.filter((d) => d.value === "[email protected]");1040 expect(hits).toHaveLength(1);1041 expect(hits[0]!.useCount).toBe(3);1042 });10431044 it("GET_IDENTITIES rejects content-script and page-relay senders", async () => {1045 const vault = await import("./vault");1046 await vault.createVault("correct-pass-12345");1047 await vault.addEntry({1048 title: "Private identity",1049 username: "[email protected]",1050 password: "pw",1051 url: "https://private.example",1052 });10531054 const senders = [1055 {1056 id: "peach-extension",1057 url: "https://private.example/signup",1058 tab: { id: 1 } as chrome.tabs.Tab,1059 },1060 { id: "peach-extension", url: "https://private.example/signup" },1061 ] satisfies chrome.runtime.MessageSender[];1062 for (const sender of senders) {1063 await expect(dispatch({ type: "GET_IDENTITIES" }, sender)).resolves.toMatchObject({1064 ok: false,1065 error: "invalid_sender",1066 });1067 }1068 });10691070 it("IS_CARD_DECLINED does not refresh the auto-lock timer", async () => {1071 const vault = await import("./vault");1072 await vault.createVault("correct-pass-12345");1073 const alarmsCreate = chrome.alarms.create as unknown as ReturnType<typeof vi.fn>;10741075 1076 alarmsCreate.mockClear();1077 await dispatch({ type: "GET_ENTRIES" });1078 expect(alarmsCreate).toHaveBeenCalled();10791080 1081 alarmsCreate.mockClear();1082 await dispatch({ type: "IS_CARD_DECLINED", payload: { origin: "https://example.com" } });1083 expect(alarmsCreate).not.toHaveBeenCalled();1084 });10851086 it("DESTROY_VAULT preserves the Pro license and celebration flag", async () => {1087 const vault = await import("./vault");1088 await vault.createVault("correct-pass-12345");1089 await vault.addEntry({ title: "Gmail", username: "june", password: "s", url: "https://mail.google.com" });10901091 1092 storage.peach_license = "PEACH-PRO-TEST-KEY";1093 storage.peach_pro_celebrated = true;10941095 const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1096 expect(res).toMatchObject({ ok: true });10971098 1099 expect(storage.peach_vault_a).toBeUndefined();1100 1101 expect(storage.peach_license).toBe("PEACH-PRO-TEST-KEY");1102 expect(storage.peach_pro_celebrated).toBe(true);1103 });11041105 it("handleMessage waits for the restore gate before serving (cold-start: no premature onboarding/lock)", async () => {1106 const messages = await import("./messages");1107 const vault = await import("./vault");11081109 let resolveGate: () => void = () => {};1110 messages.setRestoreReady(new Promise<void>((r) => { resolveGate = r; }));11111112 let settled = false;1113 const pending = dispatch({ type: "HAS_VAULT" }).then((r) => { settled = true; return r; });11141115 1116 1117 await new Promise((r) => setTimeout(r, 20));1118 expect(settled).toBe(false);11191120 1121 await vault.createVault("correct-pass-12345");1122 resolveGate();11231124 await expect(pending).resolves.toMatchObject({ ok: true, data: true });1125 });11261127 it.each([null, true, false, 1, {}, "replace", "warned-import "])("CREATE_VAULT rejects malformed replacement intent %j", async (replacement) => {1128 const result = await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password", replacement } });1129 expect(result).toMatchObject({ ok: false, error: "invalid_payload" });1130 expect(storage.peach_vault_a).toBeUndefined();1131 });11321133 it("CREATE_VAULT refuses ordinary replacement of an existing locked vault", async () => {1134 const vault = await import("./vault");1135 await vault.createVault("original-password");1136 await vault.lock();1137 const before = structuredClone(storage);1138 expect(await dispatch({ type: "CREATE_VAULT", payload: { password: "new-password" } })).toMatchObject({ ok: false, error: "vault_already_exists" });1139 expect(storage).toEqual(before);1140 expect(await vault.unlock("original-password")).toBe(true);1141 });11421143 it("CREATE_VAULT rejects an empty master password (audit HIGH — no empty-key vault)", async () => {1144 const res = await dispatch({ type: "CREATE_VAULT", payload: { password: "" } });1145 expect(res.ok).toBe(false);1146 1147 const has = await dispatch({ type: "HAS_VAULT" });1148 expect((has as { data?: boolean }).data).toBe(false);1149 });11501151 it("GET_ENTRY_FOR_FILL sends a 6-digit TOTP code, never the seed (SEV-3-C)", async () => {1152 const vault = await import("./vault");1153 await vault.createVault("correct-pass-12345");1154 const e = await vault.addEntry({1155 title: "Mail",1156 username: "june",1157 password: "pw",1158 url: "https://mail.test",1159 totp: "JBSWY3DPEHPK3PXP",1160 });11611162 const res = await dispatch(1163 { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1164 { id: "peach-extension", url: "https://mail.test/login" },1165 );1166 expect(res.ok).toBe(true);1167 const data = res.data as { totp?: string; totpCode?: string; totpRemaining?: number };1168 expect(data.totp).toBeUndefined();1169 expect(data.totpCode).toMatch(/^\d{6}$/);1170 expect(data.totpRemaining).toBeGreaterThan(0);1171 expect(data.totpRemaining).toBeLessThanOrEqual(30);1172 });11731174 it("GET_ENTRY_FOR_FILL strips passwordHistory; GET_ENTRY_FOR_EDIT keeps it", async () => {1175 const vault = await import("./vault");1176 await vault.createVault("correct-pass-12345");1177 const e = await vault.addEntry({1178 title: "Bank",1179 username: "june",1180 password: "old-pw",1181 url: "https://bank.test",1182 });1183 await vault.updateEntry(e.id, { password: "new-pw" });11841185 const fill = await dispatch(1186 { type: "GET_ENTRY_FOR_FILL", payload: { id: e.id } },1187 { id: "peach-extension", url: "https://bank.test/login" },1188 );1189 expect(fill.ok).toBe(true);1190 1191 expect((fill.data as Record<string, unknown>).passwordHistory).toBeUndefined();11921193 const edit = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1194 expect(edit.ok).toBe(true);1195 const editHist = (edit.data as { passwordHistory?: Array<{ password: string }> }).passwordHistory ?? [];1196 expect(editHist.map((h) => h.password)).toEqual(["old-pw"]);1197 });11981199 it("GET_ENTRY_FOR_EDIT returns the raw TOTP seed for the trusted edit form", async () => {1200 const vault = await import("./vault");1201 await vault.createVault("correct-pass-12345");1202 const e = await vault.addEntry({1203 title: "Mail",1204 username: "june",1205 password: "pw",1206 url: "https://mail.test",1207 totp: "JBSWY3DPEHPK3PXP",1208 });12091210 const res = await dispatch({ type: "GET_ENTRY_FOR_EDIT", payload: { id: e.id } });1211 expect(res.ok).toBe(true);1212 const data = res.data as { totp?: string };1213 expect(data.totp).toBe("JBSWY3DPEHPK3PXP");1214 });12151216 it("DESTROY_VAULT with no license clears storage without resurrecting keys", async () => {1217 const vault = await import("./vault");1218 await vault.createVault("correct-pass-12345");12191220 const res = await dispatch({ type: "DESTROY_VAULT" }, { id: "peach-extension", url: "chrome-extension://peach-extension/popup.html" });1221 expect(res).toMatchObject({ ok: true });12221223 expect(storage.peach_vault_a).toBeUndefined();1224 expect(storage.peach_license).toBeUndefined();1225 expect(storage.peach_pro_celebrated).toBeUndefined();1226 });12271228 12291230 function tabSender(url: string, tabId = 1, frameId = 0): chrome.runtime.MessageSender {1231 return { id: "peach-extension", tab: { id: tabId, url } as chrome.tabs.Tab, url, frameId };1232 }12331234 async function addPasskeyOnlyEntry(title: string, url: string) {1235 const vault = await import("./vault");1236 const generated = await generatePasskeyKeypair(-7);1237 return vault.addEntry({1238 type: "login",1239 title,1240 url,1241 passkey: {1242 rpId: new URL(url).hostname,1243 rpName: title,1244 credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1245 publicKeyCose: base64urlEncode(generated.publicKeyCose),1246 privateKeyJwk: generated.privateKeyJwk,1247 userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),1248 userName: "june",1249 userDisplayName: "June",1250 algorithm: -7,1251 signCount: 0,1252 aaguid: "AAAAAAAAAAAAAAAAAAAAAA",1253 backupEligible: true,1254 backupState: false,1255 createdAt: Date.now(),1256 },1257 });1258 }12591260 it("PB-26-201: normal inventory ignores forged domain and gesture booleans", async () => {1261 const vault = await import("./vault");1262 await vault.createVault("correct-pass-12345");1263 await vault.addEntry({ title: "GitHub", username: "victim", password: "secret", url: "https://github.com" });1264 await vault.addEntry({ title: "Evil", username: "attacker", password: "known", url: "https://evil.example.com" });12651266 const result = await dispatch(1267 {1268 type: "AUTOFILL_QUERY",1269 payload: {1270 domain: "github.com",1271 includeAll: true,1272 userGesture: true,1273 explicitSummon: true,1274 },1275 },1276 tabSender("https://evil.example.com/phish"),1277 );12781279 expect(result).toMatchObject({ ok: true });1280 expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil"]);1281 });12821283 it("PB-26-201: normal TOTP inventory is scoped to the attested frame origin", async () => {1284 const vault = await import("./vault");1285 await vault.createVault("correct-pass-12345");1286 await vault.addEntry({ title: "GitHub 2FA", password: "secret", url: "https://github.com", totp: "JBSWY3DPEHPK3PXP" });1287 await vault.addEntry({ title: "Evil 2FA", password: "known", url: "https://evil.example.com", totp: "JBSWY3DPEHPK3PXP" });12881289 const result = await dispatch(1290 { type: "AUTOFILL_QUERY", payload: { domain: "github.com", kind: "totp" } },1291 tabSender("https://evil.example.com/verify"),1292 );12931294 expect((result.data as Array<{ title: string }>).map((entry) => entry.title)).toEqual(["Evil 2FA"]);1295 });12961297 it("PB-26-201: summon capability is one-shot after inventory authorization", async () => {1298 const vault = await import("./vault");1299 const messages = await import("./messages");1300 await vault.createVault("correct-pass-12345");1301 const entry = await vault.addEntry({ title: "GitHub", username: "june", password: "secret123", url: "https://github.com" });1302 const sender = tabSender("https://evil.example.com/phish");1303 const token = messages.createSummonCapability(1, "https://evil.example.com");13041305 const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1306 expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });13071308 const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1309 expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });1310 const replay = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1311 expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1312 });13131314 it("PB-26-201: summon capability is consumed by a same-domain fill", async () => {1315 const vault = await import("./vault");1316 const messages = await import("./messages");1317 await vault.createVault("correct-pass-12345");1318 const entry = await vault.addEntry({ title: "GitHub", password: "secret123", url: "https://evil.example.com" });1319 const sender = tabSender("https://evil.example.com/login");1320 const token = messages.createSummonCapability(1, "https://evil.example.com");13211322 const inventory = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1323 expect(inventory).toMatchObject({ ok: true, data: [{ id: entry.id }] });1324 const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1325 expect(firstFill).toMatchObject({ ok: true, data: { id: entry.id } });13261327 const offDomainReplay = await dispatch(1328 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1329 tabSender("https://github.com/login"),1330 );1331 expect(offDomainReplay).toMatchObject({ ok: false, error: "entry_not_found" });1332 });13331334 it("PB-26-201: summon capability cannot fill a different entry", async () => {1335 const vault = await import("./vault");1336 const messages = await import("./messages");1337 await vault.createVault("correct-pass-12345");1338 const first = await vault.addEntry({ title: "First", password: "one", url: "https://first.example" });1339 const second = await vault.addEntry({ title: "Second", password: "two", url: "https://second.example" });1340 const sender = tabSender("https://evil.example.com/phish");1341 const token = messages.createSummonCapability(1, "https://evil.example.com");1342 await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1343 const firstFill = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: first.id, capability: token } }, sender);1344 expect(firstFill).toMatchObject({ ok: true, data: { id: first.id } });1345 const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: second.id, capability: token } }, sender);1346 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1347 expect(first.id).not.toBe(second.id);1348 });13491350 it("PB-26-201: fill before inventory is rejected without an entry oracle", async () => {1351 const vault = await import("./vault");1352 const messages = await import("./messages");1353 await vault.createVault("correct-pass-12345");1354 const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1355 const token = messages.createSummonCapability(1, "https://evil.example.com");1356 const result = await dispatch(1357 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1358 tabSender("https://evil.example.com/phish"),1359 );1360 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1361 });13621363 it("PB-26-201: an unused summon capability does not block a normal same-origin fill", async () => {1364 const vault = await import("./vault");1365 const messages = await import("./messages");1366 await vault.createVault("correct-pass-12345");1367 const entry = await vault.addEntry({1368 title: "Evil",1369 password: "known",1370 url: "https://evil.example.com",1371 });1372 const sender = tabSender("https://evil.example.com/login");1373 const token = messages.createSummonCapability(1, "https://evil.example.com");13741375 const result = await dispatch(1376 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1377 sender,1378 );13791380 expect(result).toMatchObject({ ok: true, data: { id: entry.id } });1381 });13821383 it("PB-26-201: expired fill capability is rejected before entry-specific errors", async () => {1384 vi.useFakeTimers();1385 vi.setSystemTime(new Date("2026-09-02T12:00:00Z"));1386 const vault = await import("./vault");1387 const messages = await import("./messages");1388 await vault.createVault("correct-pass-12345");1389 const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1390 const sender = tabSender("https://evil.example.com/phish");1391 const token = messages.createSummonCapability(1, "https://evil.example.com");1392 await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1393 vi.advanceTimersByTime(30_001);13941395 const result = await dispatch({ type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } }, sender);1396 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1397 });13981399 it("PB-26-201: wrong-tab fill capability is rejected before entry-specific errors", async () => {1400 const vault = await import("./vault");1401 const messages = await import("./messages");1402 await vault.createVault("correct-pass-12345");1403 const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1404 const token = messages.createSummonCapability(1, "https://evil.example.com");1405 await dispatch(1406 { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1407 tabSender("https://evil.example.com/phish"),1408 );14091410 const result = await dispatch(1411 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1412 tabSender("https://evil.example.com/phish", 2),1413 );1414 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1415 });14161417 it("PB-26-201: wrong-frame fill capability is rejected before entry-specific errors", async () => {1418 const vault = await import("./vault");1419 const messages = await import("./messages");1420 await vault.createVault("correct-pass-12345");1421 const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1422 const token = messages.createSummonCapability(1, "https://evil.example.com", 3);1423 await dispatch(1424 { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1425 tabSender("https://evil.example.com/phish", 1, 3),1426 );14271428 const result = await dispatch(1429 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1430 tabSender("https://evil.example.com/phish", 1, 4),1431 );1432 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1433 });14341435 it("PB-26-201: wrong-origin fill capability is rejected before entry-specific errors", async () => {1436 const vault = await import("./vault");1437 const messages = await import("./messages");1438 await vault.createVault("correct-pass-12345");1439 const entry = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1440 const token = messages.createSummonCapability(1, "https://evil.example.com");1441 await dispatch(1442 { type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } },1443 tabSender("https://evil.example.com/phish"),1444 );14451446 const result = await dispatch(1447 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id, capability: token } },1448 tabSender("https://other.example.com/phish"),1449 );1450 expect(result).toMatchObject({ ok: false, error: "entry_not_found" });1451 });14521453 it("PB-26-201: selecting a missing id consumes the one-shot capability without an oracle", async () => {1454 const vault = await import("./vault");1455 const messages = await import("./messages");1456 await vault.createVault("correct-pass-12345");1457 const existing = await addPasskeyOnlyEntry("GitHub passkey", "https://github.com");1458 const sender = tabSender("https://evil.example.com/phish");1459 const token = messages.createSummonCapability(1, "https://evil.example.com");1460 await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);14611462 const missing = await dispatch(1463 { type: "GET_ENTRY_FOR_FILL", payload: { id: "missing", capability: token } },1464 sender,1465 );1466 const existingReplay = await dispatch(1467 { type: "GET_ENTRY_FOR_FILL", payload: { id: existing.id, capability: token } },1468 sender,1469 );1470 expect(missing).toMatchObject({ ok: false, error: "entry_not_found" });1471 expect(existingReplay).toEqual(missing);1472 });14731474 it("PB-26-201: inventory capability cannot be reused for a second inventory", async () => {1475 const vault = await import("./vault");1476 const messages = await import("./messages");1477 await vault.createVault("correct-pass-12345");1478 await vault.addEntry({ title: "GitHub", password: "secret", url: "https://github.com" });1479 const sender = tabSender("https://evil.example.com/phish");1480 const token = messages.createSummonCapability(1, "https://evil.example.com");1481 const first = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);1482 const second = await dispatch({ type: "AUTOFILL_QUERY", payload: { domain: "evil.example.com", capability: token } }, sender);14831484 expect(first).toMatchObject({ ok: true, data: [{ title: "GitHub" }] });1485 expect(second).toMatchObject({ ok: false, error: "entry_not_found" });1486 });14871488 it("PB-26-201: cards require a capability and consume it on the selected fill", async () => {1489 const vault = await import("./vault");1490 const messages = await import("./messages");1491 await vault.createVault("correct-pass-12345");1492 const card = await vault.addEntry({1493 type: "card",1494 title: "Personal Visa",1495 cardholderName: "June Peach",1496 cardNumber: "4111111111111111",1497 cvc: "123",1498 expMonth: "12",1499 expYear: "2030",1500 });1501 const sender = tabSender("https://shop.example.com/checkout");1502 const passive = await dispatch(1503 { type: "AUTOFILL_QUERY", payload: { domain: "shop.example.com", kind: "card" } },1504 sender,1505 );1506 expect(passive).toMatchObject({ ok: true, data: [] });15071508 const token = messages.createSummonCapability(1, "https://shop.example.com");1509 const inventory = await dispatch(1510 { type: "AUTOFILL_QUERY", payload: { domain: "forged.example", kind: "card", capability: token } },1511 sender,1512 );1513 expect(inventory).toMatchObject({ ok: true, data: [{ id: card.id, title: "Personal Visa" }] });1514 expect((inventory.data as Array<Record<string, unknown>>)[0]).not.toHaveProperty("cardNumber");15151516 const fill = await dispatch(1517 { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1518 sender,1519 );1520 expect(fill).toMatchObject({ ok: true, data: { id: card.id, cardNumber: "4111111111111111" } });1521 const replay = await dispatch(1522 { type: "GET_ENTRY_FOR_FILL", payload: { id: card.id, capability: token } },1523 sender,1524 );1525 expect(replay).toMatchObject({ ok: false, error: "entry_not_found" });1526 });15271528 it("PB-26-201: inline edit popup request stores only the selected entry id", async () => {1529 const result = await dispatch(1530 { type: "OPEN_POPUP", payload: { entryId: "entry-123" } },1531 tabSender("https://example.com/login"),1532 );15331534 expect(result).toMatchObject({ ok: true });1535 expect(sessionStorage.peach_open_entry).toBe("entry-123");1536 expect(sessionStorage.peach_inline_unlock).toBeUndefined();1537 });15381539 it("MV-1: tab request with a matching domain returns the entry", async () => {1540 const vault = await import("./vault");1541 await vault.createVault("correct-pass-12345");1542 const entry = await vault.addEntry({1543 title: "GitHub",1544 username: "june",1545 password: "secret123",1546 url: "https://github.com",1547 });15481549 const res = await dispatch(1550 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1551 tabSender("https://github.com/login"),1552 );1553 expect(res).toMatchObject({ ok: true, data: { id: entry.id } });1554 });15551556 it("MV-1: tab request with a mismatched domain and no explicitSummon is refused as entry_not_found", async () => {1557 const vault = await import("./vault");1558 await vault.createVault("correct-pass-12345");1559 const entry = await vault.addEntry({1560 title: "GitHub",1561 username: "june",1562 password: "secret123",1563 url: "https://github.com",1564 });15651566 const res = await dispatch(1567 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1568 tabSender("https://evil.example.com/phish"),1569 );1570 1571 expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1572 });15731574 it("PB-26-201: explicitSummon cannot authorize off-domain fill", async () => {1575 const vault = await import("./vault");1576 await vault.createVault("correct-pass-12345");1577 const entry = await vault.addEntry({1578 title: "GitHub",1579 username: "june",1580 password: "secret123",1581 url: "https://github.com",1582 });15831584 const res = await dispatch(1585 {1586 type: "GET_ENTRY_FOR_FILL",1587 payload: { id: entry.id, explicitSummon: true },1588 },1589 tabSender("https://evil.example.com/phish"),1590 );1591 expect(res).toMatchObject({ ok: false, error: "entry_not_found" });1592 });15931594 it("MV-1: tab context with an unparseable URL is refused as origin_unverified", async () => {1595 const vault = await import("./vault");1596 await vault.createVault("correct-pass-12345");1597 const entry = await vault.addEntry({1598 title: "GitHub",1599 username: "june",1600 password: "secret123",1601 url: "https://github.com",1602 });16031604 const res = await dispatch(1605 { type: "GET_ENTRY_FOR_FILL", payload: { id: entry.id } },1606 tabSender("not a url"),1607 );1608 expect(res).toMatchObject({ ok: false, error: "origin_unverified" });1609 });16101611 16121613 async function seedTwoDomainVault() {1614 const vault = await import("./vault");1615 await vault.createVault("correct-pass-12345");1616 await vault.addEntry({1617 title: "GitHub",1618 username: "june",1619 password: "gh",1620 url: "https://github.com",1621 });1622 await vault.addEntry({1623 title: "Example",1624 username: "june",1625 password: "ex",1626 url: "https://example.com",1627 });1628 }16291630 it("MV-2: AUTOFILL_QUERY with includeAll but no userGesture returns only the domain-scoped list", async () => {1631 await seedTwoDomainVault();16321633 const res = await dispatch({1634 type: "AUTOFILL_QUERY",1635 payload: { domain: "github.com", includeAll: true },1636 });1637 expect(res.ok).toBe(true);1638 const data = res.data as Array<{ title: string }>;1639 1640 expect(data).toHaveLength(1);1641 expect(data[0].title).toBe("GitHub");1642 });16431644 it("PB-26-201: userGesture cannot authorize vault-wide inventory", async () => {1645 await seedTwoDomainVault();16461647 const res = await dispatch({1648 type: "AUTOFILL_QUERY",1649 payload: { domain: "github.com", includeAll: true, userGesture: true },1650 });1651 expect(res.ok).toBe(true);1652 const data = res.data as Array<{ title: string }>;1653 expect(data.map((d) => d.title)).toEqual(["GitHub"]);1654 });16551656 it("PB-26-104: decoy pairing messages hide devices and prior sync outcome", async () => {1657 const vault = await import("./vault");1658 const { listPairedDevices, upsertPairedDevice } = await import("./paired-devices");1659 const { setSyncRunner, triggerSyncIfReachable } = await import("./sync-trigger");1660 await vault.createVault("correct-pass-12345");1661 await vault.setupDuress("decoy-pass-67890");1662 await upsertPairedDevice({1663 deviceId: "android-real",1664 deviceName: "Real Pixel",1665 deviceType: "android",1666 longTermPublicKeyHex: "a".repeat(64),1667 trustSource: "direct",1668 pairedAt: 1_700_000_000_000,1669 });1670 setSyncRunner(async () => ({ ok: true, entriesReceived: 3, entriesSent: 2 }));1671 await triggerSyncIfReachable({ reason: "manual" });16721673 await vault.lock();1674 expect(await vault.unlock("decoy-pass-67890")).toBe(true);1675 await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toEqual({1676 ok: true,1677 data: { devices: [] },1678 });1679 await expect(dispatch({ type: "GET_SYNC_STATE" })).resolves.toEqual({1680 ok: true,1681 data: { status: "idle" },1682 });1683 expect((await listPairedDevices()).map((device) => device.deviceName)).toEqual(["Real Pixel"]);1684 });16851686 it("PB-26-104: real unlocked pairing messages retain the device list", async () => {1687 const vault = await import("./vault");1688 const { upsertPairedDevice } = await import("./paired-devices");1689 await vault.createVault("correct-pass-12345");1690 await upsertPairedDevice({1691 deviceId: "android-real",1692 deviceName: "Real Pixel",1693 deviceType: "android",1694 longTermPublicKeyHex: "a".repeat(64),1695 trustSource: "direct",1696 pairedAt: 1_700_000_000_000,1697 });16981699 await expect(dispatch({ type: "LIST_PAIRED_DEVICES" })).resolves.toMatchObject({1700 ok: true,1701 data: { devices: [{ deviceId: "android-real", deviceName: "Real Pixel" }] },1702 });1703 });17041705 async function seedPendingVouched(deviceId: string) {1706 await chrome.storage.local.set({1707 peach_pending_vouched_devices_v1: [{1708 deviceId,1709 deviceName: "New Pixel",1710 deviceType: "android",1711 longTermPublicKeyHex: "e".repeat(64),1712 signingPublicKeyHex: "a".repeat(64),1713 wsPort: 51234,1714 pairedAt: 1_700_000_000_020,1715 receivedAt: 1_700_000_000_050,1716 vouchedByDeviceId: "extension-issuer",1717 }],1718 });1719 }17201721 it("MV-7: CONFIRM_VOUCHED_DEVICE moves a pending device into the paired registry as vouched", async () => {1722 const vault = await import("./vault");1723 await vault.createVault("correct-pass-12345");1724 await seedPendingVouched("android-new");1725 const { findPairedDeviceById } = await import("./paired-devices");1726 const { listPendingVouchedDevices } = await import(1727 "./pending-vouched-devices"1728 );17291730 const res = await dispatch({1731 type: "CONFIRM_VOUCHED_DEVICE",1732 payload: { deviceId: "android-new" },1733 });1734 expect(res).toMatchObject({ ok: true });17351736 expect(await findPairedDeviceById("android-new")).toMatchObject({1737 deviceName: "New Pixel",1738 trustSource: "vouched",1739 longTermPublicKeyHex: "e".repeat(64),1740 });1741 expect(await listPendingVouchedDevices()).toHaveLength(0);1742 });17431744 it("S1: CONFIRM_VOUCHED_DEVICE refuses a pending device whose key is revoked", async () => {1745 const vault = await import("./vault");1746 await vault.createVault("correct-pass-12345");1747 await seedPendingVouched("android-relabelled");1748 const { findPairedDeviceById, revokeDeviceById, upsertPairedDevice } =1749 await import("./paired-devices");1750 const { listPendingVouchedDevices } = await import(1751 "./pending-vouched-devices"1752 );17531754 1755 1756 await upsertPairedDevice({1757 deviceId: "android-old",1758 deviceName: "New Pixel",1759 deviceType: "android",1760 longTermPublicKeyHex: "e".repeat(64),1761 signingPublicKeyHex: "a".repeat(64),1762 pairedAt: 1_700_000_000_000,1763 trustSource: "vouched",1764 });1765 await revokeDeviceById("android-old", "self");17661767 const res = await dispatch({1768 type: "CONFIRM_VOUCHED_DEVICE",1769 payload: { deviceId: "android-relabelled" },1770 });1771 expect(res).toMatchObject({ ok: false, error: "device_revoked" });1772 expect(await findPairedDeviceById("android-relabelled")).toBeNull();1773 expect(await listPendingVouchedDevices()).toHaveLength(0);1774 });17751776 it("MV-7: REJECT_VOUCHED_DEVICE clears the pending entry and never pairs it", async () => {1777 const vault = await import("./vault");1778 await vault.createVault("correct-pass-12345");1779 await seedPendingVouched("android-new");1780 const { findPairedDeviceById } = await import("./paired-devices");1781 const { listPendingVouchedDevices } = await import(1782 "./pending-vouched-devices"1783 );17841785 const res = await dispatch({1786 type: "REJECT_VOUCHED_DEVICE",1787 payload: { deviceId: "android-new" },1788 });1789 expect(res).toMatchObject({ ok: true });17901791 expect(await findPairedDeviceById("android-new")).toBeNull();1792 expect(await listPendingVouchedDevices()).toHaveLength(0);1793 });17941795 17961797 it("UNPAIR_DEVICE revokes a paired device, drops the row, and lists the revocation", async () => {1798 const vault = await import("./vault");1799 await vault.createVault("correct-pass-12345");1800 1801 1802 const identity = await import("./device-identity");1803 await identity.getOrCreateDeviceId();1804 const { findPairedDeviceById, isDeviceRevoked, listDeviceRevocations, upsertPairedDevice } =1805 await import("./paired-devices");18061807 await upsertPairedDevice({1808 deviceId: "phone-1",1809 deviceName: "June's Phone",1810 deviceType: "android",1811 longTermPublicKeyHex: "a".repeat(64),1812 signingPublicKeyHex: "b".repeat(64),1813 pairedAt: 1_700_000_000_000,1814 trustSource: "direct",1815 });18161817 const res = await dispatch({1818 type: "UNPAIR_DEVICE",1819 payload: { deviceId: "phone-1" },1820 });1821 expect(res).toMatchObject({ ok: true });18221823 1824 expect(await findPairedDeviceById("phone-1")).toBeNull();1825 1826 1827 expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1828 const records = await listDeviceRevocations();1829 expect(records).toHaveLength(1);1830 expect(records[0]).toMatchObject({1831 deviceId: "phone-1",1832 longTermPublicKeyHex: "a".repeat(64),1833 revokedByDeviceId: expect.any(String),1834 });1835 });1836 it("UNPAIR_DEVICE still evicts a peer when the local identity needs migration", async () => {1837 const vault = await import("./vault");1838 await vault.createVault("correct-pass-12345");1839 const identity = await import("./device-identity");1840 await identity.getOrCreateDeviceId();1841 delete storage.peach_local_identity_v4;1842 delete sessionStorage.peach_local_identity_session;1843 const { findPairedDeviceById, isDeviceRevoked, upsertPairedDevice } = await import("./paired-devices");1844 await upsertPairedDevice({1845 deviceId: "phone-1",1846 deviceName: "June's Phone",1847 deviceType: "android",1848 longTermPublicKeyHex: "a".repeat(64),1849 signingPublicKeyHex: "b".repeat(64),1850 pairedAt: 1_700_000_000_000,1851 trustSource: "direct",1852 });18531854 const response = await dispatch({ type: "UNPAIR_DEVICE", payload: { deviceId: "phone-1" } });18551856 expect(response).toMatchObject({ ok: true });1857 expect(await findPairedDeviceById("phone-1")).toBeNull();1858 expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);1859 });18601861 it("UNPAIR_DEVICE on an unknown id is a no-op (ok) and writes no revocation", async () => {1862 const vault = await import("./vault");1863 await vault.createVault("correct-pass-12345");1864 const { listDeviceRevocations } = await import("./paired-devices");18651866 const res = await dispatch({1867 type: "UNPAIR_DEVICE",1868 payload: { deviceId: "never-paired" },1869 });1870 expect(res).toMatchObject({ ok: true });1871 1872 1873 1874 1875 const records = await listDeviceRevocations();1876 expect(records).toHaveLength(1);1877 expect(records[0]).toMatchObject({1878 deviceId: "never-paired",1879 longTermPublicKeyHex: "0".repeat(64),1880 });1881 });18821883 it("UNPAIR_DEVICE refuses an empty payload with invalid_payload", async () => {1884 const res = await dispatch({1885 type: "UNPAIR_DEVICE",1886 payload: { deviceId: "" },1887 });1888 expect(res).toMatchObject({ ok: false, error: "invalid_payload" });1889 });1890 it("SECURE_RESET archives legacy trust, rotates identity, and reaches the new Sync anchor", async () => {1891 const vault = await import("./vault");1892 await vault.createVault("correct-pass-12345");1893 const identity = await import("./device-identity");1894 const previousDeviceId = await identity.getOrCreateDeviceId();1895 const { upsertPairedDevice } = await import("./paired-devices");1896 await upsertPairedDevice({1897 deviceId: "phone-1",1898 deviceName: "June's Phone",1899 deviceType: "android",1900 longTermPublicKeyHex: "a".repeat(64),1901 signingPublicKeyHex: "b".repeat(64),1902 pairedAt: 1_700_000_000_000,1903 trustSource: "direct",1904 });19051906 const response = await dispatch({1907 type: "SECURE_RESET",1908 payload: { password: "correct-pass-12345" },1909 });19101911 expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1912 expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);1913 });1914 it("SECURE_RESET unlocks a locked real vault before rotating identity", async () => {1915 const vault = await import("./vault");1916 await vault.createVault("correct-pass-12345");1917 const identity = await import("./device-identity");1918 const previousDeviceId = await identity.getOrCreateDeviceId();1919 const { upsertPairedDevice } = await import("./paired-devices");1920 await upsertPairedDevice({1921 deviceId: "phone-1",1922 deviceName: "June's Phone",1923 deviceType: "android",1924 longTermPublicKeyHex: "a".repeat(64),1925 signingPublicKeyHex: "b".repeat(64),1926 pairedAt: 1_700_000_000_000,1927 trustSource: "direct",1928 });1929 await vault.lock();1930 expect(vault.isUnlocked()).toBe(false);19311932 const response = await dispatch({1933 type: "SECURE_RESET",1934 payload: { password: "correct-pass-12345" },1935 });19361937 expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1938 expect(vault.isUnlocked()).toBe(true);1939 expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);1940 });1941 it("SECURE_RESET completes after fresh unlock when the locked spool hits identity migration", async () => {1942 const vault = await import("./vault");1943 const syncAdapter = await import("./sync-vault-adapter");1944 vault.setLockedSyncHooks({1945 refresh: syncAdapter.refreshLockedSyncSpool,1946 afterUnlock: syncAdapter.drainAndRefreshLockedSyncSpool,1947 });1948 await vault.createVault("correct-pass-12345");1949 const identity = await import("./device-identity");1950 const previousDeviceId = await identity.getOrCreateDeviceId();1951 const { upsertPairedDevice } = await import("./paired-devices");1952 await upsertPairedDevice({1953 deviceId: "phone-1",1954 deviceName: "June's Phone",1955 deviceType: "android",1956 longTermPublicKeyHex: "a".repeat(64),1957 signingPublicKeyHex: "b".repeat(64),1958 pairedAt: 1_700_000_000_000,1959 trustSource: "direct",1960 });1961 await vault.addEntry({ type: "login", title: "spooled", password: "secret" });1962 await syncAdapter.refreshLockedSyncSpool();1963 await vault.lock();1964 const { createLockedSyncVaultAdapter } = await import("./locked-sync-spool");1965 const lockedAdapter = await createLockedSyncVaultAdapter();1966 expect(lockedAdapter).not.toBeNull();1967 await lockedAdapter!.applyEntries({ remote: "AA==" }, { remote: Date.now() + 1 });1968 delete storage.peach_local_identity_v4;1969 delete sessionStorage.peach_local_identity_session;1970 const sessionSet = chrome.storage.session.set as unknown as ReturnType<typeof vi.fn>;1971 sessionSet.mockImplementation(async (next: Record<string, unknown>) => {1972 if (Object.hasOwn(next, "peach_local_identity_session")) {1973 throw new Error("QUOTA_BYTES");1974 }1975 Object.assign(sessionStorage, next);1976 });19771978 const unlocked = await dispatch({1979 type: "UNLOCK",1980 payload: { password: "correct-pass-12345" },1981 });1982 const pairSecrets = await import("./pair-secrets");1983 const root = Uint8Array.from((vault.getRootKeyHex() ?? "").match(/../g)!, (part) => Number.parseInt(part, 16));1984 await pairSecrets.setPairSecret("phone-1", "c".repeat(64), root);1985 root.fill(0);1986 expect(storage.peach_pair_secrets_v1).toBeDefined();1987 expect(sessionStorage.peach_pair_secrets_session).toBeDefined();1988 expect(unlocked).toMatchObject({ ok: true });19891990 const response = await dispatch({1991 type: "SECURE_RESET",1992 payload: { password: "correct-pass-12345" },1993 });19941995 expect(response).toMatchObject({ ok: true, data: { state: "V2_ANCHOR" } });1996 expect(storage.peach_local_identity_v4).toBeDefined();1997 expect(storage.peach_paired_devices_v3).toBeUndefined();1998 expect(storage.peach_pair_secrets_v1).toBeUndefined();1999 expect(sessionStorage.peach_pair_secrets_session).toBeUndefined();2000 expect(await identity.getOrCreateDeviceId()).not.toBe(previousDeviceId);2001 });2002 2003 2004 2005 2006 2007 it("F1: privileged handlers reject content-script senders but keep extension-page senders (Codex Security 2026-08-04)", async () => {2008 const vault = await import("./vault");2009 await vault.createVault("correct-pass-12345");2010 const contentScriptSender = {2011 id: "peach-extension",2012 url: "https://evil.example/page",2013 };2014 const extensionPageSender = {2015 id: "peach-extension",2016 url: "chrome-extension://peach-extension/popup.html",2017 };2018 const completion = { requestId: 1, rpId: "evil.example" };20192020 2021 await expect(2022 dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, contentScriptSender)2023 ).resolves.toMatchObject({ ok: false, error: "invalid_sender" });20242025 2026 2027 await expect(2028 dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2029 ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });2030 });20312032 it("F2: COMPLETE_FIREFOX_PASSKEY_CREATE must match the pending ceremony (Codex Security 2026-08-04)", async () => {2033 const vault = await import("./vault");2034 await vault.createVault("correct-pass-12345");2035 const extensionPageSender = {2036 id: "peach-extension",2037 url: "chrome-extension://peach-extension/popup.html",2038 };2039 const completion = {2040 requestId: 123,2041 rpId: "example.com",2042 rpName: "Example",2043 userName: "june",2044 userHandle: "BBBB",2045 credentialId: "cred-1",2046 publicKeyCose: "c3BraQ",2047 algorithm: -7 as const,2048 };20492050 2051 await expect(2052 dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2053 ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });20542055 2056 sessionStorage.passkey_pending_firefox = {2057 requestId: 123,2058 type: "create",2059 rpId: "example.com",2060 rpName: "Example",2061 userName: "june",2062 browser: "firefox",2063 challenge: "AAAA",2064 userHandle: "BBBB",2065 };20662067 2068 await expect(2069 dispatch(2070 { type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: { ...completion, userHandle: "CCCC" } },2071 extensionPageSender2072 )2073 ).resolves.toMatchObject({ ok: false, error: "no_pending_request" });20742075 2076 await expect(2077 dispatch({ type: "COMPLETE_FIREFOX_PASSKEY_CREATE", payload: completion }, extensionPageSender)2078 ).resolves.toMatchObject({ ok: true });2079 const entries = await dispatch({ type: "GET_ENTRIES" });2080 expect(entries).toMatchObject({ ok: true });2081 const stored = (entries as { data: Array<{ passkey?: { credentialId?: string } }> }).data;2082 expect(stored.some((entry) => entry.passkey?.credentialId === "cred-1")).toBe(true);2083 });20842085 it("F2: INITIATE_FIREFOX_PASSKEY_CREATE rejects an rpId the caller origin does not own (Codex Security 2026-08-04)", async () => {2086 await expect(2087 dispatch(2088 {2089 type: "INITIATE_FIREFOX_PASSKEY_CREATE",2090 payload: { rpId: "bank.example", rpName: "Bank", userName: "june" },2091 },2092 { id: "peach-extension", url: "https://evil.example/page" }2093 )2094 ).resolves.toMatchObject({ ok: false, error: "rpid_origin_mismatch" });2095 });20962097 it("after UNPAIR_DEVICE, a fresh id carrying the same revoked key is also refused (S1)", async () => {2098 2099 2100 2101 2102 const vault = await import("./vault");2103 await vault.createVault("correct-pass-12345");2104 const { isDeviceRevoked, revokeDeviceById, upsertPairedDevice } = await import(2105 "./paired-devices"2106 );21072108 await upsertPairedDevice({2109 deviceId: "phone-1",2110 deviceName: "June's Phone",2111 deviceType: "android",2112 longTermPublicKeyHex: "a".repeat(64),2113 signingPublicKeyHex: "b".repeat(64),2114 pairedAt: 1_700_000_000_000,2115 trustSource: "direct",2116 });21172118 expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(false);2119 await revokeDeviceById("phone-1", "self");2120 2121 expect(await isDeviceRevoked("phone-1", "a".repeat(64))).toBe(true);2122 expect(await isDeviceRevoked("fresh-id", "a".repeat(64))).toBe(true);2123 });21242125 21262127 it("LV-4: GET_RECOVERY_WORDS without a password returns password_required", async () => {2128 const vault = await import("./vault");2129 await vault.createVault("correct-pass-12345");21302131 const res = await dispatch({ type: "GET_RECOVERY_WORDS", payload: {} });2132 expect(res).toMatchObject({ ok: false, error: "password_required" });2133 });21342135 it("LV-4: GET_RECOVERY_WORDS with a wrong password returns wrong_password and no words", async () => {2136 const vault = await import("./vault");2137 await vault.createVault("correct-pass-12345");21382139 const res = await dispatch({2140 type: "GET_RECOVERY_WORDS",2141 payload: { password: "not-the-password" },2142 });2143 expect(res).toMatchObject({ ok: false, error: "wrong_password" });2144 expect(res.data).toBeUndefined();2145 });21462147 it("LV-4: GET_RECOVERY_WORDS with the correct password returns 12 words", async () => {2148 const vault = await import("./vault");2149 await vault.createVault("correct-pass-12345");21502151 const res = await dispatch({2152 type: "GET_RECOVERY_WORDS",2153 payload: { password: "correct-pass-12345" },2154 });2155 expect(res.ok).toBe(true);2156 expect((res.data as string[]).length).toBe(12);2157 });21582159 it("PB-26-311: cleartext export requires a fresh master-password proof", async () => {2160 const vault = await import("./vault");2161 await vault.createVault("correct-pass-12345");21622163 await expect(2164 dispatch({ type: "EXPORT_ENTRIES" as never, payload: {} }),2165 ).resolves.toMatchObject({ ok: false, error: "password_required" });2166 await expect(2167 dispatch({2168 type: "EXPORT_ENTRIES" as never,2169 payload: { password: "not-the-password" },2170 }),2171 ).resolves.toMatchObject({ ok: false, error: "wrong_password" });2172 await expect(2173 dispatch({2174 type: "EXPORT_ENTRIES" as never,2175 payload: { password: "correct-pass-12345" },2176 }),2177 ).resolves.toMatchObject({ ok: true, data: [] });2178 });21792180 it("GET_PIN_STATUS reports only a session-available PIN wrapper", async () => {2181 const vault = await import("./vault");2182 const password = "correct-pass-12345";2183 const popupSender = {2184 id: "peach-extension",2185 url: "chrome-extension://peach-extension/src/popup/index.html",2186 } as chrome.runtime.MessageSender;21872188 await vault.createVault(password);2189 await vault.setupPinUnlock(password, "1234");2190 await vault.lock();21912192 await expect(dispatch({ type: "GET_PIN_STATUS" }, popupSender)).resolves.toMatchObject({2193 ok: true,2194 data: { configured: true, available: true, attemptsRemaining: 3 },2195 });2196 });2197});