123456789101112131415161718192021222324252627282930313233343536373839404142434445declare function exportFunction(46 func: (...args: any[]) => any,47 targetScope: any,48 options?: { defineAs?: string },49): (...args: any[]) => any;5051declare function cloneInto<T>(52 obj: T,53 targetScope: any,54 options?: { cloneFunctions?: boolean },55): T;5657export function installPeachPasskeyProxy(): void {58 const w = window as unknown as Record<string, unknown>;59 if (w.__peachPasskeyProxyInstalled) return;60 w.__peachPasskeyProxyInstalled = true;6162 63 64 65 66 const sendMessage = chrome.runtime.sendMessage;6768 69 70 71 if (typeof exportFunction !== "function" || typeof cloneInto !== "function") {72 return;73 }7475 const credentials = navigator.credentials;76 if (!credentials || typeof credentials.create !== "function" || typeof credentials.get !== "function") {77 return;78 }7980 81 const pageCredentials =82 (credentials as unknown as { wrappedJSObject?: CredentialsContainer }).wrappedJSObject ??83 credentials;8485 86 const originalCreate = credentials.create.bind(credentials);87 const originalGet = credentials.get.bind(credentials);8889 function pagePromise<T>(task: () => Promise<T>): Promise<T> {90 return new window.Promise<T>((resolve, reject) => {91 task().then(resolve, reject);92 });93 }9495 exportFunction(96 function patchedCreate(options?: CredentialCreationOptions): Promise<Credential | null> {97 return pagePromise(async () => {98 if (!options?.publicKey) return originalCreate(options);99100 try {101 const publicKey = options.publicKey;102 const challenge = bufferToBase64url(toArrayBuffer(publicKey.challenge));103 const clientDataJSON = encodeJsonBytes({104 type: "webauthn.create",105 challenge,106 origin: window.location.origin,107 crossOrigin: false,108 });109110 const userId = bufferToBase64url(toArrayBuffer(publicKey.user.id));111112 const response = await sendMessage({113 type: "PASSKEY_CREATE",114 payload: {115 rpId: publicKey.rp.id ?? window.location.hostname,116 rpName: publicKey.rp.name,117 userId,118 userName: publicKey.user.name,119 userDisplayName: publicKey.user.displayName,120 challenge,121 clientDataJSON: Array.from(clientDataJSON),122 origin: window.location.origin,123 pubKeyCredParams: publicKey.pubKeyCredParams,124 excludeCredentials: (publicKey.excludeCredentials ?? []).map((descriptor) => ({125 type: descriptor.type,126 id: bufferToBase64url(toArrayBuffer(descriptor.id)),127 transports: descriptor.transports,128 })),129 authenticatorSelection: publicKey.authenticatorSelection,130 timeout: publicKey.timeout,131 attestation: publicKey.attestation,132 },133 });134135 if (!response?.ok) {136 const error = response?.error;137 if (error === "credential_excluded") {138 throw new window.DOMException("A listed credential already exists.", "InvalidStateError");139 }140 if (error === "user_cancelled") {141 throw new window.DOMException(142 "The operation either timed out or was not allowed.",143 "NotAllowedError",144 );145 }146 if (error === "pro_required") {147 window.dispatchEvent(148 new CustomEvent("peach:passkey-pro-gate", { detail: { feature: "passkeys" } }),149 );150 return originalCreate(options);151 }152 153 154 return originalCreate(options);155 }156157 const cred = validateCreateCredential(response.credential);158 return buildPublicKeyCredential(cred);159 } catch (err) {160 if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "InvalidStateError")) throw err;161 162 return originalCreate(options);163 }164 });165 },166 pageCredentials,167 { defineAs: "create" },168 );169170 exportFunction(171 function patchedGet(options?: CredentialRequestOptions): Promise<Credential | null> {172 return pagePromise(async () => {173 174 const hints = (options?.publicKey as (PublicKeyCredentialRequestOptions & { hints?: string[] }) | undefined)?.hints;175 if (!options?.publicKey || options.mediation === "conditional" || hints?.[0] === "security-key") {176 return originalGet(options);177 }178179 try {180 const publicKey = options.publicKey;181 const rpId = publicKey.rpId ?? window.location.hostname;182 const allowCredentials = (publicKey.allowCredentials ?? []).map((c) => ({183 id: bufferToBase64url(toArrayBuffer(c.id)),184 type: c.type,185 }));186187 188 let has: { ok: boolean; error?: string; hasCredentials?: boolean } | undefined;189 for (let attempt = 0; attempt < 3; attempt++) {190 try {191 has = await sendMessage({192 type: "PASSKEY_HAS_CREDENTIALS",193 payload: { rpId, allowCredentials },194 });195 } catch {196 197 has = undefined;198 }199 if (has) break;200 if (attempt < 2) await new Promise<void>((resolve) => window.setTimeout(resolve, 150));201 }202 if (has?.error === "not_applicable" || (has?.ok && has.hasCredentials === false)) {203 return originalGet(options);204 }205 if (has?.error !== "vault_locked" && !(has?.ok && has.hasCredentials === true)) {206 throw new window.DOMException("Peach could not connect to its passkey provider. Try again.", "NotAllowedError");207 }208209 const challenge = bufferToBase64url(toArrayBuffer(publicKey.challenge));210 const clientDataJSON = encodeJsonBytes({211 type: "webauthn.get",212 challenge,213 origin: window.location.origin,214 crossOrigin: false,215 });216217 const response = await sendMessage({218 type: "PASSKEY_GET",219 payload: {220 rpId,221 challenge,222 clientDataJSON: Array.from(clientDataJSON),223 origin: window.location.origin,224 allowCredentials,225 userVerification: publicKey.userVerification,226 },227 });228229 if (!response?.ok) {230 const error = response?.error;231 if (error === "user_cancelled") {232 throw new window.DOMException(233 "The operation either timed out or was not allowed.",234 "NotAllowedError",235 );236 }237 if (error === "pro_required") {238 window.dispatchEvent(239 new CustomEvent("peach:passkey-pro-gate", { detail: { feature: "passkeys" } }),240 );241 return originalGet(options);242 }243 if (error === "no_credentials" || error === "not_applicable") return originalGet(options);244 throw new window.DOMException("Peach could not complete this passkey request. Try again.", "NotAllowedError");245 }246247 const cred = validateGetCredential(response.credential);248 return buildPublicKeyCredential(cred);249 } catch (err) {250 if (err instanceof DOMException && err.name === "NotAllowedError") throw err;251 throw new window.DOMException("Peach could not complete this passkey request. Try again.", "NotAllowedError");252 }253 });254 },255 pageCredentials,256 { defineAs: "get" },257 );258259 260261 const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;262263 function isBase64url(value: unknown): value is string {264 return typeof value === "string" && value.length > 0 && BASE64URL_RE.test(value);265 }266267 function isByteArray(value: unknown): value is number[] {268 return (269 Array.isArray(value) &&270 value.length > 0 &&271 value.every((b) => typeof b === "number" && Number.isInteger(b) && b >= 0 && b <= 255)272 );273 }274275 function validateCreateCredential(cred: unknown): CreateCredential {276 if (!cred || typeof cred !== "object") throw new ValidationError("missing credential");277 const c = cred as Record<string, unknown>;278 if (c.type !== "create") throw new ValidationError("wrong credential type");279 if (!isBase64url(c.id)) throw new ValidationError("id must be base64url");280 if (!isByteArray(c.clientDataJSON)) throw new ValidationError("clientDataJSON must be a byte array");281 if (!isBase64url(c.attestationObject)) throw new ValidationError("attestationObject must be base64url");282 if (!isBase64url(c.authenticatorData)) throw new ValidationError("authenticatorData must be base64url");283 if (!isBase64url(c.publicKey)) throw new ValidationError("publicKey must be base64url");284 if (c.algorithm !== -7 && c.algorithm !== -8) throw new ValidationError("unsupported algorithm");285 return c as unknown as CreateCredential;286 }287288 function validateGetCredential(cred: unknown): GetCredential {289 if (!cred || typeof cred !== "object") throw new ValidationError("missing credential");290 const c = cred as Record<string, unknown>;291 if (c.type !== "get") throw new ValidationError("wrong credential type");292 if (!isBase64url(c.id)) throw new ValidationError("id must be base64url");293 if (!isByteArray(c.clientDataJSON)) throw new ValidationError("clientDataJSON must be a byte array");294 if (!isBase64url(c.authenticatorData)) throw new ValidationError("authenticatorData must be base64url");295 if (!isBase64url(c.signature)) throw new ValidationError("signature must be base64url");296 if (c.userHandle !== undefined && c.userHandle !== null && !isBase64url(c.userHandle)) {297 throw new ValidationError("userHandle must be base64url");298 }299 return c as unknown as GetCredential;300 }301302 303304 class ValidationError extends Error {305 constructor(message: string) {306 super(message);307 this.name = "ValidationError";308 }309 }310311 interface CreateCredential {312 type: "create";313 id: string;314 clientDataJSON: number[];315 attestationObject: string;316 authenticatorData: string;317 publicKey: string;318 algorithm: -7 | -8;319 }320321 interface GetCredential {322 type: "get";323 id: string;324 clientDataJSON: number[];325 authenticatorData: string;326 signature: string;327 userHandle: string | null;328 }329330 function toArrayBuffer(view: BufferSource): ArrayBuffer {331 const bytes = ArrayBuffer.isView(view)332 ? new Uint8Array(view.buffer, view.byteOffset, view.byteLength)333 : new Uint8Array(view);334 return new Uint8Array(bytes).buffer;335 }336337 function bufferToBase64url(buffer: ArrayBuffer): string {338 const bytes = new Uint8Array(buffer);339 let str = "";340 for (let i = 0; i < bytes.length; i += 1) str += String.fromCharCode(bytes[i]!);341 return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");342 }343344 function base64urlToBuffer(value: string): ArrayBuffer {345 const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(346 Math.ceil(value.length / 4) * 4,347 "=",348 );349 const raw = atob(padded);350 const bytes = new Uint8Array(raw.length);351 for (let i = 0; i < raw.length; i += 1) bytes[i] = raw.charCodeAt(i);352 return bytes.buffer;353 }354355 function encodeJsonBytes(value: unknown): Uint8Array {356 return new TextEncoder().encode(JSON.stringify(value));357 }358359 360361362363364365366367368369370 function buildPublicKeyCredential(cred: CreateCredential | GetCredential): PublicKeyCredential {371 const credentialId = base64urlToBuffer(cred.id);372 const clientDataJSON = new Uint8Array(cred.clientDataJSON).buffer;373374 if (cred.type === "create") {375 const attestationObject = base64urlToBuffer(cred.attestationObject);376 const authenticatorData = base64urlToBuffer(cred.authenticatorData);377 const publicKey = base64urlToBuffer(cred.publicKey);378 const obj = {379 id: cred.id,380 rawId: credentialId,381 type: "public-key" as const,382 authenticatorAttachment: "platform" as const,383 response: {384 clientDataJSON,385 attestationObject,386 getTransports: () => cloneInto(["internal"], window),387 getAuthenticatorData: () => cloneInto(authenticatorData, window),388 getPublicKey: () => cloneInto(publicKey, window),389 getPublicKeyAlgorithm: () => cred.algorithm ?? -7,390 } as AuthenticatorAttestationResponse,391 getClientExtensionResults: () => cloneInto({}, window),392 toJSON: () => cloneInto({393 id: cred.id,394 rawId: cred.id,395 type: "public-key" as const,396 response: {397 clientDataJSON: bufferToBase64url(clientDataJSON),398 attestationObject: cred.attestationObject,399 authenticatorData: cred.authenticatorData,400 publicKey: cred.publicKey,401 publicKeyAlgorithm: cred.algorithm ?? -7,402 transports: ["internal"],403 },404 authenticatorAttachment: "platform" as const,405 clientExtensionResults: {},406 }, window),407 } as unknown as PublicKeyCredential;408 return cloneInto(obj, window, { cloneFunctions: true });409 }410411 const authenticatorData = base64urlToBuffer(cred.authenticatorData);412 const signature = base64urlToBuffer(cred.signature);413 const userHandle = cred.userHandle ? base64urlToBuffer(cred.userHandle) : null;414 const obj = {415 id: cred.id,416 rawId: credentialId,417 type: "public-key" as const,418 authenticatorAttachment: "platform" as const,419 response: {420 clientDataJSON,421 authenticatorData,422 signature,423 userHandle,424 } as AuthenticatorAssertionResponse,425 getClientExtensionResults: () => cloneInto({}, window),426 toJSON: () => cloneInto({427 id: cred.id,428 rawId: cred.id,429 type: "public-key" as const,430 response: {431 clientDataJSON: bufferToBase64url(clientDataJSON),432 authenticatorData: cred.authenticatorData,433 signature: cred.signature,434 userHandle: cred.userHandle ?? null,435 },436 authenticatorAttachment: "platform" as const,437 clientExtensionResults: {},438 }, window),439 } as unknown as PublicKeyCredential;440 return cloneInto(obj, window, { cloneFunctions: true });441 }442}443444installPeachPasskeyProxy();