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 "@t3tools/shared/remote";
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 // DesktopBackendConfiguration gives primary and WSL the same bootstrap token.
168 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
169 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
170 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
171 ? primary.bootstrapToken
172 : null;
173}
174
175export async function fetchSessionState(): Promise<AuthSessionState> {
176 return retryTransientBootstrap(async () => {
177 try {
178 return await runPrimaryHttp(
179 PrimaryEnvironmentHttpClient.pipe(
180 Effect.flatMap((client) => client.auth.session({ headers: {} })),
181 ),
182 );
183 } catch (error) {
184 throw PrimaryEnvironmentRequestError.fromCause({
185 operation: "fetch-session-state",
186 cause: error,
187 });
188 }
189 });
190}
191
192function readHttpApiStatus(error: unknown): number | null {
193 if (isEnvironmentHttpCommonError(error)) {
194 return readEnvironmentHttpErrorStatus(error);
195 }
196 return HttpClientError.isHttpClientError(error) && error.response !== undefined
197 ? error.response.status
198 : null;
199}
200
201function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
202 switch (error._tag) {
203 case "EnvironmentRequestInvalidError":
204 return 400;
205 case "EnvironmentAuthInvalidError":
206 return 401;
207 case "EnvironmentScopeRequiredError":
208 case "EnvironmentOperationForbiddenError":
209 return 403;
210 case "EnvironmentResourceNotFoundError":
211 return 404;
212 case "EnvironmentInternalError":
213 return 500;
214 }
215}
216
217async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
218 return retryTransientBootstrap(async () => {
219 try {
220 return await runPrimaryHttp(
221 PrimaryEnvironmentHttpClient.pipe(
222 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
223 ),
224 );
225 } catch (error) {
226 if (
227 isEnvironmentHttpCommonError(error) &&
228 error._tag === "EnvironmentAuthInvalidError" &&
229 error.reason === "invalid_credential"
230 ) {
231 throw new PrimaryEnvironmentPairingCredentialRejectedError({
232 providedLength: credential.length,
233 cause: error,
234 });
235 }
236 throw PrimaryEnvironmentRequestError.fromCause({
237 operation: "exchange-bootstrap-credential",
238 cause: error,
239 });
240 }
241 });
242}
243
244async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
245 const startedAt = Date.now();
246
247 while (true) {
248 const session = await fetchSessionState();
249 if (session.authenticated) {
250 return session;
251 }
252
253 const elapsedMs = Date.now() - startedAt;
254 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
255 throw new PrimaryEnvironmentAuthSessionTimeoutError({
256 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
257 elapsedMs,
258 });
259 }
260
261 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
262 }
263}
264
265const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
266const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
267const BOOTSTRAP_RETRY_STEP_MS = 500;
268
269async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
270 const startedAt = Date.now();
271 while (true) {
272 try {
273 return await operation();
274 } catch (error) {
275 if (!isTransientBootstrapError(error)) {
276 throw error;
277 }
278
279 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
280 throw error;
281 }
282
283 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
284 }
285 }
286}
287
288function waitForBootstrapRetry(delayMs: number): Promise<void> {
289 return new Promise((resolve) => {
290 setTimeout(resolve, delayMs);
291 });
292}
293
294function isTransientBootstrapError(error: unknown): boolean {
295 if (isPrimaryEnvironmentRequestError(error)) {
296 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
297 }
298
299 if (error instanceof TypeError) {
300 return true;
301 }
302
303 return error instanceof DOMException && error.name === "AbortError";
304}
305
306async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
307 const currentSession = await fetchSessionState();
308 if (currentSession.authenticated && !urlCredential) {
309 return { status: "authenticated" };
310 }
311
312 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
313 if (!bootstrapCredential) {
314 return {
315 status: "requires-auth",
316 auth: currentSession.auth,
317 };
318 }
319
320 try {
321 await exchangeBootstrapCredential(bootstrapCredential);
322 await waitForAuthenticatedSessionAfterBootstrap();
323 return { status: "authenticated" };
324 } catch (error) {
325 return {
326 status: "requires-auth",
327 auth: currentSession.auth,
328 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
329 };
330 }
331}
332
333export async function submitServerAuthCredential(credential: string): Promise<void> {
334 const trimmedCredential = credential.trim();
335 if (!trimmedCredential) {
336 throw new PrimaryEnvironmentPairingCredentialRequiredError({
337 providedLength: credential.length,
338 });
339 }
340
341 resolvedAuthenticatedGateState = null;
342 await exchangeBootstrapCredential(trimmedCredential);
343 await waitForAuthenticatedSessionAfterBootstrap();
344 resolvedAuthenticatedGateState = { status: "authenticated" };
345 bootstrapPromise = null;
346 explicitPairingRequested = false;
347 stripPairingTokenFromUrl();
348}
349
350export async function createServerPairingCredential(input?: {
351 readonly label?: string;
352 readonly scopes?: ReadonlyArray<AuthGrantScope>;
353}): Promise<AuthPairingCredentialResult> {
354 const trimmedLabel = input?.label?.trim();
355 try {
356 return await runPrimaryHttp(
357 PrimaryEnvironmentHttpClient.pipe(
358 Effect.flatMap((client) =>
359 client.auth.pairingCredential({
360 headers: {},
361 payload: {
362 ...(trimmedLabel ? { label: trimmedLabel } : {}),
363 ...(input?.scopes ? { scopes: input.scopes } : {}),
364 },
365 }),
366 ),
367 ),
368 );
369 } catch (error) {
370 throw PrimaryEnvironmentRequestError.fromCause({
371 operation: "create-pairing-credential",
372 cause: error,
373 });
374 }
375}
376
377export async function revokeServerPairingLink(id: string): Promise<void> {
378 try {
379 await runPrimaryHttp(
380 PrimaryEnvironmentHttpClient.pipe(
381 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
382 ),
383 );
384 } catch (error) {
385 throw PrimaryEnvironmentRequestError.fromCause({
386 operation: "revoke-pairing-link",
387 pairingLinkId: id,
388 cause: error,
389 });
390 }
391}
392
393export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
394 try {
395 await runPrimaryHttp(
396 PrimaryEnvironmentHttpClient.pipe(
397 Effect.flatMap((client) =>
398 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
399 ),
400 ),
401 );
402 } catch (error) {
403 throw PrimaryEnvironmentRequestError.fromCause({
404 operation: "revoke-client-session",
405 sessionId,
406 cause: error,
407 });
408 }
409}
410
411export async function revokeOtherServerClientSessions(): Promise<number> {
412 try {
413 const result = await runPrimaryHttp(
414 PrimaryEnvironmentHttpClient.pipe(
415 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
416 ),
417 );
418 return result.revokedCount;
419 } catch (error) {
420 throw PrimaryEnvironmentRequestError.fromCause({
421 operation: "revoke-other-client-sessions",
422 cause: error,
423 });
424 }
425}
426
427export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
428 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
429 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
430 explicitPairingRequested = false;
431 } else if (peekPairingTokenFromUrl()) {
432 explicitPairingRequested = true;
433 }
434 if (explicitPairingRequested) {
435 const currentSession = await fetchSessionState();
436 return { status: "requires-auth", auth: currentSession.auth };
437 }
438
439 const urlCredential = takePairingTokenFromUrl();
440 const previousPromise = bootstrapPromise;
441 if (urlCredential) {
442 resolvedAuthenticatedGateState = null;
443 } else {
444 if (previousPromise) {
445 return previousPromise;
446 }
447
448 if (resolvedAuthenticatedGateState?.status === "authenticated") {
449 return resolvedAuthenticatedGateState;
450 }
451 }
452
453 const nextPromise = previousPromise
454 ? previousPromise
455 .catch(() => undefined)
456 .then(() => {
457 resolvedAuthenticatedGateState = null;
458 return bootstrapServerAuth(urlCredential);
459 })
460 : bootstrapServerAuth(urlCredential);
461 bootstrapPromise = nextPromise;
462 return nextPromise
463 .then((result) => {
464 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
465 resolvedAuthenticatedGateState = result;
466 }
467 return result;
468 })
469 .finally(() => {
470 if (bootstrapPromise === nextPromise) {
471 bootstrapPromise = null;
472 }
473 });
474}
475
476export function __resetServerAuthBootstrapForTests() {
477 bootstrapPromise = null;
478 resolvedAuthenticatedGateState = null;
479 explicitPairingRequested = false;
480}