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

auth.ts

401 lines12.1 KB

1import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 AuthEnvironmentScope,
5 ServerAuthSessionMethod,
6 AuthSessionId,
7 AuthSessionState,
8} from "@t3tools/contracts";
9import { EnvironmentHttpCommonError, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
10import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import { HttpClientError } from "effect/http";
14​
15import {
16 getPairingTokenFromUrl,
17 stripPairingTokenFromUrl as stripPairingTokenUrl,
18} from "@t3tools/shared/remote";
19​
20import { PrimaryEnvironmentHttpClient } from "./httpClient";
21import { runPrimaryHttp } from "../../lib/runtime";
22​
23const PrimaryEnvironmentRequestOperation = Schema.Literals([
24 "fetch-session-state",
25 "exchange-bootstrap-credential",
26 "fetch-environment-descriptor",
27 "create-pairing-credential",
28 "list-pairing-links",
29 "revoke-pairing-link",
30 "list-client-sessions",
31 "revoke-client-session",
32 "revoke-other-client-sessions",
33]);
34type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
35​
36export class PrimaryEnvironmentRequestError extends Schema.TaggedError<PrimaryEnvironmentRequestError>()(
37 "PrimaryEnvironmentRequestError",
38 {
39 operation: PrimaryEnvironmentRequestOperation,
40 status: Schema.Number,
41 pairingLinkId: Schema.optional(Schema.String),
42 sessionId: Schema.optional(Schema.String),
43 cause: Schema.Defect(),
44 },
45) {
46 static fromCause(input: {
47 readonly operation: PrimaryEnvironmentRequestOperation;
48 readonly cause: unknown;
49 readonly pairingLinkId?: string;
50 readonly sessionId?: string;
51 }): PrimaryEnvironmentRequestError {
52 const status = readHttpApiStatus(input.cause) ?? 500;
53 return new PrimaryEnvironmentRequestError({
54 operation: input.operation,
55 status,
56 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
57 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
58 cause: input.cause,
59 });
60 }
61​
62 override get message(): string {
63 return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
64 }
66​
67const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
68​
69export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRejectedError>()(
70 "PrimaryEnvironmentPairingCredentialRejectedError",
71 {
72 providedLength: Schema.Number,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return "Invalid pairing token. Check the token and try again.";
78 }
80​
81export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedError<PrimaryEnvironmentAuthSessionTimeoutError>()(
82 "PrimaryEnvironmentAuthSessionTimeoutError",
83 {
84 timeoutMs: Schema.Number,
85 elapsedMs: Schema.Number,
86 },
87) {
88 override get message(): string {
89 return "Timed out waiting for authenticated session after bootstrap.";
90 }
92​
93export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRequiredError>()(
94 "PrimaryEnvironmentPairingCredentialRequiredError",
95 {
96 providedLength: Schema.Number,
97 },
98) {
99 override get message(): string {
100 return "Enter a pairing token to continue.";
101 }
103​
104const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
105​
106export interface ServerPairingLinkRecord {
107 readonly id: string;
108 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
109 readonly subject: string;
110 readonly label?: string;
111 readonly createdAt: string;
112 readonly expiresAt: string;
114​
115export interface ServerClientSessionRecord {
116 readonly sessionId: AuthSessionId;
117 readonly subject: string;
118 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
119 readonly method: ServerAuthSessionMethod;
120 readonly client: AuthClientMetadata;
121 readonly issuedAt: string;
122 readonly expiresAt: string;
123 readonly lastConnectedAt: string | null;
124 readonly connected: boolean;
125 readonly current: boolean;
127​
128type ServerAuthGateState =
129 | { status: "authenticated" }
130 | {
131 status: "requires-auth";
132 auth: AuthSessionState["auth"];
133 errorMessage?: string;
134 };
135​
136let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
137let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
138let explicitPairingRequested = false;
139const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
140const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
141​
142export function peekPairingTokenFromUrl(): string | null {
143 return getPairingTokenFromUrl(new URL(window.location.href));
145​
146export function stripPairingTokenFromUrl() {
147 const url = new URL(window.location.href);
148 const next = stripPairingTokenUrl(url);
149 if (next.toString() === url.toString()) {
150 return;
151 }
152 window.history.replaceState({}, document.title, next.toString());
154​
155export function takePairingTokenFromUrl(): string | null {
156 const token = peekPairingTokenFromUrl();
157 if (!token) {
158 return null;
159 }
160 stripPairingTokenFromUrl();
161 return token;
163​
164function getDesktopBootstrapCredential(): string | null {
165 // DesktopBackendConfiguration gives primary and WSL the same bootstrap token.
166 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
167 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
168 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
169 ? primary.bootstrapToken
170 : null;
172​
173export async function fetchSessionState(): Promise<AuthSessionState> {
174 return retryTransientBootstrap(async () => {
175 try {
176 return await runPrimaryHttp(
177 PrimaryEnvironmentHttpClient.pipe(
178 Effect.flatMap((client) => client.auth.session({ headers: {} })),
179 ),
180 );
181 } catch (error) {
182 throw PrimaryEnvironmentRequestError.fromCause({
183 operation: "fetch-session-state",
184 cause: error,
185 });
186 }
187 });
189​
190function readHttpApiStatus(error: unknown): number | null {
191 if (isEnvironmentHttpCommonError(error)) {
192 return readEnvironmentHttpErrorStatus(error);
193 }
194 return HttpClientError.isHttpClientError(error) && error.response !== undefined
195 ? error.response.status
196 : null;
198​
199function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
200 switch (error._tag) {
201 case "EnvironmentRequestInvalidError":
202 return 400;
203 case "EnvironmentAuthInvalidError":
204 return 401;
205 case "EnvironmentScopeRequiredError":
206 case "EnvironmentOperationForbiddenError":
207 return 403;
208 case "EnvironmentResourceNotFoundError":
209 return 404;
210 case "EnvironmentInternalError":
211 return 500;
212 }
214​
215async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
216 return retryTransientBootstrap(async () => {
217 try {
218 return await runPrimaryHttp(
219 PrimaryEnvironmentHttpClient.pipe(
220 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
221 ),
222 );
223 } catch (error) {
224 if (
225 isEnvironmentHttpCommonError(error) &&
226 error._tag === "EnvironmentAuthInvalidError" &&
227 error.reason === "invalid_credential"
228 ) {
229 throw new PrimaryEnvironmentPairingCredentialRejectedError({
230 providedLength: credential.length,
231 cause: error,
232 });
233 }
234 throw PrimaryEnvironmentRequestError.fromCause({
235 operation: "exchange-bootstrap-credential",
236 cause: error,
237 });
238 }
239 });
241​
242async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
243 const startedAt = Date.now();
244​
245 while (true) {
246 const session = await fetchSessionState();
247 if (session.authenticated) {
248 return session;
249 }
250​
251 const elapsedMs = Date.now() - startedAt;
252 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
253 throw new PrimaryEnvironmentAuthSessionTimeoutError({
254 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
255 elapsedMs,
256 });
257 }
258​
259 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
260 }
262​
263const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
264const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
265const BOOTSTRAP_RETRY_STEP_MS = 500;
266​
267async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
268 const startedAt = Date.now();
269 while (true) {
270 try {
271 return await operation();
272 } catch (error) {
273 if (!isTransientBootstrapError(error)) {
274 throw error;
275 }
276​
277 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
278 throw error;
279 }
280​
281 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
282 }
283 }
285​
286function waitForBootstrapRetry(delayMs: number): Promise<void> {
287 return new Promise((resolve) => {
288 setTimeout(resolve, delayMs);
289 });
291​
292function isTransientBootstrapError(error: unknown): boolean {
293 if (isPrimaryEnvironmentRequestError(error)) {
294 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
295 }
296​
297 if (error instanceof TypeError) {
298 return true;
299 }
300​
301 return error instanceof DOMException && error.name === "AbortError";
303​
304async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
305 const currentSession = await fetchSessionState();
306 if (currentSession.authenticated && !urlCredential) {
307 return { status: "authenticated" };
308 }
309​
310 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
311 if (!bootstrapCredential) {
312 return {
313 status: "requires-auth",
314 auth: currentSession.auth,
315 };
316 }
317​
318 try {
319 await exchangeBootstrapCredential(bootstrapCredential);
320 await waitForAuthenticatedSessionAfterBootstrap();
321 return { status: "authenticated" };
322 } catch (error) {
323 return {
324 status: "requires-auth",
325 auth: currentSession.auth,
326 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
327 };
328 }
330​
331export async function submitServerAuthCredential(credential: string): Promise<void> {
332 const trimmedCredential = credential.trim();
333 if (!trimmedCredential) {
334 throw new PrimaryEnvironmentPairingCredentialRequiredError({
335 providedLength: credential.length,
336 });
337 }
338​
339 resolvedAuthenticatedGateState = null;
340 await exchangeBootstrapCredential(trimmedCredential);
341 await waitForAuthenticatedSessionAfterBootstrap();
342 resolvedAuthenticatedGateState = { status: "authenticated" };
343 bootstrapPromise = null;
344 explicitPairingRequested = false;
345 stripPairingTokenFromUrl();
347​
348export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
349 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
350 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
351 explicitPairingRequested = false;
352 } else if (peekPairingTokenFromUrl()) {
353 explicitPairingRequested = true;
354 }
355 if (explicitPairingRequested) {
356 const currentSession = await fetchSessionState();
357 return { status: "requires-auth", auth: currentSession.auth };
358 }
359​
360 const urlCredential = takePairingTokenFromUrl();
361 const previousPromise = bootstrapPromise;
362 if (urlCredential) {
363 resolvedAuthenticatedGateState = null;
364 } else {
365 if (previousPromise) {
366 return previousPromise;
367 }
368​
369 if (resolvedAuthenticatedGateState?.status === "authenticated") {
370 return resolvedAuthenticatedGateState;
371 }
372 }
373​
374 const nextPromise = previousPromise
375 ? previousPromise
376 .catch(() => undefined)
377 .then(() => {
378 resolvedAuthenticatedGateState = null;
379 return bootstrapServerAuth(urlCredential);
380 })
381 : bootstrapServerAuth(urlCredential);
382 bootstrapPromise = nextPromise;
383 return nextPromise
384 .then((result) => {
385 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
386 resolvedAuthenticatedGateState = result;
387 }
388 return result;
389 })
390 .finally(() => {
391 if (bootstrapPromise === nextPromise) {
392 bootstrapPromise = null;
393 }
394 });
396​
397export function __resetServerAuthBootstrapForTests() {
398 bootstrapPromise = null;
399 resolvedAuthenticatedGateState = null;
400 explicitPairingRequested = false;