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

remote.ts

272 lines8.6 KB

1import {
2 AuthAccessTokenType,
3 type AuthClientPresentationMetadata,
4 AuthEnvironmentBootstrapTokenType,
5 AuthTokenExchangeGrantType,
6 type AuthEnvironmentScope,
7 EnvironmentHttpApi,
8 EnvironmentHttpCommonError,
9} from "@t3tools/contracts";
10import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
11import type {
12 EnvironmentAuthInvalidError,
13 EnvironmentInternalError,
14 EnvironmentOperationForbiddenError,
15 EnvironmentRequestInvalidError,
16 EnvironmentScopeRequiredError,
17} from "@t3tools/contracts";
18import * as Data from "effect/Data";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Schema from "effect/Schema";
24import { FetchHttpClient, HttpClient, HttpClientError } from "effect/unstable/http";
25import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
26​
27const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
28const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
29​
30const remoteEndpointUrl = (httpBaseUrl: string, pathname: string): string => {
31 const url = new URL(httpBaseUrl);
32 url.pathname = pathname;
33 url.search = "";
34 url.hash = "";
35 return url.toString();
36};
37​
38const remoteApiBaseUrl = (httpBaseUrl: string): string => {
39 const url = new URL(httpBaseUrl);
40 url.pathname = "/";
41 url.search = "";
42 url.hash = "";
43 return url.toString();
44};
45​
46export class RemoteEnvironmentAuthFetchError extends Data.TaggedError(
47 "RemoteEnvironmentAuthFetchError",
48)<{
49 readonly message: string;
50 readonly cause: unknown;
51}> {}
52​
53export class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError(
54 "RemoteEnvironmentAuthInvalidJsonError",
55)<{
56 readonly message: string;
57 readonly cause: unknown;
58}> {}
59​
60export class RemoteEnvironmentAuthUndeclaredStatusError extends Data.TaggedError(
61 "RemoteEnvironmentAuthUndeclaredStatusError",
62)<{
63 readonly message: string;
64 readonly status: number;
65 readonly requestUrl: string;
66}> {
67 constructor(requestUrl: string, status: number) {
68 super({
69 message: `Remote auth endpoint ${requestUrl} returned undeclared status ${status}.`,
70 requestUrl,
71 status,
72 });
73 }
75​
76export class RemoteEnvironmentAuthTimeoutError extends Data.TaggedError(
77 "RemoteEnvironmentAuthTimeoutError",
78)<{
79 readonly message: string;
80 readonly requestUrl: string;
81 readonly timeoutMs: number;
82}> {
83 constructor(requestUrl: string, timeoutMs: number) {
84 super({
85 message: `Remote auth endpoint ${requestUrl} timed out after ${timeoutMs}ms.`,
86 requestUrl,
87 timeoutMs,
88 });
89 }
91​
92export type RemoteEnvironmentAuthError =
93 | EnvironmentRequestInvalidError
94 | EnvironmentAuthInvalidError
95 | EnvironmentScopeRequiredError
96 | EnvironmentOperationForbiddenError
97 | EnvironmentInternalError
98 | RemoteEnvironmentAuthFetchError
99 | RemoteEnvironmentAuthInvalidJsonError
100 | RemoteEnvironmentAuthUndeclaredStatusError
101 | RemoteEnvironmentAuthTimeoutError;
102​
103export const remoteHttpClientLayer = (
104 fetchFn: typeof globalThis.fetch,
105): Layer.Layer<HttpClient.HttpClient> =>
106 FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));
107​
108const failRemoteRequest = (
109 requestUrl: string,
110 cause: unknown,
111): Effect.Effect<never, RemoteEnvironmentAuthError> => {
112 if (cause instanceof RemoteEnvironmentAuthTimeoutError) {
113 return Effect.fail(cause);
114 }
115 if (isEnvironmentHttpCommonError(cause)) {
116 return Effect.fail(cause);
117 }
118 if (Schema.isSchemaError(cause)) {
119 return Effect.fail(
120 new RemoteEnvironmentAuthInvalidJsonError({
121 message: `Remote auth endpoint returned an invalid response from ${requestUrl}.`,
122 cause,
123 }),
124 );
125 }
126 if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
127 const response = cause.response;
128 if (response.status < 200 || response.status >= 300) {
129 return Effect.fail(
130 new RemoteEnvironmentAuthUndeclaredStatusError(requestUrl, response.status),
131 );
132 }
133 return Effect.fail(
134 new RemoteEnvironmentAuthInvalidJsonError({
135 message: `Remote auth endpoint returned an invalid response from ${requestUrl}.`,
136 cause,
137 }),
138 );
139 }
140 return Effect.fail(
141 new RemoteEnvironmentAuthFetchError({
142 message: `Failed to fetch remote auth endpoint ${requestUrl} (${String(cause)}).`,
143 cause,
144 }),
145 );
146};
147​
148const executeRemoteRequest = <A, E, R>(
149 requestUrl: string,
150 timeoutMs: number,
151 request: Effect.Effect<A, E, R>,
152): Effect.Effect<A, RemoteEnvironmentAuthError, R> =>
153 request.pipe(
154 Effect.timeoutOption(Duration.millis(timeoutMs)),
155 Effect.flatMap(
156 Option.match({
157 onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError(requestUrl, timeoutMs)),
158 onSome: Effect.succeed,
159 }),
160 ),
161 Effect.catch((cause) => failRemoteRequest(requestUrl, cause)),
162 );
163​
164export const makeEnvironmentHttpApiClient = (httpBaseUrl: string) =>
165 Effect.gen(function* () {
166 const httpClient = yield* HttpClient.HttpClient;
167 return yield* HttpApiClient.makeWith(EnvironmentHttpApi, {
168 httpClient,
169 baseUrl: remoteApiBaseUrl(httpBaseUrl),
170 });
171 });
172​
173export const bootstrapRemoteBearerSession = Effect.fn(
174 "clientRuntime.remote.bootstrapRemoteBearerSession",
175)(function* (input: {
176 readonly httpBaseUrl: string;
177 readonly credential: string;
178 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
179 readonly clientMetadata?: AuthClientPresentationMetadata;
180 readonly timeoutMs?: number;
181}) {
182 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
183 return yield* executeRemoteRequest(
184 remoteEndpointUrl(input.httpBaseUrl, "/oauth/token"),
185 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
186 client.auth.token({
187 payload: {
188 grant_type: AuthTokenExchangeGrantType,
189 subject_token: input.credential,
190 subject_token_type: AuthEnvironmentBootstrapTokenType,
191 requested_token_type: AuthAccessTokenType,
192 ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),
193 ...(input.clientMetadata?.label ? { client_label: input.clientMetadata.label } : {}),
194 ...(input.clientMetadata?.deviceType
195 ? { client_device_type: input.clientMetadata.deviceType }
196 : {}),
197 ...(input.clientMetadata?.os ? { client_os: input.clientMetadata.os } : {}),
198 },
199 }),
200 );
201});
202​
203export const fetchRemoteSessionState = Effect.fn("clientRuntime.remote.fetchRemoteSessionState")(
204 function* (input: {
205 readonly httpBaseUrl: string;
206 readonly bearerToken: string;
207 readonly timeoutMs?: number;
208 }) {
209 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
210 return yield* executeRemoteRequest(
211 remoteEndpointUrl(input.httpBaseUrl, "/api/auth/session"),
212 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
213 client.auth.session({
214 headers: {
215 authorization: `Bearer ${input.bearerToken}`,
216 },
217 }),
218 );
219 },
220);
221​
222export const fetchRemoteEnvironmentDescriptor = Effect.fn(
223 "clientRuntime.remote.fetchRemoteEnvironmentDescriptor",
224)(function* (input: { readonly httpBaseUrl: string; readonly timeoutMs?: number }) {
225 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
226 return yield* executeRemoteRequest(
227 remoteEndpointUrl(input.httpBaseUrl, "/.well-known/t3/environment"),
228 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
229 client.metadata.descriptor(),
230 );
231});
232​
233export const issueRemoteWebSocketTicket = Effect.fn(
234 "clientRuntime.remote.issueRemoteWebSocketTicket",
235)(function* (input: {
236 readonly httpBaseUrl: string;
237 readonly bearerToken: string;
238 readonly timeoutMs?: number;
239}) {
240 const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);
241 return yield* executeRemoteRequest(
242 remoteEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),
243 input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,
244 client.auth.webSocketTicket({
245 headers: {
246 authorization: `Bearer ${input.bearerToken}`,
247 },
248 }),
249 );
250});
251​
252export const resolveRemoteWebSocketConnectionUrl = Effect.fn(
253 "clientRuntime.remote.resolveRemoteWebSocketConnectionUrl",
254)(function* (input: {
255 readonly wsBaseUrl: string;
256 readonly httpBaseUrl: string;
257 readonly bearerToken: string;
258 readonly timeoutMs?: number;
259}) {
260 const issued = yield* issueRemoteWebSocketTicket({
261 httpBaseUrl: input.httpBaseUrl,
262 bearerToken: input.bearerToken,
263 ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),
264 });
265​
266 const url = new URL(input.wsBaseUrl);
267 if (url.pathname === "" || url.pathname === "/") {
268 url.pathname = "/ws";
269 }
270 url.searchParams.set("wsTicket", issued.ticket);
271 return url.toString();
272});