passkey.ts

50.1 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 chromeRequestContext(extensions: unknown): { origin: string; crossOrigin: boolean } | null {113  if (!extensions || typeof extensions !== "object" || !("remoteDesktopClientOverride" in extensions)) return null;114  const context = extensions.remoteDesktopClientOverride;115  if (!context || typeof context !== "object" || !("origin" in context) || !("sameOriginWithAncestors" in context)) return null;116  if (typeof context.origin !== "string" || typeof context.sameOriginWithAncestors !== "boolean") return null;117  try {118    const origin = new URL(context.origin);119    if ((origin.protocol !== "https:" && origin.protocol !== "http:") || origin.origin !== context.origin) return null;120    // Chromium authorizes secure origins and RP IDs, including related origins,121    // before dispatching the proxy request, then injects this trusted context.122    return { origin: context.origin, crossOrigin: !context.sameOriginWithAncestors };123  } catch {124    return null;125  }126}127128async function setBadge(text: string): Promise<void> {129  if (!chrome.action?.setBadgeText) return;130  await chrome.action.setBadgeText({ text });131  if (text) {132    await chrome.action.setBadgeBackgroundColor({ color: "#E5805C" });133  }134}135136async function clearPendingRequest(requestId: number): Promise<void> {137  if (chrome.storage.session) {138    await chrome.storage.session.remove(pendingStorageKey(requestId));139  }140  await setBadge("");141}142143async function openApprovalPopup(): Promise<void> {144  try {145    await chrome.action.openPopup();146  } catch {147    await setBadge("PK");148  }149}150151/**152 * Some ceremonies — especially conditional-UI `navigator.credentials.get`153 * calls — get cancelled by Chrome before we finish processing. Calling154 * complete*Request on a cancelled requestId rejects with "Invalid155 * requestId". That is expected, not exceptional: swallow it. Re-throwing156 * would surface an uncaught promise rejection in the SW and cascade through157 * the catch wrappers in setupPasskeyProxy.158 */159function isInvalidRequestIdError(err: unknown): boolean {160  return err instanceof Error && /invalid requestid/i.test(err.message);161}162163/**164 * Chrome throws "Missing GetResponseDetails.responseJson" when165 * completeGetRequest is called with no responseJson and no error (the166 * pass-through signal). The throw is a Chrome API quirk — the request IS167 * routed to the platform authenticator — but if we let it propagate, the168 * outer catch calls rejectGet, which sends a second completeGetRequest with169 * an error that cancels the pass-through and shows "Something went wrong" on170 * the page. Swallow it exactly as we swallow "Invalid requestId".171 */172function isMissingResponseJsonError(err: unknown): boolean {173  return err instanceof Error && /missing getresponsedetails/i.test(err.message);174}175176async function rejectCreate(177  requestId: number,178  name: string,179  message = ""180): Promise<void> {181  try {182    await chrome.webAuthenticationProxy.completeCreateRequest({183      requestId,184      error: { name, message },185    });186  } catch (err) {187    if (isInvalidRequestIdError(err)) {188      return;189    }190    throw err;191  }192}193194async function rejectGet(195  requestId: number,196  name: string,197  message = ""198): Promise<void> {199  try {200    await chrome.webAuthenticationProxy.completeGetRequest({201      requestId,202      error: { name, message },203    });204  } catch (err) {205    if (isInvalidRequestIdError(err)) {206      return;207    }208    throw err;209  }210}211212export async function getPendingPasskeyRequest(): Promise<PendingPasskeyRequest | null> {213  if (!chrome.storage.session) return null; // Firefox <132 / unsupported contexts214  const stored = (await chrome.storage.session.get(null)) as Record<string, unknown>;215  const key = Object.keys(stored).find((item) => item.startsWith(PENDING_PREFIX));216  if (!key) return null;217  const pending = stored[key];218  return pending && typeof pending === "object"219    ? (pending as PendingPasskeyRequest)220    : null;221}222223export async function resolvePendingPasskeyRequest(224  requestId: number,225  approved: boolean226): Promise<void> {227  const pending = approvals.get(requestId);228  if (!pending) {229    // Either the request expired (Chrome) or this is a Firefox-driven230    // pending where the popup performs the navigator.credentials call231    // directly. Clear both possible session keys so getPendingPasskeyRequest()232    // doesn't surface stale state on the next popup open.233    await clearPendingRequest(requestId);234    if (chrome.storage.session) {235      await chrome.storage.session.remove(FIREFOX_PENDING_KEY);236    }237    if (approved) await firefoxCeremonies.get(requestId);238    return;239  }240241  clearTimeout(pending.timeoutId);242  approvals.delete(requestId);243  await clearPendingRequest(requestId);244  pending.resolve(approved);245  if (approved) await firefoxCeremonies.get(requestId);246}247248async function promptUserApproval(request: PendingPasskeyRequest): Promise<boolean> {249  // Register before publishing the request so the popup can approve immediately.250  const approval = new Promise<boolean>((resolve) => {251    const timeoutId = setTimeout(async () => {252      approvals.delete(request.requestId);253      await clearPendingRequest(request.requestId);254      resolve(false);255    }, APPROVAL_TIMEOUT_MS);256    approvals.set(request.requestId, { resolve, timeoutId });257  });258  try {259    if (chrome.storage.session) {260      await chrome.storage.session.set({ [pendingStorageKey(request.requestId)]: request });261    }262    await openApprovalPopup();263  } catch (error) {264    await resolvePendingPasskeyRequest(request.requestId, false);265    throw error;266  }267  return approval;268}269270export async function getPasskeyProviderState(): Promise<PasskeyProviderState> {271  const settings = await vault.ensureSettingsLoaded();272  const supported = isPasskeySupported();273  const enabled = settings.passkeyProviderEnabled ?? (detectSharedBrowser() === "firefox");274  return {275    supported,276    enabled,277    attached: supported && attached,278    browserLabel: getBrowserLabel(),279    statusLabel: !supported280      ? "Interception unavailable"281      : attached282        ? "Active"283        : conflict284          ? "Another provider is active"285          : enabled286            ? "Inactive"287            : "Disabled",288    conflict,289  };290}291292async function attachPasskeyProxy(): Promise<void> {293  if (!isPasskeySupported()) {294    attached = false;295    conflict = "This browser does not expose chrome.webAuthenticationProxy.";296    return;297  }298299  // Firefox path: no chrome.webAuthenticationProxy exists. The popup-context300  // navigator.credentials creator is always ready once the user enables the301  // provider. Treat enabled = attached for state reporting purposes.302  if (detectSharedBrowser() === "firefox") {303    attached = true;304    conflict = undefined;305    return;306  }307308  if (attached) return;309310  try {311    await chrome.webAuthenticationProxy.attach();312    attached = true;313    conflict = undefined;314  } catch (error) {315    attached = false;316    conflict = error instanceof Error ? error.message : "Another provider is active.";317    console.warn("[Peach passkey] proxy attach failed", { conflict });318  }319}320321async function detachPasskeyProxy(): Promise<void> {322  if (!isPasskeySupported()) {323    attached = false;324    return;325  }326327  if (detectSharedBrowser() === "firefox") {328    attached = false;329    conflict = undefined;330    return;331  }332333  try {334    await chrome.webAuthenticationProxy.detach();335  } catch {336    // Ignore detach failures; the extension may already be detached.337  }338339  attached = false;340  conflict = undefined;341}342343export async function setPasskeyProviderEnabled(enabled: boolean): Promise<PasskeyProviderState> {344  await vault.updateSettings({ passkeyProviderEnabled: enabled });345  if (enabled) {346    await attachPasskeyProxy();347  } else {348    await detachPasskeyProxy();349  }350  return getPasskeyProviderState();351}352353async function refreshPasskeyProxy(): Promise<void> {354  const settings = await vault.ensureSettingsLoaded();355  if (settings.passkeyProviderEnabled ?? (detectSharedBrowser() === "firefox")) {356    await attachPasskeyProxy();357    return;358  }359  await detachPasskeyProxy();360}361362// Multiple accounts and credentials for one RP must remain independently usable.363function findAttachTarget(rpId: string, userName: string): VaultEntry | null {364  if (!userName) return null;365  const matches = vault.getEntries().filter((entry) => {366    if (entry.deletedAt || entry.type !== "login" || entry.passkey || entry.username !== userName) return false;367    return [entry.url, ...(entry.additionalUrls ?? [])].some((url) => {368      if (!url) return false;369      try {370        return new URL(url.includes("://") ? url : `https://${url}`).hostname === rpId;371      } catch {372        return false;373      }374    });375  });376  return matches.length === 1 ? matches[0]! : null;377}378379function hasExcludedCredential(rpId: string, excluded: Array<{ id: string; type?: string }> = []): boolean {380  return listPasskeyEntries().some((entry) => entry.passkey.rpId === rpId &&381    excluded.some((descriptor) => descriptor.type === "public-key" && descriptor.id === entry.passkey.credentialId));382}383384async function handleCreateRequest(385  request: chrome.webAuthenticationProxy.CreateRequest386): Promise<void> {387  const options = JSON.parse(request.requestDetailsJson) as PublicKeyCredentialCreationOptionsJSON & { extensions?: unknown };388  const rpId = options.rp.id;389  const rpName = options.rp.name ?? options.rp.id;390  const userName = options.user.name;391  const userDisplayName = options.user.displayName ?? options.user.name;392  if (typeof rpId !== "string" || !rpId) {393    console.warn("[Peach passkey] reject: missing rp.id");394    await rejectCreate(request.requestId, "NotSupportedError", "Missing RP ID");395    return;396  }397398  const context = chromeRequestContext(options.extensions);399  if (!context) {400    await rejectCreate(request.requestId, "SecurityError", "Missing or invalid browser request context.");401    return;402  }403404  if (!PASSKEY_CREATE_E2E_BYPASS && !(await isProUser())) {405    console.warn("[Peach passkey] reject: user is not Pro");406    await rejectCreate(407      request.requestId,408      "NotAllowedError",409      "Passkey creation requires Peach Pro."410    );411    // Show the inline passkey gate so the user knows what happened and can upgrade.412    broadcastPasskeyProGate();413    return;414  }415416  if (!vault.isUnlocked()) {417    // Same wait-for-unlock pattern handleGetRequest uses: summon the inline418    // unlock prompt on the active tab so the user can unlock without leaving419    // the page, then hold the create request open until the vault unlocks or420    // the timeout fires. Immediately rejecting here means Google shows421    // "Something went wrong" the instant the user picks Peach.422    const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) =>423      chrome.tabs.query({ active: true, lastFocusedWindow: true }, resolve)424    );425    const activeTab = tabs[0];426    if (activeTab?.id) {427      chrome.tabs.sendMessage(activeTab.id, {428        type: 'SUMMON_AUTOFILL',429        source: 'passkey-unlock',430      }).catch((err) => {431        console.warn("[Peach passkey] SUMMON_AUTOFILL failed, falling back to popup", err);432        void openApprovalPopup();433      });434    } else {435      await openApprovalPopup();436    }437438    const unlocked = await new Promise<boolean>((resolve) => {439      const timeoutId = setTimeout(() => {440        unlockWaiters.delete(request.requestId);441        resolve(false);442      }, APPROVAL_TIMEOUT_MS);443      unlockWaiters.set(request.requestId, { resolve, timeoutId });444    });445446    if (!unlocked || !vault.isUnlocked()) {447      console.warn("[Peach passkey] reject: unlock timeout");448      await rejectCreate(request.requestId, "NotAllowedError", "Not unlocked in time.");449      return;450    }451    // Vault is now unlocked — fall through to approval.452  }453454  const approved = await promptUserApproval({455    requestId: request.requestId,456    type: "create",457    rpId,458    rpName,459    userName,460    userDisplayName,461    origin: context.origin,462    crossOrigin: context.crossOrigin,463  });464  if (!approved) {465    console.warn("[Peach passkey] reject: user denied");466    await rejectCreate(request.requestId, "NotAllowedError", "User denied request.");467    return;468  }469470  if (hasExcludedCredential(rpId, options.excludeCredentials)) {471    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");472    return;473  }474475  const algorithm = pickPasskeyAlgorithm(options.pubKeyCredParams ?? []);476  if (!algorithm) {477    console.warn("[Peach passkey] reject: no supported algorithm", options.pubKeyCredParams);478    await rejectCreate(request.requestId, "NotSupportedError", "No supported algorithm offered.");479    return;480  }481  const credentialIdBytes = crypto.getRandomValues(new Uint8Array(32));482  const { publicKeyCose, publicKeySpki, privateKeyJwk } = await generatePasskeyKeypair(483    algorithm484  );485  const authData = await buildAuthenticatorData({486    rpId,487    flags: 0x4d,488    signCount: 0,489    credentialId: credentialIdBytes,490    publicKeyCose,491  });492  const attestationObject = createAttestationObject(authData);493  const clientDataJSON = buildClientDataJSON(494    "webauthn.create",495    options.challenge,496    context.origin,497    context.crossOrigin498  );499500  const passkey: PasskeyData = {501    rpId,502    rpName,503    credentialId: base64urlEncode(credentialIdBytes),504    publicKeyCose: base64urlEncode(publicKeyCose),505    privateKeyJwk,506    userHandle: options.user.id,507    userName,508    userDisplayName,509    algorithm,510    signCount: 0,511    aaguid: base64urlEncode(new Uint8Array(16)),512    backupEligible: true,513    backupState: false,514    browser: "chrome",515    transports: ["internal"],516    createdAt: Date.now(),517  };518519  if (hasExcludedCredential(rpId, options.excludeCredentials)) {520    await rejectCreate(request.requestId, "InvalidStateError", "A listed credential already exists.");521    return;522  }523524  // Attach only when the account identifies one credential-free login.525  const target = findAttachTarget(rpId, userName);526  if (target) {527    await vault.updateEntry(target.id, { passkey });528  } else {529    await vault.addEntry({530      type: "login",531      title: rpName,532      url: `https://${rpId}`,533      username: userName,534      passkey,535    });536  }537  // Consolidate only account matches whose data can be retained.538  await vault.consolidatePasskeyEntries();539540  try {541    await chrome.webAuthenticationProxy.completeCreateRequest({542      requestId: request.requestId,543      responseJson: JSON.stringify({544        id: passkey.credentialId,545        rawId: passkey.credentialId,546        type: "public-key",547        response: {548          clientDataJSON: base64urlEncode(clientDataJSON),549          authenticatorData: base64urlEncode(authData),550          attestationObject: base64urlEncode(attestationObject),551          transports: ["internal"],552          publicKey: base64urlEncode(publicKeySpki),553          publicKeyAlgorithm: algorithm,554        },555        authenticatorAttachment: "platform",556        clientExtensionResults: {},557      }),558    });559  } catch (err) {560    if (isInvalidRequestIdError(err)) {561      return;562    }563    throw err;564  }565}566567function broadcastPasskeyProGate(): void {568  chrome.tabs.query({}, (tabs) => {569    for (const tab of tabs) {570      if (tab.id !== undefined) {571        chrome.tabs.sendMessage(tab.id, { type: "PASSKEY_PRO_GATE" }).catch(() => {});572      }573    }574  });575}576577async function promptViaToast(request: PendingPasskeyRequest): Promise<boolean> {578  if (chrome.storage.session) {579    await chrome.storage.session.set({ [pendingStorageKey(request.requestId)]: request });580  }581582  if (request.tabId !== undefined) {583    chrome.tabs.sendMessage(request.tabId, {584      type: 'SHOW_PASSKEY_TOAST',585      payload: {586        toastToken: crypto.randomUUID(),587        site: request.rpId,588        origin: request.origin,589        displayName: request.userDisplayName ?? request.userName,590        username: request.userName,591        requestId: String(request.requestId),592      },593    }).catch(() => {});594  } else {595    await openApprovalPopup();596  }597598  return new Promise<boolean>((resolve) => {599    const timeoutId = setTimeout(async () => {600      approvals.delete(request.requestId);601      await clearPendingRequest(request.requestId);602      resolve(false);603    }, APPROVAL_TIMEOUT_MS);604605    approvals.set(request.requestId, { resolve, timeoutId });606  });607}608609async function handleGetRequest(610  request: chrome.webAuthenticationProxy.GetRequest611): Promise<void> {612  const options = JSON.parse(request.requestDetailsJson) as PublicKeyCredentialRequestOptionsJSON & { extensions?: unknown };613  const context = chromeRequestContext(options.extensions);614  if (!context || typeof options.rpId !== "string" || !options.rpId) {615    await rejectGet(request.requestId, "SecurityError", "Missing or invalid browser request context.");616    return;617  }618  if (!vault.isUnlocked()) {619    // Summon the inline unlock prompt on the active tab so the user can unlock620    // without leaving the page. Fall back to the popup if the content script621    // is unavailable (e.g. restricted URL, script not yet injected).622    const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) =>623      chrome.tabs.query({ active: true, currentWindow: true }, resolve)624    );625    const activeTab = tabs[0];626    if (activeTab?.id) {627      chrome.tabs.sendMessage(activeTab.id, {628        type: 'SUMMON_AUTOFILL',629        source: 'passkey-unlock',630      }).catch(() => { void openApprovalPopup(); });631    } else {632      await openApprovalPopup();633    }634635    // Hold the request open until the vault unlocks or the timeout fires.636    const unlocked = await new Promise<boolean>((resolve) => {637      const timeoutId = setTimeout(() => {638        unlockWaiters.delete(request.requestId);639        resolve(false);640      }, APPROVAL_TIMEOUT_MS);641      unlockWaiters.set(request.requestId, { resolve, timeoutId });642    });643644    if (!unlocked || !vault.isUnlocked()) {645      await rejectGet(request.requestId, "NotAllowedError", "Not unlocked in time.");646      return;647    }648    // Vault is now unlocked — fall through to authenticate.649  }650651  if (!PASSKEY_CREATE_E2E_BYPASS && !(await isProUser())) {652    await rejectGet(request.requestId, "NotAllowedError", "Passkey use requires Peach Pro.");653    broadcastPasskeyProGate();654    return;655  }656657  const passkeyBearing = vault.getEntries().filter((entry): entry is VaultEntry & { passkey: PasskeyData } =>658    entry.passkey !== undefined && !entry.deletedAt659  );660  const allowedCredentialIds = (options.allowCredentials ?? []).map((descriptor) => descriptor.id);661662  const match = passkeyBearing.find((entry) => {663    // PB-26-015: a credential-ID match must still belong to the requesting664    // RP — the assertion later signs with the stored rpId, so a foreign-RP665    // request must never select a credential from a different rpId.666    if (options.rpId && entry.passkey.rpId !== options.rpId) return false;667    if (allowedCredentialIds.length > 0) {668      return allowedCredentialIds.includes(entry.passkey.credentialId);669    }670    if (!options.rpId) return false;671    return entry.passkey.rpId === options.rpId;672  });673674  if (!match) {675    // No Peach passkey for this RP — pass through to the platform authenticator.676    // completeGetRequest with no error and no responseJson is the webAuthenticationProxy677    // signal for "I'm not handling this"; Chrome routes the request to the next678    // authenticator in the chain (the built-in browser passkey manager etc.).679    // Rejecting with NotAllowedError would propagate as an error to the page and680    // break RPs (e.g. Google) that issue a GET as part of their create-passkey flow.681    try {682      await chrome.webAuthenticationProxy.completeGetRequest({ requestId: request.requestId });683    } catch (err) {684      if (isInvalidRequestIdError(err)) return;685      if (isMissingResponseJsonError(err)) return;686      throw err;687    }688    return;689  }690691  const credential = match.passkey;692  // Chrome's webAuthenticationProxy path requires Peach-held private key material.693  // Passkeys created on Firefox have no privateKeyJwk — pass through so Chrome694  // can route to a capable authenticator instead of surfacing an error to the page.695  if (!credential.privateKeyJwk) {696    try {697      await chrome.webAuthenticationProxy.completeGetRequest({ requestId: request.requestId });698    } catch (err) {699      if (isInvalidRequestIdError(err)) return;700      if (isMissingResponseJsonError(err)) return;701      throw err;702    }703    return;704  }705706  const tabs = await new Promise<chrome.tabs.Tab[]>((resolve) => {707    chrome.tabs.query({ active: true, currentWindow: true }, resolve);708  });709  const activeTab = tabs[0];710  let canUseToast = false;711  try {712    canUseToast = !context.crossOrigin && activeTab?.id !== undefined &&713      new URL(activeTab.url ?? "").origin === context.origin;714  } catch {715    // Missing or invalid tab metadata cannot authorize page-level consent.716  }717  const pending: PendingPasskeyRequest = {718    requestId: request.requestId,719    type: "get",720    rpId: credential.rpId,721    rpName: credential.rpName,722    userName: credential.userName,723    userDisplayName: credential.userDisplayName,724    origin: context.origin,725    crossOrigin: context.crossOrigin,726    ...(canUseToast ? { tabId: activeTab.id } : {}),727  };728  const approved = await (canUseToast ? promptViaToast(pending) : promptUserApproval(pending));729  if (!approved) {730    await rejectGet(request.requestId, "NotAllowedError", "User denied request.");731    return;732  }733734  const nextSignCount = credential.signCount + 1;735  // Chrome passkeys have always been registered by Peach with BE=1 (0x4d),736  // but versions before v5.0.87 incorrectly persisted backupEligible=false.737  // WebAuthn requires BE to match registration, so repair that legacy metadata738  // while constructing the assertion GitHub and other strict RPs verify.739  const backupEligible = credential.browser === "chrome" ? true : credential.backupEligible;740  const flags = 0x05 | (backupEligible ? 0x08 : 0) | (credential.backupState ? 0x10 : 0);741  const authData = await buildAuthenticatorData({742    rpId: credential.rpId,743    flags,744    signCount: nextSignCount,745  });746  const clientDataJSON = buildClientDataJSON(747    "webauthn.get",748    options.challenge,749    context.origin,750    context.crossOrigin751  );752  const clientDataHash = new Uint8Array(753    await crypto.subtle.digest("SHA-256", new Uint8Array(clientDataJSON))754  );755  const signature = await signPasskeyAssertion(756    credential.privateKeyJwk,757    credential.algorithm,758    authData,759    clientDataHash760  );761762  await vault.updateEntry(match.id, {763    passkey: {764      ...credential,765      backupEligible,766      signCount: nextSignCount,767      lastUsedAt: Date.now(),768    },769  });770771  const responseJson = JSON.stringify({772    id: credential.credentialId,773    rawId: credential.credentialId,774    type: "public-key",775    response: {776      clientDataJSON: base64urlEncode(clientDataJSON),777      authenticatorData: base64urlEncode(authData),778      signature: base64urlEncode(signature),779      userHandle: credential.userHandle,780    },781    authenticatorAttachment: "platform",782    clientExtensionResults: {},783  });784785  try {786    await chrome.webAuthenticationProxy.completeGetRequest({787      requestId: request.requestId,788      responseJson,789    });790  } catch (err) {791    if (isInvalidRequestIdError(err)) {792      return;793    }794    throw err;795  }796}797798// ── Firefox path ────────────────────────────────────────────────────────799//800// Firefox 150+ permits extensions to call navigator.credentials.create/get801// from the popup context with their host-permitted RP IDs. Peach uses that802// surface to register passkeys on behalf of the user. The page's own803// navigator.credentials call is observed via the MAIN-world detector804// (src/content/passkeys-firefox.ts) but never blocked or replaced; Peach's805// flow is parallel and explicit (the user must engage with Peach's button).806807const FIREFOX_PENDING_KEY = "passkey_pending_firefox";808const FIREFOX_DECLINE_PREFIX = "peach_passkey_offer_declined:";809const FIREFOX_DECLINE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days810811export async function initiateFirefoxPasskeyCreate(args: {812  rpId: string;813  rpName: string;814  userName: string;815  userDisplayName?: string;816}, callerOrigin?: string): Promise<{ ok: boolean; error?: string }> {817  // The rpId must belong to the calling page's registrable domain; without818  // this, a page could initiate a ceremony for a foreign site and the819  // approval popup would display an attacker-chosen rpId. Origin is the820  // browser-attested sender origin from messages.ts, never page payload.821  // (Codex Security 2026-08-04, passkey-ceremony-approval sibling.)822  if (!callerOrigin || !isValidRpId(args.rpId, callerOrigin)) {823    return { ok: false, error: "rpid_origin_mismatch" };824  }825  if (!(await isProUser())) {826    broadcastPasskeyProGate();827    return { ok: false, error: "passkey creation requires Peach Pro" };828  }829  if (!vault.isUnlocked()) {830    await openApprovalPopup();831    return { ok: false, error: "vault_locked" };832  }833  if (!chrome.storage.session) {834    return { ok: false, error: "session storage unavailable" };835  }836837  const requestId = randomRequestId();838  const challenge = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)));839  const userHandle = base64urlEncode(crypto.getRandomValues(new Uint8Array(32)));840841  const pending: PendingPasskeyRequest = {842    requestId,843    type: "create",844    rpId: args.rpId,845    rpName: args.rpName,846    userName: args.userName,847    userDisplayName: args.userDisplayName,848    browser: "firefox",849    challenge,850    userHandle,851  };852853  await chrome.storage.session.set({ [FIREFOX_PENDING_KEY]: pending });854  await openApprovalPopup();855  return { ok: true };856}857858export async function completeFirefoxPasskeyCreate(payload: {859  requestId: number;860  rpId: string;861  rpName: string;862  userName: string;863  userDisplayName?: string;864  userHandle: string;865  credentialId: string;866  publicKeyCose: string;867  algorithm: -7 | -8;868  aaguid?: string;869  transports?: string[];870  backupEligible?: boolean;871  backupState?: boolean;872}): Promise<{ ok: boolean; error?: string }> {873  if (!vault.isUnlocked()) return { ok: false, error: "vault_locked" };874875  // Bind completion to the pending ceremony: requestId, rpId, challenge, and876  // userHandle are minted by the background at INITIATE time and only ever877  // leave extension context through the approval popup, so a page (or anything878  // replaying relayed messages) cannot synthesize a matching completion for an879  // rpId it does not own. (Codex Security 2026-08-04 MEDIUM,880  // broken-access-control.passkey-ceremony-approval.)881  const pending = chrome.storage.session882    ? ((await chrome.storage.session.get(FIREFOX_PENDING_KEY))[FIREFOX_PENDING_KEY] as883        | PendingPasskeyRequest884        | undefined)885    : undefined;886  if (887    !pending ||888    pending.requestId !== payload.requestId ||889    pending.rpId !== payload.rpId ||890    pending.userHandle !== payload.userHandle891  ) {892    return { ok: false, error: "no_pending_request" };893  }894895  if (hasExcludedCredential(payload.rpId, [{ type: "public-key", id: payload.credentialId }])) {896    return { ok: false, error: "credential_exists" };897  }898899  const passkey: PasskeyData = {900    rpId: payload.rpId,901    rpName: payload.rpName,902    credentialId: payload.credentialId,903    publicKeyCose: payload.publicKeyCose,904    userHandle: payload.userHandle,905    userName: payload.userName,906    userDisplayName: payload.userDisplayName ?? payload.userName,907    algorithm: payload.algorithm,908    signCount: 0,909    aaguid: payload.aaguid ?? base64urlEncode(new Uint8Array(16)),910    backupEligible: payload.backupEligible ?? false,911    backupState: payload.backupState ?? false,912    browser: "firefox",913    transports: payload.transports ?? ["internal"],914    createdAt: Date.now(),915  };916917  // Native Firefox credentials follow the same account-specific attachment rule.918  const target = findAttachTarget(payload.rpId, payload.userName);919  if (target) {920    await vault.updateEntry(target.id, { passkey });921  } else {922    await vault.addEntry({923      type: "login",924      title: payload.rpName || payload.rpId,925      url: `https://${payload.rpId}`,926      username: payload.userName,927      passkey,928    });929  }930  await vault.consolidatePasskeyEntries();931932  if (chrome.storage.session) {933    await chrome.storage.session.remove(FIREFOX_PENDING_KEY);934  }935  return { ok: true };936}937938const MAX_DECLINE_DOMAIN_LENGTH = 253;939940function normaliseDeclineDomain(domain: string): string | null {941  if (!domain || domain.length > MAX_DECLINE_DOMAIN_LENGTH) return null;942  try {943    const url = new URL(`https://${domain}`);944    return isValidRpId(url.hostname, url.origin) ? url.hostname : null;945  } catch {946    return null;947  }948}949950function declineKey(domain: string): string {951  return `${FIREFOX_DECLINE_PREFIX}${domain}`;952}953954export async function recordPasskeyOfferDecline(domain: string): Promise<void> {955  const validDomain = normaliseDeclineDomain(domain);956  if (!validDomain) return;957  await chrome.storage.local.set({ [declineKey(validDomain)]: Date.now() });958}959960export async function isPasskeyOfferDeclined(domain: string): Promise<boolean> {961  const validDomain = normaliseDeclineDomain(domain);962  if (!validDomain) return false;963  const key = declineKey(validDomain);964965  const stored = (await chrome.storage.local.get(key)) as Record<string, number | undefined>;966  const at = stored[key];967  if (typeof at !== "number") return false;968  if (Date.now() - at > FIREFOX_DECLINE_TTL_MS) {969    await chrome.storage.local.remove(key);970    return false;971  }972  return true;973}974975// ── Firefox content-script proxy path (v2.12.0) ────────────────────────976//977// The MAIN-world monkey-patch in src/content/passkeys-firefox.ts replaces978// navigator.credentials.create / .get on every Firefox page. It builds a979// clientDataJSON whose `origin` is the PAGE's origin (not moz-extension://),980// then hands every ceremony to the background via PASSKEY_HAS_CREDENTIALS,981// PASSKEY_CREATE, and PASSKEY_GET. The handlers below own those messages.982//983// Removal: when Firefox ships chrome.webAuthenticationProxy, the runtime flag984// FIREFOX_USE_CONTENT_SCRIPT_PROXY in src/shared/passkey-flags.ts evaluates985// to false and these handlers short-circuit. The full removal checklist is986// in that file — the deletion is purely subtractive.987988interface FirefoxAllowCredential {989  id: string;990  type?: string;991}992993interface FirefoxPubKeyCredParam {994  type?: string;995  alg: number;996}997998export interface FirefoxPasskeyHasCredentialsPayload {999  rpId: string;1000  allowCredentials: FirefoxAllowCredential[];1001}10021003export interface FirefoxPasskeyCreatePayload {1004  rpId: string;1005  rpName?: string;1006  userId: string;1007  userName: string;1008  userDisplayName?: string;1009  challenge: string;1010  clientDataJSON: number[];1011  origin: string;1012  pubKeyCredParams?: FirefoxPubKeyCredParam[];1013  excludeCredentials?: FirefoxAllowCredential[];1014  authenticatorSelection?: Record<string, unknown>;1015  timeout?: number;1016  attestation?: string;1017}10181019export interface FirefoxPasskeyGetPayload {1020  rpId: string;1021  challenge: string;1022  clientDataJSON: number[];1023  origin: string;1024  allowCredentials: FirefoxAllowCredential[];1025  userVerification?: string;1026}10271028interface FirefoxCreateCredentialResponse {1029  type: "create";1030  id: string;1031  clientDataJSON: number[];1032  attestationObject: string;1033  authenticatorData: string;1034  publicKey: string;1035  algorithm: -7 | -8;1036}10371038interface FirefoxGetCredentialResponse {1039  type: "get";1040  id: string;1041  clientDataJSON: number[];1042  authenticatorData: string;1043  signature: string;1044  userHandle: string;1045}10461047type FirefoxPasskeyResult<T> =1048  | { ok: true; credential: T }1049  | { ok: false; error: "pro_required" | "user_cancelled" | "no_credentials" | "vault_locked" | "not_applicable" | "internal_error" | "credential_excluded"; message?: string };10501051function listPasskeyEntries(): Array<VaultEntry & { passkey: PasskeyData }> {1052  return vault.getEntries().filter(1053    (entry): entry is VaultEntry & { passkey: PasskeyData } =>1054      entry.passkey !== undefined && !entry.deletedAt1055  );1056}10571058/** Decode the `origin` field out of a WebAuthn clientDataJSON byte array. */1059function clientDataJsonOrigin(bytes: number[] | undefined): string | null {1060  if (!Array.isArray(bytes)) return null;1061  try {1062    const obj = JSON.parse(new TextDecoder().decode(new Uint8Array(bytes))) as { origin?: unknown };1063    return typeof obj.origin === "string" ? obj.origin : null;1064  } catch {1065    return null;1066  }1067}10681069/**1070 * Enforce the WebAuthn rpId<->origin relationship on the Firefox proxy path,1071 * where Peach is the authenticator. The ONLY trustworthy origin is the one the1072 * browser attested for the calling page (`callerOrigin`, derived from the1073 * message sender in messages.ts) — NEVER `payload.origin`, which the page1074 * controls and can set to match any rpId (SEV-1-A / audit CRITICAL). Also1075 * refuse to sign a clientDataJSON whose embedded origin disagrees with the1076 * attested origin, so a forged ceremony can't smuggle a foreign origin into1077 * the signed bytes the RP verifies.1078 */1079function assertOriginOwnsRpId(1080  rpId: string,1081  callerOrigin: string | undefined,1082  clientDataJSON?: number[],1083): void {1084  if (!callerOrigin || !isValidRpId(rpId, callerOrigin)) {1085    throw new DOMException(1086      `SecurityError: relying party ID "${rpId}" is not a registrable domain ` +1087        `suffix of the calling origin "${callerOrigin ?? "(unknown)"}".`,1088      "SecurityError",1089    );1090  }1091  const cdjOrigin = clientDataJsonOrigin(clientDataJSON);1092  if (cdjOrigin !== null && cdjOrigin !== callerOrigin) {1093    throw new DOMException(1094      `SecurityError: clientDataJSON origin "${cdjOrigin}" does not match the ` +1095        `attested calling origin "${callerOrigin}".`,1096      "SecurityError",1097    );1098  }1099}11001101export async function handlePasskeyHasCredentials(1102  payload: FirefoxPasskeyHasCredentialsPayload,1103  callerOrigin?: string,1104): Promise<{ ok: true; hasCredentials: boolean } | { ok: false; error: string }> {1105  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1106    return { ok: false, error: "not_applicable" };1107  }1108  // Scope the existence check to the caller's own origin so an arbitrary page1109  // cannot enumerate which sites the user holds passkeys for (audit MEDIUM).1110  // A false answer is indistinguishable from "no credential" to the page.1111  if (!callerOrigin || !isValidRpId(payload.rpId, callerOrigin)) {1112    return { ok: true, hasCredentials: false };1113  }1114  if (!vault.isUnlocked()) {1115    // A locked vault cannot answer whether a credential exists until unlock.1116    return { ok: false, error: "vault_locked" };1117  }1118  const passkeys = listPasskeyEntries().filter(1119    (entry) => entry.passkey.rpId === payload.rpId1120  );1121  if (passkeys.length === 0) return { ok: true, hasCredentials: false };11221123  const allow = payload.allowCredentials ?? [];1124  if (allow.length === 0) return { ok: true, hasCredentials: true };11251126  const hasMatch = passkeys.some((entry) =>1127    allow.some((ac) => ac.id === entry.passkey.credentialId)1128  );1129  return { ok: true, hasCredentials: hasMatch };1130}11311132/**1133 * Approval prompt for the Firefox proxy ceremonies. Reuses the existing1134 * pending-passkey channel (badge + popup + 60s timeout) — the same approval1135 * UI Chrome ceremonies use, so the popup's State 11/12 view doesn't need1136 * any new code path. The page-side proxy never sees the request id; the1137 * background mints one and discards it after resolution.1138 */1139async function requestFirefoxApproval<T>(args: {1140  type: "create" | "get";1141  rpId: string;1142  rpName?: string;1143  userName: string;1144  userDisplayName?: string;1145}, operation: () => Promise<FirefoxPasskeyResult<T>>): Promise<FirefoxPasskeyResult<T>> {1146  const requestId = randomRequestId();1147  let finish!: () => void;1148  firefoxCeremonies.set(requestId, new Promise<void>((resolve) => { finish = resolve; }));1149  try {1150    const approved = await promptUserApproval({1151      requestId,1152      type: args.type,1153      rpId: args.rpId,1154      rpName: args.rpName ?? args.rpId,1155      userName: args.userName,1156      userDisplayName: args.userDisplayName,1157    });1158    if (!approved) return { ok: false, error: "user_cancelled" };1159    return await operation();1160  } finally {1161    finish();1162    firefoxCeremonies.delete(requestId);1163  }1164}11651166export async function handleFirefoxPasskeyCreate(1167  payload: FirefoxPasskeyCreatePayload,1168  callerOrigin?: string,1169): Promise<FirefoxPasskeyResult<FirefoxCreateCredentialResponse>> {1170  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1171    return { ok: false, error: "not_applicable" };1172  }1173  // WebAuthn §7.1 step 6 — the requested rpId must be owned by the page's1174  // browser-ATTESTED origin (threaded in as callerOrigin from the message1175  // sender), NOT the page-supplied payload.origin which an attacker controls.1176  // On the Firefox proxy path Peach is the authenticator and must enforce this1177  // before minting anything (audit CRITICAL — origin spoofing).1178  assertOriginOwnsRpId(payload.rpId, callerOrigin, payload.clientDataJSON);1179  if (!(await isProUser())) {1180    broadcastPasskeyProGate();1181    return { ok: false, error: "pro_required" };1182  }1183  if (!vault.isUnlocked()) {1184    await openApprovalPopup();1185    return { ok: false, error: "vault_locked" };1186  }11871188  const algorithm = pickPasskeyAlgorithm(payload.pubKeyCredParams ?? []);1189  if (!algorithm) {1190    return { ok: false, error: "internal_error", message: "No supported algorithm offered" };1191  }11921193  return requestFirefoxApproval<FirefoxCreateCredentialResponse>({1194    type: "create",1195    rpId: payload.rpId,1196    rpName: payload.rpName,1197    userName: payload.userName,1198    userDisplayName: payload.userDisplayName,1199  }, async () => {12001201    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1202      return { ok: false, error: "credential_excluded" };1203    }12041205    const { bytes: credentialIdBytes, base64url: credentialId } = generateCredentialId();1206    const { publicKeyCose, publicKeySpki, privateKeyJwk } = await generatePasskeyKeypair(algorithm);12071208    // 0x4d = UP|UV|BE|AT. Peach passkeys are synced, so BE is true on both1209    // registration paths and on later assertions.1210    const authenticatorData = await buildAuthenticatorData({1211      rpId: payload.rpId,1212      flags: 0x4d,1213      signCount: 0,1214      credentialId: credentialIdBytes,1215      publicKeyCose,1216    });1217    const attestationObject = createAttestationObject(authenticatorData);12181219    const passkey: PasskeyData = {1220      rpId: payload.rpId,1221      rpName: payload.rpName ?? payload.rpId,1222      credentialId,1223      publicKeyCose: base64urlEncode(publicKeyCose),1224      privateKeyJwk,1225      userHandle: payload.userId,1226      userName: payload.userName,1227      userDisplayName: payload.userDisplayName ?? payload.userName,1228      algorithm,1229      signCount: 0,1230      aaguid: base64urlEncode(new Uint8Array(16)),1231      backupEligible: true,1232      backupState: false,1233      browser: "firefox",1234      transports: ["internal"],1235      createdAt: Date.now(),1236    };12371238    if (hasExcludedCredential(payload.rpId, payload.excludeCredentials)) {1239      return { ok: false, error: "credential_excluded" };1240    }12411242    const target = findAttachTarget(payload.rpId, payload.userName);1243    if (target) {1244      await vault.updateEntry(target.id, { passkey });1245    } else {1246      await vault.addEntry({1247        type: "login",1248        title: payload.rpName || payload.rpId,1249        url: `https://${payload.rpId}`,1250        username: payload.userName,1251        passkey,1252      });1253    }1254    await vault.consolidatePasskeyEntries();12551256    return {1257      ok: true,1258      credential: {1259        type: "create",1260        id: credentialId,1261        // The content script already encoded clientDataJSON with the page1262        // origin; round-trip the exact bytes back so the RP sees the same1263        // hash it computes locally.1264        clientDataJSON: payload.clientDataJSON,1265        attestationObject: base64urlEncode(attestationObject),1266        authenticatorData: base64urlEncode(authenticatorData),1267        publicKey: base64urlEncode(publicKeySpki),1268        algorithm,1269      },1270    };1271  });1272}12731274export async function handleFirefoxPasskeyGet(1275  payload: FirefoxPasskeyGetPayload,1276  callerOrigin?: string,1277): Promise<FirefoxPasskeyResult<FirefoxGetCredentialResponse>> {1278  if (!FIREFOX_USE_CONTENT_SCRIPT_PROXY || (await vault.ensureSettingsLoaded()).passkeyProviderEnabled === false) {1279    return { ok: false, error: "not_applicable" };1280  }1281  // WebAuthn §7.2 step 8 — the rpId must be owned by the page's browser-attested1282  // origin (callerOrigin from the message sender), NOT the page-supplied1283  // payload.origin. Both rpId and payload.origin are attacker-controlled, so1284  // validating one against the other is no protection; a cross-origin page must1285  // not be able to coax Peach into signing an assertion scoped to another site1286  // (audit CRITICAL — assertion forgery).1287  assertOriginOwnsRpId(payload.rpId, callerOrigin, payload.clientDataJSON);1288  if (!(await isProUser())) {1289    broadcastPasskeyProGate();1290    return { ok: false, error: "pro_required" };1291  }1292  if (!vault.isUnlocked()) {1293    const requestId = randomRequestId();1294    // Register before opening the popup so an immediate unlock cannot be missed.1295    const unlocked = new Promise<boolean>((resolve) => {1296      const timeoutId = setTimeout(() => {1297        unlockWaiters.delete(requestId);1298        resolve(false);1299      }, APPROVAL_TIMEOUT_MS);1300      unlockWaiters.set(requestId, { resolve, timeoutId });1301    });1302    await openApprovalPopup();1303    if (!(await unlocked) || !vault.isUnlocked()) {1304      return { ok: false, error: "user_cancelled" };1305    }1306  }13071308  const allow = payload.allowCredentials ?? [];1309  const candidates = listPasskeyEntries().filter((entry) => {1310    if (entry.passkey.rpId !== payload.rpId) return false;1311    if (allow.length === 0) return true;1312    return allow.some((ac) => ac.id === entry.passkey.credentialId);1313  });13141315  if (candidates.length === 0) return { ok: false, error: "no_credentials" };13161317  // Most-recently-used wins when several credentials match. A future1318  // multi-account selector goes here; for now this matches the Chrome path's1319  // behavior for the common one-passkey-per-rp case.1320  candidates.sort((a, b) => (b.passkey.lastUsedAt ?? 0) - (a.passkey.lastUsedAt ?? 0));1321  const match = candidates[0]!;1322  const credential = match.passkey;13231324  const privateKeyJwk = credential.privateKeyJwk;1325  if (!privateKeyJwk) {1326    // Pre-v2.12.0 Firefox passkeys delegated to the platform authenticator1327    // — no Peach-held private key to sign with. The MAIN-world proxy treats1328    // no_credentials as a fall-through, which routes to the platform UI.1329    return { ok: false, error: "no_credentials" };1330  }13311332  return requestFirefoxApproval<FirefoxGetCredentialResponse>({1333    type: "get",1334    rpId: credential.rpId,1335    rpName: credential.rpName,1336    userName: credential.userName,1337    userDisplayName: credential.userDisplayName,1338  }, async () => {13391340    const nextSignCount = credential.signCount + 1;1341    // Legacy Chrome registrations used BE=1 even when the stored flag was false.1342    // Legacy Firefox registrations used BE=0, so retain their recorded value.1343    const backupEligible = credential.browser === "chrome" ? true : credential.backupEligible;1344    const flags = 0x05 | (backupEligible ? 0x08 : 0) | (credential.backupState ? 0x10 : 0);1345    const authenticatorData = await buildAuthenticatorData({1346      rpId: credential.rpId,1347      flags,1348      signCount: nextSignCount,1349    });13501351    // The content script supplied clientDataJSON bytes built with the page1352    // origin. SHA-256 those bytes verbatim — never re-serialize, or the hash1353    // diverges from what the RP computes.1354    const clientDataBytes = new Uint8Array(payload.clientDataJSON);1355    const clientDataHash = new Uint8Array(1356      await crypto.subtle.digest("SHA-256", clientDataBytes)1357    );1358    const signature = await signPasskeyAssertion(1359      privateKeyJwk,1360      credential.algorithm,1361      authenticatorData,1362      clientDataHash1363    );13641365    await vault.updateEntry(match.id, {1366      passkey: {1367        ...credential,1368        backupEligible,1369        signCount: nextSignCount,1370        lastUsedAt: Date.now(),1371      },1372    });13731374    return {1375      ok: true,1376      credential: {1377        type: "get",1378        id: credential.credentialId,1379        clientDataJSON: payload.clientDataJSON,1380        authenticatorData: base64urlEncode(authenticatorData),1381        signature: base64urlEncode(signature),1382        userHandle: credential.userHandle,1383      },1384    };1385  });1386}13871388export async function setupPasskeyProxy(): Promise<void> {1389  if (!isPasskeySupported()) {1390    return;1391  }13921393  // Firefox doesn't expose chrome.webAuthenticationProxy listeners. The1394  // popup-context credential creator is the entry point; nothing to wire here.1395  if (detectSharedBrowser() === "firefox") {1396    await refreshPasskeyProxy();1397    return;1398  }13991400  if (!listenersRegistered) {1401    chrome.webAuthenticationProxy.onIsUvpaaRequest.addListener((requestInfo) => {1402      // Peach is a user-verifying platform authenticator whenever the proxy1403      // is attached. The lock state is irrelevant here — the create/get1404      // handlers prompt for unlock when needed. Returning false while locked1405      // makes Google (and any RP that checks isUvpaa as a precondition) show1406      // "A passkey can't be created on this device" before the user even1407      // gets a chance to start the ceremony.1408      void chrome.webAuthenticationProxy.completeIsUvpaaRequest({1409        requestId: requestInfo.requestId,1410        isUvpaa: true,1411      });1412    });1413    chrome.webAuthenticationProxy.onCreateRequest.addListener((requestInfo) => {1414      void handleCreateRequest(requestInfo).catch(async (error) => {1415        // "Invalid requestId" means Chrome already cancelled — handlers will1416        // short-circuit, but if it propagates out from a still-in-flight branch,1417        // don't double-complete.1418        if (isInvalidRequestIdError(error)) {1419          return;1420        }1421        console.error("Peach passkey create failed", error);1422        await rejectCreate(1423          requestInfo.requestId,1424          "UnknownError",1425          error instanceof Error ? error.message : "Passkey creation failed."1426        );1427      });1428    });1429    chrome.webAuthenticationProxy.onGetRequest.addListener((requestInfo) => {1430      void handleGetRequest(requestInfo).catch(async (error) => {1431        if (isInvalidRequestIdError(error)) {1432          return;1433        }1434        console.error("Peach passkey get failed", error);1435        await rejectGet(1436          requestInfo.requestId,1437          "UnknownError",1438          error instanceof Error ? error.message : "Passkey authentication failed."1439        );1440      });1441    });1442    chrome.webAuthenticationProxy.onRequestCanceled.addListener((requestId) => {1443      // Release any unlock waiter parked for this request.1444      const waiter = unlockWaiters.get(requestId);1445      if (waiter) {1446        clearTimeout(waiter.timeoutId);1447        waiter.resolve(false);1448        unlockWaiters.delete(requestId);1449      }1450      void resolvePendingPasskeyRequest(requestId, false);1451    });1452    listenersRegistered = true;1453  }14541455  await refreshPasskeyProxy();1456}