Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopClerk.ts

236 lines8.9 KB

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 * as HostProcess from "@t3tools/shared/HostProcess";
17import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
18import * as ElectronApp from "../electron/ElectronApp.ts";
19import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
20import * as ElectronWindow from "../electron/ElectronWindow.ts";
21import * as DesktopUserData from "./DesktopUserData.ts";
22import * as DesktopEnvironment from "./DesktopEnvironment.ts";
23import * as DesktopWebLinks from "./DesktopWebLinks.ts";
24​
25declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
26​
27export class DesktopClerkBridgeInitializationError extends Schema.TaggedError<DesktopClerkBridgeInitializationError>()(
28 "DesktopClerkBridgeInitializationError",
29 {
30 stateDir: Schema.String,
31 isDevelopment: Schema.Boolean,
32 cause: Schema.Defect(),
33 },
34) {
35 override get message(): string {
36 return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
37 }
39​
40export class DesktopClerkBridgeCleanupError extends Schema.TaggedError<DesktopClerkBridgeCleanupError>()(
41 "DesktopClerkBridgeCleanupError",
42 {
43 stateDir: Schema.String,
44 isDevelopment: Schema.Boolean,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
50 }
52​
53export class DesktopClerk extends Context.Service<
54 DesktopClerk,
55 {
56 readonly configure: Effect.Effect<
57 void,
58 never,
59 | ElectronApp.ElectronApp
60 | ElectronWindow.ElectronWindow
61 | DesktopWebLinks.DesktopWebLinks
62 | Scope.Scope
63 >;
64 }
65>()("@t3tools/desktop/app/DesktopClerk") {}
66​
67function resolveDesktopClerkFrontendApiHostname(
68 publishableKey: string | undefined,
69): string | undefined {
70 const normalizedKey = publishableKey?.trim();
71 if (!normalizedKey) return undefined;
72​
73 try {
74 return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
75 } catch {
76 return undefined;
77 }
79​
80export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
81 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
82 ? undefined
83 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
84);
85​
86function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
87 return createClerkBridge({
88 storage: storage({ path: stateDir }),
89 passkeys: true,
90 renderer: {
91 scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
92 host: ElectronProtocol.DESKTOP_HOST,
93 },
94 });
96​
97/** @public Service construction is part of the canonical Effect module API. */
98export const make = Effect.gen(function* () {
99 const environment = yield* DesktopEnvironment.DesktopEnvironment;
100 const electronApp = yield* ElectronApp.ElectronApp;
101 const shell = yield* ElectronShell.ElectronShell;
102​
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 openAppLink = (value: string | undefined) => {
192 if (!value || promptLinkAppPath(value) === null) return false;
193 void runPromise(webLinks.receive(value));
194 return true;
195 };
196 const args = yield* HostProcess.Arguments;
197 args.some((value) => startProviderAuthHandoff(value) || openAppLink(value));
198 const openWebLink = (url: string) => {
199 if (!DesktopWebLinks.isWebLink(url)) return false;
200 void runPromise(webLinks.receive(url));
201 return true;
202 };
203 yield* electronApp.on("open-url", (event: { preventDefault: () => void }, url: string) => {
204 if (
205 startProviderAuthHandoff(url) ||
206 resumeProviderAuth(url) ||
207 openWebLink(url) ||
208 openAppLink(url)
209 )
210 event.preventDefault();
211 });
212 yield* electronApp.on("open-file", (event: { preventDefault: () => void }, path: string) => {
213 if (!DesktopWebLinks.isWebPageFile(path)) return;
214 event.preventDefault();
215 void runPromise(webLinks.receive(NodeURL.pathToFileURL(path).href));
216 });
217 yield* electronApp.on("second-instance", (_event: unknown, argv: readonly string[]) => {
218 if (
219 argv?.some(
220 (value) =>
221 startProviderAuthHandoff(value) || resumeProviderAuth(value) || openAppLink(value),
222 )
223 )
224 return;
225 void runPromise(
226 Effect.gen(function* () {
227 const mainWindow = yield* electronWindow.currentMainOrFirst;
228 if (Option.isSome(mainWindow)) yield* electronWindow.reveal(mainWindow.value);
229 }),
230 );
231 });
232 }).pipe(Effect.withSpan("desktop.clerk.configure")),
233 });
234});
235​
236export const layer = Layer.effect(DesktopClerk, make);