Skip to content

Commit 979ad00

Browse files
refactor(desktop): passkeys run through a per-platform backend
The bridge keeps everything platform-neutral (which frame may ask, focus, one ceremony at a time, the deadline, dropping results for a page that navigated away). PasskeyBackend is the seam a platform implements; macOS's electron-webauthn code moves to PasskeyBackendMac, so Linux and Windows can add their own without touching the bridge. Also from review: - a non-array pubKeyCredParams is a TypeError, not a cue to pick ES256 - an assertion for a credential outside the site's allowCredentials is refused; electron-webauthn applies the list to platform passkeys only - *.localhost is refused up front, since the macOS layer rejects it anyway Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f0e829a commit 979ad00

4 files changed

Lines changed: 189 additions & 76 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
2+
3+
/** What the shared bridge has already checked before a backend runs a ceremony. */
4+
export interface PasskeyCeremonyContext {
5+
/** The committed origin of the frame that asked; never the page's own claim. */
6+
readonly origin: string;
7+
/** The window the system sheet attaches to. */
8+
readonly nativeWindowHandle: Buffer;
9+
}
10+
11+
/**
12+
* One platform's way to create and use passkeys for a preview page. The
13+
* bridge in `Passkeys.ts` owns everything platform-neutral: which frame may
14+
* ask, focus, one ceremony at a time, the deadline, and dropping results for
15+
* a page that navigated away. A backend only talks to the platform.
16+
*/
17+
export interface PasskeyBackend {
18+
readonly create: (
19+
publicKey: PublicKeyCredentialCreationOptions,
20+
context: PasskeyCeremonyContext,
21+
) => Promise<PasskeyCeremonyResult>;
22+
readonly get: (
23+
publicKey: PublicKeyCredentialRequestOptions,
24+
context: PasskeyCeremonyContext,
25+
) => Promise<PasskeyCeremonyResult>;
26+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import { getPublicSuffix } from "tldts";
2+
3+
import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
4+
import { authenticatorDataFromAttestation } from "./PasskeyAttestation.ts";
5+
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
6+
7+
const ES256 = -7;
8+
9+
// WebAuthn rejects RP IDs that are public suffixes, private registries
10+
// included, so one github.io site cannot mint passkeys for every other one.
11+
const isPublicSuffix = (domain: string) =>
12+
domain !== "localhost" && getPublicSuffix(domain, { allowPrivateDomains: true }) === domain;
13+
14+
// Loaded only once a ceremony runs: the module and its native addon ship on macOS alone.
15+
const nativeOptions = async (context: PasskeyCeremonyContext) => ({
16+
webauthn: await import("electron-webauthn"),
17+
options: {
18+
currentOrigin: context.origin,
19+
topFrameOrigin: context.origin,
20+
nativeWindowHandle: context.nativeWindowHandle,
21+
isPublicSuffix,
22+
},
23+
});
24+
25+
const isBufferSource = (value: unknown): value is BufferSource =>
26+
value instanceof ArrayBuffer || ArrayBuffer.isView(value);
27+
28+
const toBase64Url = (value: BufferSource) =>
29+
Buffer.from(
30+
ArrayBuffer.isView(value)
31+
? new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
32+
: new Uint8Array(value),
33+
).toString("base64url");
34+
35+
/**
36+
* macOS passkeys through AuthenticationServices (`electron-webauthn`): the
37+
* system sheet offers iCloud Keychain, password managers, phones, and security
38+
* keys. Needs Apple's managed browser entitlement in the signed build.
39+
*/
40+
export const macPasskeyBackend: PasskeyBackend = {
41+
create: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
42+
// The native layer only converts P-256 keys and never settles for any
43+
// other algorithm, so ES256 is the only one it may negotiate.
44+
const params: unknown = publicKey.pubKeyCredParams;
45+
if (params !== undefined && !Array.isArray(params))
46+
return { success: false, error: "TypeError" };
47+
const allowsEs256 =
48+
params === undefined ||
49+
params.length === 0 ||
50+
params.some(
51+
(param: unknown) =>
52+
typeof param === "object" && param !== null && "alg" in param && param.alg === ES256,
53+
);
54+
if (!allowsEs256) return { success: false, error: "NotSupportedError" };
55+
const { webauthn, options } = await nativeOptions(context);
56+
const result = await webauthn.createCredential(
57+
{ ...publicKey, pubKeyCredParams: [{ type: "public-key", alg: ES256 }] },
58+
options,
59+
);
60+
if (!result.success) return { success: false, error: result.error };
61+
// The native layer reports parsed authenticator data as JSON and claims
62+
// every credential is a synced platform passkey; neither is reliable.
63+
const authData = authenticatorDataFromAttestation(
64+
Buffer.from(result.data.attestationObject, "base64url"),
65+
);
66+
return {
67+
success: true,
68+
data: {
69+
...result.data,
70+
authData: authData ? Buffer.from(authData).toString("base64url") : "",
71+
transports: [],
72+
},
73+
};
74+
},
75+
get: async (publicKey, context): Promise<PasskeyCeremonyResult> => {
76+
const { webauthn, options } = await nativeOptions(context);
77+
// WebAuthn defaults the RP ID to the caller's host; the native layer requires it.
78+
const result = await webauthn.getCredential(
79+
{ ...publicKey, rpId: publicKey.rpId ?? new URL(context.origin).hostname },
80+
options,
81+
);
82+
if (!result.success) return { success: false, error: result.error };
83+
// The native layer applies the site's allow list to platform passkeys only,
84+
// so a security key can answer with a credential the site did not ask for.
85+
const allowed = (Array.isArray(publicKey.allowCredentials) ? publicKey.allowCredentials : [])
86+
.filter((credential) => credential?.type === "public-key" && isBufferSource(credential.id))
87+
.map((credential) => toBase64Url(credential.id));
88+
if (allowed.length > 0 && !allowed.includes(result.data.credentialId)) {
89+
return { success: false, error: "NotAllowedError" };
90+
}
91+
return result;
92+
},
93+
};

