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

auth.ts

485 lines14.3 KB

1import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 AuthEnvironmentScope,
5 AuthPairingCredentialResult,
6 AuthSessionId,
7 AuthSessionState,
8} from "@t3tools/contracts";
9import { EnvironmentHttpCommonError } from "@t3tools/contracts";
10import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14import { HttpClientError } from "effect/unstable/http";
15​
16import {
17 getPairingTokenFromUrl,
18 stripPairingTokenFromUrl as stripPairingTokenUrl,
19} from "../../pairingUrl";
20​
21import { PrimaryEnvironmentHttpClient } from "./httpClient";
22import { runPrimaryHttp } from "../../lib/runtime";
23import * as Data from "effect/Data";
24import * as Predicate from "effect/Predicate";
25​
26export class BootstrapHttpError extends Data.TaggedError("BootstrapHttpError")<{
27 readonly message: string;
28 readonly status: number;
29}> {}
30const isBootstrapHttpError = (u: unknown): u is BootstrapHttpError =>
31 Predicate.isTagged(u, "BootstrapHttpError");
32const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
33​
34export interface ServerPairingLinkRecord {
35 readonly id: string;
36 readonly credential: string;
37 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
38 readonly subject: string;
39 readonly label?: string;
40 readonly createdAt: string;
41 readonly expiresAt: string;
43​
44export interface ServerClientSessionRecord {
45 readonly sessionId: AuthSessionId;
46 readonly subject: string;
47 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
48 readonly method: "browser-session-cookie" | "bearer-access-token";
49 readonly client: AuthClientMetadata;
50 readonly issuedAt: string;
51 readonly expiresAt: string;
52 readonly lastConnectedAt: string | null;
53 readonly connected: boolean;
54 readonly current: boolean;
56​
57type ServerAuthGateState =
58 | { status: "authenticated" }
59 | {
60 status: "requires-auth";
61 auth: AuthSessionState["auth"];
62 errorMessage?: string;
63 };
64​
65let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
66let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
67const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
68const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
69​
70export function peekPairingTokenFromUrl(): string | null {
71 return getPairingTokenFromUrl(new URL(window.location.href));
73​
74export function stripPairingTokenFromUrl() {
75 const url = new URL(window.location.href);
76 const next = stripPairingTokenUrl(url);
77 if (next.toString() === url.toString()) {
78 return;
79 }
80 window.history.replaceState({}, document.title, next.toString());
82​
83export function takePairingTokenFromUrl(): string | null {
84 const token = peekPairingTokenFromUrl();
85 if (!token) {
86 return null;
87 }
88 stripPairingTokenFromUrl();
89 return token;
91​
92function getDesktopBootstrapCredential(): string | null {
93 const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
94 return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
95 ? bootstrap.bootstrapToken
96 : null;
98​
99export async function fetchSessionState(): Promise<AuthSessionState> {
100 return retryTransientBootstrap(async () => {
101 try {
102 return await runPrimaryHttp(
103 PrimaryEnvironmentHttpClient.pipe(
104 Effect.flatMap((client) => client.auth.session({ headers: {} })),
105 ),
106 );
107 } catch (error) {
108 const status = readHttpApiStatus(error);
109 throw new BootstrapHttpError({
110 message: `Failed to load server auth session state (${status ?? "unknown"}).`,
111 status: status ?? 500,
112 });
113 }
114 });
116​
117function readHttpApiStatus(error: unknown): number | null {
118 if (isEnvironmentHttpCommonError(error)) {
119 return readEnvironmentHttpErrorStatus(error);
120 }
121 return HttpClientError.isHttpClientError(error) && error.response !== undefined
122 ? error.response.status
123 : null;
125​
126function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
127 switch (error._tag) {
128 case "EnvironmentRequestInvalidError":
129 return 400;
130 case "EnvironmentAuthInvalidError":
131 return 401;
132 case "EnvironmentScopeRequiredError":
133 case "EnvironmentOperationForbiddenError":
134 return 403;
135 case "EnvironmentInternalError":
136 return 500;
137 }
139​
140function readHttpApiErrorMessage(error: unknown, fallbackMessage: string): string {
141 if (!isEnvironmentHttpCommonError(error)) {
142 return fallbackMessage;
143 }
144 switch (error._tag) {
145 case "EnvironmentAuthInvalidError":
146 return error.reason === "missing_credential"
147 ? "Authentication required."
148 : "Invalid bootstrap credential.";
149 case "EnvironmentRequestInvalidError":
150 return error.reason === "invalid_scope"
151 ? "Requested token scope is invalid."
152 : "Requested scope exceeds the bootstrap credential grant.";
153 case "EnvironmentScopeRequiredError":
154 return `The authenticated token is missing required scope: ${error.requiredScope}.`;
155 case "EnvironmentOperationForbiddenError":
156 return "This operation is not allowed for the current session.";
157 case "EnvironmentInternalError":
158 return fallbackMessage;
159 }
161​
162const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([
163 "Invalid bootstrap credential.",
164 "Unknown bootstrap credential.",
165]);
166​
167function toFriendlyBootstrapErrorMessage(status: number, message: string): string {
168 const trimmedMessage = message.trim();
169 if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(trimmedMessage)) {
170 return "Invalid pairing token. Check the token and try again.";
171 }
172​
173 return trimmedMessage;
175​
176async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
177 return retryTransientBootstrap(async () => {
178 try {
179 return await runPrimaryHttp(
180 PrimaryEnvironmentHttpClient.pipe(
181 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
182 ),
183 );
184 } catch (error) {
185 const status = readHttpApiStatus(error) ?? 500;
186 const message = toFriendlyBootstrapErrorMessage(status, readHttpApiErrorMessage(error, ""));
187 throw new BootstrapHttpError({
188 message: message || `Failed to bootstrap auth session (${status}).`,
189 status,
190 });
191 }
192 });
194​
195async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
196 const startedAt = Date.now();
197​
198 while (true) {
199 const session = await fetchSessionState();
200 if (session.authenticated) {
201 return session;
202 }
203​
204 if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
205 throw new Error("Timed out waiting for authenticated session after bootstrap.");
206 }
207​
208 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
209 }
211​
212const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
213const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
214const BOOTSTRAP_RETRY_STEP_MS = 500;
215​
216export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
217 const startedAt = Date.now();
218 while (true) {
219 try {
220 return await operation();
221 } catch (error) {
222 if (!isTransientBootstrapError(error)) {
223 throw error;
224 }
225​
226 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
227 throw error;
228 }
229​
230 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
231 }
232 }
234​
235function waitForBootstrapRetry(delayMs: number): Promise<void> {
236 return new Promise((resolve) => {
237 setTimeout(resolve, delayMs);
238 });
240​
241function isTransientBootstrapError(error: unknown): boolean {
242 if (isBootstrapHttpError(error)) {
243 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
244 }
245​
246 if (error instanceof TypeError) {
247 return true;
248 }
249​
250 return error instanceof DOMException && error.name === "AbortError";
252​
253async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
254 const bootstrapCredential = getDesktopBootstrapCredential();
255 const currentSession = await fetchSessionState();
256 if (currentSession.authenticated) {
257 return { status: "authenticated" };
258 }
259​
260 if (!bootstrapCredential) {
261 return {
262 status: "requires-auth",
263 auth: currentSession.auth,
264 };
265 }
266​
267 try {
268 await exchangeBootstrapCredential(bootstrapCredential);
269 await waitForAuthenticatedSessionAfterBootstrap();
270 return { status: "authenticated" };
271 } catch (error) {
272 return {
273 status: "requires-auth",
274 auth: currentSession.auth,
275 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
276 };
277 }
279​
280export async function submitServerAuthCredential(credential: string): Promise<void> {
281 const trimmedCredential = credential.trim();
282 if (!trimmedCredential) {
283 throw new Error("Enter a pairing token to continue.");
284 }
285​
286 resolvedAuthenticatedGateState = null;
287 await exchangeBootstrapCredential(trimmedCredential);
288 bootstrapPromise = null;
289 stripPairingTokenFromUrl();
291​
292export async function createServerPairingCredential(input?: {
293 readonly label?: string;
294 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
295}): Promise<AuthPairingCredentialResult> {
296 const trimmedLabel = input?.label?.trim();
297 try {
298 return await runPrimaryHttp(
299 PrimaryEnvironmentHttpClient.pipe(
300 Effect.flatMap((client) =>
301 client.auth.pairingCredential({
302 headers: {},
303 payload: {
304 ...(trimmedLabel ? { label: trimmedLabel } : {}),
305 ...(input?.scopes ? { scopes: input.scopes } : {}),
306 },
307 }),
308 ),
309 ),
310 );
311 } catch (error) {
312 throw new Error(
313 readHttpApiErrorMessage(
314 error,
315 `Failed to create pairing credential (${readHttpApiStatus(error) ?? "unknown"}).`,
316 ),
317 { cause: error },
318 );
319 }
321​
322export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
323 try {
324 const pairingLinks = await runPrimaryHttp(
325 PrimaryEnvironmentHttpClient.pipe(
326 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
327 ),
328 );
329 return pairingLinks.map((pairingLink) => {
330 const timestamps = {
331 createdAt: DateTime.formatIso(pairingLink.createdAt),
332 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
333 };
334 if (pairingLink.label === undefined) {
335 return {
336 id: pairingLink.id,
337 credential: pairingLink.credential,
338 scopes: pairingLink.scopes,
339 subject: pairingLink.subject,
340 createdAt: timestamps.createdAt,
341 expiresAt: timestamps.expiresAt,
342 };
343 }
344 return {
345 id: pairingLink.id,
346 credential: pairingLink.credential,
347 scopes: pairingLink.scopes,
348 subject: pairingLink.subject,
349 label: pairingLink.label,
350 createdAt: timestamps.createdAt,
351 expiresAt: timestamps.expiresAt,
352 };
353 });
354 } catch (error) {
355 throw new Error(
356 readHttpApiErrorMessage(
357 error,
358 `Failed to load pairing links (${readHttpApiStatus(error) ?? "unknown"}).`,
359 ),
360 { cause: error },
361 );
362 }
364​
365export async function revokeServerPairingLink(id: string): Promise<void> {
366 try {
367 await runPrimaryHttp(
368 PrimaryEnvironmentHttpClient.pipe(
369 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
370 ),
371 );
372 } catch (error) {
373 throw new Error(
374 readHttpApiErrorMessage(
375 error,
376 `Failed to revoke pairing link (${readHttpApiStatus(error) ?? "unknown"}).`,
377 ),
378 { cause: error },
379 );
380 }
382​
383export async function listServerClientSessions(): Promise<
384 ReadonlyArray<ServerClientSessionRecord>
385> {
386 try {
387 const clientSessions = await runPrimaryHttp(
388 PrimaryEnvironmentHttpClient.pipe(
389 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
390 ),
391 );
392 return clientSessions.map((clientSession) => ({
393 sessionId: clientSession.sessionId,
394 subject: clientSession.subject,
395 scopes: clientSession.scopes,
396 method: clientSession.method,
397 client: clientSession.client,
398 issuedAt: DateTime.formatIso(clientSession.issuedAt),
399 expiresAt: DateTime.formatIso(clientSession.expiresAt),
400 lastConnectedAt:
401 clientSession.lastConnectedAt === null
402 ? null
403 : DateTime.formatIso(clientSession.lastConnectedAt),
404 connected: clientSession.connected,
405 current: clientSession.current,
406 }));
407 } catch (error) {
408 throw new Error(
409 readHttpApiErrorMessage(
410 error,
411 `Failed to load paired clients (${readHttpApiStatus(error) ?? "unknown"}).`,
412 ),
413 { cause: error },
414 );
415 }
417​
418export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
419 try {
420 await runPrimaryHttp(
421 PrimaryEnvironmentHttpClient.pipe(
422 Effect.flatMap((client) =>
423 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
424 ),
425 ),
426 );
427 } catch (error) {
428 throw new Error(
429 readHttpApiErrorMessage(
430 error,
431 `Failed to revoke client session (${readHttpApiStatus(error) ?? "unknown"}).`,
432 ),
433 { cause: error },
434 );
435 }
437​
438export async function revokeOtherServerClientSessions(): Promise<number> {
439 try {
440 const result = await runPrimaryHttp(
441 PrimaryEnvironmentHttpClient.pipe(
442 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
443 ),
444 );
445 return result.revokedCount;
446 } catch (error) {
447 throw new Error(
448 readHttpApiErrorMessage(
449 error,
450 `Failed to revoke other client sessions (${readHttpApiStatus(error) ?? "unknown"}).`,
451 ),
452 { cause: error },
453 );
454 }
456​
457export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
458 if (resolvedAuthenticatedGateState?.status === "authenticated") {
459 return resolvedAuthenticatedGateState;
460 }
461​
462 if (bootstrapPromise) {
463 return bootstrapPromise;
464 }
465​
466 const nextPromise = bootstrapServerAuth();
467 bootstrapPromise = nextPromise;
468 return nextPromise
469 .then((result) => {
470 if (result.status === "authenticated") {
471 resolvedAuthenticatedGateState = result;
472 }
473 return result;
474 })
475 .finally(() => {
476 if (bootstrapPromise === nextPromise) {
477 bootstrapPromise = null;
478 }
479 });
481​
482export function __resetServerAuthBootstrapForTests() {
483 bootstrapPromise = null;
484 resolvedAuthenticatedGateState = null;