Repository Public
1// WebAuthn JSON <-> binary conversion. Prefers the platform helpers (parse*OptionsFromJSON / toJSON) and falls2// back to a manual conversion with the same result. No credential material is ever logged or stored.3import { base64urlToBytes, bytesToBase64url } from "./base64url";45type Json = Record<string, unknown>;6const isRecord = (v: unknown): v is Json => typeof v === "object" && v !== null && !Array.isArray(v);78function descriptors(list: unknown): PublicKeyCredentialDescriptor[] | undefined {9 if (!Array.isArray(list)) return undefined;10 return list.filter(isRecord).map((d) => ({11 type: "public-key" as const,12 id: base64urlToBytes(String(d.id)),13 ...(Array.isArray(d.transports) ? { transports: d.transports as AuthenticatorTransport[] } : {}),14 }));15}1617/** Manual equivalent of PublicKeyCredential.parseCreationOptionsFromJSON. */18export function creationOptionsFromJSON(json: Json): PublicKeyCredentialCreationOptions {19 const user = json.user;20 if (!isRecord(user) || typeof json.challenge !== "string") throw new TypeError("invalid creation options");21 const { excludeCredentials, ...rest } = json;22 const exclude = descriptors(excludeCredentials);23 return {24 ...(rest as unknown as PublicKeyCredentialCreationOptions),25 challenge: base64urlToBytes(json.challenge),26 user: { ...(user as unknown as PublicKeyCredentialUserEntity), id: base64urlToBytes(String(user.id)) },27 ...(exclude ? { excludeCredentials: exclude } : {}),28 };29}3031/** Manual equivalent of PublicKeyCredential.parseRequestOptionsFromJSON. */32export function requestOptionsFromJSON(json: Json): PublicKeyCredentialRequestOptions {33 if (typeof json.challenge !== "string") throw new TypeError("invalid request options");34 const { allowCredentials, ...rest } = json;35 const allow = descriptors(allowCredentials);36 return {37 ...(rest as unknown as PublicKeyCredentialRequestOptions),38 challenge: base64urlToBytes(json.challenge),39 ...(allow ? { allowCredentials: allow } : {}),40 };41}4243interface CredentialLike {44 id: string;45 rawId: ArrayBuffer;46 type: string;47 authenticatorAttachment?: string | null;48 response: object;49 getClientExtensionResults?: () => unknown;50 toJSON?: () => unknown;51}5253/** Manual equivalent of PublicKeyCredential.prototype.toJSON for attestation and assertion responses. */54export function credentialToJSON(cred: CredentialLike, preferNative = true): Json {55 if (preferNative && typeof cred.toJSON === "function") {56 try {57 const native = cred.toJSON();58 if (isRecord(native) && isRecord(native.response)) return native;59 } catch {60 /* some password managers throw from toJSON: use the manual path */61 }62 }63 const r = cred.response as Partial<AuthenticatorAttestationResponse & AuthenticatorAssertionResponse>;64 const response: Json = {};65 if (r.clientDataJSON) response.clientDataJSON = bytesToBase64url(r.clientDataJSON);66 if (r.attestationObject) {67 response.attestationObject = bytesToBase64url(r.attestationObject);68 if (typeof r.getTransports === "function") response.transports = r.getTransports();69 if (typeof r.getPublicKeyAlgorithm === "function") response.publicKeyAlgorithm = r.getPublicKeyAlgorithm();70 const pk = typeof r.getPublicKey === "function" ? r.getPublicKey() : null;71 if (pk) response.publicKey = bytesToBase64url(pk);72 if (typeof r.getAuthenticatorData === "function") response.authenticatorData = bytesToBase64url(r.getAuthenticatorData());73 }74 if (r.authenticatorData && !r.attestationObject) response.authenticatorData = bytesToBase64url(r.authenticatorData);75 if (r.signature) response.signature = bytesToBase64url(r.signature);76 if (r.userHandle && r.userHandle.byteLength > 0) response.userHandle = bytesToBase64url(r.userHandle);77 const out: Json = {78 id: cred.id,79 rawId: bytesToBase64url(cred.rawId),80 type: cred.type,81 response,82 clientExtensionResults: (cred.getClientExtensionResults?.() ?? {}) as Json,83 };84 if (cred.authenticatorAttachment) out.authenticatorAttachment = cred.authenticatorAttachment;85 return out;86}8788type PKC = typeof PublicKeyCredential & {89 parseCreationOptionsFromJSON?: (o: unknown) => PublicKeyCredentialCreationOptions;90 parseRequestOptionsFromJSON?: (o: unknown) => PublicKeyCredentialRequestOptions;91 isConditionalMediationAvailable?: () => Promise<boolean>;92};93const pkc = (): PKC | undefined => (typeof PublicKeyCredential === "undefined" ? undefined : (PublicKeyCredential as PKC));9495export function webauthnSupported(): boolean {96 return typeof window !== "undefined" && !!pkc() && !!navigator.credentials;97}9899export async function conditionalMediationAvailable(): Promise<boolean> {100 try {101 return (await pkc()?.isConditionalMediationAvailable?.()) ?? false;102 } catch {103 return false;104 }105}106107export type WebAuthnFailure = "cancelled" | "unsupported" | "duplicate" | "security" | "unknown";108export class WebAuthnError extends Error {109 constructor(public readonly reason: WebAuthnFailure, cause?: unknown) {110 super(`webauthn_${reason}`);111 this.name = "WebAuthnError";112 this.cause = cause;113 }114}115function classify(e: unknown): WebAuthnError {116 const name = e instanceof Error ? e.name : "";117 if (name === "NotAllowedError" || name === "AbortError") return new WebAuthnError("cancelled", e);118 if (name === "InvalidStateError") return new WebAuthnError("duplicate", e);119 if (name === "SecurityError") return new WebAuthnError("security", e);120 if (name === "NotSupportedError") return new WebAuthnError("unsupported", e);121 return new WebAuthnError("unknown", e);122}123124/** Runs navigator.credentials.create with server options (`public_key` of WebAuthnChallenge). */125export async function createPasskey(publicKeyJson: Json): Promise<Json> {126 if (!webauthnSupported()) throw new WebAuthnError("unsupported");127 let publicKey: PublicKeyCredentialCreationOptions;128 try {129 publicKey = pkc()?.parseCreationOptionsFromJSON?.(publicKeyJson) ?? creationOptionsFromJSON(publicKeyJson);130 } catch {131 publicKey = creationOptionsFromJSON(publicKeyJson);132 }133 try {134 const cred = await navigator.credentials.create({ publicKey });135 if (!cred) throw new WebAuthnError("cancelled");136 return credentialToJSON(cred as unknown as CredentialLike);137 } catch (e) {138 throw e instanceof WebAuthnError ? e : classify(e);139 }140}141142/** Runs navigator.credentials.get. `conditional` uses autofill-assisted (conditional) mediation. */143export async function getPasskey(publicKeyJson: Json, opts: { conditional?: boolean; signal?: AbortSignal } = {}): Promise<Json> {144 if (!webauthnSupported()) throw new WebAuthnError("unsupported");145 let publicKey: PublicKeyCredentialRequestOptions;146 try {147 publicKey = pkc()?.parseRequestOptionsFromJSON?.(publicKeyJson) ?? requestOptionsFromJSON(publicKeyJson);148 } catch {149 publicKey = requestOptionsFromJSON(publicKeyJson);150 }151 try {152 const cred = await navigator.credentials.get({153 publicKey,154 ...(opts.conditional ? { mediation: "conditional" as CredentialMediationRequirement } : {}),155 ...(opts.signal ? { signal: opts.signal } : {}),156 });157 if (!cred) throw new WebAuthnError("cancelled");158 return credentialToJSON(cred as unknown as CredentialLike);159 } catch (e) {160 throw e instanceof WebAuthnError ? e : classify(e);161 }162}163