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 DesktopAppIdentity from "./DesktopAppIdentity.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 // Electron scopes the single-instance lock to the userData directory and
98 // creates that directory when the lock is acquired. The SDK bridge takes
99 // the lock at creation, so userData must already point at the real
100 // directory here — under the default productName-derived path, acquiring
101 // the lock would create "T3 Code (Alpha)" and make the legacy-install
102 // detection in resolveUserDataPath match on fresh installs.
103 const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
104 yield* electronApp.setPath("userData", userDataPath);
105
106 const bridge = yield* Effect.acquireRelease(
107 Effect.try({
108 try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
109 catch: (cause) =>
110 new DesktopClerkBridgeInitializationError({
111 stateDir: environment.stateDir,
112 isDevelopment: environment.isDevelopment,
113 cause,
114 }),
115 }),
116 (bridge) =>
117 Effect.try({
118 try: () => bridge.cleanup(),
119 catch: (cause) =>
120 new DesktopClerkBridgeCleanupError({
121 stateDir: environment.stateDir,
122 isDevelopment: environment.isDevelopment,
123 cause,
124 }),
125 }).pipe(Effect.orDie),
126 );
127
128 return DesktopClerk.of({
129 configure: Effect.gen(function* () {
130 const electronApp = yield* ElectronApp.ElectronApp;
131 const electronWindow = yield* ElectronWindow.ElectronWindow;
132 const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
133 const runPromise = Effect.runPromiseWith(context);
134
135 // The SDK bridge holds Electron's single-instance lock (acquired at
136 // bridge creation) so OAuth deep-link callbacks on Windows/Linux are
137 // forwarded to the running app. In a secondary instance the bridge has
138 // already begun quitting the app; app.quit() is asynchronous, so stop
139 // bootstrap here before whenReady can fire.
140 if (!bridge.isPrimaryInstance) {
141 yield* electronApp.quit;
142 return yield* Effect.interrupt;
143 }
144
145 const startProviderAuthHandoff = (value: string | undefined) => {
146 if (!value) return false;
147 const request = readCodexAuthHandoff(value, environment.isDevelopment);
148 if (!request) return false;
149 void runPromise(
150 Effect.gen(function* () {
151 yield* electronApp.whenReady;
152 yield* Effect.tryPromise({
153 try: () =>
154 receiveCodexAuthCallback(
155 request.authorizationUrl,
156 (url) => runPromise(shell.openExternal(url)),
157 (callbackUrl) => codexAuthDeliveryUrl(request, callbackUrl),
158 ),
159 catch: () =>
160 new CodexAuthCallbackError({
161 detail:
162 "Could not receive hosted web ChatGPT sign-in. Retry or use the redirect URL in the web app.",
163 }),
164 });
165 }).pipe(
166 Effect.catch(() => Effect.logWarning("Could not complete ChatGPT desktop handoff.")),
167 ),
168 );
169 return true;
170 };
171 const resumeProviderAuth = (value: string | undefined) => {
172 const destination = providerAuthReturnUrl(value);
173 const expectedOrigin = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}://app`;
174 if (!destination?.startsWith(`${expectedOrigin}/`)) return false;
175 void runPromise(
176 Effect.gen(function* () {
177 const mainWindow = yield* electronWindow.currentMainOrFirst;
178 if (Option.isNone(mainWindow)) return;
179 yield* Effect.promise(() => mainWindow.value.loadURL(destination));
180 yield* electronWindow.reveal(mainWindow.value);
181 }).pipe(
182 Effect.catchCause((cause) =>
183 Effect.logWarning("Could not return to provider setup", cause),
184 ),
185 ),
186 );
187 return true;
188 };
189 const args = yield* HostProcessArguments;
190 args.some((value) => startProviderAuthHandoff(value));
191 yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
192 if (startProviderAuthHandoff(url) || resumeProviderAuth(url)) event.preventDefault();
193 });
194 yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
195 if (argv?.some((value) => startProviderAuthHandoff(value) || resumeProviderAuth(value)))
196 return;
197 void runPromise(
198 Effect.gen(function* () {
199 const mainWindow = yield* electronWindow.currentMainOrFirst;
200 if (Option.isSome(mainWindow)) yield* electronWindow.reveal(mainWindow.value);
201 }),
202 );
203 });
204 }).pipe(Effect.withSpan("desktop.clerk.configure")),
205 });
206});
207
208export const layer = Layer.effect(DesktopClerk, make);