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