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

auth.ts

471 lines14.0 KB

1import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 AuthEnvironmentScope,
5 AuthPairingCredentialResult,
6 ServerAuthSessionMethod,
7 AuthSessionId,
8 AuthSessionState,
9} from "@t3tools/contracts";
10import { EnvironmentHttpCommonError, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
11import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
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";
23​
24const PrimaryEnvironmentRequestOperation = Schema.Literals([
25 "fetch-session-state",
26 "exchange-bootstrap-credential",
27 "fetch-environment-descriptor",
28 "create-pairing-credential",
29 "list-pairing-links",
30 "revoke-pairing-link",
31 "list-client-sessions",
32 "revoke-client-session",
33 "revoke-other-client-sessions",
34]);
35type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
36​
37export class PrimaryEnvironmentRequestError extends Schema.TaggedError<PrimaryEnvironmentRequestError>()(
38 "PrimaryEnvironmentRequestError",
39 {
40 operation: PrimaryEnvironmentRequestOperation,
41 status: Schema.Number,
42 pairingLinkId: Schema.optional(Schema.String),
43 sessionId: Schema.optional(Schema.String),
44 cause: Schema.Defect(),
45 },
46) {
47 static fromCause(input: {
48 readonly operation: PrimaryEnvironmentRequestOperation;
49 readonly cause: unknown;
50 readonly pairingLinkId?: string;
51 readonly sessionId?: string;
52 }): PrimaryEnvironmentRequestError {
53 const status = readHttpApiStatus(input.cause) ?? 500;
54 return new PrimaryEnvironmentRequestError({
55 operation: input.operation,
56 status,
57 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
58 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
59 cause: input.cause,
60 });
61 }
62​
63 override get message(): string {
64 return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
65 }
67​
68const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
69​
70export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRejectedError>()(
71 "PrimaryEnvironmentPairingCredentialRejectedError",
72 {
73 providedLength: Schema.Number,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return "Invalid pairing token. Check the token and try again.";
79 }
81​
82export const isPrimaryEnvironmentPairingCredentialRejectedError = Schema.is(
83 PrimaryEnvironmentPairingCredentialRejectedError,
84);
85​
86export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedError<PrimaryEnvironmentAuthSessionTimeoutError>()(
87 "PrimaryEnvironmentAuthSessionTimeoutError",
88 {
89 timeoutMs: Schema.Number,
90 elapsedMs: Schema.Number,
91 },
92) {
93 override get message(): string {
94 return "Timed out waiting for authenticated session after bootstrap.";
95 }
97​
98export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRequiredError>()(
99 "PrimaryEnvironmentPairingCredentialRequiredError",
100 {
101 providedLength: Schema.Number,
102 },
103) {
104 override get message(): string {
105 return "Enter a pairing token to continue.";
106 }
108​
109const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
110​
111export interface ServerPairingLinkRecord {
112 readonly id: string;
113 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
114 readonly subject: string;
115 readonly label?: string;
116 readonly createdAt: string;
117 readonly expiresAt: string;
119​
120export interface ServerClientSessionRecord {
121 readonly sessionId: AuthSessionId;
122 readonly subject: string;
123 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
124 readonly method: ServerAuthSessionMethod;
125 readonly client: AuthClientMetadata;
126 readonly issuedAt: string;
127 readonly expiresAt: string;
128 readonly lastConnectedAt: string | null;
129 readonly connected: boolean;
130 readonly current: boolean;
132​
133type ServerAuthGateState =
134 | { status: "authenticated" }
135 | {
136 status: "requires-auth";
137 auth: AuthSessionState["auth"];
138 errorMessage?: string;
139 };
140​
141let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
142let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
143const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
144const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
145​
146export function peekPairingTokenFromUrl(): string | null {
147 return getPairingTokenFromUrl(new URL(window.location.href));
149​
150export function stripPairingTokenFromUrl() {
151 const url = new URL(window.location.href);
152 const next = stripPairingTokenUrl(url);
153 if (next.toString() === url.toString()) {
154 return;
155 }
156 window.history.replaceState({}, document.title, next.toString());
158​
159export function takePairingTokenFromUrl(): string | null {
160 const token = peekPairingTokenFromUrl();
161 if (!token) {
162 return null;
163 }
164 stripPairingTokenFromUrl();
165 return token;
167​
168function getDesktopBootstrapCredential(): string | null {
169 // Both backends share the same bootstrap token (DesktopBackendConfiguration
170 // mints one tokenRef and feeds it to both resolvers), so picking the
171 // primary entry is fine even when the WSL backend is also registered.
172 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
173 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
174 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
175 ? primary.bootstrapToken
176 : null;
178​
179export async function fetchSessionState(): Promise<AuthSessionState> {
180 return retryTransientBootstrap(async () => {
181 try {
182 return await runPrimaryHttp(
183 PrimaryEnvironmentHttpClient.pipe(
184 Effect.flatMap((client) => client.auth.session({ headers: {} })),
185 ),
186 );
187 } catch (error) {
188 throw PrimaryEnvironmentRequestError.fromCause({
189 operation: "fetch-session-state",
190 cause: error,
191 });
192 }
193 });
195​
196function readHttpApiStatus(error: unknown): number | null {
197 if (isEnvironmentHttpCommonError(error)) {
198 return readEnvironmentHttpErrorStatus(error);
199 }
200 return HttpClientError.isHttpClientError(error) && error.response !== undefined
201 ? error.response.status
202 : null;
204​
205function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
206 switch (error._tag) {
207 case "EnvironmentRequestInvalidError":
208 return 400;
209 case "EnvironmentAuthInvalidError":
210 return 401;
211 case "EnvironmentScopeRequiredError":
212 case "EnvironmentOperationForbiddenError":
213 return 403;
214 case "EnvironmentResourceNotFoundError":
215 return 404;
216 case "EnvironmentInternalError":
217 return 500;
218 }
220​
221async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
222 return retryTransientBootstrap(async () => {
223 try {
224 return await runPrimaryHttp(
225 PrimaryEnvironmentHttpClient.pipe(
226 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
227 ),
228 );
229 } catch (error) {
230 if (
231 isEnvironmentHttpCommonError(error) &&
232 error._tag === "EnvironmentAuthInvalidError" &&
233 error.reason === "invalid_credential"
234 ) {
235 throw new PrimaryEnvironmentPairingCredentialRejectedError({
236 providedLength: credential.length,
237 cause: error,
238 });
239 }
240 throw PrimaryEnvironmentRequestError.fromCause({
241 operation: "exchange-bootstrap-credential",
242 cause: error,
243 });
244 }
245 });
247​
248async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
249 const startedAt = Date.now();
250​
251 while (true) {
252 const session = await fetchSessionState();
253 if (session.authenticated) {
254 return session;
255 }
256​
257 const elapsedMs = Date.now() - startedAt;
258 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
259 throw new PrimaryEnvironmentAuthSessionTimeoutError({
260 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
261 elapsedMs,
262 });
263 }
264​
265 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
266 }
268​
269const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
270const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
271const BOOTSTRAP_RETRY_STEP_MS = 500;
272​
273export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
274 const startedAt = Date.now();
275 while (true) {
276 try {
277 return await operation();
278 } catch (error) {
279 if (!isTransientBootstrapError(error)) {
280 throw error;
281 }
282​
283 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
284 throw error;
285 }
286​
287 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
288 }
289 }
291​
292function waitForBootstrapRetry(delayMs: number): Promise<void> {
293 return new Promise((resolve) => {
294 setTimeout(resolve, delayMs);
295 });
297​
298function isTransientBootstrapError(error: unknown): boolean {
299 if (isPrimaryEnvironmentRequestError(error)) {
300 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
301 }
302​
303 if (error instanceof TypeError) {
304 return true;
305 }
306​
307 return error instanceof DOMException && error.name === "AbortError";
309​
310async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
311 const currentSession = await fetchSessionState();
312 if (currentSession.authenticated && !urlCredential) {
313 return { status: "authenticated" };
314 }
315​
316 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
317 if (!bootstrapCredential) {
318 return {
319 status: "requires-auth",
320 auth: currentSession.auth,
321 };
322 }
323​
324 try {
325 await exchangeBootstrapCredential(bootstrapCredential);
326 await waitForAuthenticatedSessionAfterBootstrap();
327 return { status: "authenticated" };
328 } catch (error) {
329 return {
330 status: "requires-auth",
331 auth: currentSession.auth,
332 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
333 };
334 }
336​
337export async function submitServerAuthCredential(credential: string): Promise<void> {
338 const trimmedCredential = credential.trim();
339 if (!trimmedCredential) {
340 throw new PrimaryEnvironmentPairingCredentialRequiredError({
341 providedLength: credential.length,
342 });
343 }
344​
345 resolvedAuthenticatedGateState = null;
346 await exchangeBootstrapCredential(trimmedCredential);
347 await waitForAuthenticatedSessionAfterBootstrap();
348 resolvedAuthenticatedGateState = { status: "authenticated" };
349 bootstrapPromise = null;
350 stripPairingTokenFromUrl();
352​
353export async function createServerPairingCredential(input?: {
354 readonly label?: string;
355 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
356}): Promise<AuthPairingCredentialResult> {
357 const trimmedLabel = input?.label?.trim();
358 try {
359 return await runPrimaryHttp(
360 PrimaryEnvironmentHttpClient.pipe(
361 Effect.flatMap((client) =>
362 client.auth.pairingCredential({
363 headers: {},
364 payload: {
365 ...(trimmedLabel ? { label: trimmedLabel } : {}),
366 ...(input?.scopes ? { scopes: input.scopes } : {}),
367 },
368 }),
369 ),
370 ),
371 );
372 } catch (error) {
373 throw PrimaryEnvironmentRequestError.fromCause({
374 operation: "create-pairing-credential",
375 cause: error,
376 });
377 }
379​
380export async function revokeServerPairingLink(id: string): Promise<void> {
381 try {
382 await runPrimaryHttp(
383 PrimaryEnvironmentHttpClient.pipe(
384 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
385 ),
386 );
387 } catch (error) {
388 throw PrimaryEnvironmentRequestError.fromCause({
389 operation: "revoke-pairing-link",
390 pairingLinkId: id,
391 cause: error,
392 });
393 }
395​
396export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
397 try {
398 await runPrimaryHttp(
399 PrimaryEnvironmentHttpClient.pipe(
400 Effect.flatMap((client) =>
401 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
402 ),
403 ),
404 );
405 } catch (error) {
406 throw PrimaryEnvironmentRequestError.fromCause({
407 operation: "revoke-client-session",
408 sessionId,
409 cause: error,
410 });
411 }
413​
414export async function revokeOtherServerClientSessions(): Promise<number> {
415 try {
416 const result = await runPrimaryHttp(
417 PrimaryEnvironmentHttpClient.pipe(
418 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
419 ),
420 );
421 return result.revokedCount;
422 } catch (error) {
423 throw PrimaryEnvironmentRequestError.fromCause({
424 operation: "revoke-other-client-sessions",
425 cause: error,
426 });
427 }
429​
430export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
431 const urlCredential = takePairingTokenFromUrl();
432 const previousPromise = bootstrapPromise;
433 if (urlCredential) {
434 resolvedAuthenticatedGateState = null;
435 } else {
436 if (previousPromise) {
437 return previousPromise;
438 }
439​
440 if (resolvedAuthenticatedGateState?.status === "authenticated") {
441 return resolvedAuthenticatedGateState;
442 }
443 }
444​
445 const nextPromise = previousPromise
446 ? previousPromise
447 .catch(() => undefined)
448 .then(() => {
449 resolvedAuthenticatedGateState = null;
450 return bootstrapServerAuth(urlCredential);
451 })
452 : bootstrapServerAuth(urlCredential);
453 bootstrapPromise = nextPromise;
454 return nextPromise
455 .then((result) => {
456 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
457 resolvedAuthenticatedGateState = result;
458 }
459 return result;
460 })
461 .finally(() => {
462 if (bootstrapPromise === nextPromise) {
463 bootstrapPromise = null;
464 }
465 });
467​
468export function __resetServerAuthBootstrapForTests() {
469 bootstrapPromise = null;
470 resolvedAuthenticatedGateState = null;