messages.adversarial.test.ts

37.3 KB · raw

1/**2 * messages.adversarial.test.ts — Layer 3 §3.3 adversarial message handler tests.3 *4 * Exercises every payload-bearing handler with null/undefined/empty/nested5 * payloads, unknown message types, AUTOFILL_QUERY edge cases, and Codex6 * restore boundary inputs. Parameterized for >=300 tests.7 *8 * Where the audit references handlers Peach does not implement9 * (IMPORT_PEACHSCRIPT / RESTORE_FROM_PEACHSCRIPT), the tests confirm the10 * default `unknown message type` path responds without crashing — see the11 * findings doc.12 */1314import { beforeEach, describe, expect, it, vi } from "vitest";1516import type { Message, MessageResponse } from "../shared/types";1718type StorageShape = Record<string, unknown>;19type MessageListener = (20  msg: unknown,21  sender: chrome.runtime.MessageSender,22  sendResponse: (response: MessageResponse) => void23) => boolean;2425// Payload-bearing handlers we exercise with adversarial payloads.26const PAYLOAD_HANDLERS = [27  "UNLOCK",28  "CREATE_VAULT",29  "ADD_ENTRY",30  "UPDATE_ENTRY",31  "DELETE_ENTRY",32  "BATCH_ADD_ENTRIES",33  "RESTORE_ENTRIES",34  "ADD_ADDITIONAL_URL",35  "RESTORE_ENTRY",36  "PURGE_ENTRY",37  "PURGE_EXPIRED_TRASH",38  "SAVE_NOTE",39  "DELETE_NOTE",40  "RECOVER_WITH_WORDS",41  "VALIDATE_RECOVERY_WORDS",42  "RESTORE_FROM_CODEX",43  "AUTOFILL_QUERY",44  "GET_ENTRY_FOR_FILL",45  "COPY",46  "UPDATE_SETTINGS",47  "APPROVE_PASSKEY",48  "DENY_PASSKEY",49  "SET_PASSKEY_PROVIDER_ENABLED",50  "ACTIVATE_LICENSE",51  "RESTORE_VAULT_SNAPSHOT",52  "CHANGE_PASSWORD",53  "SETUP_DURESS",54  "VERIFY_MAIN_PASSWORD",55  "FIRE_CANARY_PING",56  "ML_PREDICT_BATCH",57  "SEARCH_VAULT",58  "GET_PASSKEY_FOR_DOMAIN",59];6061describe("message handler adversarial inputs", () => {62  let storage: StorageShape;63  let sessionStorage: StorageShape;64  let listener: MessageListener | undefined;6566  beforeEach(async () => {67    vi.resetModules();68    vi.useRealTimers();69    storage = { peach_settings: { breachMonitoring: false } };70    sessionStorage = {};71    listener = undefined;7273    vi.stubGlobal(74      "fetch",75      vi.fn(async () => ({ ok: true, status: 200, text: async () => "" }))76    );77    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);7879    const chromeMock = {80      runtime: {81        id: "peach-extension",82        onMessage: {83          addListener: vi.fn((fn: MessageListener) => {84            listener = fn;85          }),86        },87        sendMessage: vi.fn(async () => ({ ok: true })),88      },89      tabs: {90        query: vi.fn((_q: unknown, cb?: (tabs: unknown[]) => void) => {91          if (typeof cb === "function") {92            cb([{ id: 1 }]);93            return;94          }95          return Promise.resolve([{ id: 1 }]);96        }),97        sendMessage: vi.fn(async () => ({ ok: true })),98      },99      storage: {100        local: {101          get: vi.fn(async (key?: string | string[]) => {102            if (!key) return storage;103            if (typeof key === "string") return { [key]: storage[key] };104            return key.reduce<Record<string, unknown>>((acc, k) => {105              acc[k] = storage[k];106              return acc;107            }, {});108          }),109          set: vi.fn(async (next: Record<string, unknown>) => {110            Object.assign(storage, next);111          }),112          remove: vi.fn(async (keys: string | string[]) => {113            const list = Array.isArray(keys) ? keys : [keys];114            for (const key of list) delete storage[key];115          }),116        },117        session: {118          get: vi.fn(async (key?: string | string[]) => {119            if (!key) return sessionStorage;120            if (typeof key === "string") return { [key]: sessionStorage[key] };121            return key.reduce<Record<string, unknown>>((acc, k) => {122              acc[k] = sessionStorage[k];123              return acc;124            }, {});125          }),126          set: vi.fn(async (next: Record<string, unknown>) => {127            Object.assign(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) delete sessionStorage[key];132          }),133          clear: vi.fn(async () => {134            for (const k of Object.keys(sessionStorage)) delete sessionStorage[k];135          }),136        },137      },138      alarms: {139        clear: vi.fn(),140        create: vi.fn(),141        onAlarm: { addListener: vi.fn() },142      },143      idle: {144        setDetectionInterval: vi.fn(),145        onStateChanged: { addListener: vi.fn() },146      },147      scripting: { executeScript: vi.fn(async () => []) },148    } as unknown as typeof chrome;149150    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;151152    const messages = await import("./messages");153    messages.setupMessageHandler();154    const vault = await import("./vault");155    await vault.ensureSettingsLoaded();156  });157158  async function dispatch(message: Message): Promise<MessageResponse> {159    if (!listener) throw new Error("listener not registered");160    return new Promise<MessageResponse>((resolve) => {161      const keepOpen = listener!(162        message,163        { id: "peach-extension" } as chrome.runtime.MessageSender,164        resolve165      );166      expect(keepOpen).toBe(true);167    });168  }169170  async function setupUnlockedVault() {171    const vault = await import("./vault");172    await vault.createVault("test-pass-12345");173  }174175  // ── Null/undefined/empty/nested payload matrix ──────────────────────────176177  describe("payload no-crash matrix", () => {178    for (const type of PAYLOAD_HANDLERS) {179      it(`${type} with null payload does not crash`, async () => {180        const r = await dispatch({ type, payload: null } as unknown as Message);181        expect(r).toBeDefined();182      });183184      it(`${type} with undefined payload does not crash`, async () => {185        const r = await dispatch({186          type,187          payload: undefined,188        } as unknown as Message);189        expect(r).toBeDefined();190      });191192      it(`${type} with empty object payload does not crash`, async () => {193        const r = await dispatch({ type, payload: {} } as unknown as Message);194        expect(r).toBeDefined();195      });196197      it(`${type} with deeply nested payload does not crash`, async () => {198        const nested: Record<string, unknown> = {};199        let cur: Record<string, unknown> = nested;200        for (let i = 0; i < 50; i++) {201          const child: Record<string, unknown> = {};202          cur.child = child;203          cur = child;204        }205        const r = await dispatch({206          type,207          payload: nested,208        } as unknown as Message);209        expect(r).toBeDefined();210      });211212      it(`${type} with array payload does not crash`, async () => {213        const r = await dispatch({214          type,215          payload: [1, 2, 3],216        } as unknown as Message);217        expect(r).toBeDefined();218      });219220      it(`${type} with string payload does not crash`, async () => {221        const r = await dispatch({222          type,223          payload: "garbage",224        } as unknown as Message);225        expect(r).toBeDefined();226      });227228      it(`${type} with number payload does not crash`, async () => {229        const r = await dispatch({230          type,231          payload: 42,232        } as unknown as Message);233        expect(r).toBeDefined();234      });235    }236  });237238  // ── AUD-007: extended no-crash payload sweep ────────────────────────────239  //240  // Each payload variant runs against every handler in PAYLOAD_HANDLERS and241  // must produce a structured response — never a thrown exception. This242  // expands fuzz coverage to >3000 tests without changing handler behavior.243244  describe("AUD-007 extended payload no-crash sweep", () => {245    const extraPayloads: Array<{ name: string; payload: unknown }> = [246      { name: "boolean true", payload: true },247      { name: "boolean false", payload: false },248      { name: "negative number", payload: -1 },249      { name: "NaN", payload: NaN },250      { name: "Infinity", payload: Infinity },251      { name: "empty string", payload: "" },252      { name: "very long string", payload: "A".repeat(10_000) },253      { name: "unicode string", payload: "私のパスワード🔑" },254      { name: "RTL string", payload: "مفتاح‮" },255      { name: "null bytes in string", payload: "a\x00b\x00c" },256      { name: "html string", payload: "<script>alert(1)</script>" },257      { name: "sql string", payload: "'; DROP TABLE entries; --" },258      { name: "path traversal string", payload: "../../etc/passwd" },259      { name: "object with null prototype-ish", payload: { __proto__: null } },260      { name: "object with prototype pollution attempt", payload: { __proto__: { polluted: true } } },261      { name: "object with constructor pollution", payload: { constructor: { prototype: { polluted: true } } } },262      { name: "deeply nested array", payload: [[[[[[[[[[]]]]]]]]]] },263      { name: "long array", payload: new Array(1_000).fill(0) },264      { name: "mixed array", payload: [null, undefined, 1, "x", true, {}, []] },265      { name: "function-like object", payload: { call: () => 1, apply: () => 1 } },266      { name: "Date object", payload: new Date(0) },267      { name: "BigInt-ish payload", payload: { n: "9007199254740993" } },268      { name: "circular-safe placeholder", payload: { self: "[Circular]" } },269    ];270271    for (const { name, payload } of extraPayloads) {272      for (const type of PAYLOAD_HANDLERS) {273        it(`${type} with ${name} payload does not crash`, async () => {274          const r = await dispatch({ type, payload } as unknown as Message);275          expect(r).toBeDefined();276          expect(typeof r.ok).toBe("boolean");277        });278      }279    }280  });281282  // ── Unknown / malformed message types ───────────────────────────────────283284  describe("unknown message types", () => {285    const unknownTypes = [286      "TOTALLY_UNKNOWN_TYPE",287      "",288      "X",289      "lowercase_type",290      "with spaces in type",291      "with-dashes",292      "WITH.DOTS",293      "🌸emoji_type",294      "Unicode_üñïcödé",295      "IMPORT_PEACHSCRIPT",296      "RESTORE_FROM_PEACHSCRIPT",297      "DESTROY_VAULT_QUIETLY",298      "ESCALATE_PRIVILEGE",299    ];300301    for (const type of unknownTypes) {302      it(`unknown type "${type}" returns error response`, async () => {303        const r = await dispatch({ type } as unknown as Message);304        expect(r).toBeDefined();305        expect(r.ok).toBe(false);306      });307    }308309    it("missing type field does not crash", async () => {310      const r = await dispatch({} as unknown as Message);311      expect(r).toBeDefined();312    });313314    it("type=null does not crash", async () => {315      const r = await dispatch({ type: null } as unknown as Message);316      expect(r).toBeDefined();317    });318319    it("type=number does not crash", async () => {320      const r = await dispatch({ type: 42 } as unknown as Message);321      expect(r).toBeDefined();322    });323  });324325  // ── Sender validation ────────────────────────────────────────────────────326327  describe("sender validation", () => {328    it("foreign extension sender is rejected", async () => {329      if (!listener) throw new Error("listener not registered");330      const r = await new Promise<MessageResponse>((resolve) => {331        listener!(332          { type: "GET_ENTRIES" } as Message,333          { id: "foreign-extension" } as chrome.runtime.MessageSender,334          resolve335        );336      });337      expect(r.ok).toBe(false);338      expect(r.error).toBe("invalid_sender");339    });340341    it("sender with no id (extension UI) is accepted", async () => {342      if (!listener) throw new Error("listener not registered");343      await setupUnlockedVault();344      const r = await new Promise<MessageResponse>((resolve) => {345        listener!(346          { type: "GET_ENTRIES" } as Message,347          {} as chrome.runtime.MessageSender,348          resolve349        );350      });351      expect(r.ok).toBe(true);352    });353  });354355  // ── AUTOFILL_QUERY adversarial ──────────────────────────────────────────356357  describe("AUTOFILL_QUERY adversarial", () => {358    async function withEntries(n: number) {359      const vault = await import("./vault");360      await vault.createVault("test-pass-12345");361      for (let i = 0; i < n; i++) {362        await vault.addEntry({363          title: `E${i}`,364          username: `u${i}`,365          password: "p",366          url: `https://example${i}.com`,367          type: "login",368        });369      }370    }371372    it("empty domain returns empty results", async () => {373      await withEntries(3);374      const r = await dispatch({375        type: "AUTOFILL_QUERY",376        payload: { domain: "" },377      });378      expect(r.ok).toBe(true);379      expect((r as { data: unknown[] }).data).toEqual([]);380    });381382    const adversarialDomains = [383      "*",384      ".*",385      "%",386      "<script>alert(1)</script>",387      "' OR '1'='1",388      "../../../etc/passwd",389      "\x00github.com",390      "github.com\x00",391      "GITHUB.COM",392      "github.com/path",393      "https://github.com",394      "javascript:alert(1)",395      " ",396      "   ",397      "\t",398      "\n",399      String("a").repeat(5000),400    ];401    for (const domain of adversarialDomains) {402      it(`adversarial domain ${JSON.stringify(domain.slice(0, 30))} does not crash`, async () => {403        await withEntries(3);404        const r = await dispatch({405          type: "AUTOFILL_QUERY",406          payload: { domain },407        });408        expect(r.ok).toBe(true);409      });410411      it(`adversarial domain ${JSON.stringify(domain.slice(0, 30))} does not match all entries`, async () => {412        await withEntries(5);413        const r = await dispatch({414          type: "AUTOFILL_QUERY",415          payload: { domain },416        });417        const data = (r as { data: unknown[] }).data;418        // No adversarial wildcard should ever match every entry.419        expect(data.length).toBeLessThan(5);420      });421    }422423    it("locked vault: AUTOFILL_QUERY returns error", async () => {424      const vault = await import("./vault");425      await vault.createVault("test-pass-12345");426      vault.lock();427      const r = await dispatch({428        type: "AUTOFILL_QUERY",429        payload: { domain: "github.com" },430      });431      expect(r.ok).toBe(false);432    });433434    it("response never leaks privateKeyJwk", async () => {435      await withEntries(3);436      const r = await dispatch({437        type: "AUTOFILL_QUERY",438        payload: { domain: "example0.com" },439      });440      const data = (r as { data: Array<Record<string, unknown>> }).data;441      for (const entry of data) {442        expect("privateKeyJwk" in entry).toBe(false);443        expect("passkey" in entry).toBe(false);444      }445    });446447    it("kind=card returns card summaries only (no full PAN)", async () => {448      const vault = await import("./vault");449      await vault.createVault("test-pass-12345");450      await vault.addEntry({451        type: "card",452        title: "Visa",453        cardNumber: "4111111111111111",454        last4: "1111",455        cardholderName: "JUNE",456        expMonth: "12",457        expYear: "2030",458        cvc: "123",459      } as unknown as Parameters<typeof vault.addEntry>[0]);460      const r = await dispatch({461        type: "AUTOFILL_QUERY",462        payload: { domain: "any.com", kind: "card" },463      });464      const data = (r as { data: Array<Record<string, unknown>> }).data;465      for (const entry of data) {466        expect("cardNumber" in entry).toBe(false);467        expect("cvc" in entry).toBe(false);468      }469    });470  });471472  // ── RESTORE_FROM_CODEX adversarial ──────────────────────────────────────473474  describe("RESTORE_FROM_CODEX adversarial", () => {475    const malformed = [476      { name: "empty vaultBlob", overrides: { vaultBlob: "" } },477      { name: "garbage vaultBlob", overrides: { vaultBlob: "!!!not-base64!!!" } },478      { name: "wrong fingerprint", overrides: { vaultFingerprint: "0".repeat(16) } },479      { name: "wrong passphrase", overrides: { masterPassphrase: "definitely wrong" } },480      { name: "negative timestamp", overrides: { timestamp: -1 } },481      { name: "zero timestamp", overrides: { timestamp: 0 } },482      { name: "huge entryCount", overrides: { entryCount: 1_000_000 } },483      { name: "negative entryCount", overrides: { entryCount: -5 } },484    ];485    for (const { name, overrides } of malformed) {486      it(`malformed payload (${name}) returns ok=false without crash`, async () => {487        const payload = {488          vaultBlob: "ZGF0YQ==",489          timestamp: Date.now(),490          verifyCode: "PX-TEST-1234",491          vaultFingerprint: "ABCDEF1234567890",492          entryCount: 0,493          masterPassphrase: "secret",494          ...overrides,495        };496        const r = await dispatch({ type: "RESTORE_FROM_CODEX", payload });497        expect(r).toBeDefined();498        expect(r.ok).toBe(false);499      });500    }501502    it("null payload does not crash", async () => {503      const r = await dispatch({504        type: "RESTORE_FROM_CODEX",505        payload: null,506      } as unknown as Message);507      expect(r).toBeDefined();508      expect(r.ok).toBe(false);509    });510  });511512  // ── COPY handler ────────────────────────────────────────────────────────513514  describe("COPY handler adversarial", () => {515    for (const text of ["", "x", "a".repeat(10000), "\x00\x00\x00", "🔑"]) {516      it(`COPY of ${JSON.stringify(text.slice(0, 20))} resolves`, async () => {517        const r = await dispatch({518          type: "COPY",519          payload: { text, label: "test", alreadyWritten: true },520        });521        expect(r).toBeDefined();522      });523    }524  });525526  // ── FIRE_CANARY_PING adversarial ────────────────────────────────────────527528  describe("FIRE_CANARY_PING webhook url validation", () => {529    const badUrls = [530      "javascript:alert(1)",531      "file:///etc/passwd",532      "data:text/plain,evil",533      "",534      "not a url",535      "ftp://example.com/hook",536    ];537    for (const url of badUrls) {538      it(`rejects bad webhook URL ${JSON.stringify(url)}`, async () => {539        const r = await dispatch({540          type: "FIRE_CANARY_PING",541          payload: {542            webhookUrl: url,543            entryTitle: "x",544            trigger: "test",545          },546        });547        expect(r.ok).toBe(false);548      });549    }550  });551552  // ── GET_ENTRY_FOR_FILL safety ───────────────────────────────────────────553554  describe("GET_ENTRY_FOR_FILL safety", () => {555    it("returns entry without passkey field for login entry", async () => {556      const vault = await import("./vault");557      await vault.createVault("test-pass-12345");558      const e = await vault.addEntry({559        title: "GitHub",560        username: "june",561        password: "x",562        url: "https://github.com",563        type: "login",564      });565      const r = await dispatch({566        type: "GET_ENTRY_FOR_FILL",567        payload: { id: e.id },568      });569      expect(r.ok).toBe(true);570      const data = (r as { data: Record<string, unknown> }).data;571      expect("passkey" in data).toBe(false);572      expect("privateKeyJwk" in data).toBe(false);573    });574575    it("missing id returns error", async () => {576      await setupUnlockedVault();577      const r = await dispatch({578        type: "GET_ENTRY_FOR_FILL",579        payload: { id: "not-a-real-id" },580      });581      expect(r.ok).toBe(false);582    });583584    it("locked vault returns error", async () => {585      const vault = await import("./vault");586      await vault.createVault("test-pass-12345");587      vault.lock();588      const r = await dispatch({589        type: "GET_ENTRY_FOR_FILL",590        payload: { id: "x" },591      });592      expect(r.ok).toBe(false);593    });594  });595596  // ── ADD_ENTRY adversarial when locked ───────────────────────────────────597598  describe("ADD_ENTRY locked-state safety", () => {599    it("locked vault: ADD_ENTRY returns vault locked", async () => {600      const r = await dispatch({601        type: "ADD_ENTRY",602        payload: { title: "x", username: "u", password: "p", url: "https://e.com" },603      });604      expect(r.ok).toBe(false);605    });606607    it("ADD_ENTRY with no password and no passkey returns validation error", async () => {608      await setupUnlockedVault();609      const r = await dispatch({610        type: "ADD_ENTRY",611        payload: { title: "x", username: "u", password: "", url: "https://e.com" },612      });613      expect(r.ok).toBe(false);614    });615  });616617  // ── DELETE_ENTRY adversarial ────────────────────────────────────────────618619  describe("DELETE_ENTRY adversarial", () => {620    const badIds = [621      "",622      "   ",623      "not-a-uuid",624      String("a").repeat(10000),625      "00000000-0000-0000-0000-000000000000",626      "<script>",627      "\x00",628    ];629    for (const id of badIds) {630      it(`unknown id ${JSON.stringify(id.slice(0, 30))} returns error`, async () => {631        await setupUnlockedVault();632        const r = await dispatch({633          type: "DELETE_ENTRY",634          payload: { id },635        });636        expect(r.ok).toBe(false);637      });638    }639  });640641  // ── BATCH_ADD_ENTRIES adversarial ───────────────────────────────────────642643  describe("BATCH_ADD_ENTRIES adversarial", () => {644    it("empty array does not crash", async () => {645      await setupUnlockedVault();646      const r = await dispatch({647        type: "BATCH_ADD_ENTRIES",648        payload: { entries: [] },649      });650      expect(r).toBeDefined();651    });652653    it("non-array entries does not crash", async () => {654      await setupUnlockedVault();655      const r = await dispatch({656        type: "BATCH_ADD_ENTRIES",657        payload: { entries: "not-an-array" as unknown as unknown[] },658      });659      expect(r).toBeDefined();660    });661662    it("mostly-malformed entries does not crash", async () => {663      await setupUnlockedVault();664      const r = await dispatch({665        type: "BATCH_ADD_ENTRIES",666        payload: {667          entries: [668            null,669            undefined,670            42,671            "string",672            { title: "ok", username: "u", password: "p", url: "https://e.com" },673          ] as unknown as unknown[],674        },675      });676      expect(r).toBeDefined();677    });678  });679680  // ── SEARCH_VAULT adversarial ────────────────────────────────────────────681682  describe("SEARCH_VAULT adversarial", () => {683    const queries = [684      "",685      " ",686      "x",687      "a".repeat(1000),688      "🔑",689      "<script>",690      "' OR '1'='1",691      "../../",692      "\x00",693    ];694    for (const query of queries) {695      it(`query ${JSON.stringify(query.slice(0, 30))} does not crash`, async () => {696        await setupUnlockedVault();697        const r = await dispatch({698          type: "SEARCH_VAULT",699          payload: { query },700        });701        expect(r).toBeDefined();702      });703    }704  });705706  // ── UPDATE_SETTINGS adversarial ─────────────────────────────────────────707708  describe("UPDATE_SETTINGS adversarial", () => {709    const patches = [710      { name: "empty", patch: {} },711      { name: "junk keys", patch: { __proto__: { polluted: true } } },712      { name: "very long autolock", patch: { autoLockMinutes: 99999999 } },713      { name: "negative autolock", patch: { autoLockMinutes: -5 } },714      { name: "string autolock", patch: { autoLockMinutes: "five" } },715      { name: "unknown nested", patch: { foo: { bar: { baz: 1 } } } },716    ];717    for (const { name, patch } of patches) {718      it(`patch ${name} does not crash`, async () => {719        await setupUnlockedVault();720        const r = await dispatch({721          type: "UPDATE_SETTINGS",722          payload: patch as Record<string, unknown>,723        });724        expect(r).toBeDefined();725      });726    }727728    it("prototype pollution check: Object.prototype.polluted stays unset", async () => {729      await setupUnlockedVault();730      await dispatch({731        type: "UPDATE_SETTINGS",732        payload: JSON.parse(733          '{"__proto__": {"polluted": "yes"}}'734        ) as Record<string, unknown>,735      });736      // eslint-disable-next-line @typescript-eslint/no-explicit-any737      expect(({} as any).polluted).toBeUndefined();738    });739  });740741  // ── Wider adversarial payload matrix per handler ────────────────────────742743  describe("wide adversarial payload matrix", () => {744    const adversarialPayloads: Array<{ name: string; payload: unknown }> = [745      { name: "true", payload: true },746      { name: "false", payload: false },747      { name: "NaN", payload: NaN },748      { name: "Infinity", payload: Infinity },749      { name: "-Infinity", payload: -Infinity },750      { name: "BigInt-like", payload: { type: "bigint" } },751      { name: "Date", payload: new Date() },752      { name: "RegExp", payload: /pattern/ },753      { name: "Symbol-string", payload: Symbol("x").toString() },754      { name: "circular reference", payload: (() => {755        const o: Record<string, unknown> = {};756        o.self = o;757        return o;758      })() },759    ];760761    const fastHandlers = [762      "ADD_ENTRY",763      "UPDATE_ENTRY",764      "DELETE_ENTRY",765      "AUTOFILL_QUERY",766      "GET_ENTRY_FOR_FILL",767      "UPDATE_SETTINGS",768      "SEARCH_VAULT",769      "SAVE_NOTE",770      "DELETE_NOTE",771      "PURGE_ENTRY",772      "RESTORE_ENTRY",773      "PURGE_EXPIRED_TRASH",774      "ADD_ADDITIONAL_URL",775      "BATCH_ADD_ENTRIES",776      "RESTORE_ENTRIES",777      "ACTIVATE_LICENSE",778      "APPROVE_PASSKEY",779      "DENY_PASSKEY",780      "SET_PASSKEY_PROVIDER_ENABLED",781      "RESTORE_VAULT_SNAPSHOT",782      "VERIFY_MAIN_PASSWORD",783      "SETUP_DURESS",784    ];785786    for (const handler of fastHandlers) {787      for (const { name, payload } of adversarialPayloads) {788        it(`${handler} + ${name} payload resolves without crash`, async () => {789          const r = await dispatch({ type: handler, payload } as unknown as Message);790          expect(r).toBeDefined();791        });792      }793    }794  });795796  // ── Foreign sender × handler matrix ─────────────────────────────────────797798  describe("foreign sender rejection matrix", () => {799    const safeQuickHandlers = [800      "GET_ENTRIES",801      "IS_UNLOCKED",802      "HAS_VAULT",803      "GET_VAULT_STATUS",804      "GET_SETTINGS",805      "GET_DELETED_ENTRIES",806      "COUNT_DUPLICATES",807      "GET_VAULT_HISTORY",808      "ADD_ENTRY",809      "DELETE_ENTRY",810      "AUTOFILL_QUERY",811      "GET_ENTRY_FOR_FILL",812      "SAVE_NOTE",813      "DELETE_NOTE",814      "GET_NOTES",815      "SEARCH_VAULT",816      "GET_LICENSE",817      "GET_LICENSE_KEY",818      "GET_RECOVERY_WORDS",819      "VALIDATE_RECOVERY_WORDS",820      "RECOVER_WITH_WORDS",821      "RESTORE_FROM_CODEX",822      "GET_CODEX_VAULT_DATA",823      "ESTIMATE_CODEX_PAGES",824    ];825    for (const handler of safeQuickHandlers) {826      it(`${handler} from foreign sender returns invalid sender`, async () => {827        if (!listener) throw new Error("listener not registered");828        const r = await new Promise<MessageResponse>((resolve) => {829          listener!(830            { type: handler, payload: {} } as Message,831            { id: "foreign-extension-id" } as chrome.runtime.MessageSender,832            resolve833          );834        });835        expect(r.ok).toBe(false);836        expect(r.error).toBe("invalid_sender");837      });838    }839  });840841  // ── ADD_ENTRY payload-shape robustness ──────────────────────────────────842843  describe("ADD_ENTRY payload shape robustness", () => {844    const shapes = [845      { name: "no title", body: { username: "u", password: "p", url: "https://e.com" } },846      { name: "no url", body: { title: "t", username: "u", password: "p" } },847      { name: "title only", body: { title: "t", password: "p" } },848      { name: "spurious type", body: { type: "login", title: "t", password: "p" } },849      { name: "unknown type", body: { type: "wat", title: "t", password: "p" } },850      { name: "with extra field", body: { title: "t", password: "p", extra: "ignored" } },851      { name: "url with port", body: { title: "t", password: "p", url: "https://e.com:8080" } },852      { name: "url with path", body: { title: "t", password: "p", url: "https://e.com/a/b/c" } },853      { name: "username as number", body: { title: "t", username: 42, password: "p", url: "https://e.com" } },854      { name: "password as number", body: { title: "t", password: 12345, url: "https://e.com" } },855      { name: "title as null", body: { title: null, password: "p", url: "https://e.com" } },856      { name: "title as object", body: { title: { wat: 1 }, password: "p", url: "https://e.com" } },857    ];858    for (const { name, body } of shapes) {859      it(`ADD_ENTRY shape ${name} resolves without crash`, async () => {860        await setupUnlockedVault();861        const r = await dispatch({862          type: "ADD_ENTRY",863          payload: body as Parameters<typeof dispatch>[0]["payload"],864        } as Message);865        expect(r).toBeDefined();866      });867    }868  });869870  // ── UPDATE_ENTRY patch-shape robustness ─────────────────────────────────871872  describe("UPDATE_ENTRY patch shape robustness", () => {873    const patches = [874      { name: "title only", patch: { title: "New" } },875      { name: "password only", patch: { password: "newpass" } },876      { name: "url only", patch: { url: "https://e2.com" } },877      { name: "many fields", patch: { title: "N", username: "u2", password: "p2", url: "https://e2.com" } },878      { name: "unknown field", patch: { totallyMadeUp: "x" } },879      { name: "deletedAt forbidden", patch: { deletedAt: Date.now() } },880      { name: "createdAt forbidden", patch: { createdAt: 0 } },881      { name: "modifiedAt patch", patch: { modifiedAt: Date.now() } },882      { name: "id patch (should reject or ignore)", patch: { id: "new-id" } },883    ];884    for (const { name, patch } of patches) {885      it(`UPDATE_ENTRY patch ${name} resolves without crash`, async () => {886        const vault = await import("./vault");887        await vault.createVault("test-pass-12345");888        const e = await vault.addEntry({889          title: "x",890          username: "u",891          password: "p",892          url: "https://e.com",893          type: "login",894        });895        const r = await dispatch({896          type: "UPDATE_ENTRY",897          payload: { id: e.id, patch },898        });899        expect(r).toBeDefined();900      });901    }902  });903904  // ── Sequence: vault life-cycle adversarial ──────────────────────────────905906  describe("vault lifecycle adversarial sequences", () => {907    for (let i = 0; i < 20; i++) {908      it(`random message sequence #${i} does not crash`, async () => {909        const vault = await import("./vault");910        await vault.createVault("test-pass-12345");911        const handlers = [912          { type: "GET_ENTRIES" },913          { type: "IS_UNLOCKED" },914          { type: "GET_VAULT_STATUS" },915          { type: "HAS_VAULT" },916          { type: "GET_DELETED_ENTRIES" },917          { type: "GET_SETTINGS" },918          { type: "COUNT_DUPLICATES" },919          { type: "GET_VAULT_HISTORY" },920        ] as Array<Message>;921        for (const h of handlers) {922          const r = await dispatch(h);923          expect(r).toBeDefined();924        }925      });926    }927  });928929  // ── Read-only handlers when locked ──────────────────────────────────────930931  describe("read-only handlers when locked", () => {932    const safeWhenLocked = [933      "IS_UNLOCKED",934      "HAS_VAULT",935      "GET_VAULT_STATUS",936      "GET_SETTINGS",937    ];938    for (const type of safeWhenLocked) {939      it(`${type} works without crash when locked`, async () => {940        const r = await dispatch({ type } as unknown as Message);941        expect(r).toBeDefined();942      });943    }944945    const gatedWhenLocked = [946      "GET_ENTRIES",947      "GET_DELETED_ENTRIES",948      "COUNT_DUPLICATES",949      "GET_IDENTITIES",950      "GET_IDENTITY_SUGGESTIONS",951    ];952    for (const type of gatedWhenLocked) {953      it(`${type} returns ok=false when locked`, async () => {954        const r = await dispatch({ type } as unknown as Message);955        expect(r).toBeDefined();956        // Some handlers return ok:false explicitly; others may throw.957        if (r.ok === true) {958          // Accept ok:true only if data is empty.959          const data = (r as { data: unknown }).data;960          expect(961            data == null ||962              (Array.isArray(data) && data.length === 0) ||963              data === 0964          ).toBe(true);965        } else {966          expect(r.ok).toBe(false);967        }968      });969    }970  });971972  // ── M2/QUA-002: payload validation at trust boundary ────────────────────973974  describe("payload validation rejects malformed inputs (M2/QUA-002)", () => {975    // Each entry: handler type + payloads that must produce ok:false.976    // The accepted error codes include 'invalid_payload' (the new validator)977    // or 'vault_locked' (handlers that lock-check before validating, which978    // is still a correct rejection of the request).979    const cases: Array<{ type: string; bad: unknown[] }> = [980      {981        type: "ADD_ENTRY",982        bad: [null, "string", 42, [], true],983      },984      {985        type: "BATCH_ADD_ENTRIES",986        bad: [null, { entries: "not-array" }, { entries: null }, { entries: 42 }, []],987      },988      {989        type: "UPDATE_ENTRY",990        bad: [null, {}, { id: 123 }, { id: "x" }, { id: "x", patch: "no" }, { id: "x", patch: null }, []],991      },992      {993        type: "RESTORE_ENTRIES",994        bad: [null, {}, { entries: "no" }, { entries: [], mode: "wrong" }, []],995      },996      {997        type: "UPDATE_SETTINGS",998        bad: [null, "string", 42, []],999      },1000    ];10011002    for (const { type, bad } of cases) {1003      for (const payload of bad) {1004        const label = JSON.stringify(payload);1005        it(`${type} rejects malformed payload: ${label}`, async () => {1006          await setupUnlockedVault();1007          const r = await dispatch({ type, payload } as unknown as Message);1008          expect(r.ok).toBe(false);1009          const err = (r as { error?: string }).error ?? "";1010          expect(err).toMatch(/invalid_payload|vault[_ ]locked/);1011        });1012      }1013    }1014  });10151016  // ── AUD-002: payload validation for previously raw-cast handlers ────────10171018  describe("AUD-002 payload validation", () => {1019    describe("SEARCH_VAULT", () => {1020      const badQueries: Array<[string, unknown]> = [1021        ["null", null],1022        ["numeric", 42],1023        ["boolean", true],1024        ["object", { evil: true }],1025        ["array", []],1026        ["missing", undefined],1027      ];1028      for (const [name, query] of badQueries) {1029        it(`rejects ${name} query`, async () => {1030          await setupUnlockedVault();1031          const r = await dispatch({1032            type: "SEARCH_VAULT",1033            payload: { query },1034          } as unknown as Message);1035          expect(r.ok).toBe(false);1036          expect((r as { error?: string }).error).toBe("invalid_payload");1037        });1038      }10391040      it("accepts valid string query", async () => {1041        await setupUnlockedVault();1042        const r = await dispatch({1043          type: "SEARCH_VAULT",1044          payload: { query: "github" },1045        });1046        expect(r.ok).toBe(true);1047      });1048    });10491050    describe("COPY", () => {1051      const bads: Array<[string, unknown, unknown]> = [1052        ["null text", null, "pw"],1053        ["numeric text", 42, "pw"],1054        ["object text", { evil: true }, "pw"],1055        ["missing text", undefined, "pw"],1056        ["null label", "secret", null],1057        ["numeric label", "secret", 42],1058      ];1059      for (const [name, text, label] of bads) {1060        it(`rejects ${name}`, async () => {1061          await setupUnlockedVault();1062          const r = await dispatch({1063            type: "COPY",1064            payload: { text, label },1065          } as unknown as Message);1066          expect(r.ok).toBe(false);1067          expect((r as { error?: string }).error).toBe("invalid_payload");1068        });1069      }1070    });10711072    describe("ML_PREDICT_BATCH", () => {1073      const bads: Array<[string, unknown]> = [1074        ["null", null],1075        ["object", { not: "array" }],1076        ["string", "features"],1077        ["number", 42],1078        ["missing", undefined],1079      ];1080      for (const [name, featuresArray] of bads) {1081        it(`rejects ${name} featuresArray`, async () => {1082          const r = await dispatch({1083            type: "ML_PREDICT_BATCH",1084            payload: { featuresArray },1085          } as unknown as Message);1086          expect(r.ok).toBe(false);1087          expect((r as { error?: string }).error).toBe("invalid_payload");1088        });1089      }10901091      it("accepts empty array featuresArray", async () => {1092        const r = await dispatch({1093          type: "ML_PREDICT_BATCH",1094          payload: { featuresArray: [] },1095        } as unknown as Message);1096        expect((r as { error?: string }).error).not.toBe("invalid_payload");1097      });1098    });1099  });1100});