‎apps/desktop/src/preview/Passkeys.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,53 @@ describe("PreviewPasskeys", () => {
177177
});
178178
assert.deepStrictEqual(unsupported, { success: false, error: "NotSupportedError" });
179179
assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
180+
181+
// A malformed algorithm list is the page's error, not a cue to pick ES256.
182+
const malformed = yield* call(PASSKEY_CREATE_CHANNEL, {
183+
...publicKey,
184+
pubKeyCredParams: { type: "public-key", alg: -7 },
185+
});
186+
assert.deepStrictEqual(malformed, { success: false, error: "TypeError" });
187+
assert.strictEqual(webauthn.createCredential.mock.calls.length, 1);
188+
}).pipe(Effect.provide(bridgeLayer)),
189+
);
190+
191+
it.effect("answers only with a credential the site allowed", () =>
192+
Effect.gen(function* () {
193+
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
194+
const { guest, call } = makeGuest();
195+
passkeys.attachGuest(guest);
196+
const assertion = (credentialId: string) => ({
197+
success: true,
198+
data: {
199+
credentialId,
200+
clientDataJSON: "Ag",
201+
authenticatorData: "Aw",
202+
signature: "BA",
203+
userHandle: "BQ",
204+
},
205+
});
206+
const publicKey = {
207+
challenge: new Uint8Array([1]),
208+
rpId: "example.com",
209+
allowCredentials: [{ type: "public-key", id: new Uint8Array([1]) }],
210+
};
211+
212+
// macOS applies the allow list to passkeys but not to security keys.
213+
webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
214+
const other = yield* call(PASSKEY_GET_CHANNEL, publicKey);
215+
assert.deepStrictEqual(other, { success: false, error: "NotAllowedError" });
216+
217+
webauthn.getCredential.mockResolvedValueOnce(assertion("AQ"));
218+
assert.deepInclude(yield* call(PASSKEY_GET_CHANNEL, publicKey), { success: true });
219+
220+
// With no allow list, any of the site's credentials will do.
221+
webauthn.getCredential.mockResolvedValueOnce(assertion("Ag"));
222+
const discoverable = yield* call(PASSKEY_GET_CHANNEL, {
223+
challenge: new Uint8Array([1]),
224+
rpId: "example.com",
225+
});
226+
assert.deepInclude(discoverable, { success: true });
180227
}).pipe(Effect.provide(bridgeLayer)),
181228
);
182229

