passkey-chrome-ceremony.test.ts

36.8 KB · raw

1/**2 * passkey-chrome-ceremony.test.ts — covers the Chrome3 * chrome.webAuthenticationProxy ceremony path that the Firefox-proxy test4 * file does NOT exercise.5 *6 * Bugs this file locks down (all three shipped in v3.6.105/v3.6.106):7 *   1. isUvpaa was gated on vault.isUnlocked() → Chromium RPs (Google) showed8 *      "A passkey can't be created on this device" before a locked-vault user9 *      could even start the ceremony.10 *   2. handleCreateRequest used to immediately reject with NotAllowedError on11 *      a locked vault. Should wait for unlock the same way handleGetRequest12 *      does.13 *   3. clientDataJSON.origin was built from `https://${rpId}` regardless of14 *      the page hostname — so registering at https://myaccount.google.com15 *      with rpId=google.com signed origin=https://google.com, which the RP16 *      then rejected. resolvePageOrigin() must use the active tab origin17 *      when it is a registrable-suffix match, otherwise fall back safely.18 *19 * The Chrome path also applies to every Chromium derivative — Brave, Edge,20 * Vivaldi, Opera, Arc — because chrome.webAuthenticationProxy is provided21 * by Chromium itself. UA is irrelevant here; feature presence routes us in.22 * See browser.test.ts for the routing coverage.23 */2425import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";2627vi.mock("./license", async (importOriginal) => {28  const actual = await importOriginal<typeof import("./license")>();29  return {30    ...actual,31    isProUser: vi.fn(async () => true),32  };33});3435vi.mock("../shared/passkey-flags", () => ({36  FIREFOX_USE_CONTENT_SCRIPT_PROXY: false,37}));3839type StorageShape = Record<string, unknown>;4041interface ProxyListeners {42  create?: (req: { requestId: number; requestDetailsJson: string }) => void;43  get?: (req: { requestId: number; requestDetailsJson: string }) => void;44  uvpaa?: (req: { requestId: number }) => void;45  cancel?: (requestId: number) => void;46}4748interface CompleteCaptures {49  create: Array<{ requestId: number; responseJson?: string; error?: { name: string; message: string } }>;50  get: Array<{ requestId: number; responseJson?: string; error?: { name: string; message: string } }>;51  uvpaa: Array<{ requestId: number; isUvpaa: boolean }>;52}5354describe("chrome webAuthenticationProxy ceremony", () => {55  let storage: StorageShape;56  let sessionStorage: StorageShape;57  let proxyListeners: ProxyListeners;58  let completes: CompleteCaptures;59  let tabsSendMessage: ReturnType<typeof vi.fn>;60  let activeTabs: Array<{ id?: number; url?: string }>;61  let broadcastTabs: Array<{ id?: number }>;62  let openPopup: ReturnType<typeof vi.fn>;6364  beforeEach(async () => {65    vi.resetModules();66    vi.useRealTimers();67    storage = { peach_settings: { breachMonitoring: false, passkeyProviderEnabled: true } };68    sessionStorage = {};69    proxyListeners = {};70    completes = { create: [], get: [], uvpaa: [] };71    tabsSendMessage = vi.fn(async () => ({ ok: true }));72    activeTabs = [{ id: 1, url: "https://myaccount.google.com/security/passkeys" }];73    broadcastTabs = [{ id: 1 }, { id: 2 }];74    openPopup = vi.fn(async () => {});7576    const chromeMock = {77      runtime: {78        id: "peach-extension",79        getURL: vi.fn(() => "chrome-extension://abcd/"),80        onMessage: { addListener: vi.fn() },81        sendMessage: vi.fn(async () => ({ ok: true })),82      },83      tabs: {84        query: vi.fn((q: unknown, callback?: (t: Array<{ id?: number; url?: string }>) => void) => {85          const query = q as { active?: boolean; currentWindow?: boolean; lastFocusedWindow?: boolean };86          const list = query.active ? activeTabs : broadcastTabs;87          if (typeof callback === "function") { callback(list); return; }88          return Promise.resolve(list);89        }),90        sendMessage: tabsSendMessage,91      },92      storage: {93        local: {94          get: vi.fn(async (key?: string | string[]) => {95            if (!key) return storage;96            if (typeof key === "string") return { [key]: storage[key] };97            return key.reduce<Record<string, unknown>>((r, k) => { r[k] = storage[k]; return r; }, {});98          }),99          set: vi.fn(async (next: Record<string, unknown>) => Object.assign(storage, next)),100          remove: vi.fn(async (keys: string | string[]) => {101            const list = Array.isArray(keys) ? keys : [keys];102            for (const k of list) delete storage[k];103          }),104        },105        session: {106          get: vi.fn(async (key?: string | string[] | null) => {107            if (key === null || key === undefined) return sessionStorage;108            if (typeof key === "string") return { [key]: sessionStorage[key] };109            return (key as string[]).reduce<Record<string, unknown>>((r, k) => { r[k] = sessionStorage[k]; return r; }, {});110          }),111          set: vi.fn(async (next: Record<string, unknown>) => Object.assign(sessionStorage, next)),112          remove: vi.fn(async (keys: string | string[]) => {113            const list = Array.isArray(keys) ? keys : [keys];114            for (const k of list) delete sessionStorage[k];115          }),116          clear: vi.fn(async () => { sessionStorage = {}; }),117        },118      },119      action: {120        setBadgeText: vi.fn(async () => {}),121        setBadgeBackgroundColor: vi.fn(async () => {}),122        openPopup,123      },124      alarms: { clear: vi.fn(), create: vi.fn(), onAlarm: { addListener: vi.fn() } },125      idle: { setDetectionInterval: vi.fn(), onStateChanged: { addListener: vi.fn() } },126      scripting: { executeScript: vi.fn(async () => []) },127      webAuthenticationProxy: {128        attach: vi.fn(async () => {}),129        detach: vi.fn(async () => {}),130        completeCreateRequest: vi.fn(async (details: typeof completes.create[number]) => {131          completes.create.push(details);132        }),133        completeGetRequest: vi.fn(async (details: typeof completes.get[number]) => {134          completes.get.push(details);135        }),136        completeIsUvpaaRequest: vi.fn(async (details: typeof completes.uvpaa[number]) => {137          completes.uvpaa.push(details);138        }),139        onCreateRequest: { addListener: vi.fn((fn: ProxyListeners["create"]) => { proxyListeners.create = fn; }) },140        onGetRequest: { addListener: vi.fn((fn: ProxyListeners["get"]) => { proxyListeners.get = fn; }) },141        onIsUvpaaRequest: { addListener: vi.fn((fn: ProxyListeners["uvpaa"]) => { proxyListeners.uvpaa = fn; }) },142        onRequestCanceled: { addListener: vi.fn((fn: ProxyListeners["cancel"]) => { proxyListeners.cancel = fn; }) },143      },144    } as unknown as typeof chrome;145146    (globalThis as { chrome?: typeof chrome }).chrome = chromeMock;147    vi.stubGlobal("__PEACH_E2E_PASSKEYS__", false);148149    const vaultModule = await import("./vault");150    await vaultModule.ensureSettingsLoaded();151    const passkey = await import("./passkey");152    await passkey.setupPasskeyProxy();153  });154155  afterEach(() => {156    vi.unstubAllGlobals();157  });158159  it("leaves Chrome native passkeys available when interception has no saved preference", async () => {160    vi.resetModules();161    storage.peach_settings = { breachMonitoring: false };162    vi.mocked(chrome.webAuthenticationProxy.attach).mockClear();163    const passkey = await import("./passkey");164    await passkey.setupPasskeyProxy();165    expect(chrome.webAuthenticationProxy.attach).not.toHaveBeenCalled();166    await expect(passkey.getPasskeyProviderState()).resolves.toMatchObject({ enabled: false, attached: false });167  });168169  function fireCreate(options: object, requestId = 100): void {170    proxyListeners.create!({171      requestId,172      requestDetailsJson: JSON.stringify(options),173    });174  }175176  function fireGet(options: object, requestId = 200): void {177    proxyListeners.get!({178      requestId,179      requestDetailsJson: JSON.stringify(options),180    });181  }182183  async function waitForCreateComplete(requestId: number, timeoutMs = 2000): Promise<typeof completes.create[number]> {184    const start = Date.now();185    while (Date.now() - start < timeoutMs) {186      const found = completes.create.find((c) => c.requestId === requestId);187      if (found) return found;188      await new Promise((r) => setTimeout(r, 10));189    }190    throw new Error(`completeCreateRequest never called for requestId=${requestId}`);191  }192193  async function waitForGetComplete(requestId: number, timeoutMs = 2000): Promise<typeof completes.get[number]> {194    const start = Date.now();195    while (Date.now() - start < timeoutMs) {196      const found = completes.get.find((c) => c.requestId === requestId);197      if (found) return found;198      await new Promise((r) => setTimeout(r, 10));199    }200    throw new Error(`completeGetRequest never called for requestId=${requestId}`);201  }202203  // Auto-approve any pending Peach popup approval as it appears.204  function autoApprove() {205    void (async () => {206      const passkey = await import("./passkey");207      for (let i = 0; i < 200; i += 1) {208        const pending = await passkey.getPendingPasskeyRequest();209        if (pending) {210          await passkey.resolvePendingPasskeyRequest(pending.requestId, true);211          return;212        }213        await new Promise((r) => setTimeout(r, 10));214      }215    })();216  }217218  function autoDeny() {219    void (async () => {220      const passkey = await import("./passkey");221      for (let i = 0; i < 200; i += 1) {222        const pending = await passkey.getPendingPasskeyRequest();223        if (pending) {224          await passkey.resolvePendingPasskeyRequest(pending.requestId, false);225          return;226        }227        await new Promise((r) => setTimeout(r, 10));228      }229    })();230  }231232  function buildCreateOptions(overrides: Partial<{233    rpId: string;234    rpName: string;235    userName: string;236    userDisplayName: string;237    userIdB64: string;238    challenge: string;239    pubKeyCredParams: Array<{ alg: number; type: string }>;240  }> = {}) {241    return {242      rp: { id: overrides.rpId ?? "google.com", name: overrides.rpName ?? "Google" },243      user: {244        id: overrides.userIdB64 ?? "dXNlci1pZA",245        name: overrides.userName ?? "[email protected]",246        displayName: overrides.userDisplayName ?? "June",247      },248      challenge: overrides.challenge ?? "Y2hhbGxlbmdl",249      pubKeyCredParams: overrides.pubKeyCredParams ?? [250        { alg: -7, type: "public-key" },251        { alg: -257, type: "public-key" },252      ],253    };254  }255256  function decodeClientData(b64url: string): { type: string; challenge: string; origin: string; crossOrigin: boolean } {257    const padded = b64url.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(b64url.length / 4) * 4, "=");258    const json = atob(padded);259    const bytes = new Uint8Array(json.length);260    for (let i = 0; i < json.length; i += 1) bytes[i] = json.charCodeAt(i);261    return JSON.parse(new TextDecoder().decode(bytes));262  }263264  // ─────────────────────────────────────────────────────────────────────265  // isUvpaa — must report true regardless of lock state. (bug #2)266  // ─────────────────────────────────────────────────────────────────────267268  it("isUvpaa returns true when the vault is locked (regression — was 'A passkey can't be created on this device')", async () => {269    proxyListeners.uvpaa!({ requestId: 1 });270    await new Promise((r) => setTimeout(r, 0));271    expect(completes.uvpaa).toEqual([{ requestId: 1, isUvpaa: true }]);272  });273274  it("isUvpaa returns true when the vault is unlocked", async () => {275    const vault = await import("./vault");276    await vault.createVault("correct-pass-12345");277    proxyListeners.uvpaa!({ requestId: 7 });278    await new Promise((r) => setTimeout(r, 0));279    expect(completes.uvpaa).toEqual([{ requestId: 7, isUvpaa: true }]);280  });281282  // ─────────────────────────────────────────────────────────────────────283  // Locked-vault create: wait for unlock, then proceed. (bug #3)284  // ─────────────────────────────────────────────────────────────────────285286  it("handleCreateRequest on a locked vault summons inline unlock and proceeds once unlocked", async () => {287    const vault = await import("./vault");288    await vault.createVault("correct-pass-12345");289    vault.lock();290291    autoApprove();292    fireCreate(buildCreateOptions(), 101);293294    // Wait long enough for the request to park in unlockWaiters and for the295    // SUMMON_AUTOFILL message to fire, then unlock.296    await new Promise((r) => setTimeout(r, 50));297    expect(tabsSendMessage).toHaveBeenCalledWith(298      1,299      expect.objectContaining({ type: "SUMMON_AUTOFILL", source: "passkey-unlock" })300    );301302    // Unlocking fires onVaultUnlocked() via the messages handler. Tests can303    // skip the message dispatcher and call unlock() directly — the messages304    // handler's onVaultUnlocked() call is what production hits, but the305    // module-internal waiter notifier is what we need to fire here.306    await vault.unlock("correct-pass-12345");307    const passkey = await import("./passkey");308    passkey.onVaultUnlocked();309310    const done = await waitForCreateComplete(101);311    expect(done.error).toBeUndefined();312    expect(done.responseJson).toBeDefined();313  });314315  it("handleCreateRequest rejects with NotAllowedError when unlock waits timeout", async () => {316    vi.useFakeTimers();317    const vault = await import("./vault");318    await vault.createVault("correct-pass-12345");319    vault.lock();320321    fireCreate(buildCreateOptions(), 102);322323    // Allow the request to park.324    await vi.advanceTimersByTimeAsync(10);325    // Jump past APPROVAL_TIMEOUT_MS (60s).326    await vi.advanceTimersByTimeAsync(60_500);327    vi.useRealTimers();328329    const done = await waitForCreateComplete(102);330    expect(done.error).toMatchObject({ name: "NotAllowedError" });331    expect(done.responseJson).toBeUndefined();332  });333334  // ─────────────────────────────────────────────────────────────────────335  // clientDataJSON.origin — page origin via active tab, not synthesized336  // from rpId. (bug #1)337  // ─────────────────────────────────────────────────────────────────────338339  it("create encodes the active tab origin into clientDataJSON when hostname is a subdomain of the rpId", async () => {340    const vault = await import("./vault");341    await vault.createVault("correct-pass-12345");342343    activeTabs = [{ id: 1, url: "https://myaccount.google.com/security/passkeys" }];344345    autoApprove();346    fireCreate(buildCreateOptions({ rpId: "google.com" }), 110);347    const done = await waitForCreateComplete(110);348349    const response = JSON.parse(done.responseJson!);350    const clientData = decodeClientData(response.response.clientDataJSON);351    expect(clientData.origin).toBe("https://myaccount.google.com");352    expect(clientData.type).toBe("webauthn.create");353  });354355  it("create encodes the active tab origin when hostname equals the rpId exactly", async () => {356    const vault = await import("./vault");357    await vault.createVault("correct-pass-12345");358359    activeTabs = [{ id: 1, url: "https://github.com/settings/security" }];360361    autoApprove();362    fireCreate(buildCreateOptions({ rpId: "github.com", rpName: "GitHub" }), 111);363    const done = await waitForCreateComplete(111);364365    const response = JSON.parse(done.responseJson!);366    const clientData = decodeClientData(response.response.clientDataJSON);367    expect(clientData.origin).toBe("https://github.com");368  });369370  it("create falls back to https://<rpId> when the active tab is not a registrable-suffix match (safety)", async () => {371    const vault = await import("./vault");372    await vault.createVault("correct-pass-12345");373374    // User switched tabs to evil.example before we resolved — refuse to375    // sign for that origin and fall back instead of leaking a signature376    // for a hostile origin.377    activeTabs = [{ id: 1, url: "https://evil.example/passkey" }];378379    autoApprove();380    fireCreate(buildCreateOptions({ rpId: "google.com" }), 112);381    const done = await waitForCreateComplete(112);382383    const response = JSON.parse(done.responseJson!);384    const clientData = decodeClientData(response.response.clientDataJSON);385    expect(clientData.origin).toBe("https://google.com");386  });387388  it("create falls back to https://<rpId> when the active tab has no URL", async () => {389    const vault = await import("./vault");390    await vault.createVault("correct-pass-12345");391392    activeTabs = [{ id: 1 }]; // no url393394    autoApprove();395    fireCreate(buildCreateOptions({ rpId: "google.com" }), 113);396    const done = await waitForCreateComplete(113);397398    const response = JSON.parse(done.responseJson!);399    const clientData = decodeClientData(response.response.clientDataJSON);400    expect(clientData.origin).toBe("https://google.com");401  });402403  // ─────────────────────────────────────────────────────────────────────404  // Core create ceremony.405  // ─────────────────────────────────────────────────────────────────────406407  it("create rejects with NotSupportedError when rp.id is missing", async () => {408    const vault = await import("./vault");409    await vault.createVault("correct-pass-12345");410411    fireCreate({ rp: { name: "No id" }, user: { id: "x", name: "u" }, challenge: "c", pubKeyCredParams: [{ alg: -7, type: "public-key" }] }, 120);412    const done = await waitForCreateComplete(120);413    expect(done.error).toMatchObject({ name: "NotSupportedError" });414  });415416  it("create rejects with NotSupportedError when no supported algorithm is offered", async () => {417    const vault = await import("./vault");418    await vault.createVault("correct-pass-12345");419420    autoApprove();421    fireCreate(buildCreateOptions({ pubKeyCredParams: [{ alg: -257, type: "public-key" }] }), 121);422    const done = await waitForCreateComplete(121);423    expect(done.error).toMatchObject({ name: "NotSupportedError" });424  });425426  it("create rejects with NotAllowedError when the user denies the approval", async () => {427    const vault = await import("./vault");428    await vault.createVault("correct-pass-12345");429430    autoDeny();431    fireCreate(buildCreateOptions(), 122);432    const done = await waitForCreateComplete(122);433    expect(done.error).toMatchObject({ name: "NotAllowedError" });434  });435436  it("create rejects with NotAllowedError + broadcasts the pro gate when the user is not Pro", async () => {437    const license = await import("./license");438    (license.isProUser as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce(false);439440    const vault = await import("./vault");441    await vault.createVault("correct-pass-12345");442443    fireCreate(buildCreateOptions(), 123);444    const done = await waitForCreateComplete(123);445    expect(done.error).toMatchObject({ name: "NotAllowedError" });446    // Pro gate broadcasted to every tab via tabs.sendMessage with PASSKEY_PRO_GATE.447    expect(tabsSendMessage).toHaveBeenCalledWith(448      expect.any(Number),449      expect.objectContaining({ type: "PASSKEY_PRO_GATE" })450    );451  });452453  it("create persists the passkey to the vault and tags it browser:'chrome'", async () => {454    const vault = await import("./vault");455    await vault.createVault("correct-pass-12345");456457    autoApprove();458    fireCreate(buildCreateOptions({ rpId: "github.com", rpName: "GitHub" }), 124);459    await waitForCreateComplete(124);460461    const stored = vault.getEntries().find((e) => e.passkey?.rpId === "github.com");462    expect(stored).toBeDefined();463    expect(stored!.passkey!.browser).toBe("chrome");464    expect(stored!.passkey!.backupEligible).toBe(true);465    expect(stored!.passkey!.signCount).toBe(0);466    expect(stored!.passkey!.privateKeyJwk).toBeDefined();467468    const createResponse = JSON.parse(completes.create.find((c) => c.requestId === 124)!.responseJson!);469    const authenticatorData = Uint8Array.from(atob(createResponse.response.authenticatorData.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(createResponse.response.authenticatorData.length / 4) * 4, "=")), (char) => char.charCodeAt(0));470    expect(authenticatorData[32]! & 0x08).toBe(0x08);471  });472473  it("create attaches the passkey to an existing login entry for the same domain instead of creating a new one", async () => {474    const vault = await import("./vault");475    await vault.createVault("correct-pass-12345");476    const existing = await vault.addEntry({477      type: "login",478      title: "GitHub",479      url: "https://github.com",480      username: "june",481      password: "hunter2",482    });483    const beforeCount = vault.getEntries().length;484485    autoApprove();486    fireCreate(buildCreateOptions({ rpId: "github.com", rpName: "GitHub", userName: "june" }), 125);487    await waitForCreateComplete(125);488489    expect(vault.getEntries().length).toBe(beforeCount);490    const updated = vault.getEntries().find((e) => e.id === existing.id);491    expect(updated?.passkey?.rpId).toBe("github.com");492  });493494495  it("preserves repeated registrations for the same RP and account", async () => {496    const vault = await import("./vault");497    await vault.createVault("correct-pass-12345");498    const ids: string[] = [];499    for (const requestId of [810, 811, 812]) {500      autoApprove();501      fireCreate(buildCreateOptions({ userName: requestId === 812 ? "other" : "june" }), requestId);502      const completed = await waitForCreateComplete(requestId);503      ids.push(JSON.parse(completed.responseJson!).id);504    }505    expect(new Set(ids).size).toBe(3);506    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());507    for (const [index, id] of ids.entries()) {508      autoApprove();509      fireGet({ rpId: "google.com", challenge: "Y2g", allowCredentials: [{ type: "public-key", id }] }, 820 + index);510      expect(JSON.parse((await waitForGetComplete(820 + index)).responseJson!).id).toBe(id);511    }512    vault.lock();513    expect(await vault.unlock("correct-pass-12345")).toBe(true);514    expect(vault.getEntries().map(entry => entry.passkey?.credentialId).sort()).toEqual(ids.sort());515  });516517  it.each(["different", "June", "", "ambiguous"])("does not attach to %s account candidates", async (account) => {518    const vault = await import("./vault");519    await vault.createVault("correct-pass-12345");520    const draft = { type: "login" as const, title: "Login", url: "https://google.com", username: account === "ambiguous" ? "june" : account, password: "pw" };521    const login = await vault.addEntry(draft);522    if (account === "ambiguous") await vault.addEntry(draft);523    autoApprove();524    fireCreate(buildCreateOptions({ userName: "june" }), 813);525    await waitForCreateComplete(813);526    expect(vault.getEntryById(login.id)?.passkey).toBeUndefined();527    expect(vault.getEntries().filter(entry => entry.passkey)).toHaveLength(1);528  });529530  it.each(["active", "foreign-rp", "deleted"])("honors excluded credential with %s state after approval", async (state) => {531    const vault = await import("./vault");532    await vault.createVault("correct-pass-12345");533    const seeded = await seedPasskey(state === "foreign-rp" ? "another.com" : "google.com");534    const entry = vault.getEntries().find(candidate => candidate.passkey?.credentialId === seeded.credentialId)!;535    if (state === "deleted") await vault.deleteEntry(entry.id);536    const before = vault.getEntries();537    const generate = vi.spyOn(crypto.subtle, "generateKey");538    autoApprove();539    fireCreate({ ...buildCreateOptions(), excludeCredentials: [{ type: "public-key", id: seeded.credentialId }] }, 814);540    const completed = await waitForCreateComplete(814);541    if (state === "active") {542      expect(completed.error?.name).toBe("InvalidStateError");543      expect(generate).not.toHaveBeenCalled();544      expect(vault.getEntries()).toEqual(before);545    } else {546      expect(completed.responseJson).toBeDefined();547    }548    generate.mockRestore();549  });550551552  it("rechecks excluded credentials when the vault changes during key generation", async () => {553    const vault = await import("./vault");554    await vault.createVault("correct-pass-12345");555    const seeded = await seedPasskey("another.com");556    const original = crypto.subtle.generateKey.bind(crypto.subtle);557    const generate = vi.spyOn(crypto.subtle, "generateKey").mockImplementation(async (...args: Parameters<typeof crypto.subtle.generateKey>) => {558      const generated = await Reflect.apply(original, crypto.subtle, args);559      await vault.updateEntry(seeded.entry.id, { passkey: { ...seeded.entry.passkey!, rpId: "google.com" } });560      return generated;561    });562    autoApprove();563    fireCreate({ ...buildCreateOptions(), excludeCredentials: [{ type: "public-key", id: seeded.credentialId }] }, 815);564    const completed = await waitForCreateComplete(815);565    expect(completed.error?.name).toBe("InvalidStateError");566    expect(vault.getEntries()).toHaveLength(1);567    generate.mockRestore();568  });569570  // ─────────────────────────────────────────────────────────────────────571  // Get ceremony.572  // ─────────────────────────────────────────────────────────────────────573574  async function seedPasskey(rpId: string, opts?: { signCount?: number }) {575    const vault = await import("./vault");576    const { base64urlEncode, generatePasskeyKeypair } = await import("./passkey-crypto");577    const generated = await generatePasskeyKeypair(-7);578    const credentialId = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)));579    const entry = await vault.addEntry({580      type: "login",581      title: rpId,582      url: `https://${rpId}`,583      username: "june",584      passkey: {585        rpId,586        rpName: rpId,587        credentialId,588        publicKeyCose: base64urlEncode(generated.publicKeyCose),589        privateKeyJwk: generated.privateKeyJwk,590        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(16))),591        userName: "june",592        userDisplayName: "June",593        algorithm: -7,594        signCount: opts?.signCount ?? 0,595        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",596        backupEligible: false,597        backupState: false,598        browser: "chrome",599        transports: ["internal"],600        createdAt: Date.now(),601      },602    });603    return { entry, credentialId };604  }605606  it("get passes through to platform when no stored credential matches the rpId", async () => {607    const vault = await import("./vault");608    await vault.createVault("correct-pass-12345");609610    fireGet({ rpId: "github.com", challenge: "Y2g", allowCredentials: [] }, 200);611    const done = await waitForGetComplete(200);612    // Pass-through: no error and no responseJson — Chrome routes to next authenticator.613    expect(done.error).toBeUndefined();614    expect(done.responseJson).toBeUndefined();615  });616617  // PB-26-015: a credential-ID match must still belong to the requesting rpId —618  // a foreign-RP request listing a known credential id must not select it.619  it("get does not match a credential whose stored rpId differs from the request rpId", async () => {620    const vault = await import("./vault");621    await vault.createVault("correct-pass-12345");622    const { credentialId } = await seedPasskey("github.com");623624    fireGet(625      {626        rpId: "evil.example",627        challenge: "Y2g",628        allowCredentials: [{ type: "public-key", id: credentialId }],629      },630      205,631    );632    const done = await waitForGetComplete(205);633    expect(done.error).toBeUndefined();634    expect(done.responseJson).toBeUndefined();635  });636637  it("get encodes the active tab page origin into clientDataJSON (not https://<rpId>)", async () => {638    const vault = await import("./vault");639    await vault.createVault("correct-pass-12345");640    await seedPasskey("google.com");641642    activeTabs = [{ id: 1, url: "https://accounts.google.com/login" }];643644    autoApprove();645    fireGet({ rpId: "google.com", challenge: "Y2g", allowCredentials: [] }, 201);646    const done = await waitForGetComplete(201);647648    const response = JSON.parse(done.responseJson!);649    const clientData = decodeClientData(response.response.clientDataJSON);650    expect(clientData.origin).toBe("https://accounts.google.com");651    expect(clientData.type).toBe("webauthn.get");652  });653654  it("get increments signCount and updates lastUsedAt on success", async () => {655    const vault = await import("./vault");656    await vault.createVault("correct-pass-12345");657    const { entry } = await seedPasskey("github.com", { signCount: 7 });658659    autoApprove();660    fireGet({ rpId: "github.com", challenge: "Y2g", allowCredentials: [] }, 202);661    await waitForGetComplete(202);662663    const after = vault.getEntries().find((e) => e.id === entry.id);664    expect(after!.passkey!.signCount).toBe(8);665    expect(after!.passkey!.lastUsedAt).toBeDefined();666  });667668  it("get preserves the BE flag used to register legacy Chrome passkeys", async () => {669    const vault = await import("./vault");670    await vault.createVault("correct-pass-12345");671    const { entry } = await seedPasskey("github.com");672673    expect(entry.passkey!.browser).toBe("chrome");674    expect(entry.passkey!.backupEligible).toBe(false);675676    autoApprove();677    fireGet({ rpId: "github.com", challenge: "Y2g", allowCredentials: [] }, 206);678    const done = await waitForGetComplete(206);679    const response = JSON.parse(done.responseJson!);680    const authenticatorData = Uint8Array.from(681      atob(response.response.authenticatorData.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(response.response.authenticatorData.length / 4) * 4, "=")),682      (char) => char.charCodeAt(0),683    );684685    expect(authenticatorData[32]! & 0x08).toBe(0x08);686    expect(vault.getEntries().find((candidate) => candidate.id === entry.id)!.passkey!.backupEligible).toBe(true);687  });688689  it("get passes through to platform when the stored passkey has no private key (Firefox-created)", async () => {690    const vault = await import("./vault");691    await vault.createVault("correct-pass-12345");692    const { base64urlEncode, generatePasskeyKeypair } = await import("./passkey-crypto");693    const generated = await generatePasskeyKeypair(-7);694    await vault.addEntry({695      type: "login",696      title: "Cross-browser passkey",697      passkey: {698        rpId: "webauthn.io",699        rpName: "WebAuthn.io",700        credentialId: base64urlEncode(crypto.getRandomValues(new Uint8Array(32))),701        publicKeyCose: base64urlEncode(generated.publicKeyCose),702        // privateKeyJwk intentionally absent — pre-v2.12 Firefox passkey703        // delegated signing to the platform authenticator.704        userHandle: base64urlEncode(crypto.getRandomValues(new Uint8Array(16))),705        userName: "june",706        userDisplayName: "June",707        algorithm: -7,708        signCount: 0,709        aaguid: "AAAAAAAAAAAAAAAAAAAAAA",710        backupEligible: false,711        backupState: false,712        browser: "firefox",713        transports: ["internal"],714        createdAt: Date.now(),715      },716    });717718    fireGet({ rpId: "webauthn.io", challenge: "Y2g", allowCredentials: [] }, 203);719    const done = await waitForGetComplete(203);720    // Pass-through: no error and no responseJson — Chrome routes to next authenticator.721    expect(done.error).toBeUndefined();722    expect(done.responseJson).toBeUndefined();723  });724725  it("get on a locked vault parks the request and proceeds after unlock", async () => {726    const vault = await import("./vault");727    await vault.createVault("correct-pass-12345");728    await seedPasskey("github.com");729    vault.lock();730731    autoApprove();732    fireGet({ rpId: "github.com", challenge: "Y2g", allowCredentials: [] }, 204);733734    await new Promise((r) => setTimeout(r, 50));735    expect(tabsSendMessage).toHaveBeenCalledWith(736      1,737      expect.objectContaining({ type: "SUMMON_AUTOFILL", source: "passkey-unlock" })738    );739740    await vault.unlock("correct-pass-12345");741    const passkey = await import("./passkey");742    passkey.onVaultUnlocked();743744    const done = await waitForGetComplete(204);745    expect(done.error).toBeUndefined();746    expect(done.responseJson).toBeDefined();747  });748749  // ─────────────────────────────────────────────────────────────────────750  // onRequestCanceled — popup-closed / RP-cancelled cleanup.751  // ─────────────────────────────────────────────────────────────────────752753  // ─────────────────────────────────────────────────────────────────────754  // "Invalid requestId" survival — conditional-UI gets cancel fast.755  // ─────────────────────────────────────────────────────────────────────756757  it("pass-through swallows 'Invalid requestId' from a cancelled conditional-UI get without throwing", async () => {758    const vault = await import("./vault");759    await vault.createVault("correct-pass-12345");760761    // Simulate Chrome cancelling the request between handleGetRequest running762    // and the pass-through completeGetRequest call landing.763    const ce = (globalThis as { chrome: typeof chrome }).chrome.webAuthenticationProxy764      .completeGetRequest as unknown as ReturnType<typeof vi.fn>;765    ce.mockImplementationOnce(async () => {766      throw new Error("Invalid requestId");767    });768769    // No matching passkey for this rpId → pass-through completeGetRequest call,770    // which must NOT propagate the Invalid requestId error.771    let resolved = false;772    proxyListeners.get!({773      requestId: 999,774      requestDetailsJson: JSON.stringify({ rpId: "unknown.example", challenge: "x", allowCredentials: [] }),775    });776    // Allow the handler to finish; if it threw, the test would unhandle-reject.777    await new Promise((r) => setTimeout(r, 30));778    resolved = true;779    expect(resolved).toBe(true);780  });781782  it("rejectCreate swallows 'Invalid requestId' from a cancelled create", async () => {783    const vault = await import("./vault");784    await vault.createVault("correct-pass-12345");785786    const ce = (globalThis as { chrome: typeof chrome }).chrome.webAuthenticationProxy787      .completeCreateRequest as unknown as ReturnType<typeof vi.fn>;788    ce.mockImplementationOnce(async () => {789      throw new Error("Invalid requestId");790    });791792    // Force the early rp.id missing path so rejectCreate runs first.793    fireCreate({ rp: {}, user: { id: "x", name: "u" }, challenge: "c", pubKeyCredParams: [{ alg: -7, type: "public-key" }] }, 998);794    await new Promise((r) => setTimeout(r, 30));795    // No assertions on completes — the assertion is that the handler did796    // not throw an unhandled rejection (the test would fail under vitest's797    // unhandled-rejection guard otherwise).798  });799800  it("onRequestCanceled clears a parked unlock waiter so the handler exits promptly", async () => {801    const vault = await import("./vault");802    await vault.createVault("correct-pass-12345");803    vault.lock();804805    fireCreate(buildCreateOptions(), 997);806    // Wait for the request to park.807    await new Promise((r) => setTimeout(r, 30));808809    proxyListeners.cancel!(997);810811    const done = await waitForCreateComplete(997, 500);812    expect(done.error).toMatchObject({ name: "NotAllowedError" });813  });814815  it("onRequestCanceled resolves a still-pending approval as denied", async () => {816    const vault = await import("./vault");817    await vault.createVault("correct-pass-12345");818819    fireCreate(buildCreateOptions(), 301);820821    // Wait for the approval to be registered.822    const passkey = await import("./passkey");823    let pending: Awaited<ReturnType<typeof passkey.getPendingPasskeyRequest>> = null;824    for (let i = 0; i < 50; i += 1) {825      pending = await passkey.getPendingPasskeyRequest();826      if (pending) break;827      await new Promise((r) => setTimeout(r, 10));828    }829    expect(pending).toBeTruthy();830831    proxyListeners.cancel!(301);832833    // After cancel the pending session record should be cleared.834    for (let i = 0; i < 50; i += 1) {835      const after = await passkey.getPendingPasskeyRequest();836      if (!after) return;837      await new Promise((r) => setTimeout(r, 10));838    }839    throw new Error("pending passkey request was not cleared after onRequestCanceled");840  });841});