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

auth.ts

548 lines16.4 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 credential: string;
123 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
124 readonly subject: string;
125 readonly label?: string;
126 readonly createdAt: string;
127 readonly expiresAt: string;
129​
130export interface ServerClientSessionRecord {
131 readonly sessionId: AuthSessionId;
132 readonly subject: string;
133 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
134 readonly method: ServerAuthSessionMethod;
135 readonly client: AuthClientMetadata;
136 readonly issuedAt: string;
137 readonly expiresAt: string;
138 readonly lastConnectedAt: string | null;
139 readonly connected: boolean;
140 readonly current: boolean;
142​
143type ServerAuthGateState =
144 | { status: "authenticated" }
145 | {
146 status: "requires-auth";
147 auth: AuthSessionState["auth"];
148 errorMessage?: string;
149 };
150​
151let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
152let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
153const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
154const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
155​
156export function peekPairingTokenFromUrl(): string | null {
157 return getPairingTokenFromUrl(new URL(window.location.href));
159​
160export function stripPairingTokenFromUrl() {
161 const url = new URL(window.location.href);
162 const next = stripPairingTokenUrl(url);
163 if (next.toString() === url.toString()) {
164 return;
165 }
166 window.history.replaceState({}, document.title, next.toString());
168​
169export function takePairingTokenFromUrl(): string | null {
170 const token = peekPairingTokenFromUrl();
171 if (!token) {
172 return null;
173 }
174 stripPairingTokenFromUrl();
175 return token;
177​
178function getDesktopBootstrapCredential(): string | null {
179 // Both backends share the same bootstrap token (DesktopBackendConfiguration
180 // mints one tokenRef and feeds it to both resolvers), so picking the
181 // primary entry is fine even when the WSL backend is also registered.
182 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
183 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
184 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
185 ? primary.bootstrapToken
186 : null;
188​
189export async function fetchSessionState(): Promise<AuthSessionState> {
190 return retryTransientBootstrap(async () => {
191 try {
192 return await runPrimaryHttp(
193 PrimaryEnvironmentHttpClient.pipe(
194 Effect.flatMap((client) => client.auth.session({ headers: {} })),
195 ),
196 );
197 } catch (error) {
198 throw PrimaryEnvironmentRequestError.fromCause({
199 operation: "fetch-session-state",
200 cause: error,
201 });
202 }
203 });
205​
206function readHttpApiStatus(error: unknown): number | null {
207 if (isEnvironmentHttpCommonError(error)) {
208 return readEnvironmentHttpErrorStatus(error);
209 }
210 return HttpClientError.isHttpClientError(error) && error.response !== undefined
211 ? error.response.status
212 : null;
214​
215function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
216 switch (error._tag) {
217 case "EnvironmentRequestInvalidError":
218 return 400;
219 case "EnvironmentAuthInvalidError":
220 return 401;
221 case "EnvironmentScopeRequiredError":
222 case "EnvironmentOperationForbiddenError":
223 return 403;
224 case "EnvironmentResourceNotFoundError":
225 return 404;
226 case "EnvironmentInternalError":
227 return 500;
228 }
230​
231async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
232 return retryTransientBootstrap(async () => {
233 try {
234 return await runPrimaryHttp(
235 PrimaryEnvironmentHttpClient.pipe(
236 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
237 ),
238 );
239 } catch (error) {
240 if (
241 isEnvironmentHttpCommonError(error) &&
242 error._tag === "EnvironmentAuthInvalidError" &&
243 error.reason === "invalid_credential"
244 ) {
245 throw new PrimaryEnvironmentPairingCredentialRejectedError({
246 providedLength: credential.length,
247 cause: error,
248 });
249 }
250 throw PrimaryEnvironmentRequestError.fromCause({
251 operation: "exchange-bootstrap-credential",
252 cause: error,
253 });
254 }
255 });
257​
258async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
259 const startedAt = Date.now();
260​
261 while (true) {
262 const session = await fetchSessionState();
263 if (session.authenticated) {
264 return session;
265 }
266​
267 const elapsedMs = Date.now() - startedAt;
268 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
269 throw new PrimaryEnvironmentAuthSessionTimeoutError({
270 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
271 elapsedMs,
272 });
273 }
274​
275 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
276 }
278​
279const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
280const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
281const BOOTSTRAP_RETRY_STEP_MS = 500;
282​
283export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
284 const startedAt = Date.now();
285 while (true) {
286 try {
287 return await operation();
288 } catch (error) {
289 if (!isTransientBootstrapError(error)) {
290 throw error;
291 }
292​
293 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
294 throw error;
295 }
296​
297 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
298 }
299 }
301​
302function waitForBootstrapRetry(delayMs: number): Promise<void> {
303 return new Promise((resolve) => {
304 setTimeout(resolve, delayMs);
305 });
307​
308function isTransientBootstrapError(error: unknown): boolean {
309 if (isPrimaryEnvironmentRequestError(error)) {
310 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
311 }
312​
313 if (error instanceof TypeError) {
314 return true;
315 }
316​
317 return error instanceof DOMException && error.name === "AbortError";
319​
320async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
321 const bootstrapCredential = getDesktopBootstrapCredential();
322 const currentSession = await fetchSessionState();
323 if (currentSession.authenticated) {
324 return { status: "authenticated" };
325 }
326​
327 if (!bootstrapCredential) {
328 return {
329 status: "requires-auth",
330 auth: currentSession.auth,
331 };
332 }
333​
334 try {
335 await exchangeBootstrapCredential(bootstrapCredential);
336 await waitForAuthenticatedSessionAfterBootstrap();
337 return { status: "authenticated" };
338 } catch (error) {
339 return {
340 status: "requires-auth",
341 auth: currentSession.auth,
342 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
343 };
344 }
346​
347export async function submitServerAuthCredential(credential: string): Promise<void> {
348 const trimmedCredential = credential.trim();
349 if (!trimmedCredential) {
350 throw new PrimaryEnvironmentPairingCredentialRequiredError({
351 providedLength: credential.length,
352 });
353 }
354​
355 resolvedAuthenticatedGateState = null;
356 await exchangeBootstrapCredential(trimmedCredential);
357 bootstrapPromise = null;
358 stripPairingTokenFromUrl();
360​
361export async function createServerPairingCredential(input?: {
362 readonly label?: string;
363 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
364}): Promise<AuthPairingCredentialResult> {
365 const trimmedLabel = input?.label?.trim();
366 try {
367 return await runPrimaryHttp(
368 PrimaryEnvironmentHttpClient.pipe(
369 Effect.flatMap((client) =>
370 client.auth.pairingCredential({
371 headers: {},
372 payload: {
373 ...(trimmedLabel ? { label: trimmedLabel } : {}),
374 ...(input?.scopes ? { scopes: input.scopes } : {}),
375 },
376 }),
377 ),
378 ),
379 );
380 } catch (error) {
381 throw PrimaryEnvironmentRequestError.fromCause({
382 operation: "create-pairing-credential",
383 cause: error,
384 });
385 }
387​
388export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
389 try {
390 const pairingLinks = await runPrimaryHttp(
391 PrimaryEnvironmentHttpClient.pipe(
392 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
393 ),
394 );
395 return pairingLinks.map((pairingLink) => {
396 const timestamps = {
397 createdAt: DateTime.formatIso(pairingLink.createdAt),
398 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
399 };
400 if (pairingLink.label === undefined) {
401 return {
402 id: pairingLink.id,
403 credential: pairingLink.credential,
404 scopes: pairingLink.scopes,
405 subject: pairingLink.subject,
406 createdAt: timestamps.createdAt,
407 expiresAt: timestamps.expiresAt,
408 };
409 }
410 return {
411 id: pairingLink.id,
412 credential: pairingLink.credential,
413 scopes: pairingLink.scopes,
414 subject: pairingLink.subject,
415 label: pairingLink.label,
416 createdAt: timestamps.createdAt,
417 expiresAt: timestamps.expiresAt,
418 };
419 });
420 } catch (error) {
421 throw PrimaryEnvironmentRequestError.fromCause({
422 operation: "list-pairing-links",
423 cause: error,
424 });
425 }
427​
428export async function revokeServerPairingLink(id: string): Promise<void> {
429 try {
430 await runPrimaryHttp(
431 PrimaryEnvironmentHttpClient.pipe(
432 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
433 ),
434 );
435 } catch (error) {
436 throw PrimaryEnvironmentRequestError.fromCause({
437 operation: "revoke-pairing-link",
438 pairingLinkId: id,
439 cause: error,
440 });
441 }
443​
444export async function listServerClientSessions(): Promise<
445 ReadonlyArray<ServerClientSessionRecord>
446> {
447 try {
448 const clientSessions = await runPrimaryHttp(
449 PrimaryEnvironmentHttpClient.pipe(
450 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
451 ),
452 );
453 return clientSessions.map((clientSession) => ({
454 sessionId: clientSession.sessionId,
455 subject: clientSession.subject,
456 scopes: clientSession.scopes,
457 method: clientSession.method,
458 client: clientSession.client,
459 issuedAt: DateTime.formatIso(clientSession.issuedAt),
460 expiresAt: DateTime.formatIso(clientSession.expiresAt),
461 lastConnectedAt:
462 clientSession.lastConnectedAt === null
463 ? null
464 : DateTime.formatIso(clientSession.lastConnectedAt),
465 connected: clientSession.connected,
466 current: clientSession.current,
467 }));
468 } catch (error) {
469 throw PrimaryEnvironmentRequestError.fromCause({
470 operation: "list-client-sessions",
471 cause: error,
472 });
473 }
475​
476export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
477 try {
478 await runPrimaryHttp(
479 PrimaryEnvironmentHttpClient.pipe(
480 Effect.flatMap((client) =>
481 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
482 ),
483 ),
484 );
485 } catch (error) {
486 throw PrimaryEnvironmentRequestError.fromCause({
487 operation: "revoke-client-session",
488 sessionId,
489 cause: error,
490 });
491 }
493​
494export async function revokeOtherServerClientSessions(): Promise<number> {
495 try {
496 const result = await runPrimaryHttp(
497 PrimaryEnvironmentHttpClient.pipe(
498 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
499 ),
500 );
501 return result.revokedCount;
502 } catch (error) {
503 throw PrimaryEnvironmentRequestError.fromCause({
504 operation: "revoke-other-client-sessions",
505 cause: error,
506 });
507 }
509​
510export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
511 if (resolvedAuthenticatedGateState?.status === "authenticated") {
512 return resolvedAuthenticatedGateState;
513 }
514​
515 if (bootstrapPromise) {
516 return bootstrapPromise;
517 }
518​
519 const nextPromise = bootstrapServerAuth();
520 bootstrapPromise = nextPromise;
521 return nextPromise
522 .then((result) => {
523 if (result.status === "authenticated") {
524 resolvedAuthenticatedGateState = result;
525 }
526 return result;
527 })
528 .finally(() => {
529 if (bootstrapPromise === nextPromise) {
530 bootstrapPromise = null;
531 }
532 });
534​
535// Used by the WSL backend swap: invalidate the cached authenticated state
536// (the new backend signs sessions with a different key) and re-bootstrap
537// against the desktop bootstrap credential so the next WS reconnect doesn't
538// hit 401 and start a reauth loop in the renderer.
539export async function reauthenticatePrimaryEnvironment(): Promise<ServerAuthGateState> {
540 resolvedAuthenticatedGateState = null;
541 bootstrapPromise = null;
542 return resolveInitialServerAuthGateState();
544​
545export function __resetServerAuthBootstrapForTests() {
546 bootstrapPromise = null;
547 resolvedAuthenticatedGateState = null;