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

auth.ts

545 lines16.3 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 DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import { HttpClientError } from "effect/unstable/http";
16​
17import {
18 getPairingTokenFromUrl,
19 stripPairingTokenFromUrl as stripPairingTokenUrl,
20} from "../../pairingUrl";
21​
22import { PrimaryEnvironmentHttpClient } from "./httpClient";
23import { runPrimaryHttp } from "../../lib/runtime";
24​
25const PrimaryEnvironmentRequestOperation = Schema.Literals([
26 "fetch-session-state",
27 "exchange-bootstrap-credential",
28 "fetch-environment-descriptor",
29 "create-pairing-credential",
30 "list-pairing-links",
31 "revoke-pairing-link",
32 "list-client-sessions",
33 "revoke-client-session",
34 "revoke-other-client-sessions",
35]);
36type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
37​
38export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<PrimaryEnvironmentRequestError>()(
39 "PrimaryEnvironmentRequestError",
40 {
41 operation: PrimaryEnvironmentRequestOperation,
42 status: Schema.Number,
43 pairingLinkId: Schema.optional(Schema.String),
44 sessionId: Schema.optional(Schema.String),
45 cause: Schema.Defect(),
46 },
47) {
48 static fromCause(input: {
49 readonly operation: PrimaryEnvironmentRequestOperation;
50 readonly cause: unknown;
51 readonly pairingLinkId?: string;
52 readonly sessionId?: string;
53 }): PrimaryEnvironmentRequestError {
54 const status = readHttpApiStatus(input.cause) ?? 500;
55 return new PrimaryEnvironmentRequestError({
56 operation: input.operation,
57 status,
58 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
59 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
60 cause: input.cause,
61 });
62 }
63​
64 override get message(): string {
65 return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
66 }
68​
69export const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
70​
71export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRejectedError>()(
72 "PrimaryEnvironmentPairingCredentialRejectedError",
73 {
74 providedLength: Schema.Number,
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return "Invalid pairing token. Check the token and try again.";
80 }
82​
83export const isPrimaryEnvironmentPairingCredentialRejectedError = Schema.is(
84 PrimaryEnvironmentPairingCredentialRejectedError,
85);
86​
87export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedErrorClass<PrimaryEnvironmentAuthSessionTimeoutError>()(
88 "PrimaryEnvironmentAuthSessionTimeoutError",
89 {
90 timeoutMs: Schema.Number,
91 elapsedMs: Schema.Number,
92 },
93) {
94 override get message(): string {
95 return "Timed out waiting for authenticated session after bootstrap.";
96 }
98​
99export const isPrimaryEnvironmentAuthSessionTimeoutError = Schema.is(
100 PrimaryEnvironmentAuthSessionTimeoutError,
101);
102​
103export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRequiredError>()(
104 "PrimaryEnvironmentPairingCredentialRequiredError",
105 {
106 providedLength: Schema.Number,
107 },
108) {
109 override get message(): string {
110 return "Enter a pairing token to continue.";
111 }
113​
114export const isPrimaryEnvironmentPairingCredentialRequiredError = Schema.is(
115 PrimaryEnvironmentPairingCredentialRequiredError,
116);
117​
118const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
119​
120export interface ServerPairingLinkRecord {
121 readonly id: string;
122 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
123 readonly subject: string;
124 readonly label?: string;
125 readonly createdAt: string;
126 readonly expiresAt: string;
128​
129export interface ServerClientSessionRecord {
130 readonly sessionId: AuthSessionId;
131 readonly subject: string;
132 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
133 readonly method: ServerAuthSessionMethod;
134 readonly client: AuthClientMetadata;
135 readonly issuedAt: string;
136 readonly expiresAt: string;
137 readonly lastConnectedAt: string | null;
138 readonly connected: boolean;
139 readonly current: boolean;
141​
142type ServerAuthGateState =
143 | { status: "authenticated" }
144 | {
145 status: "requires-auth";
146 auth: AuthSessionState["auth"];
147 errorMessage?: string;
148 };
149​
150let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
151let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
152const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
153const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
154​
155export function peekPairingTokenFromUrl(): string | null {
156 return getPairingTokenFromUrl(new URL(window.location.href));
158​
159export function stripPairingTokenFromUrl() {
160 const url = new URL(window.location.href);
161 const next = stripPairingTokenUrl(url);
162 if (next.toString() === url.toString()) {
163 return;
164 }
165 window.history.replaceState({}, document.title, next.toString());
167​
168export function takePairingTokenFromUrl(): string | null {
169 const token = peekPairingTokenFromUrl();
170 if (!token) {
171 return null;
172 }
173 stripPairingTokenFromUrl();
174 return token;
176​
177function getDesktopBootstrapCredential(): string | null {
178 // Both backends share the same bootstrap token (DesktopBackendConfiguration
179 // mints one tokenRef and feeds it to both resolvers), so picking the
180 // primary entry is fine even when the WSL backend is also registered.
181 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
182 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
183 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
184 ? primary.bootstrapToken
185 : null;
187​
188export async function fetchSessionState(): Promise<AuthSessionState> {
189 return retryTransientBootstrap(async () => {
190 try {
191 return await runPrimaryHttp(
192 PrimaryEnvironmentHttpClient.pipe(
193 Effect.flatMap((client) => client.auth.session({ headers: {} })),
194 ),
195 );
196 } catch (error) {
197 throw PrimaryEnvironmentRequestError.fromCause({
198 operation: "fetch-session-state",
199 cause: error,
200 });
201 }
202 });
204​
205function readHttpApiStatus(error: unknown): number | null {
206 if (isEnvironmentHttpCommonError(error)) {
207 return readEnvironmentHttpErrorStatus(error);
208 }
209 return HttpClientError.isHttpClientError(error) && error.response !== undefined
210 ? error.response.status
211 : null;
213​
214function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
215 switch (error._tag) {
216 case "EnvironmentRequestInvalidError":
217 return 400;
218 case "EnvironmentAuthInvalidError":
219 return 401;
220 case "EnvironmentScopeRequiredError":
221 case "EnvironmentOperationForbiddenError":
222 return 403;
223 case "EnvironmentResourceNotFoundError":
224 return 404;
225 case "EnvironmentInternalError":
226 return 500;
227 }
229​
230async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
231 return retryTransientBootstrap(async () => {
232 try {
233 return await runPrimaryHttp(
234 PrimaryEnvironmentHttpClient.pipe(
235 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
236 ),
237 );
238 } catch (error) {
239 if (
240 isEnvironmentHttpCommonError(error) &&
241 error._tag === "EnvironmentAuthInvalidError" &&
242 error.reason === "invalid_credential"
243 ) {
244 throw new PrimaryEnvironmentPairingCredentialRejectedError({
245 providedLength: credential.length,
246 cause: error,
247 });
248 }
249 throw PrimaryEnvironmentRequestError.fromCause({
250 operation: "exchange-bootstrap-credential",
251 cause: error,
252 });
253 }
254 });
256​
257async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
258 const startedAt = Date.now();
259​
260 while (true) {
261 const session = await fetchSessionState();
262 if (session.authenticated) {
263 return session;
264 }
265​
266 const elapsedMs = Date.now() - startedAt;
267 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
268 throw new PrimaryEnvironmentAuthSessionTimeoutError({
269 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
270 elapsedMs,
271 });
272 }
273​
274 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
275 }
277​
278const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
279const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
280const BOOTSTRAP_RETRY_STEP_MS = 500;
281​
282export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
283 const startedAt = Date.now();
284 while (true) {
285 try {
286 return await operation();
287 } catch (error) {
288 if (!isTransientBootstrapError(error)) {
289 throw error;
290 }
291​
292 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
293 throw error;
294 }
295​
296 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
297 }
298 }
300​
301function waitForBootstrapRetry(delayMs: number): Promise<void> {
302 return new Promise((resolve) => {
303 setTimeout(resolve, delayMs);
304 });
306​
307function isTransientBootstrapError(error: unknown): boolean {
308 if (isPrimaryEnvironmentRequestError(error)) {
309 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
310 }
311​
312 if (error instanceof TypeError) {
313 return true;
314 }
315​
316 return error instanceof DOMException && error.name === "AbortError";
318​
319async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
320 const bootstrapCredential = getDesktopBootstrapCredential();
321 const currentSession = await fetchSessionState();
322 if (currentSession.authenticated) {
323 return { status: "authenticated" };
324 }
325​
326 if (!bootstrapCredential) {
327 return {
328 status: "requires-auth",
329 auth: currentSession.auth,
330 };
331 }
332​
333 try {
334 await exchangeBootstrapCredential(bootstrapCredential);
335 await waitForAuthenticatedSessionAfterBootstrap();
336 return { status: "authenticated" };
337 } catch (error) {
338 return {
339 status: "requires-auth",
340 auth: currentSession.auth,
341 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
342 };
343 }
345​
346export async function submitServerAuthCredential(credential: string): Promise<void> {
347 const trimmedCredential = credential.trim();
348 if (!trimmedCredential) {
349 throw new PrimaryEnvironmentPairingCredentialRequiredError({
350 providedLength: credential.length,
351 });
352 }
353​
354 resolvedAuthenticatedGateState = null;
355 await exchangeBootstrapCredential(trimmedCredential);
356 bootstrapPromise = null;
357 stripPairingTokenFromUrl();
359​
360export async function createServerPairingCredential(input?: {
361 readonly label?: string;
362 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
363}): Promise<AuthPairingCredentialResult> {
364 const trimmedLabel = input?.label?.trim();
365 try {
366 return await runPrimaryHttp(
367 PrimaryEnvironmentHttpClient.pipe(
368 Effect.flatMap((client) =>
369 client.auth.pairingCredential({
370 headers: {},
371 payload: {
372 ...(trimmedLabel ? { label: trimmedLabel } : {}),
373 ...(input?.scopes ? { scopes: input.scopes } : {}),
374 },
375 }),
376 ),
377 ),
378 );
379 } catch (error) {
380 throw PrimaryEnvironmentRequestError.fromCause({
381 operation: "create-pairing-credential",
382 cause: error,
383 });
384 }
386​
387export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
388 try {
389 const pairingLinks = await runPrimaryHttp(
390 PrimaryEnvironmentHttpClient.pipe(
391 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
392 ),
393 );
394 return pairingLinks.map((pairingLink) => {
395 const timestamps = {
396 createdAt: DateTime.formatIso(pairingLink.createdAt),
397 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
398 };
399 if (pairingLink.label === undefined) {
400 return {
401 id: pairingLink.id,
402 scopes: pairingLink.scopes,
403 subject: pairingLink.subject,
404 createdAt: timestamps.createdAt,
405 expiresAt: timestamps.expiresAt,
406 };
407 }
408 return {
409 id: pairingLink.id,
410 scopes: pairingLink.scopes,
411 subject: pairingLink.subject,
412 label: pairingLink.label,
413 createdAt: timestamps.createdAt,
414 expiresAt: timestamps.expiresAt,
415 };
416 });
417 } catch (error) {
418 throw PrimaryEnvironmentRequestError.fromCause({
419 operation: "list-pairing-links",
420 cause: error,
421 });
422 }
424​
425export async function revokeServerPairingLink(id: string): Promise<void> {
426 try {
427 await runPrimaryHttp(
428 PrimaryEnvironmentHttpClient.pipe(
429 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
430 ),
431 );
432 } catch (error) {
433 throw PrimaryEnvironmentRequestError.fromCause({
434 operation: "revoke-pairing-link",
435 pairingLinkId: id,
436 cause: error,
437 });
438 }
440​
441export async function listServerClientSessions(): Promise<
442 ReadonlyArray<ServerClientSessionRecord>
443> {
444 try {
445 const clientSessions = await runPrimaryHttp(
446 PrimaryEnvironmentHttpClient.pipe(
447 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
448 ),
449 );
450 return clientSessions.map((clientSession) => ({
451 sessionId: clientSession.sessionId,
452 subject: clientSession.subject,
453 scopes: clientSession.scopes,
454 method: clientSession.method,
455 client: clientSession.client,
456 issuedAt: DateTime.formatIso(clientSession.issuedAt),
457 expiresAt: DateTime.formatIso(clientSession.expiresAt),
458 lastConnectedAt:
459 clientSession.lastConnectedAt === null
460 ? null
461 : DateTime.formatIso(clientSession.lastConnectedAt),
462 connected: clientSession.connected,
463 current: clientSession.current,
464 }));
465 } catch (error) {
466 throw PrimaryEnvironmentRequestError.fromCause({
467 operation: "list-client-sessions",
468 cause: error,
469 });
470 }
472​
473export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
474 try {
475 await runPrimaryHttp(
476 PrimaryEnvironmentHttpClient.pipe(
477 Effect.flatMap((client) =>
478 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
479 ),
480 ),
481 );
482 } catch (error) {
483 throw PrimaryEnvironmentRequestError.fromCause({
484 operation: "revoke-client-session",
485 sessionId,
486 cause: error,
487 });
488 }
490​
491export async function revokeOtherServerClientSessions(): Promise<number> {
492 try {
493 const result = await runPrimaryHttp(
494 PrimaryEnvironmentHttpClient.pipe(
495 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
496 ),
497 );
498 return result.revokedCount;
499 } catch (error) {
500 throw PrimaryEnvironmentRequestError.fromCause({
501 operation: "revoke-other-client-sessions",
502 cause: error,
503 });
504 }
506​
507export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
508 if (resolvedAuthenticatedGateState?.status === "authenticated") {
509 return resolvedAuthenticatedGateState;
510 }
511​
512 if (bootstrapPromise) {
513 return bootstrapPromise;
514 }
515​
516 const nextPromise = bootstrapServerAuth();
517 bootstrapPromise = nextPromise;
518 return nextPromise
519 .then((result) => {
520 if (result.status === "authenticated") {
521 resolvedAuthenticatedGateState = result;
522 }
523 return result;
524 })
525 .finally(() => {
526 if (bootstrapPromise === nextPromise) {
527 bootstrapPromise = null;
528 }
529 });
531​
532// Used by the WSL backend swap: invalidate the cached authenticated state
533// (the new backend signs sessions with a different key) and re-bootstrap
534// against the desktop bootstrap credential so the next WS reconnect doesn't
535// hit 401 and start a reauth loop in the renderer.
536export async function reauthenticatePrimaryEnvironment(): Promise<ServerAuthGateState> {
537 resolvedAuthenticatedGateState = null;
538 bootstrapPromise = null;
539 return resolveInitialServerAuthGateState();
541​
542export function __resetServerAuthBootstrapForTests() {
543 bootstrapPromise = null;
544 resolvedAuthenticatedGateState = null;