123import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";45678910111213141516171819202122const exportedFns = new Map<string, (...args: any[]) => any>();2324function stubExportFunction(25 func: (...args: any[]) => any,26 _targetScope: any,27 options?: { defineAs?: string },28): (...args: any[]) => any {29 const name = options?.defineAs;30 if (name) {31 exportedFns.set(name, func);32 33 if (_targetScope && _targetScope !== globalThis) {34 _targetScope[name] = func;35 }36 }37 return func;38}3940let pageScopeValues = new WeakSet<object>();4142function stubCloneInto<T>(obj: T, _targetScope: unknown, _options?: { cloneFunctions?: boolean }): T {43 function clone(value: unknown): unknown {44 if (typeof value === "function") {45 return (...args: unknown[]) => {46 const result: unknown = Reflect.apply(value, undefined, args);47 if (result && typeof result === "object" && !pageScopeValues.has(result)) {48 return new Proxy(result, {49 get() { throw new Error("Permission denied to access privileged object"); },50 has() { throw new Error("Permission denied to access privileged object"); },51 ownKeys() { throw new Error("Permission denied to access privileged object"); },52 });53 }54 return result;55 };56 }57 if (!value || typeof value !== "object") return value;58 const copied = value instanceof ArrayBuffer ? value.slice(0) : Array.isArray(value)59 ? value.map(clone)60 : Object.fromEntries(Object.entries(value).map(([key, child]) => [key, clone(child)]));61 pageScopeValues.add(copied);62 return copied;63 }64 return clone(obj) as T;65}66676869let mockSendMessage: ReturnType<typeof vi.fn>;7071function setupChromeMock() {72 mockSendMessage = vi.fn().mockResolvedValue({ ok: false, error: "not_applicable" });73 vi.stubGlobal("chrome", {74 runtime: {75 id: "peach-extension",76 sendMessage: mockSendMessage,77 getURL: vi.fn(() => "moz-extension://abcd/"),78 },79 });80}81828384function base64url(bytes: Uint8Array): string {85 let str = "";86 for (const b of bytes) str += String.fromCharCode(b);87 return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");88}8990function makeCreateOptions(rpId = "github.com"): CredentialCreationOptions {91 return {92 publicKey: {93 rp: { id: rpId, name: "GitHub" },94 user: { id: new Uint8Array(16), name: "june", displayName: "June" },95 challenge: new Uint8Array(16),96 pubKeyCredParams: [{ alg: -7, type: "public-key" }],97 },98 } as CredentialCreationOptions;99}100101function makeGetOptions(rpId = "github.com"): CredentialRequestOptions {102 return {103 publicKey: {104 rpId,105 challenge: new Uint8Array(16),106 allowCredentials: [{ id: new Uint8Array(32), type: "public-key" }],107 },108 } as CredentialRequestOptions;109}110111function validCreateCredential() {112 return {113 type: "create",114 id: base64url(new Uint8Array(32)),115 clientDataJSON: Array.from(new TextEncoder().encode(JSON.stringify({ type: "webauthn.create", challenge: "x", origin: "https://github.com", crossOrigin: false }))),116 attestationObject: base64url(new Uint8Array(64)),117 authenticatorData: base64url(new Uint8Array(37)),118 publicKey: base64url(new Uint8Array(64)),119 algorithm: -7,120 };121}122123function validGetCredential() {124 return {125 type: "get",126 id: base64url(new Uint8Array(32)),127 clientDataJSON: Array.from(new TextEncoder().encode(JSON.stringify({ type: "webauthn.get", challenge: "x", origin: "https://github.com", crossOrigin: false }))),128 authenticatorData: base64url(new Uint8Array(37)),129 signature: base64url(new Uint8Array(64)),130 userHandle: base64url(new Uint8Array(16)),131 };132}133134135136describe("PB-26-209: exportFunction privileged bridge", () => {137 let nativeGet: ReturnType<typeof vi.fn>;138 let nativeCreate: ReturnType<typeof vi.fn>;139 beforeEach(async () => {140 vi.resetModules();141 setupChromeMock();142 exportedFns.clear();143 pageScopeValues = new WeakSet<object>();144145 146 vi.stubGlobal("exportFunction", stubExportFunction);147 vi.stubGlobal("cloneInto", stubCloneInto);148149 150 delete (window as any).__peachPasskeyProxyInstalled;151152 153 154 nativeCreate = vi.fn(async () => null);155 nativeGet = vi.fn(async () => null);156 Object.defineProperty(navigator, "credentials", {157 value: { create: nativeCreate, get: nativeGet },158 configurable: true,159 });160161 await import("./passkeys-firefox");162 });163164 afterEach(() => {165 vi.unstubAllGlobals();166 });167168169 it("serializes exclusion IDs from sliced BufferSource descriptors", async () => {170 mockSendMessage.mockResolvedValue({ ok: false, error: "not_applicable" });171 const options = makeCreateOptions();172 const bytes = new Uint8Array([9, 1, 2, 3, 9]);173 options.publicKey!.excludeCredentials = [{ type: "public-key", id: new DataView(bytes.buffer, 1, 3), transports: ["internal"] }];174 await navigator.credentials.create(options);175 expect(mockSendMessage).toHaveBeenCalledWith(expect.objectContaining({ payload: expect.objectContaining({ excludeCredentials: [{ type: "public-key", id: "AQID", transports: ["internal"] }] }) }));176 });177178 it("preserves InvalidStateError without native fallback", async () => {179 mockSendMessage.mockResolvedValue({ ok: false, error: "credential_excluded" });180 await expect(navigator.credentials.create(makeCreateOptions())).rejects.toMatchObject({ name: "InvalidStateError" });181 expect(nativeCreate).not.toHaveBeenCalled();182 });183184 describe("no forgeable response channel", () => {185 it("exports non-async wrappers so Firefox can return page-scope promises", () => {186 expect(exportedFns.get("create")?.constructor.name).toBe("Function");187 expect(exportedFns.get("get")?.constructor.name).toBe("Function");188 });189190 it("a forged PEACH_PASSKEY_RESPONSE with a correct-former UUID has no listener and no effect", async () => {191 192 193 const postSpy = vi.spyOn(window, "postMessage");194195 196 const forged = new MessageEvent("message", {197 data: {198 type: "PEACH_PASSKEY_RESPONSE",199 id: "00000000-0000-0000-0000-000000000000",200 payload: { ok: true, credential: validCreateCredential() },201 },202 source: window,203 });204 window.dispatchEvent(forged);205206 207 208 209 const passkeyPostCalls = postSpy.mock.calls.filter(210 ([data]) => {211 const d = data as { type?: string };212 return d?.type === "PEACH_PASSKEY_REQUEST" || d?.type === "PEACH_PASSKEY_RESPONSE";213 },214 );215 expect(passkeyPostCalls).toHaveLength(0);216 postSpy.mockRestore();217 });218219 it("production code has no PEACH_PASSKEY_RESPONSE message listener", async () => {220 221 const fs = await import("node:fs");222 const path = await import("node:path");223 const source = fs.readFileSync(224 path.resolve(process.cwd(), "src/content/passkeys-firefox.ts"),225 "utf-8",226 );227 expect(source).not.toContain("PEACH_PASSKEY_RESPONSE");228 expect(source).not.toContain("PEACH_PASSKEY_REQUEST");229 230 expect(source).not.toMatch(/window\.postMessage\s*\(/);231 });232 });233234 describe("malformed responses fail closed", () => {235 it("create: falls through to original when credential.id is not base64url", async () => {236 mockSendMessage.mockResolvedValueOnce({237 ok: true,238 credential: { ...validCreateCredential(), id: "!!!not-base64url!!!" },239 });240241 const result = navigator.credentials.create(makeCreateOptions());242 243 244 await expect(result).resolves.toBeNull();245 });246247 it("create: falls through when credential type is wrong", async () => {248 mockSendMessage.mockResolvedValueOnce({249 ok: true,250 credential: { ...validCreateCredential(), type: "get" },251 });252253 await expect(254 navigator.credentials.create(makeCreateOptions()),255 ).resolves.toBeNull();256 });257258 it("create: falls through when clientDataJSON is missing", async () => {259 const cred = validCreateCredential();260 delete (cred as any).clientDataJSON;261 mockSendMessage.mockResolvedValueOnce({ ok: true, credential: cred });262263 await expect(264 navigator.credentials.create(makeCreateOptions()),265 ).resolves.toBeNull();266 });267268 it("create: falls through when attestationObject is not base64url", async () => {269 mockSendMessage.mockResolvedValueOnce({270 ok: true,271 credential: { ...validCreateCredential(), attestationObject: "not valid!" },272 });273274 await expect(275 navigator.credentials.create(makeCreateOptions()),276 ).resolves.toBeNull();277 });278279 it("create: falls through when algorithm is unsupported", async () => {280 mockSendMessage.mockResolvedValueOnce({281 ok: true,282 credential: { ...validCreateCredential(), algorithm: -999 },283 });284285 await expect(286 navigator.credentials.create(makeCreateOptions()),287 ).resolves.toBeNull();288 });289290 it("get: rejects when signature is not base64url", async () => {291 292 mockSendMessage293 .mockResolvedValueOnce({ ok: true, hasCredentials: true })294 .mockResolvedValueOnce({295 ok: true,296 credential: { ...validGetCredential(), signature: "!!!invalid!!!" },297 });298299 await expect(300 navigator.credentials.get(makeGetOptions()),301 ).rejects.toMatchObject({ name: "NotAllowedError" });302 });303304 it("get: rejects when authenticatorData is not base64url", async () => {305 mockSendMessage306 .mockResolvedValueOnce({ ok: true, hasCredentials: true })307 .mockResolvedValueOnce({308 ok: true,309 credential: { ...validGetCredential(), authenticatorData: "" },310 });311312 await expect(313 navigator.credentials.get(makeGetOptions()),314 ).rejects.toMatchObject({ name: "NotAllowedError" });315 });316317 it("get: rejects when credential is null", async () => {318 mockSendMessage319 .mockResolvedValueOnce({ ok: true, hasCredentials: true })320 .mockResolvedValueOnce({ ok: true, credential: null });321322 await expect(323 navigator.credentials.get(makeGetOptions()),324 ).rejects.toMatchObject({ name: "NotAllowedError" });325 });326 });327328 describe("privileged bridge captures sendMessage at install time", () => {329 it("wrapper closure uses the captured sendMessage, not a re-lookup", async () => {330 331 332 333 const original = mockSendMessage;334 const replacement = vi.fn().mockResolvedValue({ ok: false, error: "not_applicable" });335 vi.stubGlobal("chrome", {336 runtime: { id: "peach-extension", sendMessage: replacement, getURL: vi.fn(() => "moz-extension://abcd/") },337 });338339 340 mockSendMessage = original;341 await navigator.credentials.create(makeCreateOptions());342343 344 expect(replacement).not.toHaveBeenCalled();345 });346 });347348 describe("valid responses produce credentials", () => {349 it("get: leaves conditional requests and their cancellation signal with Firefox", async () => {350 const controller = new AbortController();351 const options: CredentialRequestOptions = {352 ...makeGetOptions(), mediation: "conditional", signal: controller.signal,353 };354 mockSendMessage355 .mockResolvedValueOnce({ ok: true, hasCredentials: true })356 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });357 await expect(navigator.credentials.get(options)).resolves.toBeNull();358 expect(nativeGet).toHaveBeenCalledWith(options);359 expect(mockSendMessage).not.toHaveBeenCalled();360 });361362 it("get: waits for a cold background instead of opening Firefox native UI", async () => {363 mockSendMessage364 .mockRejectedValueOnce(new Error("Could not establish connection. Receiving end does not exist."))365 .mockResolvedValueOnce({ ok: false, error: "vault_locked" })366 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });367 const result = await navigator.credentials.get(makeGetOptions());368 expect(result?.id).toBe(validGetCredential().id);369 expect(nativeGet).not.toHaveBeenCalled();370 });371372 it("get: retries a missing background response before continuing through unlock", async () => {373 mockSendMessage374 .mockResolvedValueOnce(undefined)375 .mockResolvedValueOnce({ ok: false, error: "vault_locked" })376 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });377 expect((await navigator.credentials.get(makeGetOptions()))?.id).toBe(validGetCredential().id);378 expect(nativeGet).not.toHaveBeenCalled();379 });380381 it("get: rejects unavailable Peach instead of silently opening native Firefox UI", async () => {382 mockSendMessage.mockRejectedValue(new Error("Receiving end does not exist"));383 await expect(navigator.credentials.get(makeGetOptions())).rejects.toMatchObject({ name: "NotAllowedError" });384 expect(mockSendMessage).toHaveBeenCalledTimes(3);385 expect(nativeGet).not.toHaveBeenCalled();386 });387388 it("get: rejects a Peach operation error instead of opening native Firefox UI", async () => {389 mockSendMessage390 .mockResolvedValueOnce({ ok: true, hasCredentials: true })391 .mockResolvedValueOnce({ ok: false, error: "operation_failed" });392 await expect(navigator.credentials.get(makeGetOptions())).rejects.toMatchObject({ name: "NotAllowedError" });393 expect(nativeGet).not.toHaveBeenCalled();394 });395396 it("get: never retries a signing request after a delivery error", async () => {397 mockSendMessage398 .mockResolvedValueOnce({ ok: true, hasCredentials: true })399 .mockRejectedValueOnce(new Error("Background disconnected"));400 await expect(navigator.credentials.get(makeGetOptions())).rejects.toMatchObject({ name: "NotAllowedError" });401 expect(mockSendMessage).toHaveBeenCalledTimes(2);402 expect(nativeGet).not.toHaveBeenCalled();403 });404405 it("get: preserves native sign-in when interception is disabled", async () => {406 mockSendMessage.mockResolvedValueOnce({ ok: false, error: "not_applicable" });407 const options = makeGetOptions();408 await expect(navigator.credentials.get(options)).resolves.toBeNull();409 expect(nativeGet).toHaveBeenCalledWith(options);410 expect(mockSendMessage).toHaveBeenCalledTimes(1);411 });412413 it("get: rejects a failed credential check without retrying a delivered reply", async () => {414 mockSendMessage.mockResolvedValueOnce({ ok: false, error: "internal_error" });415 await expect(navigator.credentials.get(makeGetOptions())).rejects.toMatchObject({ name: "NotAllowedError" });416 expect(mockSendMessage).toHaveBeenCalledTimes(1);417 expect(nativeGet).not.toHaveBeenCalled();418 });419420 it("get: preserves an explicit security-key request without contacting Peach", async () => {421 const options = makeGetOptions();422 options.publicKey = { ...options.publicKey!, hints: ["security-key"] } as PublicKeyCredentialRequestOptions;423 await expect(navigator.credentials.get(options)).resolves.toBeNull();424 expect(nativeGet).toHaveBeenCalledWith(options);425 expect(mockSendMessage).not.toHaveBeenCalled();426 });427428 it.each([429 "new Uint8Array([1, 2, 3, 4]).buffer",430 "new Uint8Array(new Uint8Array([9, 1, 2, 3, 4, 9]).buffer, 1, 4)",431 ])("get: preserves page-realm buffers and view offsets (%s)", async (expression) => {432 const { runInNewContext } = await import("node:vm");433 const challenge: BufferSource = runInNewContext(expression);434 const credentialId: ArrayBuffer = runInNewContext("new Uint8Array([5, 6, 7, 8]).buffer");435 expect(challenge instanceof ArrayBuffer).toBe(false);436 mockSendMessage437 .mockResolvedValueOnce({ ok: true, hasCredentials: true })438 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });439 await navigator.credentials.get({440 publicKey: { challenge, rpId: "github.com", allowCredentials: [{ id: credentialId, type: "public-key" }] },441 });442 const request = mockSendMessage.mock.calls.find(([message]) => message.type === "PASSKEY_GET")?.[0] as {443 payload: { challenge: string; clientDataJSON: number[]; allowCredentials: { id: string }[] };444 };445 expect(request.payload.challenge).toBe("AQIDBA");446 expect(request.payload.allowCredentials).toEqual([{ id: "BQYHCA", type: "public-key" }]);447 expect(JSON.parse(new TextDecoder().decode(new Uint8Array(request.payload.clientDataJSON))).challenge).toBe("AQIDBA");448 });449450 it("create: preserves the challenge and user ID from the page's ArrayBuffer realm", async () => {451 const { runInNewContext } = await import("node:vm");452 const options = makeCreateOptions();453 options.publicKey!.challenge = runInNewContext("new Uint8Array([1, 2, 3, 4]).buffer");454 options.publicKey!.user.id = runInNewContext("new Uint8Array([5, 6, 7, 8]).buffer");455 mockSendMessage.mockResolvedValueOnce({ ok: true, credential: validCreateCredential() });456 await navigator.credentials.create(options);457 const request = mockSendMessage.mock.calls[0]![0] as { payload: { challenge: string; userId: string } };458 expect(request.payload.challenge).toBe("AQIDBA");459 expect(request.payload.userId).toBe("BQYHCA");460 });461462 it("get: exposes method results to a page serializing the assertion", async () => {463 const expected = validGetCredential();464 mockSendMessage465 .mockResolvedValueOnce({ ok: true, hasCredentials: true })466 .mockResolvedValueOnce({ ok: true, credential: expected });467 const credential = await navigator.credentials.get(makeGetOptions()) as PublicKeyCredential;468 expect(Object.keys(credential.getClientExtensionResults())).toEqual([]);469 expect(JSON.parse(JSON.stringify(credential))).toMatchObject({470 id: expected.id, response: { signature: expected.signature, userHandle: expected.userHandle },471 clientExtensionResults: {},472 });473 });474475 it("create: exposes binary getters and method results to the page", async () => {476 const expected = validCreateCredential();477 mockSendMessage.mockResolvedValueOnce({ ok: true, credential: expected });478 const credential = await navigator.credentials.create(makeCreateOptions()) as PublicKeyCredential;479 const response = credential.response as AuthenticatorAttestationResponse;480 expect(response.getTransports()).toEqual(["internal"]);481 expect(new Uint8Array(response.getAuthenticatorData())).toHaveLength(37);482 expect(new Uint8Array(response.getPublicKey()!)).toHaveLength(64);483 expect(response.getPublicKeyAlgorithm()).toBe(-7);484 expect(Object.keys(credential.getClientExtensionResults())).toEqual([]);485 expect(JSON.parse(JSON.stringify(credential))).toMatchObject({486 id: expected.id, response: { attestationObject: expected.attestationObject },487 clientExtensionResults: {},488 });489 });490491 it("create: returns a PublicKeyCredential-shaped object for a valid response", async () => {492 mockSendMessage.mockResolvedValueOnce({ ok: true, credential: validCreateCredential() });493494 const cred = await navigator.credentials.create(makeCreateOptions());495 expect(cred).not.toBeNull();496 expect((cred as any).type).toBe("public-key");497 expect((cred as any).id).toBeDefined();498 expect((cred as any).rawId).toBeDefined();499 expect((cred as any).response).toBeDefined();500 expect((cred as any).response.attestationObject).toBeDefined();501 });502503 it("get: returns a PublicKeyCredential-shaped object for a valid response", async () => {504 mockSendMessage505 .mockResolvedValueOnce({ ok: true, hasCredentials: true })506 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });507508 const cred = await navigator.credentials.get(makeGetOptions());509 expect(cred).not.toBeNull();510 expect((cred as any).type).toBe("public-key");511 expect((cred as any).response.signature).toBeDefined();512 expect((cred as any).response.authenticatorData).toBeDefined();513 });514515 it("create: throws NotAllowedError on user_cancelled", async () => {516 mockSendMessage.mockResolvedValueOnce({ ok: false, error: "user_cancelled" });517518 await expect(519 navigator.credentials.create(makeCreateOptions()),520 ).rejects.toMatchObject({ name: "NotAllowedError" });521 });522523 it("get: throws NotAllowedError on user_cancelled", async () => {524 mockSendMessage525 .mockResolvedValueOnce({ ok: true, hasCredentials: true })526 .mockResolvedValueOnce({ ok: false, error: "user_cancelled" });527528 await expect(529 navigator.credentials.get(makeGetOptions()),530 ).rejects.toMatchObject({ name: "NotAllowedError" });531 });532533 it("create: falls through on vault_locked", async () => {534 mockSendMessage.mockResolvedValueOnce({ ok: false, error: "vault_locked" });535 await expect(536 navigator.credentials.create(makeCreateOptions()),537 ).resolves.toBeNull();538 });539540 it("get: continues through unlock when the credential check reports vault_locked", async () => {541 mockSendMessage542 .mockResolvedValueOnce({ ok: false, error: "vault_locked" })543 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });544 const result = await navigator.credentials.get(makeGetOptions());545 expect(result?.id).toBe(validGetCredential().id);546 expect(nativeGet).not.toHaveBeenCalled();547 });548549 it("get: rejects an abandoned unlock without opening native Firefox UI", async () => {550 mockSendMessage551 .mockResolvedValueOnce({ ok: false, error: "vault_locked" })552 .mockResolvedValueOnce({ ok: false, error: "user_cancelled" });553 await expect(navigator.credentials.get(makeGetOptions())).rejects.toMatchObject({ name: "NotAllowedError" });554 expect(nativeGet).not.toHaveBeenCalled();555 });556557 it("get: falls through on no_credentials after has-credentials pre-check", async () => {558 mockSendMessage559 .mockResolvedValueOnce({ ok: true, hasCredentials: true })560 .mockResolvedValueOnce({ ok: false, error: "no_credentials" });561 await expect(562 navigator.credentials.get(makeGetOptions()),563 ).resolves.toBeNull();564 });565566 it("get: falls through when has-credentials returns false", async () => {567 mockSendMessage.mockResolvedValueOnce({ ok: true, hasCredentials: false });568 569 await navigator.credentials.get(makeGetOptions());570 const calls = mockSendMessage.mock.calls.map((c) => (c[0] as { type: string }).type);571 expect(calls).not.toContain("PASSKEY_GET");572 });573 });574575 describe("origin handling", () => {576 it("create: sends window.location.origin in the request, not a page-supplied value", async () => {577 mockSendMessage.mockResolvedValueOnce({ ok: true, credential: validCreateCredential() });578579 await navigator.credentials.create(makeCreateOptions());580581 const call = mockSendMessage.mock.calls[0]![0] as { type: string; payload: { origin: string; clientDataJSON: number[] } };582 expect(call.payload.origin).toBe(window.location.origin);583584 585 const clientData = JSON.parse(new TextDecoder().decode(new Uint8Array(call.payload.clientDataJSON)));586 expect(clientData.origin).toBe(window.location.origin);587 });588589 it("get: sends window.location.origin in the request", async () => {590 mockSendMessage591 .mockResolvedValueOnce({ ok: true, hasCredentials: true })592 .mockResolvedValueOnce({ ok: true, credential: validGetCredential() });593594 await navigator.credentials.get(makeGetOptions());595596 const getCall = mockSendMessage.mock.calls.find(597 (c) => (c[0] as { type: string }).type === "PASSKEY_GET",598 );599 const payload = (getCall![0] as { payload: { origin: string } }).payload;600 expect(payload.origin).toBe(window.location.origin);601 });602 });603604 describe("exportFunction unavailable", () => {605 it("falls through to native when exportFunction is not available", async () => {606 vi.resetModules();607 608 vi.stubGlobal("exportFunction", undefined);609 vi.stubGlobal("cloneInto", undefined);610611 const nativeCreate = vi.fn(async () => null);612 Object.defineProperty(navigator, "credentials", {613 value: { create: nativeCreate, get: vi.fn(async () => null) },614 configurable: true,615 });616617 await import("./passkeys-firefox");618619 620 await navigator.credentials.create(makeCreateOptions());621 expect(nativeCreate).toHaveBeenCalled();622 623 expect(mockSendMessage).not.toHaveBeenCalled();624 });625 });626});