Open History to see the last commit
1import { createClerkBridge } from "@clerk/electron";
2import { storage } from "@clerk/electron/storage";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9
10import { codexAuthDeliveryUrl, readCodexAuthHandoff } from "@t3tools/shared/codexAuthHandoff";
11import { receiveCodexAuthCallback, CodexAuthCallbackError } from "./CodexAuthCallback.ts";
12import * as ElectronShell from "../electron/ElectronShell.ts";
13import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
14import { HostProcessArguments } from "@t3tools/shared/hostProcess";
15import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
16import * as ElectronApp from "../electron/ElectronApp.ts";
17import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
18import * as ElectronWindow from "../electron/ElectronWindow.ts";
19import * as DesktopUserData from "./DesktopUserData.ts";
20import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21
22declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
23
24export class DesktopClerkBridgeInitializationError extends Schema.TaggedError<DesktopClerkBridgeInitializationError>()(
25 "DesktopClerkBridgeInitializationError",
26 {
27 stateDir: Schema.String,
28 isDevelopment: Schema.Boolean,
29 cause: Schema.Defect(),
30 },
31) {
32 override get message(): string {
33 return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
34 }
35}
36
37export class DesktopClerkBridgeCleanupError extends Schema.TaggedError<DesktopClerkBridgeCleanupError>()(
38 "DesktopClerkBridgeCleanupError",
39 {
40 stateDir: Schema.String,
41 isDevelopment: Schema.Boolean,
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
47 }
48}
49
50export class DesktopClerk extends Context.Service<
51 DesktopClerk,
52 {
53 readonly configure: Effect.Effect<
54 void,
55 never,
56 ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
57 >;
58 }
59>()("@t3tools/desktop/app/DesktopClerk") {}
60
61function resolveDesktopClerkFrontendApiHostname(
62 publishableKey: string | undefined,
63): string | undefined {
64 const normalizedKey = publishableKey?.trim();
65 if (!normalizedKey) return undefined;
66
67 try {
68 return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
69 } catch {
70 return undefined;
71 }
72}
73
74export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
75 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
76 ? undefined
77 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
78);
79
80function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
81 return createClerkBridge({
82 storage: storage({ path: stateDir }),
83 passkeys: true,
84 renderer: {
85 scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
86 host: ElectronProtocol.DESKTOP_HOST,
87 },
88 });
89}
90
91/** @public Service construction is part of the canonical Effect module API. */
92export const make = Effect.gen(function* () {
93 const environment = yield* DesktopEnvironment.DesktopEnvironment;
94 const electronApp = yield* ElectronApp.ElectronApp;
95 const shell = yield* ElectronShell.ElectronShell;
96
97 // The SDK bridge acquires Electron's profile-scoped single-instance lock.
98 // Must not yield: the bridge registers a scheme Electron rejects once ready.
99 const userDataPath = yield* DesktopUserData.resolveUserDataPath(environment);
100 yield* electronApp.setPath("userData", userDataPath);
101
102 const bridge = yield* Effect.acquireRelease(
103 Effect.try({
104 try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
105 catch: (cause) =>
106 new DesktopClerkBridgeInitializationError({
107 stateDir: environment.stateDir,
108 isDevelopment: environment.isDevelopment,
109 cause,
110 }),
111 }),
112 (bridge) =>
113 Effect.try({
114 try: () => bridge.cleanup(),
115 catch: (cause) =>
116 new DesktopClerkBridgeCleanupError({
117 stateDir: environment.stateDir,
118 isDevelopment: environment.isDevelopment,
119 cause,
120 }),
121 }).pipe(Effect.orDie),
122 );
123
124 return DesktopClerk.of({
125 configure: Effect.gen(function* () {
126 const electronApp = yield* ElectronApp.ElectronApp;
127 const electronWindow = yield* ElectronWindow.ElectronWindow;
128 const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
129 const runPromise = Effect.runPromiseWith(context);
130
131 // The SDK bridge holds Electron's single-instance lock (acquired at
132 // bridge creation) so OAuth deep-link callbacks on Windows/Linux are
133 // forwarded to the running app. In a secondary instance the bridge has
134 // already begun quitting the app; app.quit() is asynchronous, so stop
135 // bootstrap here before whenReady can fire.
136 if (!bridge.isPrimaryInstance) {
137 yield* electronApp.quit;
138 return yield* Effect.interrupt;
139 }
140
141 const startProviderAuthHandoff = (value: string | undefined) => {
142 if (!value) return false;
143 const request = readCodexAuthHandoff(value, environment.isDevelopment);
144 if (!request) return false;
145 void runPromise(
146 Effect.gen(function* () {
147 yield* electronApp.whenReady;
148 yield* Effect.tryPromise({
149 try: () =>
150 receiveCodexAuthCallback(
151 request.authorizationUrl,
152 (url) => runPromise(shell.openExternal(url)),
153 (callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl),
154 ),
155 catch: () =>
156 new CodexAuthCallbackError({
157 detail:
158 "Could not receive hosted web ChatGPT sign-in. Retry or use the redirect URL in the web app.",
159 }),
160 });
161 }).pipe(
162 Effect.catch(() => Effect.logWarning("Could not complete ChatGPT desktop handoff.")),
163 ),
164 );
165 return true;
166 };
167 const resumeProviderAuth = (value: string | undefined) => {
168 const destination = providerAuthReturnUrl(value);
169 const expectedOrigin = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}://app`;
170 if (!destination?.startsWith(`${expectedOrigin}/`)) return false;
171 void runPromise(
172 Effect.gen(function* () {
173 const mainWindow = yield* electronWindow.currentMainOrFirst;
174 if (Option.isNone(mainWindow)) return;
175 yield* Effect.promise(() => mainWindow.value.loadURL(destination));
176 yield* electronWindow.reveal(mainWindow.value);
177 }).pipe(
178 Effect.catchCause((cause) =>
179 Effect.logWarning("Could not return to provider setup", cause),
180 ),
181 ),
182 );
183 return true;
184 };
185 const args = yield* HostProcessArguments;
186 args.some((value) => startProviderAuthHandoff(value));
187 yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
188 if (startProviderAuthHandoff(url) || resumeProviderAuth(url)) event.preventDefault();
189 });
190 yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
191 if (argv?.some((value) => startProviderAuthHandoff(value) || resumeProviderAuth(value)))
192 return;
193 void runPromise(
194 Effect.gen(function* () {
195 const mainWindow = yield* electronWindow.currentMainOrFirst;
196 if (Option.isSome(mainWindow)) yield* electronWindow.reveal(mainWindow.value);
197 }),
198 );
199 });
200 }).pipe(Effect.withSpan("desktop.clerk.configure")),
201 });
202});
203
204export const layer = Layer.effect(DesktopClerk, make);