@@ -189,6 +236,10 @@ describe("PreviewPasskeys", () => {
189236
const lan = makeGuest("http://192.168.1.5:3000");
190237
passkeys.attachGuest(lan.guest);
191238
assert.deepStrictEqual(yield* lan.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
239+
// macOS refuses `*.localhost`, so the page hears no rather than a native error.
240+
const subdomain = makeGuest("http://app.localhost:3000");
241+
passkeys.attachGuest(subdomain.guest);
242+
assert.deepStrictEqual(yield* subdomain.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
192243

193244
const page = makeGuest();
194245
passkeys.attachGuest(page.guest);

‎apps/desktop/src/preview/Passkeys.ts‎

Lines changed: 19 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
// @effect-diagnostics globalTimers:off - Ceremonies settle inside IPC handlers, outside an Effect runtime.
22
import type { IpcMainInvokeEvent, Session, WebContents, WebFrameMain } from "electron";
33
import { app, BrowserWindow, dialog, webContents as electronWebContents } from "electron";
4-
import type { WebauthnGetRequestOptions } from "electron-webauthn";
54
import * as Context from "effect/Context";
65
import * as Effect from "effect/Effect";
76
import * as FileSystem from "effect/FileSystem";
87
import * as Layer from "effect/Layer";
98
import * as Schema from "effect/Schema";
10-
import { getPublicSuffix } from "tldts";
119

1210
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
1311
import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
14-
import { authenticatorDataFromAttestation } from "./PasskeyAttestation.ts";
12+
import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
13+
import { macPasskeyBackend } from "./PasskeyBackendMac.ts";
1514
import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
1615

1716
const PasskeyPackageMetadata = Schema.Struct({
@@ -69,11 +68,6 @@ export class PreviewPasskeys extends Context.Service<
6968

7069
const notAllowed: PasskeyCeremonyResult = { success: false, error: "NotAllowedError" };
7170

72-
// WebAuthn rejects RP IDs that are public suffixes, private registries
73-
// included, so one github.io site cannot mint passkeys for every other one.
74-
const isPublicSuffix = (domain: string) =>
75-
domain !== "localhost" && getPublicSuffix(domain, { allowPrivateDomains: true }) === domain;
76-
7771
const accountLabel = (account: Electron.WebAuthnAccount) =>
7872
account.displayName && account.name && account.displayName !== account.name
7973
? `${account.displayName} (${account.name})`
@@ -105,13 +99,6 @@ const chooseAccount = async (details: Electron.SelectWebauthnAccountDetails) =>
10599
return details.accounts[response]?.credentialId;
106100
};
107101

108-
type WebAuthn = typeof import("electron-webauthn");
109-
type Ceremony = (
110-
webauthn: WebAuthn,
111-
options: WebauthnGetRequestOptions,
112-
) => Promise<PasskeyCeremonyResult>;
113-
114-
const ES256 = -7;
115102
const NATIVE_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
116103
const NATIVE_MAX_TIMEOUT_MS = 60 * 60 * 1000;
117104

@@ -130,64 +117,25 @@ const withDeadline = (ceremony: Promise<PasskeyCeremonyResult>, milliseconds: nu
130117
return Promise.race([ceremony, deadline]).finally(() => clearTimeout(timer));
131118
};
132119

133-
// Secure contexts only, as in Chromium: https, or http on this machine.
120+
// Secure contexts only: https, or http on this machine. Chromium also trusts
121+
// `*.localhost`, but the macOS layer refuses it, so it is turned away here
122+
// instead of failing deeper with a less useful error.
134123
const isTrustworthyOrigin = (origin: string) => {
135124
if (!URL.canParse(origin)) return false;
136125
const { protocol, hostname } = new URL(origin);
137126
return (
138127
protocol === "https:" ||
139128
(protocol === "http:" &&
140-
(hostname === "localhost" ||
141-
hostname.endsWith(".localhost") ||
142-
hostname === "127.0.0.1" ||
143-
hostname === "[::1]"))
129+
(hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]"))
144130
);
145131
};
146132

147-
const createCeremony =
148-
(publicKey: PublicKeyCredentialCreationOptions): Ceremony =>
149-
async (webauthn, options) => {
150-
// The native layer only converts P-256 keys and never settles for any
151-
// other algorithm, so ES256 is the only one it may negotiate.
152-
const params: unknown = publicKey.pubKeyCredParams;
153-
const allowsEs256 =
154-
!Array.isArray(params) ||
155-
params.length === 0 ||
156-
params.some(
157-
(param: unknown) =>
158-
typeof param === "object" && param !== null && "alg" in param && param.alg === ES256,
159-
);
160-
if (!allowsEs256) return { success: false, error: "NotSupportedError" };
161-
const result = await webauthn.createCredential(
162-
{ ...publicKey, pubKeyCredParams: [{ type: "public-key", alg: ES256 }] },
163-
options,
164-
);
165-
if (!result.success) return { success: false, error: result.error };
166-
// The native layer reports parsed authenticator data as JSON and claims
167-
// every credential is a synced platform passkey; neither is reliable.
168-
const authData = authenticatorDataFromAttestation(
169-
Buffer.from(result.data.attestationObject, "base64url"),
170-
);
171-
return {
172-
success: true,
173-
data: {
174-
...result.data,
175-
authData: authData ? Buffer.from(authData).toString("base64url") : "",
176-
transports: [],
177-
},
178-
};
179-
};
180-
181-
const getCeremony =
182-
(publicKey: PublicKeyCredentialRequestOptions, origin: string): Ceremony =>
183-
async (webauthn, options) => {
184-
// WebAuthn defaults the RP ID to the caller's host; the native layer requires it.
185-
const result = await webauthn.getCredential(
186-
{ ...publicKey, rpId: publicKey.rpId ?? new URL(origin).hostname },
187-
options,
188-
);
189-
return result.success ? result : { success: false, error: result.error };
190-
};
133+
/**
134+
* The platform that serves preview pages' passkey ceremonies, or none. Windows
135+
* needs none: Chromium already hands WebAuthn to Windows Hello there.
136+
*/
137+
const backendFor = (platform: NodeJS.Platform): PasskeyBackend | undefined =>
138+
platform === "darwin" ? macPasskeyBackend : undefined;
191139

192140
const make = Effect.gen(function* () {
193141
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -204,7 +152,8 @@ const make = Effect.gen(function* () {
204152
)
205153
: undefined;
206154
const keychainAccessGroup = metadata?.touchIdKeychainAccessGroup;
207-
const bridgeEnabled = metadata?.browserPasskeys === true;
155+
const backend = metadata?.browserPasskeys === true ? backendFor(environment.platform) : undefined;
156+
const bridgeEnabled = backend !== undefined;
208157
const sessionsWithHandlers = new WeakSet<Session>();
209158

210159
return PreviewPasskeys.of({
@@ -228,12 +177,12 @@ const make = Effect.gen(function* () {
228177
});
229178
},
230179
attachGuest: (guest) => {
231-
if (!bridgeEnabled) return () => {};
180+
if (backend === undefined) return () => {};
232181
let ceremonyPending = false;
233182
const serve = async (
234183
event: IpcMainInvokeEvent,
235184
publicKey: { readonly timeout?: unknown } | undefined,
236-
ceremony: (origin: string) => Ceremony,
185+
ceremony: (context: PasskeyCeremonyContext) => Promise<PasskeyCeremonyResult>,
237186
): Promise<PasskeyCeremonyResult> => {
238187
// Only the guest's main frame runs the bridge preload.
239188
const frame = event.senderFrame;
@@ -256,14 +205,8 @@ const make = Effect.gen(function* () {
256205

257206
ceremonyPending = true;
258207
try {
259-
const webauthn = await import("electron-webauthn");
260208
const result = await withDeadline(
261-
ceremony(origin)(webauthn, {
262-
currentOrigin: origin,
263-
topFrameOrigin: origin,
264-
nativeWindowHandle: host.getNativeWindowHandle(),
265-
isPublicSuffix,
266-
}),
209+
ceremony({ origin, nativeWindowHandle: host.getNativeWindowHandle() }),
267210
ceremonyDeadline(publicKey.timeout),
268211
);
269212
// A credential minted for a document that navigated away belongs to nobody.
@@ -286,10 +229,10 @@ const make = Effect.gen(function* () {
286229
guest.ipc.handle(
287230
PASSKEY_CREATE_CHANNEL,
288231
(event, publicKey: PublicKeyCredentialCreationOptions) =>
289-
serve(event, publicKey, () => createCeremony(publicKey)),
232+
serve(event, publicKey, (context) => backend.create(publicKey, context)),
290233
);
291234
guest.ipc.handle(PASSKEY_GET_CHANNEL, (event, publicKey: PublicKeyCredentialRequestOptions) =>
292-
serve(event, publicKey, (origin) => getCeremony(publicKey, origin)),
235+
serve(event, publicKey, (context) => backend.get(publicKey, context)),
293236
);
294237
return detach;
295238
},

0 commit comments

Comments
 (0)