passkey.ts

50.3 KB · raw

1import { isProUser } from "./license";2import * as vault from "./vault";3import {4  base64urlEncode,5  buildAuthenticatorData,6  buildClientDataJSON,7  createAttestationObject,8  generateCredentialId,9  generatePasskeyKeypair,10  pickPasskeyAlgorithm,11  signPasskeyAssertion,12} from "./passkey-crypto";13import { detectBrowser as detectSharedBrowser, firefoxVersion } from "../shared/browser";14import { FIREFOX_USE_CONTENT_SCRIPT_PROXY } from "../shared/passkey-flags";15import { isValidRpId } from "../shared/passkey-utils";16import type {17  PasskeyData,18  PasskeyProviderState,19  PendingPasskeyRequest,20  VaultEntry,21} from "../shared/types";2223declare const __PEACH_E2E_PASSKEYS__: boolean;2425const PENDING_PREFIX = "passkey_pending_";26const APPROVAL_TIMEOUT_MS = 60_000;2728let listenersRegistered = false;29let attached = false;30let conflict: string | undefined;31const PASSKEY_CREATE_E2E_BYPASS = __PEACH_E2E_PASSKEYS__ === true;3233// Approval must not close and lock the popup before a Firefox ceremony persists.34const firefoxCeremonies = new Map<number, Promise<void>>();3536const approvals = new Map<37  number,38  { resolve: (approved: boolean) => void; timeoutId: ReturnType<typeof setTimeout> }39>();4041// Resolvers for GET requests that arrived while the vault was locked and are42// waiting for the user to unlock before the passkey flow can continue.43const unlockWaiters = new Map<number, { resolve: (ok: boolean) => void; timeoutId: ReturnType<typeof setTimeout> }>();4445export function onVaultUnlocked(): void {46  for (const { resolve, timeoutId } of unlockWaiters.values()) {47    clearTimeout(timeoutId);48    resolve(true);49  }50  unlockWaiters.clear();51}5253/**54 * Resolve every still-pending passkey request as denied and clear unlock55 * waiters. Called from the popup-disconnect path so a closed popup releases56 * the page-side caller in <200ms instead of leaving it stuck for the full57 * APPROVAL_TIMEOUT_MS (60s) (M8/COR-009).58 */59export async function denyAllPendingPasskeyRequests(): Promise<void> {60  if (approvals.size === 0 && unlockWaiters.size === 0) return;61  for (const [rid, { resolve, timeoutId }] of approvals.entries()) {62    clearTimeout(timeoutId);63    resolve(false);64    approvals.delete(rid);65    await clearPendingRequest(rid).catch(() => {});66  }67  for (const { resolve, timeoutId } of unlockWaiters.values()) {68    clearTimeout(timeoutId);69    resolve(false);70  }71  unlockWaiters.clear();72}7374function isPasskeySupported(): boolean {75  if (typeof chrome.webAuthenticationProxy?.attach === "function") return true;76  // Firefox 150+ exposes navigator.credentials.create/get from the popup77  // context with extension host permissions. Cannot intercept page-side78  // calls (no equivalent of webAuthenticationProxy), but registration via79  // Peach's own popup-driven flow works.80  if (detectSharedBrowser() === "firefox") {81    const ver = firefoxVersion();82    if (Number.isFinite(ver) && ver >= 150) return true;83  }84  return false;85}8687export const detectBrowser = detectSharedBrowser;8889function getBrowserLabel(): string {90  const ua = navigator.userAgent;91  if (/Firefox\/(\d+)/.test(ua)) {92    const version = ua.match(/Firefox\/(\d+)/)?.[1];93    return version ? `Firefox ${version}` : "Firefox";94  }95  const version = ua.match(/Chrome\/(\d+)/)?.[1];96  return version ? `Chrome ${version}` : "Chromium";97}9899function pendingStorageKey(requestId: number): string {100  return `${PENDING_PREFIX}${requestId}`;101}102103function randomRequestId(): number {104  // 53-bit crypto-random integer — unbrute-forceable, unlike the old105  // Date.now()+Math.random synthetic id (~10-20 bits). Fits a JS safe106  // integer so it round-trips through String/Number for the toast path.107  // (Audit 2026-08-20 #1/#10.)108  const u = crypto.getRandomValues(new Uint32Array(2));109  return u[0] * 0x200000 + (u[1] >>> 11);110}111112function originFromRpId(rpId: string): string {113  return /^(localhost|127\.0\.0\.1|\[::1\])$/i.test(rpId)114    ? `http://${rpId}`115    : `https://${rpId}`;116}117118/**119 * The clientDataJSON sent back to the RP must contain the page's actual120 * origin — not a synthesized one. `chrome.webAuthenticationProxy` does not121 * surface the requesting origin in CreateRequest/GetRequest, so we read it122 * from the active tab and validate that its hostname is a registrable123 * suffix match for the rpId. WebAuthn requires this relationship anyway, so124 * a mismatch indicates either a stale active tab or a hostile environment;125 * we fall back to https://<rpId> in that case to avoid silently signing the126 * wrong origin.127 *128 * Without this, a passkey created on https://myaccount.google.com gets129 * clientDataJSON.origin = "https://google.com", and Google's RP rejects the130 * attestation with "Something went wrong" because the origin hash doesn't131 * match what its own JS captured at create time.132 */133async function resolvePageOrigin(rpId: string): Promise<string> {134  try {135    const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) =>136      chrome.tabs.query({ active: true, lastFocusedWindow: true }, resolve)137    );138    const url = tabs[0]?.url;139    if (url) {140      const parsed = new URL(url);141      const host = parsed.hostname.toLowerCase();142      const rp = rpId.toLowerCase();143      if (host === rp || host.endsWith(`.${rp}`)) {144        return parsed.origin;145      }146    }147  } catch {148    // fall through to rpId-derived origin149  }150  return originFromRpId(rpId);151}152153async function setBadge(text: string): Promise<void> {154  if (!chrome.action?.setBadgeText) return;155  await chrome.action.setBadgeText({ text });156  if (text) {157    await chrome.action.setBadgeBackgroundColor({ color: "#E5805C" });158  }159}160161async function clearPendingRequest(requestId: number): Promise<void> {162  if (chrome.storage.session) {163    await chrome.storage.session.remove(pendingStorageKey(requestId));164  }165  await setBadge("");166}167168async function openApprovalPopup(): Promise<void> {169  try {170    await chrome.action.openPopup();171  } catch {172    await setBadge("PK");173  }174}175176/**177 * Some ceremonies — especially conditional-UI `navigator.credentials.get`178 * calls — get cancelled by Chrome before we finish processing. Calling179 * complete*Request on a cancelled requestId rejects with "Invalid180 * requestId". That is expected, not exceptional: swallow it. Re-throwing181 * would surface an uncaught promise rejection in the SW and cascade through182 * the catch wrappers in setupPasskeyProxy.183 */184function isInvalidRequestIdError(err: unknown): boolean {185  return err instanceof Error && /invalid requestid/i.test(err.message);186}187188/**189 * Chrome throws "Missing GetResponseDetails.responseJson" when190 * completeGetRequest is called with no responseJson and no error (the191 * pass-through signal). The throw is a Chrome API quirk — the request IS192 * routed to the platform authenticator — but if we let it propagate, the193 * outer catch calls rejectGet, which sends a second completeGetRequest with194 * an error that cancels the pass-through and shows "Something went wrong" on195 * the page. Swallow it exactly as we swallow "Invalid requestId".196 */197function isMissingResponseJsonError(err: unknown): boolean {198  return err instanceof Error && /missing getresponsedetails/i.test(err.message);199}200201async function rejectCreate(202  requestId: number,203  name: string,204  message = ""205): Promise<void> {206  try {207    await chrome.webAuthenticationProxy.completeCreateRequest({208      requestId,209      error: { name, message },210    });211  } catch (err) {212    if (isInvalidRequestIdError(err)) {213      return;214    }215    throw err;216  }217}218219async function rejectGet(220  requestId: number,221  name: string,222  message = ""223): Promise<void> {224  try {225    await chrome.webAuthenticationProxy.completeGetRequest({226      requestId,227      error: { name, message },228    });229  } catch (err) {230    if (isInvalidRequestIdError(err)) {231      return;232    }233    throw err;234  }235}236237export async function getPendingPasskeyRequest(): Promise<PendingPasskeyRequest | null> {238  if (!chrome.storage.session) return null; // Firefox <132 / unsupported contexts239  const stored = (await chrome.storage.session.get(null)) as Record<string, unknown>;240  const key = Object.keys(stored).find((item) => item.startsWith(PENDING_PREFIX));241  if (!key) return null;242  const pending = stored[key];243  return pending && typeof pending === "object"244    ? (pending as PendingPasskeyRequest)245    : null;246}247248export async function resolvePendingPasskeyRequest(249  requestId: number,250  approved: boolean251): Promise<void> {252  const pending = approvals.get(requestId);253  if (!pending) {254    // Either the request expired (Chrome) or this is a Firefox-driven255    // pending where the popup performs the navigator.credentials call256    // directly. Clear both possible session keys so getPendingPasskeyRequest()257    // doesn't surface stale state on the next popup open.258    await clearPendingRequest(requestId);259    if (chrome.storage.session) {260      await chrome.storage.session.remove(FIREFOX_PENDING_KEY);261    }262    if (approved) await firefoxCeremonies.get(requestId);263    return;264  }265266  clearTimeout(pending.timeoutId);267  approvals.delete(requestId);268  await clearPendingRequest(requestId);269  pending.resolve(approved);270  if (approved) await firefoxCeremonies.get(requestId);271}272273async function promptUserApproval(request: PendingPasskeyRequest): Promise<boolean> {274  // Register before publishing the request so the popup can approve immediately.275  const approval = new Promise<boolean>((resolve) => {276    const timeoutId = setTimeout(async () => {277      approvals.delete(request.requestId);278      await clearPendingRequest(request.requestId);279      resolve(false);280    }, APPROVAL_TIMEOUT_MS);281    approvals.set(request.requestId, { resolve, timeoutId });282  });283  try {284    if (chrome.storage.session) {285      await chrome.storage.session.set({ [pendingStorageKey(request.requestId)]: request });286    }287    await openApprovalPopup();288  } catch (error) {289    await resolvePendingPasskeyRequest(request.requestId, false);290    throw error;291  }292  return approval;293}294295export async function getPasskeyProviderState(): Promise<PasskeyProviderState> {296  const settings = await vault.ensureSettingsLoaded();297  const supported = isPasskeySupported();298  const enabled = settings.passkeyProviderEnabled ?? (detectSharedBrowser() === "firefox");299  return {300    supported,301    enabled,302    attached: supported && attached,303    browserLabel: getBrowserLabel(),304    statusLabel: !supported305      ? "Interception unavailable"306      : attached307        ? "Active"308        : conflict309          ? "Another provider is active"310          : enabled311            ? "Inactive"312            : "Disabled",313    conflict,314  };315}316317async function attachPasskeyProxy(): Promise<void> {318  if (!isPasskeySupported()) {319    attached = false;320    conflict = "This browser does not expose chrome.webAuthenticationProxy.";321    return;322  }323324  // Firefox path: no chrome.webAuthenticationProxy exists. The popup-context325  // navigator.credentials creator is always ready once the user enables the326  // provider. Treat enabled = attached for state reporting purposes.327  if (detectSharedBrowser() === "firefox") {328    attached = true;329    conflict = undefined;330    return;331  }332333  if (attached) return;334335  try {336    await chrome.webAuthenticationProxy.attach();337    attached = true;338    conflict = undefined;339  } catch (error) {340    attached = false;341    conflict = error instanceof Error ? error.message : "Another provider is active.";342    console.warn("[Peach passkey] proxy attach failed", { conflict });343  }344}345346async function detachPasskeyProxy(): Promise<void> {347  if (!isPasskeySupported()) {348    attached = false;349    return;350  }351352  if (detectSharedBrowser() === "firefox") {353    attached = false;354    conflict = undefined;355    return;356  }357358  try {359    await chrome.webAuthenticationProxy.detach();360  } catch {361    // Ignore detach failures; the extension may already be detached.362  }363364  attached = false;365  conflict = undefined;366}367368export async function setPasskeyProviderEnabled(enabled: boolean): Promise<PasskeyProviderState> {369  await vault.updateSettings({ passkeyProviderEnabled: enabled });370  if (enabled) {371    await attachPasskeyProxy();372  } else {373    await detachPasskeyProxy();374  }375  return getPasskeyProviderState();376}377378async function refreshPasskeyProxy(): Promise<void> {379  const settings = await vault.ensureSettingsLoaded();380  if (settings.passkeyProviderEnabled ?? (detectSharedBrowser() === "firefox")) {381    await attachPasskeyProxy();382    return;383  }384  await detachPasskeyProxy();385}386387// Multiple accounts and credentials for one RP must remain independently usable.388function findAttachTarget(rpId: string, userName: string): VaultEntry | null {389  if (!userName) return null;390  const matches = vault.getEntries().filter((entry) => {391    if (entry.deletedAt || entry.type !== "login" || entry.passkey || entry.username !== userName) return false;392    return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {393      if (!url) return false;394      try {395        return new URL(url.includes("://") ? url : `https://${url}`).hostname === rpId;396      } catch {397        return false;398      }399    });400  });401  return matches.length === 1 ? matches[0]! : null;402}403404function hasExcludedCredential(rpId: string, excluded: Array<{ id: string; type?: string }> = []): boolean {405  return listPasskeyEntries().some((entry) => entry.passkey.rpId === rpId &&406    excluded.some((descriptor) => descriptor.type === "public-key" && descriptor.id === entry.passkey.credentialId));407}408409async function handleCreateRequest(410  request: chrome.webAuthenticationProxy.CreateRequest411): Promise<void> {412  const options = JSON.parse(request.requestDetailsJson) as PublicKeyCredentialCreationOptionsJSON;413  const rpId = options.rp.id;414  const rpName = options.rp.name ?? options.rp.id;415  const userName = options.user.name;416  const userDisplayName = options.user.displayName ?? options.user.name;417  if (!rpId) {418    console.warn("[Peach passkey] reject: missing rp.id");419    await rejectCreate(request.requestId, "NotSupportedError", "Missing RP ID");420    return;421  }422423  // Capture the page origin NOW — before any popup opens. Once the extension424  // action popup fires, it can steal lastFocusedWindow so the tabs query425  // returns no results and falls back to https://<rpId>. For sites where the426  // page origin is a subdomain of the rpId (e.g. myaccount.google.com vs427  // rpId google.com) that fallback produces the wrong origin and the RP428  // rejects the attestation with "Something went wrong".429  const pageOrigin = await resolvePageOrigin(rpId);430431  if (!PASSKEY_CREATE_E2E_BYPASS && !(await isProUser())) {432    console.warn("[Peach passkey] reject: user is not Pro");433    await rejectCreate(434      request.requestId,435      "NotAllowedError",436      "Passkey creation requires Peach Pro."437    );438    // Show the inline passkey gate so the user knows what happened and can upgrade.439    broadcastPasskeyProGate();440    return;441  }442443  if (!vault.isUnlocked()) {444    // Same wait-for-unlock pattern handleGetRequest uses: summon the inline445    // unlock prompt on the active tab so the user can unlock without leaving446    // the page, then hold the create request open until the vault unlocks or447    // the timeout fires. Immediately rejecting here means Google shows448    // "Something went wrong" the instant the user picks Peach.449    const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) =>450      chrome.tabs.query({ active: true, lastFocusedWindow: true }, resolve)451    );452    const activeTab = tabs[0];453    if (activeTab?.id) {454      chrome.tabs.sendMessage(activeTab.id, {455        type: 'SUMMON_AUTOFILL',456        source: 'passkey-unlock',457      }).catch((err) => {458        console.warn("[Peach passkey] SUMMON_AUTOFILL failed, falling back to popup", err);459        void openApprovalPopup();460      });461    } else {462      await openApprovalPopup();463    }464465    const unlocked = await new Promise<boolean>((resolve) => {466      const timeoutId = setTimeout(() => {467        unlockWaiters.delete(request.requestId);468        resolve(false);469      }, APPROVAL_TIMEOUT_MS);470      unlockWaiters.set(request.requestId, { resolve, timeoutId });471    });472473    if (!unlocked || !vault.isUnlocked()) {474      console.warn("[Peach passkey] reject: unlock timeout");475      await rejectCreate(request.requestId, "NotAllowedError", "Not unlocked in time.");476      return;477    }478    // Vault is now unlocked — fall through to approval.479  }480481  const approved = await promptUserApproval({482    requestId: request.requestId,483    type: "create",484    rpId,485    rpName,486    userName,487    userDisplayName,488  });489  if (!approved) {490    console.warn("[Peach passkey] reject: user denied");491    await rejectCreate(request.requestId, "NotAllowedError", "User denied request.");492    return;493  }494495  if (hasExcludedCredential(rpId, options.excludeCredentials)) {496    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");497    return;498  }499500  const algorithm = pickPasskeyAlgorithm(options.pubKeyCredParams ?? []);501  if (!algorithm) {502    console.warn("[Peach passkey] reject: no supported algorithm", options.pubKeyCredParams);503    await rejectCreate(request.requestId, "NotSupportedError", "No supported algorithm offered.");504    return;505  }506  const credentialIdBytes = crypto.getRandomValues(new Uint8Array(32));507  const { publicKeyCose, publicKeySpki, privateKeyJwk } = await generatePasskeyKeypair(508    algorithm509  );510  const authData = await buildAuthenticatorData({511    rpId,512    flags: 0x4d,513    signCount: 0,514    credentialId: credentialIdBytes,515    publicKeyCose,516  });517  const attestationObject = createAttestationObject(authData);518  const clientDataJSON = buildClientDataJSON(519    "webauthn.create",520    options.challenge,521    pageOrigin522  );523524  const passkey: PasskeyData = {525    rpId,526    rpName,527    credentialId: base64urlEncode(credentialIdBytes),528    publicKeyCose: base64urlEncode(publicKeyCose),529    privateKeyJwk,530    userHandle: options.user.id,531    userName,532    userDisplayName,533    algorithm,534    signCount: 0,535    aaguid: base64urlEncode(new Uint8Array(16)),536    backupEligible: true,537    backupState: false,538    browser: "chrome",539    transports: ["internal"],540    createdAt: Date.now(),541  };542543  if (hasExcludedCredential(rpId, options.excludeCredentials)) {544    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");545    return;546  }547548  // Attach only when the account identifies one credential-free login.549  const target = findAttachTarget(rpId, userName);550  if (target) {551    await vault.updateEntry(target.id, { passkey });552  } else {553    await vault.addEntry({554      type: "login",555      title: rpName,556      url: `https://${rpId}`,557      username: userName,558      passkey,559    });560  }561  // Consolidate only account matches whose data can be retained.562  await vault.consolidatePasskeyEntries();563564  try {565    await chrome.webAuthenticationProxy.completeCreateRequest({566      requestId: request.requestId,567      responseJson: JSON.stringify({568        id: passkey.credentialId,569        rawId: passkey.credentialId,570        type: "public-key",571        response: {572          clientDataJSON: base64urlEncode(clientDataJSON),573          authenticatorData: base64urlEncode(authData),574          attestationObject: base64urlEncode(attestationObject),575          transports: ["internal"],576          publicKey: base64urlEncode(publicKeySpki),577          publicKeyAlgorithm: algorithm,578        },579        authenticatorAttachment: "platform",580        clientExtensionResults: {},581      }),582    });583  } catch (err) {584    if (isInvalidRequestIdError(err)) {585      return;586    }587    throw err;588  }589}590591function broadcastPasskeyProGate(): void {592  chrome.tabs.query({}, (tabs) => {593    for (const tab of tabs) {594      if (tab.id !== undefined) {595        chrome.tabs.sendMessage(tab.id, { type: "PASSKEY_PRO_GATE" }).catch(() => {});596      }597    }598  });599}600601async function promptViaToast(request: PendingPasskeyRequest): Promise<boolean> {602  if (chrome.storage.session) {603    await chrome.storage.session.set({ [pendingStorageKey(request.requestId)]: request });604  }605606  const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) => {607    chrome.tabs.query({ active: true, currentWindow: true }, resolve);608  });609  const tab = tabs[0];610611  if (tab?.id) {612    chrome.tabs.sendMessage(tab.id, {613      type: 'SHOW_PASSKEY_TOAST',614      payload: {615        toastToken: crypto.randomUUID(),616        site: request.rpId,617        displayName: request.userDisplayName ?? request.userName,618        username: request.userName,619        requestId: String(request.requestId),620      },621    }).catch(() => {});622  } else {623    await openApprovalPopup();624  }625626  return new Promise<boolean>((resolve) => {627    const timeoutId = setTimeout(async () => {628      approvals.delete(request.requestId);629      await clearPendingRequest(request.requestId);630      resolve(false);631    }, APPROVAL_TIMEOUT_MS);632633    approvals.set(request.requestId, { resolve, timeoutId });634  });635}636637async function handleGetRequest(638  request: chrome.webAuthenticationProxy.GetRequest639): Promise<void> {640  const options = JSON.parse(request.requestDetailsJson) as PublicKeyCredentialRequestOptionsJSON;641  if (!vault.isUnlocked()) {642    // Summon the inline unlock prompt on the active tab so the user can unlock643    // without leaving the page. Fall back to the popup if the content script644    // is unavailable (e.g. restricted URL, script not yet injected).645    const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) =>646      chrome.tabs.query({ active: true, currentWindow: true }, resolve)647    );648    const activeTab = tabs[0];649    if (activeTab?.id) {650      chrome.tabs.sendMessage(activeTab.id, {651        type: 'SUMMON_AUTOFILL',652        source: 'passkey-unlock',653      }).catch(() => { void openApprovalPopup(); });654    } else {655      await openApprovalPopup();656    }657658    // Hold the request open until the vault unlocks or the timeout fires.659    const unlocked = await new Promise<boolean>((resolve) => {660      const timeoutId = setTimeout(() => {661        unlockWaiters.delete(request.requestId);662        resolve(false);663      }, APPROVAL_TIMEOUT_MS);664      unlockWaiters.set(request.requestId, { resolve, timeoutId });665    });666667    if (!unlocked || !vault.isUnlocked()) {668      await rejectGet(request.requestId, "NotAllowedError", "Not unlocked in time.");669      return;670    }671    // Vault is now unlocked — fall through to authenticate.672  }673674  if (!PASSKEY_CREATE_E2E_BYPASS && !(await isProUser())) {675    await rejectGet(request.requestId, "NotAllowedError", "Passkey use requires Peach Pro.");676    broadcastPasskeyProGate();677    return;678  }679680  const passkeyBearing = vault.getEntries().filter((entry): entry is VaultEntry & { passkey: PasskeyData } =>681    entry.passkey !== undefined && !entry.deletedAt682  );683  const allowedCredentialIds = (options.allowCredentials ?? []).map((descriptor) => descriptor.id);684685  const match = passkeyBearing.find((entry) => {686    // PB-26-015: a credential-ID match must still belong to the requesting687    // RP — the assertion later signs with the stored rpId, so a foreign-RP688    // request must never select a credential from a different rpId.689    if (options.rpId && entry.passkey.rpId !== options.rpId) return false;690    if (allowedCredentialIds.length > 0) {691      return allowedCredentialIds.includes(entry.passkey.credentialId);692    }693    if (!options.rpId) return false;694    return entry.passkey.rpId === options.rpId;695  });696697  if (!match) {698    // No Peach passkey for this RP — pass through to the platform authenticator.699    // completeGetRequest with no error and no responseJson is the webAuthenticationProxy700    // signal for "I'm not handling this"; Chrome routes the request to the next701    // authenticator in the chain (the built-in browser passkey manager etc.).702    // Rejecting with NotAllowedError would propagate as an error to the page and703    // break RPs (e.g. Google) that issue a GET as part of their create-passkey flow.704    try {705      await chrome.webAuthenticationProxy.completeGetRequest({ requestId: request.requestId });706    } catch (err) {707      if (isInvalidRequestIdError(err)) return;708      if (isMissingResponseJsonError(err)) return;709      throw err;710    }711    return;712  }713714  const credential = match.passkey;715  // Chrome's webAuthenticationProxy path requires Peach-held private key material.716  // Passkeys created on Firefox have no privateKeyJwk — pass through so Chrome717  // can route to a capable authenticator instead of surfacing an error to the page.718  if (!credential.privateKeyJwk) {719    try {720      await chrome.webAuthenticationProxy.completeGetRequest({ requestId: request.requestId });721    } catch (err) {722      if (isInvalidRequestIdError(err)) return;723      if (isMissingResponseJsonError(err)) return;724      throw err;725    }726    return;727  }728729  const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) => {730    chrome.tabs.query({ active: true, currentWindow: true }, resolve);731  });732  const approvalBinding = {733    tabId: tabs[0]?.id,734    origin: await resolvePageOrigin(credential.rpId),735  };736  const approved = await promptViaToast({737    requestId: request.requestId,738    type: "get",739    rpId: credential.rpId,740    rpName: credential.rpName,741    userName: credential.userName,742    userDisplayName: credential.userDisplayName,743    ...approvalBinding,744  });745  if (!approved) {746    await rejectGet(request.requestId, "NotAllowedError", "User denied request.");747    return;748  }749750  const nextSignCount = credential.signCount + 1;751  // Chrome passkeys have always been registered by Peach with BE=1 (0x4d),752  // but versions before v5.0.87 incorrectly persisted backupEligible=false.753  // WebAuthn requires BE to match registration, so repair that legacy metadata754  // while constructing the assertion GitHub and other strict RPs verify.755  const backupEligible = credential.browser === "chrome" ? true : credential.backupEligible;756  const flags = 0x05 | (backupEligible ? 0x08 : 0) | (credential.backupState ? 0x10 : 0);757  const authData = await buildAuthenticatorData({758    rpId: credential.rpId,759    flags,760    signCount: nextSignCount,761  });762  const clientDataJSON = buildClientDataJSON(763    "webauthn.get",764    options.challenge,765    await resolvePageOrigin(credential.rpId)766  );767  const clientDataHash = new Uint8Array(768    await crypto.subtle.digest("SHA-256", new Uint8Array(clientDataJSON))769  );770  const signature = await signPasskeyAssertion(771    credential.privateKeyJwk,772    credential.algorithm,773    authData,774    clientDataHash775  );776777  await vault.updateEntry(match.id, {778    passkey: {779      ...credential,780      backupEligible,781      signCount: nextSignCount,782      lastUsedAt: Date.now(),783    },784  });785786  const responseJson = JSON.stringify({787    id: credential.credentialId,788    rawId: credential.credentialId,789    type: "public-key",790    response: {791      clientDataJSON: base64urlEncode(clientDataJSON),792      authenticatorData: base64urlEncode(authData),793      signature: base64urlEncode(signature),794      userHandle: credential.userHandle,795    },796    authenticatorAttachment: "platform",797    clientExtensionResults: {},798  });799800  try {801    await chrome.webAuthenticationProxy.completeGetRequest({802      requestId: request.requestId,803      responseJson,804    });805  } catch (err) {806    if (isInvalidRequestIdError(err)) {807      return;808    }809    throw err;810  }811}812813// ── Firefox path ────────────────────────────────────────────────────────814//815// Firefox 150+ permits extensions to call navigator.credentials.create/get816// from the popup context with their host-permitted RP IDs. Peach uses that817// surface to register passkeys on behalf of the user. The page's own818// navigator.credentials call is observed via the MAIN-world detector819// (src/content/passkeys-firefox.ts) but never blocked or replaced; Peach's820// flow is parallel and explicit (the user must engage with Peach's button).821822const FIREFOX_PENDING_KEY = "passkey_pending_firefox";823const FIREFOX_DECLINE_PREFIX = "peach_passkey_offer_declined:";824const FIREFOX_DECLINE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days825826export async function initiateFirefoxPasskeyCreate(args: {827  rpId: string;828  rpName: string;829  userName: string;830  userDisplayName?: string;831}, callerOrigin?: string): Promise<{ ok: boolean; error?: string }> {832  // The rpId must belong to the calling page's registrable domain; without833  // this, a page could initiate a ceremony for a foreign site and the834  // approval popup would display an attacker-chosen rpId. Origin is the835  // browser-attested sender origin from messages.ts, never page payload.836  // (Codex Security 2026-08-04, passkey-ceremony-approval sibling.)837  if (!callerOrigin || !isValidRpId(args.rpId, callerOrigin)) {838    return { ok: false, error: "rpid_origin_mismatch" };839  }840  if (!(await isProUser())) {841    broadcastPasskeyProGate();842    return { ok: false, error: "passkey creation requires Peach Pro" };843  }844  if (!vault.isUnlocked()) {845    await openApprovalPopup();846    return { ok: false, error: "vault_locked" };847  }848  if (!chrome.storage.session) {849    return { ok: false, error: "session storage unavailable" };850  }851852  const requestId = randomRequestId();853  const challenge = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)));854  const userHandle = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)));855856  const pending: PendingPasskeyRequest = {857    requestId,858    type: "create",859    rpId: args.rpId,860    rpName: args.rpName,861    userName: args.userName,862    userDisplayName: args.userDisplayName,863    browser: "firefox",864    challenge,865    userHandle,866  };867868  await chrome.storage.session.set({ [FIREFOX_PENDING_KEY]: pending });869  await openApprovalPopup();870  return { ok: true };871}872873export async function completeFirefoxPasskeyCreate(payload: {874  requestId: number;875  rpId: string;876  rpName: string;877  userName: string;878  userDisplayName?: string;879  userHandle: string;880  credentialId: string;881  publicKeyCose: string;882  algorithm: -7 | -8;883  aaguid?: string;884  transports?: string[];885  backupEligible?: boolean;886  backupState?: boolean;887}): Promise<{ ok: boolean; error?: string }> {888  if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };889890  // Bind completion to the pending ceremony: requestId, rpId, challenge, and891  // userHandle are minted by the background at INITIATE time and only ever892  // leave extension context through the approval popup, so a page (or anything893  // replaying relayed messages) cannot synthesize a matching completion for an894  // rpId it does not own. (Codex Security 2026-08-04 MEDIUM,895  // broken-access-control.passkey-ceremony-approval.)896  const pending = chrome.storage.session897    ? ((await chrome.storage.session.get(FIREFOX_PENDING_KEY))[FIREFOX_PENDING_KEY] as898        | PendingPasskeyRequest899        | undefined)900    : undefined;901  if (902    !pending ||903    pending.requestId !== payload.requestId ||904    pending.rpId !== payload.rpId ||905    pending.userHandle !== payload.userHandle906  ) {907    return { ok: false, error: "no_pending_request" };908  }909910  if (hasExcludedCredential(payload.rpId, [{ type: "public-key", id: payload.credentialId }])) {911    return { ok: false, error: "credential_exists" };912  }913914  const passkey: PasskeyData = {915    rpId: payload.rpId,916    rpName: payload.rpName,917    credentialId: payload.credentialId,918    publicKeyCose: payload.publicKeyCose,919    userHandle: payload.userHandle,920    userName: payload.userName,921    userDisplayName: payload.userDisplayName ?? payload.userName,922    algorithm: payload.algorithm,923    signCount: 0,924    aaguid: payload.aaguid ?? base64urlEncode(new Uint8Array(16)),925    backupEligible: payload.backupEligible ?? false,926    backupState: payload.backupState ?? false,927    browser: "firefox",928    transports: payload.transports ?? ["internal"],929    createdAt: Date.now(),930  };931932  // Native Firefox credentials follow the same account-specific attachment rule.933  const target = findAttachTarget(payload.rpId, payload.userName);934  if (target) {935    await vault.updateEntry(target.id, { passkey });936  } else {937    await vault.addEntry({938      type: "login",939      title: payload.rpName || payload.rpId,940      url: `https://${payload.rpId}`,941      username: payload.userName,942      passkey,943    });944  }945  await vault.consolidatePasskeyEntries();946947  if (chrome.storage.session) {948    await chrome.storage.session.remove(FIREFOX_PENDING_KEY);949  }950  return { ok: true };951}952953const MAX_DECLINE_DOMAIN_LENGTH = 253;954955function normaliseDeclineDomain(domain: string): string | null {956  if (!domain || domain.length > MAX_DECLINE_DOMAIN_LENGTH) return null;957  try {958    const url = new URL(`https://${domain}`);959    return isValidRpId(url.hostname, url.origin) ? url.hostname : null;960  } catch {961    return null;962  }963}964965function declineKey(domain: string): string {966  return `${FIREFOX_DECLINE_PREFIX}${domain}`;967}968969export async function recordPasskeyOfferDecline(domain: string): Promise<void> {970  const validDomain = normaliseDeclineDomain(domain);971  if (!validDomain) return;972  await chrome.storage.local.set({ [declineKey(validDomain)]: Date.now() });973}974975export async function isPasskeyOfferDeclined(domain: string): Promise<boolean> {976  const validDomain = normaliseDeclineDomain(domain);977  if (!validDomain) return false;978  const key = declineKey(validDomain);979980  const stored = (await chrome.storage.local.get(key)) as Record<string, number | undefined>;981  const at = stored[key];982  if (typeof at !== "number") return false;983  if (Date.now() - at > FIREFOX_DECLINE_TTL_MS) {984    await chrome.storage.local.remove(key);985    return false;986  }987  return true;988}989990// ── Firefox content-script proxy path (v2.12.0) ────────────────────────991//992// The MAIN-world monkey-patch in src/content/passkeys-firefox.ts replaces993// navigator.credentials.create / .get on every Firefox page. It builds a994// clientDataJSON whose `origin` is the PAGE's origin (not moz-extension://),995// then hands every ceremony to the background via PASSKEY_HAS_CREDENTIALS,996// PASSKEY_CREATE, and PASSKEY_GET. The handlers below own those messages.997//998// Removal: when Firefox ships chrome.webAuthenticationProxy, the runtime flag999// FIREFOX_USE_CONTENT_SCRIPT_PROXY in src/shared/passkey-flags.ts evaluates1000// to false and these handlers short-circuit. The full removal checklist is1001// in that file — the deletion is purely subtractive.10021003interface FirefoxAllowCredential {1004  id: string;1005  type?: string;1006}10071008interface FirefoxPubKeyCredParam {1009  type?: string;1010  alg: number;1011}10121013export interface FirefoxPasskeyHasCredentialsPayload {1014  rpId: string;1015  allowCredentials: FirefoxAllowCredential[];1016}10171018export interface FirefoxPasskeyCreatePayload {1019  rpId: string;1020  rpName?: string;1021  userId: string;1022  userName: string;1023  userDisplayName?: string;1024  challenge: string;1025  clientDataJSON: number[];1026  origin: string;1027  pubKeyCredParams?: FirefoxPubKeyCredParam[];1028  excludeCredentials?: FirefoxAllowCredential[];1029  authenticatorSelection?: Record<string, unknown>;1030  timeout?: number;1031  attestation?: string;1032}10331034export interface FirefoxPasskeyGetPayload {1035  rpId: string;1036  challenge: string;1037  clientDataJSON: number[];1038  origin: string;1039  allowCredentials: FirefoxAllowCredential[];1040  userVerification?: string;1041}10421043interface FirefoxCreateCredentialResponse {1044  type: "create";1045  id: string;1046  clientDataJSON: number[];1047  attestationObject: string;1048  authenticatorData: string;1049  publicKey: string;1050  algorithm: -7 | -8;1051}10521053interface FirefoxGetCredentialResponse {1054  type: "get";1055  id: string;1056  clientDataJSON: number[];1057  authenticatorData: string;1058  signature: string;1059  userHandle: string;1060}10611062type FirefoxPasskeyResult<T> =1063  | { ok: true; credential: T }1064  | { ok: false; error: "pro_required" | "user_cancelled" | "no_credentials" | "vault_locked" | "not_applicable" | "internal_error" | "credential_excluded"; message?: string };10651066function listPasskeyEntries(): Array<VaultEntry & { passkey: PasskeyData }> {1067  return vault.getEntries().filter(1068    (entry): entry is VaultEntry & { passkey: PasskeyData } =>1069      entry.passkey !== undefined && !entry.deletedAt1070  );1071}10721073/** Decode the `origin` field out of a WebAuthn clientDataJSON byte array. */1074function clientDataJsonOrigin(bytes: number[] | undefined): string | null {1075  if (!Array.isArray(bytes)) return null;1076  try {1077    const obj = JSON.parse(new TextDecoder().decode(new Uint8Array(bytes))) as { origin?: unknown };1078    return typeof obj.origin === "string" ? obj.origin : null;1079  } catch {1080    return null;1081  }1082}10831084/**1085 * Enforce the WebAuthn rpId<->origin relationship on the Firefox proxy path,1086 * where Peach is the authenticator. The ONLY trustworthy origin is the one the1087 * browser attested for the calling page (`callerOrigin`, derived from the1088 * message sender in messages.ts) — NEVER `payload.origin`, which the page1089 * controls and can set to match any rpId (SEV-1-A / audit CRITICAL). Also1090 * refuse to sign a clientDataJSON whose embedded origin disagrees with the1091 * attested origin, so a forged ceremony can't smuggle a foreign origin into1092 * the signed bytes the RP verifies.1093 */1094function assertOriginOwnsRpId(1095  rpId: string,1096  callerOrigin: string | undefined,1097  clientDataJSON?: number[],1098): void {1099  if (!callerOrigin || !isValidRpId(rpId, callerOrigin)) {1100    throw new DOMException(1101      `SecurityError: relying party ID "${rpId}" is not a registrable domain ` +1102        `suffix of the calling origin "${callerOrigin ?? "(unknown)"}".`,1103      "SecurityError",1104    );1105  }1106  const cdjOrigin = clientDataJsonOrigin(clientDataJSON);1107  if (cdjOrigin !== null && cdjOrigin !== callerOrigin) {1108    throw new DOMException(1109      `SecurityError: clientDataJSON origin "${cdjOrigin}" does not match the ` +1110        `attested calling origin "${callerOrigin}".`,1111      "SecurityError",1112    );1113  }1114}11151116export async function handlePasskeyHasCredentials(1117  payload: FirefoxPasskeyHasCredentialsPayload,1118  callerOrigin?: string,1119): Promise<{ ok: true; hasCredentials: boolean } | { ok: false; error: string }> {1120  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1121    return { ok: false, error: "not_applicable" };1122  }1123  // Scope the existence check to the caller's own origin so an arbitrary page1124  // cannot enumerate which sites the user holds passkeys for (audit MEDIUM).1125  // A false answer is indistinguishable from "no credential" to the page.1126  if (!callerOrigin || !isValidRpId(payload.rpId, callerOrigin)) {1127    return { ok: true, hasCredentials: false };1128  }1129  if (!vault.isUnlocked()) {1130    // A locked vault cannot answer whether a credential exists until unlock.1131    return { ok: false, error: "vault_locked" };1132  }1133  const passkeys = listPasskeyEntries().filter(1134    (entry) => entry.passkey.rpId === payload.rpId1135  );1136  if (passkeys.length === 0) return { ok: true, hasCredentials: false };11371138  const allow = payload.allowCredentials ?? [];1139  if (allow.length === 0) return { ok: true, hasCredentials: true };11401141  const hasMatch = passkeys.some((entry) =>1142    allow.some((ac) => ac.id === entry.passkey.credentialId)1143  );1144  return { ok: true, hasCredentials: hasMatch };1145}11461147/**1148 * Approval prompt for the Firefox proxy ceremonies. Reuses the existing1149 * pending-passkey channel (badge + popup + 60s timeout) — the same approval1150 * UI Chrome ceremonies use, so the popup's State 11/12 view doesn't need1151 * any new code path. The page-side proxy never sees the request id; the1152 * background mints one and discards it after resolution.1153 */1154async function requestFirefoxApproval<T>(args: {1155  type: "create" | "get";1156  rpId: string;1157  rpName?: string;1158  userName: string;1159  userDisplayName?: string;1160}, operation: () => Promise<FirefoxPasskeyResult<T>>): Promise<FirefoxPasskeyResult<T>> {1161  const requestId = randomRequestId();1162  let finish!: () => void;1163  firefoxCeremonies.set(requestId, new Promise<void>((resolve) => { finish = resolve; }));1164  try {1165    const approved = await promptUserApproval({1166      requestId,1167      type: args.type,1168      rpId: args.rpId,1169      rpName: args.rpName ?? args.rpId,1170      userName: args.userName,1171      userDisplayName: args.userDisplayName,1172    });1173    if (!approved) return { ok: false, error: "user_cancelled" };1174    return await operation();1175  } finally {1176    finish();1177    firefoxCeremonies.delete(requestId);1178  }1179}11801181export async function handleFirefoxPasskeyCreate(1182  payload: FirefoxPasskeyCreatePayload,1183  callerOrigin?: string,1184): Promise<FirefoxPasskeyResult<FirefoxCreateCredentialResponse>> {1185  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1186    return { ok: false, error: "not_applicable" };1187  }1188  // WebAuthn §7.1 step 6 — the requested rpId must be owned by the page's1189  // browser-ATTESTED origin (threaded in as callerOrigin from the message1190  // sender), NOT the page-supplied payload.origin which an attacker controls.1191  // On the Firefox proxy path Peach is the authenticator and must enforce this1192  // before minting anything (audit CRITICAL — origin spoofing).1193  assertOriginOwnsRpId(payload.rpId, callerOrigin, payload.clientDataJSON);1194  if (!(await isProUser())) {1195    broadcastPasskeyProGate();1196    return { ok: false, error: "pro_required" };1197  }1198  if (!vault.isUnlocked()) {1199    await openApprovalPopup();1200    return { ok: false, error: "vault_locked" };1201  }12021203  const algorithm = pickPasskeyAlgorithm(payload.pubKeyCredParams ?? []);1204  if (!algorithm) {1205    return { ok: false, error: "internal_error", message: "No supported algorithm offered" };1206  }12071208  return requestFirefoxApproval<FirefoxCreateCredentialResponse>({1209    type: "create",1210    rpId: payload.rpId,1211    rpName: payload.rpName,1212    userName: payload.userName,1213    userDisplayName: payload.userDisplayName,1214  }, async () => {12151216    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1217      return { ok: false, error: "credential_excluded" };1218    }12191220    const { bytes: credentialIdBytes, base64url: credentialId } = generateCredentialId();1221    const { publicKeyCose, publicKeySpki, privateKeyJwk } = await generatePasskeyKeypair(algorithm);12221223    // 0x4d = UP|UV|BE|AT. Peach passkeys are synced, so BE is true on both1224    // registration paths and on later assertions.1225    const authenticatorData = await buildAuthenticatorData({1226      rpId: payload.rpId,1227      flags: 0x4d,1228      signCount: 0,1229      credentialId: credentialIdBytes,1230      publicKeyCose,1231    });1232    const attestationObject = createAttestationObject(authenticatorData);12331234    const passkey: PasskeyData = {1235      rpId: payload.rpId,1236      rpName: payload.rpName ?? payload.rpId,1237      credentialId,1238      publicKeyCose: base64urlEncode(publicKeyCose),1239      privateKeyJwk,1240      userHandle: payload.userId,1241      userName: payload.userName,1242      userDisplayName: payload.userDisplayName ?? payload.userName,1243      algorithm,1244      signCount: 0,1245      aaguid: base64urlEncode(new Uint8Array(16)),1246      backupEligible: true,1247      backupState: false,1248      browser: "firefox",1249      transports: ["internal"],1250      createdAt: Date.now(),1251    };12521253    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1254      return { ok: false, error: "credential_excluded" };1255    }12561257    const target = findAttachTarget(payload.rpId, payload.userName);1258    if (target) {1259      await vault.updateEntry(target.id, { passkey });1260    } else {1261      await vault.addEntry({1262        type: "login",1263        title: payload.rpName || payload.rpId,1264        url: `https://${payload.rpId}`,1265        username: payload.userName,1266        passkey,1267      });1268    }1269    await vault.consolidatePasskeyEntries();12701271    return {1272      ok: true,1273      credential: {1274        type: "create",1275        id: credentialId,1276        // The content script already encoded clientDataJSON with the page1277        // origin; round-trip the exact bytes back so the RP sees the same1278        // hash it computes locally.1279        clientDataJSON: payload.clientDataJSON,1280        attestationObject: base64urlEncode(attestationObject),1281        authenticatorData: base64urlEncode(authenticatorData),1282        publicKey: base64urlEncode(publicKeySpki),1283        algorithm,1284      },1285    };1286  });1287}12881289export async function handleFirefoxPasskeyGet(1290  payload: FirefoxPasskeyGetPayload,1291  callerOrigin?: string,1292): Promise<FirefoxPasskeyResult<FirefoxGetCredentialResponse>> {1293  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1294    return { ok: false, error: "not_applicable" };1295  }1296  // WebAuthn §7.2 step 8 — the rpId must be owned by the page's browser-attested1297  // origin (callerOrigin from the message sender), NOT the page-supplied1298  // payload.origin. Both rpId and payload.origin are attacker-controlled, so1299  // validating one against the other is no protection; a cross-origin page must1300  // not be able to coax Peach into signing an assertion scoped to another site1301  // (audit CRITICAL — assertion forgery).1302  assertOriginOwnsRpId(payload.rpId, callerOrigin, payload.clientDataJSON);1303  if (!(await isProUser())) {1304    broadcastPasskeyProGate();1305    return { ok: false, error: "pro_required" };1306  }1307  if (!vault.isUnlocked()) {1308    const requestId = randomRequestId();1309    // Register before opening the popup so an immediate unlock cannot be missed.1310    const unlocked = new Promise<boolean>((resolve) => {1311      const timeoutId = setTimeout(() => {1312        unlockWaiters.delete(requestId);1313        resolve(false);1314      }, APPROVAL_TIMEOUT_MS);1315      unlockWaiters.set(requestId, { resolve, timeoutId });1316    });1317    await openApprovalPopup();1318    if (!(await unlocked) || !vault.isUnlocked()) {1319      return { ok: false, error: "user_cancelled" };1320    }1321  }13221323  const allow = payload.allowCredentials ?? [];1324  const candidates = listPasskeyEntries().filter((entry) => {1325    if (entry.passkey.rpId !== payload.rpId) return false;1326    if (allow.length === 0) return true;1327    return allow.some((ac) => ac.id === entry.passkey.credentialId);1328  });13291330  if (candidates.length === 0) return { ok: false, error: "no_credentials" };13311332  // Most-recently-used wins when several credentials match. A future1333  // multi-account selector goes here; for now this matches the Chrome path's1334  // behavior for the common one-passkey-per-rp case.1335  candidates.sort((a, b) => (b.passkey.lastUsedAt ?? 0) - (a.passkey.lastUsedAt ?? 0));1336  const match = candidates[0]!;1337  const credential = match.passkey;13381339  const privateKeyJwk = credential.privateKeyJwk;1340  if (!privateKeyJwk) {1341    // Pre-v2.12.0 Firefox passkeys delegated to the platform authenticator1342    // — no Peach-held private key to sign with. The MAIN-world proxy treats1343    // no_credentials as a fall-through, which routes to the platform UI.1344    return { ok: false, error: "no_credentials" };1345  }13461347  return requestFirefoxApproval<FirefoxGetCredentialResponse>({1348    type: "get",1349    rpId: credential.rpId,1350    rpName: credential.rpName,1351    userName: credential.userName,1352    userDisplayName: credential.userDisplayName,1353  }, async () => {13541355    const nextSignCount = credential.signCount + 1;1356    // Legacy Chrome registrations used BE=1 even when the stored flag was false.1357    // Legacy Firefox registrations used BE=0, so retain their recorded value.1358    const backupEligible = credential.browser === "chrome" ? true : credential.backupEligible;1359    const flags = 0x05 | (backupEligible ? 0x08 : 0) | (credential.backupState ? 0x10 : 0);1360    const authenticatorData = await buildAuthenticatorData({1361      rpId: credential.rpId,1362      flags,1363      signCount: nextSignCount,1364    });13651366    // The content script supplied clientDataJSON bytes built with the page1367    // origin. SHA-256 those bytes verbatim — never re-serialize, or the hash1368    // diverges from what the RP computes.1369    const clientDataBytes = new Uint8Array(payload.clientDataJSON);1370    const clientDataHash = new Uint8Array(1371      await crypto.subtle.digest("SHA-256", clientDataBytes)1372    );1373    const signature = await signPasskeyAssertion(1374      privateKeyJwk,1375      credential.algorithm,1376      authenticatorData,1377      clientDataHash1378    );13791380    await vault.updateEntry(match.id, {1381      passkey: {1382        ...credential,1383        backupEligible,1384        signCount: nextSignCount,1385        lastUsedAt: Date.now(),1386      },1387    });13881389    return {1390      ok: true,1391      credential: {1392        type: "get",1393        id: credential.credentialId,1394        clientDataJSON: payload.clientDataJSON,1395        authenticatorData: base64urlEncode(authenticatorData),1396        signature: base64urlEncode(signature),1397        userHandle: credential.userHandle,1398      },1399    };1400  });1401}14021403export async function setupPasskeyProxy(): Promise<void> {1404  if (!isPasskeySupported()) {1405    return;1406  }14071408  // Firefox doesn't expose chrome.webAuthenticationProxy listeners. The1409  // popup-context credential creator is the entry point; nothing to wire here.1410  if (detectSharedBrowser() === "firefox") {1411    await refreshPasskeyProxy();1412    return;1413  }14141415  if (!listenersRegistered) {1416    chrome.webAuthenticationProxy.onIsUvpaaRequest.addListener((requestInfo) => {1417      // Peach is a user-verifying platform authenticator whenever the proxy1418      // is attached. The lock state is irrelevant here — the create/get1419      // handlers prompt for unlock when needed. Returning false while locked1420      // makes Google (and any RP that checks isUvpaa as a precondition) show1421      // "A passkey can't be created on this device" before the user even1422      // gets a chance to start the ceremony.1423      void chrome.webAuthenticationProxy.completeIsUvpaaRequest({1424        requestId: requestInfo.requestId,1425        isUvpaa: true,1426      });1427    });1428    chrome.webAuthenticationProxy.onCreateRequest.addListener((requestInfo) => {1429      void handleCreateRequest(requestInfo).catch(async (error) => {1430        // "Invalid requestId" means Chrome already cancelled — handlers will1431        // short-circuit, but if it propagates out from a still-in-flight branch,1432        // don't double-complete.1433        if (isInvalidRequestIdError(error)) {1434          return;1435        }1436        console.error("Peach passkey create failed", error);1437        await rejectCreate(1438          requestInfo.requestId,1439          "UnknownError",1440          error instanceof Error ? error.message : "Passkey creation failed."1441        );1442      });1443    });1444    chrome.webAuthenticationProxy.onGetRequest.addListener((requestInfo) => {1445      void handleGetRequest(requestInfo).catch(async (error) => {1446        if (isInvalidRequestIdError(error)) {1447          return;1448        }1449        console.error("Peach passkey get failed", error);1450        await rejectGet(1451          requestInfo.requestId,1452          "UnknownError",1453          error instanceof Error ? error.message : "Passkey authentication failed."1454        );1455      });1456    });1457    chrome.webAuthenticationProxy.onRequestCanceled.addListener((requestId) => {1458      // Release any unlock waiter parked for this request.1459      const waiter = unlockWaiters.get(requestId);1460      if (waiter) {1461        clearTimeout(waiter.timeoutId);1462        waiter.resolve(false);1463        unlockWaiters.delete(requestId);1464      }1465      void resolvePendingPasskeyRequest(requestId, false);1466    });1467    listenersRegistered = true;1468  }14691470  await refreshPasskeyProxy();1471}