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