Open History to see the last commit
1import type { CreateCredentialResult, GetCredentialResult } from "electron-webauthn";
2
3import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
4
5export type PasskeyCeremonyResult =
6 | Extract<CreateCredentialResult, { success: true }>
7 | Extract<GetCredentialResult, { success: true }>
8 | { readonly success: false; readonly error: string };
9
10type PasskeyChannel = typeof PASSKEY_CREATE_CHANNEL | typeof PASSKEY_GET_CHANNEL;
11// Credential Management Level 1 added `mediation` to creation requests.
12type CreationOptions = CredentialCreationOptions & {
13 readonly mediation?: CredentialMediationRequirement;
14};
15type InvokePasskeyCeremony = (channel: PasskeyChannel, publicKey: unknown) => Promise<unknown>;
16
17const NOT_ALLOWED_MESSAGE =
18 "The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client.";
19const DOM_EXCEPTION_NAMES = new Set([
20 "AbortError",
21 "InvalidStateError",
22 "NotAllowedError",
23 "NotSupportedError",
24 "SecurityError",
25]);
26
27const fromBase64Url = (value: string) => {
28 const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
29 const binary = atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "="));
30 return Uint8Array.from(binary, (character) => character.charCodeAt(0)).buffer;
31};
32
33const toBase64Url = (buffer: ArrayBuffer) =>
34 btoa(String.fromCharCode(...new Uint8Array(buffer)))
35 .replaceAll("+", "-")
36 .replaceAll("/", "_")
37 .replace(/=+$/u, "");
38
39const ceremonyError = (name: string) =>
40 name === "TypeError"
41 ? new TypeError("The passkey request options are invalid.")
42 : new DOMException(
43 NOT_ALLOWED_MESSAGE,
44 DOM_EXCEPTION_NAMES.has(name) ? name : "NotAllowedError",
45 );
46
47/**
48 * Chromium ignores members it does not know, so functions and other uncloneable
49 * values drop out here instead of failing the whole ceremony.
50 */
51const toCloneable = (value: unknown): unknown => {
52 if (value instanceof ArrayBuffer) return value.slice(0);
53 if (ArrayBuffer.isView(value)) {
54 return new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice();
55 }
56 if (Array.isArray(value)) return value.map(toCloneable);
57 if (typeof value === "object" && value !== null) {
58 return Object.fromEntries(
59 Object.entries(value).flatMap(([key, member]) =>
60 typeof member === "function" || member === undefined ? [] : [[key, toCloneable(member)]],
61 ),
62 );
63 }
64 return value;
65};
66
67// The objects below borrow the native prototypes so `instanceof` checks pass.
68// Their own properties shadow the native getters, which only work on objects
69// Chromium created itself.
70const withValues = <T extends object>(target: T, values: Record<string, unknown>) => {
71 for (const [key, value] of Object.entries(values)) {
72 Object.defineProperty(target, key, { value, enumerable: true, configurable: true });
73 }
74 return target;
75};
76
77const prfOutputs = (prf: {
78 readonly enabled?: boolean;
79 readonly results?: { readonly first?: string; readonly second?: string };
80}): AuthenticationExtensionsPRFOutputs => {
81 const first = prf.results?.first;
82 const second = prf.results?.second;
83 return {
84 ...(prf.enabled === undefined ? {} : { enabled: prf.enabled }),
85 ...(first === undefined
86 ? {}
87 : {
88 results: {
89 first: fromBase64Url(first),
90 ...(second === undefined ? {} : { second: fromBase64Url(second) }),
91 },
92 }),
93 };
94};
95
96const extensionResultsJson = (results: AuthenticationExtensionsClientOutputs) =>
97 JSON.parse(
98 JSON.stringify(results, (_key, value: unknown) =>
99 value instanceof ArrayBuffer ? toBase64Url(value) : value,
100 ),
101 ) as unknown;
102
103const makeCredential = (input: {
104 readonly id: string;
105 readonly authenticatorAttachment: AuthenticatorAttachment | null;
106 readonly response: AuthenticatorResponse;
107 readonly responseJson: Record<string, unknown>;
108 readonly extensionResults: AuthenticationExtensionsClientOutputs;
109}) =>
110 withValues(Object.create(PublicKeyCredential.prototype) as PublicKeyCredential, {
111 id: input.id,
112 rawId: fromBase64Url(input.id),
113 type: "public-key",
114 authenticatorAttachment: input.authenticatorAttachment,
115 response: input.response,
116 getClientExtensionResults: () => input.extensionResults,
117 toJSON: () => ({
118 id: input.id,
119 rawId: input.id,
120 type: "public-key",
121 ...(input.authenticatorAttachment === null
122 ? {}
123 : { authenticatorAttachment: input.authenticatorAttachment }),
124 response: input.responseJson,
125 clientExtensionResults: extensionResultsJson(input.extensionResults),
126 }),
127 });
128
129const credentialFromCreateResult = (
130 data: Extract<CreateCredentialResult, { success: true }>["data"],
131) => {
132 const transports = [...data.transports];
133 const publicKey = data.publicKey.length > 0 ? data.publicKey : null;
134 const extensionResults: AuthenticationExtensionsClientOutputs = {
135 ...(data.extensions.credProps ? { credProps: { ...data.extensions.credProps } } : {}),
136 ...(data.extensions.prf ? { prf: prfOutputs(data.extensions.prf) } : {}),
137 ...(data.extensions.largeBlob ? { largeBlob: { ...data.extensions.largeBlob } } : {}),
138 };
139 return makeCredential({
140 id: data.credentialId,
141 // The native layer cannot tell a synced passkey from a security key.
142 authenticatorAttachment: null,
143 response: withValues(
144 Object.create(AuthenticatorAttestationResponse.prototype) as AuthenticatorAttestationResponse,
145 {
146 clientDataJSON: fromBase64Url(data.clientDataJSON),
147 attestationObject: fromBase64Url(data.attestationObject),
148 getTransports: () => [...transports],
149 getAuthenticatorData: () => fromBase64Url(data.authData),
150 getPublicKey: () => (publicKey === null ? null : fromBase64Url(publicKey)),
151 getPublicKeyAlgorithm: () => data.publicKeyAlgorithm,
152 },
153 ),
154 responseJson: {
155 clientDataJSON: data.clientDataJSON,
156 attestationObject: data.attestationObject,
157 authenticatorData: data.authData,
158 transports,
159 ...(publicKey === null ? {} : { publicKey }),
160 publicKeyAlgorithm: data.publicKeyAlgorithm,
161 },
162 extensionResults,
163 });
164};
165
166const credentialFromGetResult = (data: Extract<GetCredentialResult, { success: true }>["data"]) => {
167 const userHandle = data.userHandle.length > 0 ? data.userHandle : null;
168 const { prf, largeBlob } = data.extensions ?? {};
169 const extensionResults: AuthenticationExtensionsClientOutputs = {
170 ...(prf ? { prf: prfOutputs(prf) } : {}),
171 ...(largeBlob
172 ? {
173 largeBlob: {
174 ...(largeBlob.blob === undefined ? {} : { blob: fromBase64Url(largeBlob.blob) }),
175 ...(largeBlob.written === undefined ? {} : { written: largeBlob.written }),
176 },
177 }
178 : {}),
179 };
180 return makeCredential({
181 id: data.credentialId,
182 authenticatorAttachment: null,
183 response: withValues(
184 Object.create(AuthenticatorAssertionResponse.prototype) as AuthenticatorAssertionResponse,
185 {
186 clientDataJSON: fromBase64Url(data.clientDataJSON),
187 authenticatorData: fromBase64Url(data.authenticatorData),
188 signature: fromBase64Url(data.signature),
189 userHandle: userHandle === null ? null : fromBase64Url(userHandle),
190 },
191 ),
192 responseJson: {
193 clientDataJSON: data.clientDataJSON,
194 authenticatorData: data.authenticatorData,
195 signature: data.signature,
196 ...(userHandle === null ? {} : { userHandle }),
197 },
198 extensionResults,
199 });
200};
201
202const abortReason = (signal: AbortSignal) =>
203 signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
204
205/**
206 * Conditional (autofill and automatic upgrade) requests stay native: the system
207 * sheet is modal and must not open on its own.
208 */
209export function installPasskeyBridge(invoke: InvokePasskeyCeremony) {
210 if (typeof CredentialsContainer === "undefined" || typeof PublicKeyCredential === "undefined") {
211 return;
212 }
213 const run = async (
214 channel: PasskeyChannel,
215 publicKey: unknown,
216 signal: AbortSignal | undefined,
217 ): Promise<PublicKeyCredential> => {
218 if (signal?.aborted) throw abortReason(signal);
219 const ceremony = invoke(channel, toCloneable(publicKey)).then(
220 (value) => {
221 const result = value as PasskeyCeremonyResult;
222 if (!result.success) throw ceremonyError(result.error);
223 return "attestationObject" in result.data
224 ? credentialFromCreateResult(result.data)
225 : credentialFromGetResult(result.data);
226 },
227 (error: unknown) => {
228 throw error instanceof DOMException || error instanceof TypeError
229 ? error
230 : ceremonyError("NotAllowedError");
231 },
232 );
233 if (!signal) return ceremony;
234 return new Promise((resolve, reject) => {
235 const onAbort = () => reject(abortReason(signal));
236 signal.addEventListener("abort", onAbort, { once: true });
237 ceremony.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
238 });
239 };
240
241 const container = CredentialsContainer.prototype;
242 const nativeCreate = container.create;
243 const nativeGet = container.get;
244 const define = (target: object, key: string, value: unknown) =>
245 Object.defineProperty(target, key, { value, configurable: true, writable: true });
246
247 define(
248 container,
249 "create",
250 function create(this: CredentialsContainer, options?: CreationOptions) {
251 return options?.publicKey && options.mediation !== "conditional"
252 ? run(PASSKEY_CREATE_CHANNEL, options.publicKey, options.signal)
253 : Reflect.apply(nativeCreate, this, [options]);
254 },
255 );
256 define(
257 container,
258 "get",
259 function get(this: CredentialsContainer, options?: CredentialRequestOptions) {
260 return options?.publicKey && options.mediation !== "conditional"
261 ? run(PASSKEY_GET_CHANNEL, options.publicKey, options.signal)
262 : Reflect.apply(nativeGet, this, [options]);
263 },
264 );
265
266 define(PublicKeyCredential, "isUserVerifyingPlatformAuthenticatorAvailable", async () => true);
267 define(PublicKeyCredential, "isConditionalMediationAvailable", async () => false);
268 const nativeCapabilities = PublicKeyCredential.getClientCapabilities;
269 if (typeof nativeCapabilities === "function") {
270 define(PublicKeyCredential, "getClientCapabilities", async () => ({
271 ...(await Reflect.apply(nativeCapabilities, PublicKeyCredential, [])),
272 conditionalCreate: false,
273 conditionalGet: false,
274 hybridTransport: true,
275 passkeyPlatformAuthenticator: true,
276 userVerifyingPlatformAuthenticator: true,
277 }));
278 }
279}