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(window.history.state, 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) || isTransportError(error.cause);
298 }
299
300 if (error instanceof TypeError) {
301 return true;
302 }
303
304 return error instanceof DOMException && error.name === "AbortError";
305}
306
307function isTransportError(error: unknown): boolean {
308 return HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
309}
310
311async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
312 const currentSession = await fetchSessionState();
313 if (currentSession.authenticated && !urlCredential) {
314 return { status: "authenticated" };
315 }
316
317 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
318 if (!bootstrapCredential) {
319 return {
320 status: "requires-auth",
321 auth: currentSession.auth,
322 };
323 }
324
325 try {
326 await exchangeBootstrapCredential(bootstrapCredential);
327 await waitForAuthenticatedSessionAfterBootstrap();
328 return { status: "authenticated" };
329 } catch (error) {
330 return {
331 status: "requires-auth",
332 auth: currentSession.auth,
333 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
334 };
335 }
336}
337
338export async function submitServerAuthCredential(credential: string): Promise<void> {
339 const trimmedCredential = credential.trim();
340 if (!trimmedCredential) {
341 throw new PrimaryEnvironmentPairingCredentialRequiredError({
342 providedLength: credential.length,
343 });
344 }
345
346 resolvedAuthenticatedGateState = null;
347 await exchangeBootstrapCredential(trimmedCredential);
348 await waitForAuthenticatedSessionAfterBootstrap();
349 resolvedAuthenticatedGateState = { status: "authenticated" };
350 bootstrapPromise = null;
351 explicitPairingRequested = false;
352 stripPairingTokenFromUrl();
353}
354
355export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
356 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
357 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
358 explicitPairingRequested = false;
359 } else if (peekPairingTokenFromUrl()) {
360 explicitPairingRequested = true;
361 }
362 if (explicitPairingRequested) {
363 const currentSession = await fetchSessionState();
364 return { status: "requires-auth", auth: currentSession.auth };
365 }
366
367 const urlCredential = takePairingTokenFromUrl();
368 const previousPromise = bootstrapPromise;
369 if (urlCredential) {
370 resolvedAuthenticatedGateState = null;
371 } else {
372 if (previousPromise) {
373 return previousPromise;
374 }
375
376 if (resolvedAuthenticatedGateState?.status === "authenticated") {
377 return resolvedAuthenticatedGateState;
378 }
379 }
380
381 const nextPromise = previousPromise
382 ? previousPromise
383 .catch(() => undefined)
384 .then(() => {
385 resolvedAuthenticatedGateState = null;
386 return bootstrapServerAuth(urlCredential);
387 })
388 : bootstrapServerAuth(urlCredential);
389 bootstrapPromise = nextPromise;
390 return nextPromise
391 .then((result) => {
392 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
393 resolvedAuthenticatedGateState = result;
394 }
395 return result;
396 })
397 .finally(() => {
398 if (bootstrapPromise === nextPromise) {
399 bootstrapPromise = null;
400 }
401 });
402}
403
404export function __resetServerAuthBootstrapForTests() {
405 bootstrapPromise = null;
406 resolvedAuthenticatedGateState = null;
407 explicitPairingRequested = false;
408}