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 { promptLinkAppPath } from "@t3tools/shared/promptLinks";
16import { readPairingAppLink } from "@t3tools/shared/remote";
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
19import * as ElectronApp from "../electron/ElectronApp.ts";
20import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
21import * as ElectronWindow from "../electron/ElectronWindow.ts";
22import * as DesktopUserData from "./DesktopUserData.ts";
23import * as DesktopEnvironment from "./DesktopEnvironment.ts";
24import * as DesktopWebLinks from "./DesktopWebLinks.ts";
25
26declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
27
28export class DesktopClerkBridgeInitializationError extends Schema.TaggedError<DesktopClerkBridgeInitializationError>()(
29 "DesktopClerkBridgeInitializationError",
30 {
31 stateDir: Schema.String,
32 isDevelopment: Schema.Boolean,
33 cause: Schema.Defect(),
34 },
35) {
36 override get message(): string {
37 return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
38 }
39}
40
41export class DesktopClerkBridgeCleanupError extends Schema.TaggedError<DesktopClerkBridgeCleanupError>()(
42 "DesktopClerkBridgeCleanupError",
43 {
44 stateDir: Schema.String,
45 isDevelopment: Schema.Boolean,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
51 }
52}
53
54export class DesktopClerk extends Context.Service<
55 DesktopClerk,
56 {
57 readonly configure: Effect.Effect<
58 void,
59 never,
60 | ElectronApp.ElectronApp
61 | ElectronWindow.ElectronWindow
62 | DesktopWebLinks.DesktopWebLinks
63 | Scope.Scope
64 >;
65 }
66>()("@t3tools/desktop/app/DesktopClerk") {}
67
68function resolveDesktopClerkFrontendApiHostname(
69 publishableKey: string | undefined,
70): string | undefined {
71 const normalizedKey = publishableKey?.trim();
72 if (!normalizedKey) return undefined;
73
74 try {
75 return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
76 } catch {
77 return undefined;
78 }
79}
80
81export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
82 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
83 ? undefined
84 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
85);
86
87function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
88 return createClerkBridge({
89 storage: storage({ path: stateDir }),
90 manageSingleInstanceLock: false,
91 passkeys: true,
92 renderer: {
93 scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
94 host: ElectronProtocol.DESKTOP_HOST,
95 },
96 });
97}
98
99/** @public */
100export const make = Effect.gen(function* () {
101 const environment = yield* DesktopEnvironment.DesktopEnvironment;
102 const electronApp = yield* ElectronApp.ElectronApp;
103 const shell = yield* ElectronShell.ElectronShell;
104
105 // Must not yield: the bridge registers a scheme Electron rejects once ready.
106 const userDataPath = yield* DesktopUserData.resolveUserDataPath(environment);
107 yield* electronApp.setPath("userData", userDataPath);
108
109 // Clerk skips the profile lock on macOS. Interrupt before runtime construction because quit is asynchronous.
110 if (!(yield* electronApp.requestSingleInstanceLock)) {
111 yield* electronApp.quit;
112 return yield* Effect.interrupt;
113 }
114
115 const pendingSecondInstances: Array<readonly string[]> = [];
116 let handleSecondInstance = (argv: readonly string[]) => {
117 pendingSecondInstances.push(argv);
118 };
119 yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
120 handleSecondInstance(argv);
121 });
122 // macOS hands a launch link to open-url, which can fire before configure runs.
123 const pendingOpenUrls: Array<string> = [];
124 let handleOpenUrl = (url: string) => {
125 pendingOpenUrls.push(url);
126 return true;
127 };
128 yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
129 if (handleOpenUrl(url)) event.preventDefault();
130 });
131
132 yield* Effect.acquireRelease(
133 Effect.try({
134 try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
135 catch: (cause) =>
136 new DesktopClerkBridgeInitializationError({
137 stateDir: environment.stateDir,
138 isDevelopment: environment.isDevelopment,
139 cause,
140 }),
141 }),
142 (bridge) =>
143 Effect.try({
144 try: () => bridge.cleanup(),
145 catch: (cause) =>
146 new DesktopClerkBridgeCleanupError({
147 stateDir: environment.stateDir,
148 isDevelopment: environment.isDevelopment,
149 cause,
150 }),
151 }).pipe(Effect.orDie),
152 );
153
154 return DesktopClerk.of({
155 configure: Effect.gen(function* () {
156 const electronApp = yield* ElectronApp.ElectronApp;
157 const electronWindow = yield* ElectronWindow.ElectronWindow;
158 const webLinks = yield* DesktopWebLinks.DesktopWebLinks;
159 const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
160 const runPromise = Effect.runPromiseWith(context);
161
162 const startProviderAuthHandoff = (value: string | undefined) => {
163 if (!value) return false;
164 const request = readCodexAuthHandoff(value, environment.isDevelopment);
165 if (!request) return false;
166 void runPromise(
167 Effect.gen(function* () {
168 yield* electronApp.whenReady;
169 yield* Effect.tryPromise({
170 try: () =>
171 receiveCodexAuthCallback(
172 request.authorizationUrl,
173 (url) => runPromise(shell.openExternal(url)),
174 (callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl),
175 ),
176 catch: () =>
177 new CodexAuthCallbackError({
178 detail:
179 "Could not receive hosted web ChatGPT sign-in. Retry or use the redirect URL in the web app.",
180 }),
181 });
182 }).pipe(
183 Effect.catch(() => Effect.logWarning("Could not complete ChatGPT desktop handoff.")),
184 ),
185 );
186 return true;
187 };
188 const resumeProviderAuth = (value: string | undefined) => {
189 const destination = providerAuthReturnUrl(value);
190 const expectedOrigin = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}://app`;
191 if (!destination?.startsWith(`${expectedOrigin}/`)) return false;
192 void runPromise(
193 Effect.gen(function* () {
194 const mainWindow = yield* electronWindow.currentMainOrFirst;
195 if (Option.isNone(mainWindow)) return;
196 yield* Effect.promise(() => mainWindow.value.loadURL(destination));
197 yield* electronWindow.reveal(mainWindow.value);
198 }).pipe(
199 Effect.catchCause((cause) =>
200 Effect.logWarning("Could not return to provider setup", cause),
201 ),
202 ),
203 );
204 return true;
205 };
206 const openAppLink = (value: string | undefined) => {
207 if (!value || (promptLinkAppPath(value) === null && readPairingAppLink(value) === null))
208 return false;
209 void runPromise(webLinks.receive(value));
210 return true;
211 };
212 const args = yield* HostProcess.Arguments;
213 args.some((value) => startProviderAuthHandoff(value) || openAppLink(value));
214 const openWebLink = (url: string) => {
215 if (!DesktopWebLinks.isWebLink(url)) return false;
216 void runPromise(webLinks.receive(url));
217 return true;
218 };
219 handleOpenUrl = (url) =>
220 startProviderAuthHandoff(url) ||
221 resumeProviderAuth(url) ||
222 openWebLink(url) ||
223 openAppLink(url);
224 for (const url of pendingOpenUrls.splice(0)) handleOpenUrl(url);
225 yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
226 if (!DesktopWebLinks.isWebPageFile(path)) return;
227 event.preventDefault();
228 void runPromise(webLinks.receive(NodeURL.pathToFileURL(path).href));
229 });
230 handleSecondInstance = (argv) => {
231 if (
232 argv?.some(
233 (value) =>
234 startProviderAuthHandoff(value) || resumeProviderAuth(value) || openAppLink(value),
235 )
236 )
237 return;
238 void runPromise(
239 Effect.gen(function* () {
240 const mainWindow = yield* electronWindow.currentMainOrFirst;
241 if (Option.isSome(mainWindow)) yield* electronWindow.reveal(mainWindow.value);
242 }),
243 );
244 };
245 for (const argv of pendingSecondInstances.splice(0)) handleSecondInstance(argv);
246 }).pipe(Effect.withSpan("desktop.clerk.configure")),
247 });
248});
249
250export const layer = Layer.effect(DesktopClerk, make);