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 credential: string;
123 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
124 readonly subject: string;
125 readonly label?: string;
126 readonly createdAt: string;
127 readonly expiresAt: string;
128}
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;
141}
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));
158}
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());
167}
168
169export function takePairingTokenFromUrl(): string | null {
170 const token = peekPairingTokenFromUrl();
171 if (!token) {
172 return null;
173 }
174 stripPairingTokenFromUrl();
175 return token;
176}
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;
187}
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 });
204}
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;
213}
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 "EnvironmentInternalError":
225 return 500;
226 }
227}
228
229async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
230 return retryTransientBootstrap(async () => {
231 try {
232 return await runPrimaryHttp(
233 PrimaryEnvironmentHttpClient.pipe(
234 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
235 ),
236 );
237 } catch (error) {
238 if (
239 isEnvironmentHttpCommonError(error) &&
240 error._tag === "EnvironmentAuthInvalidError" &&
241 error.reason === "invalid_credential"
242 ) {
243 throw new PrimaryEnvironmentPairingCredentialRejectedError({
244 providedLength: credential.length,
245 cause: error,
246 });
247 }
248 throw PrimaryEnvironmentRequestError.fromCause({
249 operation: "exchange-bootstrap-credential",
250 cause: error,
251 });
252 }
253 });
254}
255
256async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
257 const startedAt = Date.now();
258
259 while (true) {
260 const session = await fetchSessionState();
261 if (session.authenticated) {
262 return session;
263 }
264
265 const elapsedMs = Date.now() - startedAt;
266 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
267 throw new PrimaryEnvironmentAuthSessionTimeoutError({
268 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
269 elapsedMs,
270 });
271 }
272
273 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
274 }
275}
276
277const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
278const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
279const BOOTSTRAP_RETRY_STEP_MS = 500;
280
281export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
282 const startedAt = Date.now();
283 while (true) {
284 try {
285 return await operation();
286 } catch (error) {
287 if (!isTransientBootstrapError(error)) {
288 throw error;
289 }
290
291 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
292 throw error;
293 }
294
295 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
296 }
297 }
298}
299
300function waitForBootstrapRetry(delayMs: number): Promise<void> {
301 return new Promise((resolve) => {
302 setTimeout(resolve, delayMs);
303 });
304}
305
306function isTransientBootstrapError(error: unknown): boolean {
307 if (isPrimaryEnvironmentRequestError(error)) {
308 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
309 }
310
311 if (error instanceof TypeError) {
312 return true;
313 }
314
315 return error instanceof DOMException && error.name === "AbortError";
316}
317
318async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
319 const bootstrapCredential = getDesktopBootstrapCredential();
320 const currentSession = await fetchSessionState();
321 if (currentSession.authenticated) {
322 return { status: "authenticated" };
323 }
324
325 if (!bootstrapCredential) {
326 return {
327 status: "requires-auth",
328 auth: currentSession.auth,
329 };
330 }
331
332 try {
333 await exchangeBootstrapCredential(bootstrapCredential);
334 await waitForAuthenticatedSessionAfterBootstrap();
335 return { status: "authenticated" };
336 } catch (error) {
337 return {
338 status: "requires-auth",
339 auth: currentSession.auth,
340 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
341 };
342 }
343}
344
345export async function submitServerAuthCredential(credential: string): Promise<void> {
346 const trimmedCredential = credential.trim();
347 if (!trimmedCredential) {
348 throw new PrimaryEnvironmentPairingCredentialRequiredError({
349 providedLength: credential.length,
350 });
351 }
352
353 resolvedAuthenticatedGateState = null;
354 await exchangeBootstrapCredential(trimmedCredential);
355 bootstrapPromise = null;
356 stripPairingTokenFromUrl();
357}
358
359export async function createServerPairingCredential(input?: {
360 readonly label?: string;
361 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
362}): Promise<AuthPairingCredentialResult> {
363 const trimmedLabel = input?.label?.trim();
364 try {
365 return await runPrimaryHttp(
366 PrimaryEnvironmentHttpClient.pipe(
367 Effect.flatMap((client) =>
368 client.auth.pairingCredential({
369 headers: {},
370 payload: {
371 ...(trimmedLabel ? { label: trimmedLabel } : {}),
372 ...(input?.scopes ? { scopes: input.scopes } : {}),
373 },
374 }),
375 ),
376 ),
377 );
378 } catch (error) {
379 throw PrimaryEnvironmentRequestError.fromCause({
380 operation: "create-pairing-credential",
381 cause: error,
382 });
383 }
384}
385
386export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
387 try {
388 const pairingLinks = await runPrimaryHttp(
389 PrimaryEnvironmentHttpClient.pipe(
390 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
391 ),
392 );
393 return pairingLinks.map((pairingLink) => {
394 const timestamps = {
395 createdAt: DateTime.formatIso(pairingLink.createdAt),
396 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
397 };
398 if (pairingLink.label === undefined) {
399 return {
400 id: pairingLink.id,
401 credential: pairingLink.credential,
402 scopes: pairingLink.scopes,
403 subject: pairingLink.subject,
404 createdAt: timestamps.createdAt,
405 expiresAt: timestamps.expiresAt,
406 };
407 }
408 return {
409 id: pairingLink.id,
410 credential: pairingLink.credential,
411 scopes: pairingLink.scopes,
412 subject: pairingLink.subject,
413 label: pairingLink.label,
414 createdAt: timestamps.createdAt,
415 expiresAt: timestamps.expiresAt,
416 };
417 });
418 } catch (error) {
419 throw PrimaryEnvironmentRequestError.fromCause({
420 operation: "list-pairing-links",
421 cause: error,
422 });
423 }
424}
425
426export async function revokeServerPairingLink(id: string): Promise<void> {
427 try {
428 await runPrimaryHttp(
429 PrimaryEnvironmentHttpClient.pipe(
430 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
431 ),
432 );
433 } catch (error) {
434 throw PrimaryEnvironmentRequestError.fromCause({
435 operation: "revoke-pairing-link",
436 pairingLinkId: id,
437 cause: error,
438 });
439 }
440}
441
442export async function listServerClientSessions(): Promise<
443 ReadonlyArray<ServerClientSessionRecord>
444> {
445 try {
446 const clientSessions = await runPrimaryHttp(
447 PrimaryEnvironmentHttpClient.pipe(
448 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
449 ),
450 );
451 return clientSessions.map((clientSession) => ({
452 sessionId: clientSession.sessionId,
453 subject: clientSession.subject,
454 scopes: clientSession.scopes,
455 method: clientSession.method,
456 client: clientSession.client,
457 issuedAt: DateTime.formatIso(clientSession.issuedAt),
458 expiresAt: DateTime.formatIso(clientSession.expiresAt),
459 lastConnectedAt:
460 clientSession.lastConnectedAt === null
461 ? null
462 : DateTime.formatIso(clientSession.lastConnectedAt),
463 connected: clientSession.connected,
464 current: clientSession.current,
465 }));
466 } catch (error) {
467 throw PrimaryEnvironmentRequestError.fromCause({
468 operation: "list-client-sessions",
469 cause: error,
470 });
471 }
472}
473
474export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
475 try {
476 await runPrimaryHttp(
477 PrimaryEnvironmentHttpClient.pipe(
478 Effect.flatMap((client) =>
479 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
480 ),
481 ),
482 );
483 } catch (error) {
484 throw PrimaryEnvironmentRequestError.fromCause({
485 operation: "revoke-client-session",
486 sessionId,
487 cause: error,
488 });
489 }
490}
491
492export async function revokeOtherServerClientSessions(): Promise<number> {
493 try {
494 const result = await runPrimaryHttp(
495 PrimaryEnvironmentHttpClient.pipe(
496 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
497 ),
498 );
499 return result.revokedCount;
500 } catch (error) {
501 throw PrimaryEnvironmentRequestError.fromCause({
502 operation: "revoke-other-client-sessions",
503 cause: error,
504 });
505 }
506}
507
508export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
509 if (resolvedAuthenticatedGateState?.status === "authenticated") {
510 return resolvedAuthenticatedGateState;
511 }
512
513 if (bootstrapPromise) {
514 return bootstrapPromise;
515 }
516
517 const nextPromise = bootstrapServerAuth();
518 bootstrapPromise = nextPromise;
519 return nextPromise
520 .then((result) => {
521 if (result.status === "authenticated") {
522 resolvedAuthenticatedGateState = result;
523 }
524 return result;
525 })
526 .finally(() => {
527 if (bootstrapPromise === nextPromise) {
528 bootstrapPromise = null;
529 }
530 });
531}
532
533// Used by the WSL backend swap: invalidate the cached authenticated state
534// (the new backend signs sessions with a different key) and re-bootstrap
535// against the desktop bootstrap credential so the next WS reconnect doesn't
536// hit 401 and start a reauth loop in the renderer.
537export async function reauthenticatePrimaryEnvironment(): Promise<ServerAuthGateState> {
538 resolvedAuthenticatedGateState = null;
539 bootstrapPromise = null;
540 return resolveInitialServerAuthGateState();
541}
542
543export function __resetServerAuthBootstrapForTests() {
544 bootstrapPromise = null;
545 resolvedAuthenticatedGateState = null;
546}