Open History to see the last commit
1import {
2 DesktopCloudAuthFetchInputSchema,
3 DesktopCloudAuthFetchResultSchema,
4} from "@t3tools/contracts";
5import {
6 clerkFrontendApiHostnameFromPublishableKey,
7 isAllowedClerkFrontendApiHostname,
8} from "@t3tools/shared/relayAuth";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import { identity } from "effect/Function";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
16
17import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
18import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
19import * as IpcChannels from "../channels.ts";
20import { makeIpcMethod } from "../DesktopIpc.ts";
21
22declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
23
24export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
25 readonly reason: string;
26 readonly cause?: unknown;
27}> {
28 override get message() {
29 return this.reason;
30 }
31}
32
33function configuredClerkFrontendApiHostname(): string | null {
34 const publishableKey =
35 process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
36 (typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
37 ? ""
38 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
39 if (!publishableKey) return null;
40
41 return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
42}
43
44const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
45 isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
46
47export function validateClerkFrontendApiUrl(rawUrl: string): URL {
48 const url = new URL(rawUrl);
49 if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
50 throw new DesktopCloudAuthFetchError({
51 reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
52 });
53 }
54 return url;
55}
56
57function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
58 return Effect.gen(function* () {
59 const method = (input.method ?? "GET") as "GET" | "POST";
60 const headers = new Headers(input.headers);
61 const response = yield* HttpClientRequest.make(method)(url).pipe(
62 HttpClientRequest.setHeaders(headers),
63 input.body === undefined
64 ? identity
65 : HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
66 HttpClient.execute,
67 Effect.mapError(
68 (cause) =>
69 new DesktopCloudAuthFetchError({
70 reason: "Desktop cloud auth fetch failed to execute.",
71 cause,
72 }),
73 ),
74 );
75
76 const body = yield* response.text.pipe(
77 Effect.mapError(
78 (cause) =>
79 new DesktopCloudAuthFetchError({
80 reason: "Desktop cloud auth fetch response could not be read.",
81 cause,
82 }),
83 ),
84 );
85
86 return {
87 ok: response.status >= 200 && response.status < 300,
88 status: response.status,
89 statusText: "",
90 headers: response.headers,
91 body,
92 };
93 });
94}
95
96const electronNetFetchLayer = Layer.unwrap(
97 Effect.gen(function* () {
98 const electronFetch = yield* Effect.promise(async () => {
99 const electron = (await import("electron")) as {
100 readonly net?: { readonly fetch?: typeof globalThis.fetch };
101 };
102 return typeof electron.net?.fetch === "function"
103 ? electron.net.fetch.bind(electron.net)
104 : null;
105 }).pipe(Effect.catchCause(() => Effect.succeed(null)));
106
107 if (!electronFetch) {
108 yield* Effect.logWarning(
109 "electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
110 );
111 }
112
113 return FetchHttpClient.layer.pipe(
114 Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
115 );
116 }),
117);
118
119export const createCloudAuthRequest = makeIpcMethod({
120 channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
121 payload: Schema.Void,
122 result: Schema.String,
123 handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
124 const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
125 return yield* cloudAuth.createRequest;
126 }),
127});
128
129export const getCloudAuthToken = makeIpcMethod({
130 channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
131 payload: Schema.Void,
132 result: Schema.NullOr(Schema.String),
133 handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
134 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
135 return Option.getOrNull(yield* tokenStore.get);
136 }),
137});
138
139export const setCloudAuthToken = makeIpcMethod({
140 channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
141 payload: Schema.String,
142 result: Schema.Boolean,
143 handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
144 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
145 return yield* tokenStore.set(token);
146 }),
147});
148
149export const clearCloudAuthToken = makeIpcMethod({
150 channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
151 payload: Schema.Void,
152 result: Schema.Void,
153 handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
154 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
155 yield* tokenStore.clear;
156 }),
157});
158
159export const fetchCloudAuth = makeIpcMethod({
160 channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
161 payload: DesktopCloudAuthFetchInputSchema,
162 result: DesktopCloudAuthFetchResultSchema,
163 handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
164 const url = yield* Effect.try({
165 try: () => validateClerkFrontendApiUrl(input.url),
166 catch: (cause) =>
167 cause instanceof DesktopCloudAuthFetchError
168 ? cause
169 : new DesktopCloudAuthFetchError({
170 reason: "Desktop cloud auth fetch received an invalid URL.",
171 cause,
172 }),
173 });
174
175 return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
176 }),
177});