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