Open History to see the last commit
1// @effect-diagnostics globalTimers:off - Ceremonies settle inside IPC handlers, outside an Effect runtime.
2import type { IpcMainInvokeEvent, Session, WebContents, WebFrameMain } from "electron";
3import { app, BrowserWindow, dialog, webContents as electronWebContents } from "electron";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9
10import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
11import { PASSKEY_CREATE_CHANNEL, PASSKEY_GET_CHANNEL } from "./GuestProtocol.ts";
12import type { PasskeyBackend, PasskeyCeremonyContext } from "./PasskeyBackend.ts";
13import { macPasskeyBackend } from "./PasskeyBackendMac.ts";
14import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts";
15
16const PasskeyPackageMetadata = Schema.Struct({
17 t3codeWebAuthn: Schema.optional(
18 Schema.Struct({
19 touchIdKeychainAccessGroup: Schema.optional(Schema.String),
20 browserPasskeys: Schema.optional(Schema.Boolean),
21 }),
22 ),
23});
24const decodePasskeyPackageMetadata = Schema.decodeEffect(
25 Schema.fromJsonString(PasskeyPackageMetadata),
26);
27
28export class PreviewPasskeysConfigureError extends Schema.TaggedError<PreviewPasskeysConfigureError>()(
29 "PreviewPasskeysConfigureError",
30 {
31 keychainAccessGroup: Schema.String,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to enable Touch ID passkeys for the in-app browser (keychain group ${this.keychainAccessGroup}).`;
37 }
38}
39
40export class PreviewPasskeys extends Context.Service<
41 PreviewPasskeys,
42 {
43 readonly bridgeEnabled: boolean;
44 /** Runs after app ready. */
45 readonly configure: Effect.Effect<void>;
46 readonly installSessionHandlers: (session: Session) => void;
47 readonly attachGuest: (guest: WebContents) => () => void;
48 }
49>()("@t3tools/desktop/preview/Passkeys/PreviewPasskeys") {}
50
51const notAllowed: PasskeyCeremonyResult = { success: false, error: "NotAllowedError" };
52
53const accountLabel = (account: Electron.WebAuthnAccount) =>
54 account.displayName && account.name && account.displayName !== account.name
55 ? `${account.displayName} (${account.name})`
56 : (account.name ?? account.displayName ?? "Unnamed passkey");
57
58const ownerWindow = (frame: WebFrameMain | null) => {
59 const contents = frame ? electronWebContents.fromFrame(frame) : undefined;
60 const owner = contents?.hostWebContents ?? contents;
61 return owner ? BrowserWindow.fromWebContents(owner) : null;
62};
63
64const chooseAccount = async (details: Electron.SelectWebauthnAccountDetails) => {
65 const [onlyAccount] = details.accounts;
66 // The Touch ID prompt that follows already asks the user to confirm.
67 if (details.accounts.length === 1) return onlyAccount?.credentialId;
68 const options: Electron.MessageBoxOptions = {
69 type: "none",
70 message: "Choose a passkey",
71 detail: details.relyingPartyId,
72 buttons: [...details.accounts.map(accountLabel), "Cancel"],
73 cancelId: details.accounts.length,
74 defaultId: 0,
75 noLink: true,
76 };
77 const parent = ownerWindow(details.frame);
78 const { response } = parent
79 ? await dialog.showMessageBox(parent, options)
80 : await dialog.showMessageBox(options);
81 return details.accounts[response]?.credentialId;
82};
83
84const NATIVE_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
85const NATIVE_MAX_TIMEOUT_MS = 60 * 60 * 1000;
86
87// Mirrors the native layer's own clamp, plus a margin: it can leave a ceremony
88// unsettled, and the page must still get an answer.
89const ceremonyDeadline = (timeout: unknown) =>
90 (typeof timeout === "number" && timeout > 0
91 ? Math.min(timeout, NATIVE_MAX_TIMEOUT_MS)
92 : NATIVE_DEFAULT_TIMEOUT_MS) + 5_000;
93
94const withDeadline = (ceremony: Promise<PasskeyCeremonyResult>, milliseconds: number) => {
95 let timer: ReturnType<typeof setTimeout> | undefined;
96 const deadline = new Promise<PasskeyCeremonyResult>((resolve) => {
97 timer = setTimeout(() => resolve(notAllowed), milliseconds);
98 });
99 return Promise.race([ceremony, deadline]).finally(() => clearTimeout(timer));
100};
101
102// Secure contexts only: https, or http on this machine. Chromium also trusts
103// `*.localhost`, but the macOS layer refuses it, so it is turned away here
104// instead of failing deeper with a less useful error.
105const isTrustworthyOrigin = (origin: string) => {
106 if (!URL.canParse(origin)) return false;
107 const { protocol, hostname } = new URL(origin);
108 return (
109 protocol === "https:" ||
110 (protocol === "http:" &&
111 (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]"))
112 );
113};
114
115/**
116 * Windows needs none: Chromium already hands WebAuthn to Windows Hello there.
117 */
118const backendFor = (platform: NodeJS.Platform): PasskeyBackend | undefined =>
119 platform === "darwin" ? macPasskeyBackend : undefined;
120
121const make = Effect.gen(function* () {
122 const environment = yield* DesktopEnvironment.DesktopEnvironment;
123 const fileSystem = yield* FileSystem.FileSystem;
124
125 const metadata =
126 environment.platform === "darwin" && environment.isPackaged
127 ? yield* fileSystem
128 .readFileString(environment.path.join(environment.appRoot, "package.json"))
129 .pipe(
130 Effect.flatMap(decodePasskeyPackageMetadata),
131 Effect.map((parsed) => parsed.t3codeWebAuthn),
132 Effect.orElseSucceed(() => undefined),
133 )
134 : undefined;
135 const keychainAccessGroup = metadata?.touchIdKeychainAccessGroup;
136 const backend = metadata?.browserPasskeys === true ? backendFor(environment.platform) : undefined;
137 const bridgeEnabled = backend !== undefined;
138 const sessionsWithHandlers = new WeakSet<Session>();
139
140 return PreviewPasskeys.of({
141 bridgeEnabled,
142 configure: Effect.gen(function* () {
143 if (keychainAccessGroup === undefined) return;
144 yield* Effect.try({
145 try: () => app.configureWebAuthn({ touchID: { keychainAccessGroup } }),
146 catch: (cause) => new PreviewPasskeysConfigureError({ keychainAccessGroup, cause }),
147 }).pipe(Effect.catch((error) => Effect.logWarning(error.message, { cause: error.cause })));
148 }).pipe(Effect.withSpan("desktop.previewPasskeys.configure")),
149 installSessionHandlers: (session) => {
150 if (sessionsWithHandlers.has(session)) return;
151 sessionsWithHandlers.add(session);
152 session.on("select-webauthn-account", (_event, details, callback) => {
153 // The request stays pending until the callback runs, so it must run once.
154 void chooseAccount(details).then(
155 (credentialId) => callback(credentialId),
156 () => callback(),
157 );
158 });
159 },
160 attachGuest: (guest) => {
161 if (backend === undefined) return () => {};
162 let ceremonyPending = false;
163 const serve = async (
164 event: IpcMainInvokeEvent,
165 publicKey: { readonly timeout?: unknown } | undefined,
166 ceremony: (context: PasskeyCeremonyContext) => Promise<PasskeyCeremonyResult>,
167 ): Promise<PasskeyCeremonyResult> => {
168 // Only the guest's main frame runs the bridge preload.
169 const frame = event.senderFrame;
170 if (!frame || frame !== guest.mainFrame) return notAllowed;
171 // The page shares a JS world with the preload, so nothing it sends can
172 // be trusted for the origin. Read the committed origin before any await:
173 // the frame object outlives a navigation.
174 const origin = frame.origin;
175 if (!isTrustworthyOrigin(origin) || ceremonyPending || !guest.isFocused()) {
176 return notAllowed;
177 }
178 if (typeof publicKey !== "object" || publicKey === null) {
179 return { success: false, error: "TypeError" };
180 }
181 const host = guest.hostWebContents
182 ? BrowserWindow.fromWebContents(guest.hostWebContents)
183 : null;
184 if (!host || host.isDestroyed()) return notAllowed;
185
186 ceremonyPending = true;
187 try {
188 const result = await withDeadline(
189 ceremony({ origin, nativeWindowHandle: host.getNativeWindowHandle() }),
190 ceremonyDeadline(publicKey.timeout),
191 );
192 // A credential minted for a document that navigated away belongs to nobody.
193 const sameDocument =
194 !frame.isDestroyed() && frame === guest.mainFrame && frame.origin === origin;
195 return sameDocument ? result : notAllowed;
196 } catch {
197 return notAllowed;
198 } finally {
199 ceremonyPending = false;
200 }
201 };
202 const detach = () => {
203 guest.ipc.removeHandler(PASSKEY_CREATE_CHANNEL);
204 guest.ipc.removeHandler(PASSKEY_GET_CHANNEL);
205 };
206 detach();
207 guest.ipc.handle(
208 PASSKEY_CREATE_CHANNEL,
209 (event, publicKey: PublicKeyCredentialCreationOptions) =>
210 serve(event, publicKey, (context) => backend.create(publicKey, context)),
211 );
212 guest.ipc.handle(PASSKEY_GET_CHANNEL, (event, publicKey: PublicKeyCredentialRequestOptions) =>
213 serve(event, publicKey, (context) => backend.get(publicKey, context)),
214 );
215 return detach;
216 },
217 });
218}).pipe(Effect.withSpan("PreviewPasskeys.make"));
219
220export const layer = Layer.effect(PreviewPasskeys, make);