Open History to see the last commit
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 }
67}
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 }
81}
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 }
97}
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 }
112}
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;
127}
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;
140}
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));
157}
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());
166}
167
168export function takePairingTokenFromUrl(): string | null {
169 const token = peekPairingTokenFromUrl();
170 if (!token) {
171 return null;
172 }
173 stripPairingTokenFromUrl();
174 return token;
175}
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;
186}
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 });
203}
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;
212}
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 }
228}
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 });
255}
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 }
276}
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 }
299}
300
301function waitForBootstrapRetry(delayMs: number): Promise<void> {
302 return new Promise((resolve) => {
303 setTimeout(resolve, delayMs);
304 });
305}
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";
317}
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 }
344}
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 await waitForAuthenticatedSessionAfterBootstrap();
357 resolvedAuthenticatedGateState = { status: "authenticated" };
358 bootstrapPromise = null;
359 stripPairingTokenFromUrl();
360}
361
362export async function createServerPairingCredential(input?: {
363 readonly label?: string;
364 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
365}): Promise<AuthPairingCredentialResult> {
366 const trimmedLabel = input?.label?.trim();
367 try {
368 return await runPrimaryHttp(
369 PrimaryEnvironmentHttpClient.pipe(
370 Effect.flatMap((client) =>
371 client.auth.pairingCredential({
372 headers: {},
373 payload: {
374 ...(trimmedLabel ? { label: trimmedLabel } : {}),
375 ...(input?.scopes ? { scopes: input.scopes } : {}),
376 },
377 }),
378 ),
379 ),
380 );
381 } catch (error) {
382 throw PrimaryEnvironmentRequestError.fromCause({
383 operation: "create-pairing-credential",
384 cause: error,
385 });
386 }
387}
388
389export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
390 try {
391 const pairingLinks = await runPrimaryHttp(
392 PrimaryEnvironmentHttpClient.pipe(
393 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
394 ),
395 );
396 return pairingLinks.map((pairingLink) => {
397 const timestamps = {
398 createdAt: DateTime.formatIso(pairingLink.createdAt),
399 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
400 };
401 if (pairingLink.label === undefined) {
402 return {
403 id: pairingLink.id,
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 scopes: pairingLink.scopes,
413 subject: pairingLink.subject,
414 label: pairingLink.label,
415 createdAt: timestamps.createdAt,
416 expiresAt: timestamps.expiresAt,
417 };
418 });
419 } catch (error) {
420 throw PrimaryEnvironmentRequestError.fromCause({
421 operation: "list-pairing-links",
422 cause: error,
423 });
424 }
425}
426
427export async function revokeServerPairingLink(id: string): Promise<void> {
428 try {
429 await runPrimaryHttp(
430 PrimaryEnvironmentHttpClient.pipe(
431 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
432 ),
433 );
434 } catch (error) {
435 throw PrimaryEnvironmentRequestError.fromCause({
436 operation: "revoke-pairing-link",
437 pairingLinkId: id,
438 cause: error,
439 });
440 }
441}
442
443export async function listServerClientSessions(): Promise<
444 ReadonlyArray<ServerClientSessionRecord>
445> {
446 try {
447 const clientSessions = await runPrimaryHttp(
448 PrimaryEnvironmentHttpClient.pipe(
449 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
450 ),
451 );
452 return clientSessions.map((clientSession) => ({
453 sessionId: clientSession.sessionId,
454 subject: clientSession.subject,
455 scopes: clientSession.scopes,
456 method: clientSession.method,
457 client: clientSession.client,
458 issuedAt: DateTime.formatIso(clientSession.issuedAt),
459 expiresAt: DateTime.formatIso(clientSession.expiresAt),
460 lastConnectedAt:
461 clientSession.lastConnectedAt === null
462 ? null
463 : DateTime.formatIso(clientSession.lastConnectedAt),
464 connected: clientSession.connected,
465 current: clientSession.current,
466 }));
467 } catch (error) {
468 throw PrimaryEnvironmentRequestError.fromCause({
469 operation: "list-client-sessions",
470 cause: error,
471 });
472 }
473}
474
475export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
476 try {
477 await runPrimaryHttp(
478 PrimaryEnvironmentHttpClient.pipe(
479 Effect.flatMap((client) =>
480 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
481 ),
482 ),
483 );
484 } catch (error) {
485 throw PrimaryEnvironmentRequestError.fromCause({
486 operation: "revoke-client-session",
487 sessionId,
488 cause: error,
489 });
490 }
491}
492
493export async function revokeOtherServerClientSessions(): Promise<number> {
494 try {
495 const result = await runPrimaryHttp(
496 PrimaryEnvironmentHttpClient.pipe(
497 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
498 ),
499 );
500 return result.revokedCount;
501 } catch (error) {
502 throw PrimaryEnvironmentRequestError.fromCause({
503 operation: "revoke-other-client-sessions",
504 cause: error,
505 });
506 }
507}
508
509export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
510 if (resolvedAuthenticatedGateState?.status === "authenticated") {
511 return resolvedAuthenticatedGateState;
512 }
513
514 if (bootstrapPromise) {
515 return bootstrapPromise;
516 }
517
518 const nextPromise = bootstrapServerAuth();
519 bootstrapPromise = nextPromise;
520 return nextPromise
521 .then((result) => {
522 if (result.status === "authenticated") {
523 resolvedAuthenticatedGateState = result;
524 }
525 return result;
526 })
527 .finally(() => {
528 if (bootstrapPromise === nextPromise) {
529 bootstrapPromise = null;
530 }
531 });
532}
533
534// Used by the WSL backend swap: invalidate the cached authenticated state
535// (the new backend signs sessions with a different key) and re-bootstrap
536// against the desktop bootstrap credential so the next WS reconnect doesn't
537// hit 401 and start a reauth loop in the renderer.
538export async function reauthenticatePrimaryEnvironment(): Promise<ServerAuthGateState> {
539 resolvedAuthenticatedGateState = null;
540 bootstrapPromise = null;
541 return resolveInitialServerAuthGateState();
542}
543
544export function __resetServerAuthBootstrapForTests() {
545 bootstrapPromise = null;
546 resolvedAuthenticatedGateState = null;
547}