Open History to see the last commit
1import type {
2 AuthBrowserSessionResult,
3 AuthClientMetadata,
4 AuthConnectDeviceRequest,
5 AuthEnvironmentScope,
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 Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14import { HttpClientError } from "effect/http";
15
16import {
17 getPairingTokenFromUrl,
18 stripPairingTokenFromUrl as stripPairingTokenUrl,
19} from "@t3tools/shared/remote";
20
21import { PrimaryEnvironmentHttpClient } from "./httpClient";
22import { runPrimaryHttp } from "../../lib/runtime";
23
24const PrimaryEnvironmentRequestOperation = Schema.Literals([
25 "fetch-session-state",
26 "exchange-bootstrap-credential",
27 "fetch-environment-descriptor",
28 "create-pairing-credential",
29 "list-pairing-links",
30 "revoke-pairing-link",
31 "list-client-sessions",
32 "revoke-client-session",
33 "revoke-other-client-sessions",
34]);
35type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
36
37export class PrimaryEnvironmentRequestError extends Schema.TaggedError<PrimaryEnvironmentRequestError>()(
38 "PrimaryEnvironmentRequestError",
39 {
40 operation: PrimaryEnvironmentRequestOperation,
41 status: Schema.Number,
42 pairingLinkId: Schema.optional(Schema.String),
43 sessionId: Schema.optional(Schema.String),
44 cause: Schema.Defect(),
45 },
46) {
47 static fromCause(input: {
48 readonly operation: PrimaryEnvironmentRequestOperation;
49 readonly cause: unknown;
50 readonly pairingLinkId?: string;
51 readonly sessionId?: string;
52 }): PrimaryEnvironmentRequestError {
53 const status = readHttpApiStatus(input.cause) ?? 500;
54 return new PrimaryEnvironmentRequestError({
55 operation: input.operation,
56 status,
57 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
58 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
59 cause: input.cause,
60 });
61 }
62
63 override get message(): string {
64 return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
65 }
66}
67
68const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
69
70export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRejectedError>()(
71 "PrimaryEnvironmentPairingCredentialRejectedError",
72 {
73 providedLength: Schema.Number,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return "Invalid pairing token. Check the token and try again.";
79 }
80}
81
82export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedError<PrimaryEnvironmentAuthSessionTimeoutError>()(
83 "PrimaryEnvironmentAuthSessionTimeoutError",
84 {
85 timeoutMs: Schema.Number,
86 elapsedMs: Schema.Number,
87 },
88) {
89 override get message(): string {
90 return "Timed out waiting for authenticated session after bootstrap.";
91 }
92}
93
94export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRequiredError>()(
95 "PrimaryEnvironmentPairingCredentialRequiredError",
96 {
97 providedLength: Schema.Number,
98 },
99) {
100 override get message(): string {
101 return "Enter a pairing token to continue.";
102 }
103}
104
105const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
106
107export interface ServerPairingLinkRecord {
108 readonly id: string;
109 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
110 readonly subject: string;
111 readonly label?: string;
112 readonly createdAt: string;
113 readonly expiresAt: string;
114 readonly connectDeviceRequest?: AuthConnectDeviceRequest;
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 case "EnvironmentConnectApprovalPendingError":
210 return 403;
211 case "EnvironmentResourceNotFoundError":
212 return 404;
213 case "EnvironmentInternalError":
214 return 500;
215 }
216}
217
218async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
219 return retryTransientBootstrap(async () => {
220 try {
221 return await runPrimaryHttp(
222 PrimaryEnvironmentHttpClient.pipe(
223 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
224 ),
225 );
226 } catch (error) {
227 if (
228 isEnvironmentHttpCommonError(error) &&
229 error._tag === "EnvironmentAuthInvalidError" &&
230 error.reason === "invalid_credential"
231 ) {
232 throw new PrimaryEnvironmentPairingCredentialRejectedError({
233 providedLength: credential.length,
234 cause: error,
235 });
236 }
237 throw PrimaryEnvironmentRequestError.fromCause({
238 operation: "exchange-bootstrap-credential",
239 cause: error,
240 });
241 }
242 });
243}
244
245async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
246 const startedAt = Date.now();
247
248 while (true) {
249 const session = await fetchSessionState();
250 if (session.authenticated) {
251 return session;
252 }
253
254 const elapsedMs = Date.now() - startedAt;
255 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
256 throw new PrimaryEnvironmentAuthSessionTimeoutError({
257 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
258 elapsedMs,
259 });
260 }
261
262 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
263 }
264}
265
266const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
267const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
268const BOOTSTRAP_RETRY_STEP_MS = 500;
269
270async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
271 const startedAt = Date.now();
272 while (true) {
273 try {
274 return await operation();
275 } catch (error) {
276 if (!isTransientBootstrapError(error)) {
277 throw error;
278 }
279
280 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
281 throw error;
282 }
283
284 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
285 }
286 }
287}
288
289function waitForBootstrapRetry(delayMs: number): Promise<void> {
290 return new Promise((resolve) => {
291 setTimeout(resolve, delayMs);
292 });
293}
294
295function isTransientBootstrapError(error: unknown): boolean {
296 if (isPrimaryEnvironmentRequestError(error)) {
297 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
298 }
299
300 if (error instanceof TypeError) {
301 return true;
302 }
303
304 return error instanceof DOMException && error.name === "AbortError";
305}
306
307async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
308 const currentSession = await fetchSessionState();
309 if (currentSession.authenticated && !urlCredential) {
310 return { status: "authenticated" };
311 }
312
313 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
314 if (!bootstrapCredential) {
315 return {
316 status: "requires-auth",
317 auth: currentSession.auth,
318 };
319 }
320
321 try {
322 await exchangeBootstrapCredential(bootstrapCredential);
323 await waitForAuthenticatedSessionAfterBootstrap();
324 return { status: "authenticated" };
325 } catch (error) {
326 return {
327 status: "requires-auth",
328 auth: currentSession.auth,
329 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
330 };
331 }
332}
333
334export async function submitServerAuthCredential(credential: string): Promise<void> {
335 const trimmedCredential = credential.trim();
336 if (!trimmedCredential) {
337 throw new PrimaryEnvironmentPairingCredentialRequiredError({
338 providedLength: credential.length,
339 });
340 }
341
342 resolvedAuthenticatedGateState = null;
343 await exchangeBootstrapCredential(trimmedCredential);
344 await waitForAuthenticatedSessionAfterBootstrap();
345 resolvedAuthenticatedGateState = { status: "authenticated" };
346 bootstrapPromise = null;
347 explicitPairingRequested = false;
348 stripPairingTokenFromUrl();
349}
350
351export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
352 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
353 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
354 explicitPairingRequested = false;
355 } else if (peekPairingTokenFromUrl()) {
356 explicitPairingRequested = true;
357 }
358 if (explicitPairingRequested) {
359 const currentSession = await fetchSessionState();
360 return { status: "requires-auth", auth: currentSession.auth };
361 }
362
363 const urlCredential = takePairingTokenFromUrl();
364 const previousPromise = bootstrapPromise;
365 if (urlCredential) {
366 resolvedAuthenticatedGateState = null;
367 } else {
368 if (previousPromise) {
369 return previousPromise;
370 }
371
372 if (resolvedAuthenticatedGateState?.status === "authenticated") {
373 return resolvedAuthenticatedGateState;
374 }
375 }
376
377 const nextPromise = previousPromise
378 ? previousPromise
379 .catch(() => undefined)
380 .then(() => {
381 resolvedAuthenticatedGateState = null;
382 return bootstrapServerAuth(urlCredential);
383 })
384 : bootstrapServerAuth(urlCredential);
385 bootstrapPromise = nextPromise;
386 return nextPromise
387 .then((result) => {
388 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
389 resolvedAuthenticatedGateState = result;
390 }
391 return result;
392 })
393 .finally(() => {
394 if (bootstrapPromise === nextPromise) {
395 bootstrapPromise = null;
396 }
397 });
398}
399
400export function __resetServerAuthBootstrapForTests() {
401 bootstrapPromise = null;
402 resolvedAuthenticatedGateState = null;
403 explicitPairingRequested = false;
404}