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

cloudAuth.ts

154 lines5.0 KB

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 * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
14​
15import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
16import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
17import * as IpcChannels from "../channels.ts";
18import { makeIpcMethod } from "../DesktopIpc.ts";
19​
20declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
21​
22export class DesktopCloudAuthFetchError extends Data.TaggedError("DesktopCloudAuthFetchError")<{
23 readonly reason: string;
24 readonly cause?: unknown;
25}> {
26 override get message() {
27 return this.reason;
28 }
30​
31function configuredClerkFrontendApiHostname(): string | null {
32 const publishableKey =
33 process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ||
34 (typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
35 ? ""
36 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__.trim());
37 if (!publishableKey) return null;
38​
39 return clerkFrontendApiHostnameFromPublishableKey(publishableKey);
41​
42const allowedClerkFrontendApiHosts = (hostname: string): boolean =>
43 isAllowedClerkFrontendApiHostname(hostname, configuredClerkFrontendApiHostname());
44​
45export function validateClerkFrontendApiUrl(rawUrl: string): URL {
46 const url = new URL(rawUrl);
47 if (url.protocol !== "https:" || !allowedClerkFrontendApiHosts(url.hostname)) {
48 throw new DesktopCloudAuthFetchError({
49 reason: "Desktop cloud auth fetch is restricted to Clerk Frontend API HTTPS hosts.",
50 });
51 }
52 return url;
54​
55export const createCloudAuthRequest = makeIpcMethod({
56 channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
57 payload: Schema.Void,
58 result: Schema.String,
59 handler: Effect.fn("desktop.ipc.cloudAuth.createRequest")(function* () {
60 const cloudAuth = yield* DesktopCloudAuth.DesktopCloudAuth;
61 return yield* cloudAuth.createRequest;
62 }),
63});
64​
65export const getCloudAuthToken = makeIpcMethod({
66 channel: IpcChannels.GET_CLOUD_AUTH_TOKEN_CHANNEL,
67 payload: Schema.Void,
68 result: Schema.NullOr(Schema.String),
69 handler: Effect.fn("desktop.ipc.cloudAuth.getToken")(function* () {
70 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
71 return Option.getOrNull(yield* tokenStore.get);
72 }),
73});
74​
75export const setCloudAuthToken = makeIpcMethod({
76 channel: IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL,
77 payload: Schema.String,
78 result: Schema.Boolean,
79 handler: Effect.fn("desktop.ipc.cloudAuth.setToken")(function* (token) {
80 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
81 return yield* tokenStore.set(token);
82 }),
83});
84​
85export const clearCloudAuthToken = makeIpcMethod({
86 channel: IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL,
87 payload: Schema.Void,
88 result: Schema.Void,
89 handler: Effect.fn("desktop.ipc.cloudAuth.clearToken")(function* () {
90 const tokenStore = yield* DesktopCloudAuthTokenStore.DesktopCloudAuthTokenStore;
91 yield* tokenStore.clear;
92 }),
93});
94​
95export const fetchCloudAuth = makeIpcMethod({
96 channel: IpcChannels.FETCH_CLOUD_AUTH_CHANNEL,
97 payload: DesktopCloudAuthFetchInputSchema,
98 result: DesktopCloudAuthFetchResultSchema,
99 handler: Effect.fn("desktop.ipc.cloudAuth.fetch")(function* (input) {
100 const url = yield* Effect.try({
101 try: () => validateClerkFrontendApiUrl(input.url),
102 catch: (cause) =>
103 cause instanceof DesktopCloudAuthFetchError
104 ? cause
105 : new DesktopCloudAuthFetchError({
106 reason: "Desktop cloud auth fetch received an invalid URL.",
107 cause,
108 }),
109 });
110​
111 const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
112 url,
113 {
114 headers: input.headers,
115 },
116 );
117 const request =
118 input.body === undefined
119 ? requestWithoutBody
120 : HttpClientRequest.bodyText(
121 requestWithoutBody,
122 input.body,
123 Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
124 );
125​
126 const response = yield* HttpClient.execute(request).pipe(
127 Effect.mapError(
128 (cause) =>
129 new DesktopCloudAuthFetchError({
130 reason: "Desktop cloud auth fetch failed.",
131 cause,
132 }),
133 ),
134 );
135​
136 const body = yield* response.text.pipe(
137 Effect.mapError(
138 (cause) =>
139 new DesktopCloudAuthFetchError({
140 reason: "Desktop cloud auth fetch response could not be read.",
141 cause,
142 }),
143 ),
144 );
145​
146 return {
147 ok: response.status >= 200 && response.status < 300,
148 status: response.status,
149 statusText: "",
150 headers: response.headers,
151 body,
152 };
153 }),
154});