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 } 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 const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
180 return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
181 ? bootstrap.bootstrapToken
182 : null;
183}
184
185export async function fetchSessionState(): Promise<AuthSessionState> {
186 return retryTransientBootstrap(async () => {
187 try {
188 return await runPrimaryHttp(
189 PrimaryEnvironmentHttpClient.pipe(
190 Effect.flatMap((client) => client.auth.session({ headers: {} })),
191 ),
192 );
193 } catch (error) {
194 throw PrimaryEnvironmentRequestError.fromCause({
195 operation: "fetch-session-state",
196 cause: error,
197 });
198 }
199 });
200}
201
202function readHttpApiStatus(error: unknown): number | null {
203 if (isEnvironmentHttpCommonError(error)) {
204 return readEnvironmentHttpErrorStatus(error);
205 }
206 return HttpClientError.isHttpClientError(error) && error.response !== undefined
207 ? error.response.status
208 : null;
209}
210
211function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
212 switch (error._tag) {
213 case "EnvironmentRequestInvalidError":
214 return 400;
215 case "EnvironmentAuthInvalidError":
216 return 401;
217 case "EnvironmentScopeRequiredError":
218 case "EnvironmentOperationForbiddenError":
219 return 403;
220 case "EnvironmentInternalError":
221 return 500;
222 }
223}
224
225async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
226 return retryTransientBootstrap(async () => {
227 try {
228 return await runPrimaryHttp(
229 PrimaryEnvironmentHttpClient.pipe(
230 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
231 ),
232 );
233 } catch (error) {
234 if (
235 isEnvironmentHttpCommonError(error) &&
236 error._tag === "EnvironmentAuthInvalidError" &&
237 error.reason === "invalid_credential"
238 ) {
239 throw new PrimaryEnvironmentPairingCredentialRejectedError({
240 providedLength: credential.length,
241 cause: error,
242 });
243 }
244 throw PrimaryEnvironmentRequestError.fromCause({
245 operation: "exchange-bootstrap-credential",
246 cause: error,
247 });
248 }
249 });
250}
251
252async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
253 const startedAt = Date.now();
254
255 while (true) {
256 const session = await fetchSessionState();
257 if (session.authenticated) {
258 return session;
259 }
260
261 const elapsedMs = Date.now() - startedAt;
262 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
263 throw new PrimaryEnvironmentAuthSessionTimeoutError({
264 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
265 elapsedMs,
266 });
267 }
268
269 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
270 }
271}
272
273const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
274const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
275const BOOTSTRAP_RETRY_STEP_MS = 500;
276
277export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
278 const startedAt = Date.now();
279 while (true) {
280 try {
281 return await operation();
282 } catch (error) {
283 if (!isTransientBootstrapError(error)) {
284 throw error;
285 }
286
287 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
288 throw error;
289 }
290
291 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
292 }
293 }
294}
295
296function waitForBootstrapRetry(delayMs: number): Promise<void> {
297 return new Promise((resolve) => {
298 setTimeout(resolve, delayMs);
299 });
300}
301
302function isTransientBootstrapError(error: unknown): boolean {
303 if (isPrimaryEnvironmentRequestError(error)) {
304 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
305 }
306
307 if (error instanceof TypeError) {
308 return true;
309 }
310
311 return error instanceof DOMException && error.name === "AbortError";
312}
313
314async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
315 const bootstrapCredential = getDesktopBootstrapCredential();
316 const currentSession = await fetchSessionState();
317 if (currentSession.authenticated) {
318 return { status: "authenticated" };
319 }
320
321 if (!bootstrapCredential) {
322 return {
323 status: "requires-auth",
324 auth: currentSession.auth,
325 };
326 }
327
328 try {
329 await exchangeBootstrapCredential(bootstrapCredential);
330 await waitForAuthenticatedSessionAfterBootstrap();
331 return { status: "authenticated" };
332 } catch (error) {
333 return {
334 status: "requires-auth",
335 auth: currentSession.auth,
336 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
337 };
338 }
339}
340
341export async function submitServerAuthCredential(credential: string): Promise<void> {
342 const trimmedCredential = credential.trim();
343 if (!trimmedCredential) {
344 throw new PrimaryEnvironmentPairingCredentialRequiredError({
345 providedLength: credential.length,
346 });
347 }
348
349 resolvedAuthenticatedGateState = null;
350 await exchangeBootstrapCredential(trimmedCredential);
351 bootstrapPromise = null;
352 stripPairingTokenFromUrl();
353}
354
355export async function createServerPairingCredential(input?: {
356 readonly label?: string;
357 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
358}): Promise<AuthPairingCredentialResult> {
359 const trimmedLabel = input?.label?.trim();
360 try {
361 return await runPrimaryHttp(
362 PrimaryEnvironmentHttpClient.pipe(
363 Effect.flatMap((client) =>
364 client.auth.pairingCredential({
365 headers: {},
366 payload: {
367 ...(trimmedLabel ? { label: trimmedLabel } : {}),
368 ...(input?.scopes ? { scopes: input.scopes } : {}),
369 },
370 }),
371 ),
372 ),
373 );
374 } catch (error) {
375 throw PrimaryEnvironmentRequestError.fromCause({
376 operation: "create-pairing-credential",
377 cause: error,
378 });
379 }
380}
381
382export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
383 try {
384 const pairingLinks = await runPrimaryHttp(
385 PrimaryEnvironmentHttpClient.pipe(
386 Effect.flatMap((client) => client.auth.pairingLinks({ headers: {} })),
387 ),
388 );
389 return pairingLinks.map((pairingLink) => {
390 const timestamps = {
391 createdAt: DateTime.formatIso(pairingLink.createdAt),
392 expiresAt: DateTime.formatIso(pairingLink.expiresAt),
393 };
394 if (pairingLink.label === undefined) {
395 return {
396 id: pairingLink.id,
397 credential: pairingLink.credential,
398 scopes: pairingLink.scopes,
399 subject: pairingLink.subject,
400 createdAt: timestamps.createdAt,
401 expiresAt: timestamps.expiresAt,
402 };
403 }
404 return {
405 id: pairingLink.id,
406 credential: pairingLink.credential,
407 scopes: pairingLink.scopes,
408 subject: pairingLink.subject,
409 label: pairingLink.label,
410 createdAt: timestamps.createdAt,
411 expiresAt: timestamps.expiresAt,
412 };
413 });
414 } catch (error) {
415 throw PrimaryEnvironmentRequestError.fromCause({
416 operation: "list-pairing-links",
417 cause: error,
418 });
419 }
420}
421
422export async function revokeServerPairingLink(id: string): Promise<void> {
423 try {
424 await runPrimaryHttp(
425 PrimaryEnvironmentHttpClient.pipe(
426 Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),
427 ),
428 );
429 } catch (error) {
430 throw PrimaryEnvironmentRequestError.fromCause({
431 operation: "revoke-pairing-link",
432 pairingLinkId: id,
433 cause: error,
434 });
435 }
436}
437
438export async function listServerClientSessions(): Promise<
439 ReadonlyArray<ServerClientSessionRecord>
440> {
441 try {
442 const clientSessions = await runPrimaryHttp(
443 PrimaryEnvironmentHttpClient.pipe(
444 Effect.flatMap((client) => client.auth.clients({ headers: {} })),
445 ),
446 );
447 return clientSessions.map((clientSession) => ({
448 sessionId: clientSession.sessionId,
449 subject: clientSession.subject,
450 scopes: clientSession.scopes,
451 method: clientSession.method,
452 client: clientSession.client,
453 issuedAt: DateTime.formatIso(clientSession.issuedAt),
454 expiresAt: DateTime.formatIso(clientSession.expiresAt),
455 lastConnectedAt:
456 clientSession.lastConnectedAt === null
457 ? null
458 : DateTime.formatIso(clientSession.lastConnectedAt),
459 connected: clientSession.connected,
460 current: clientSession.current,
461 }));
462 } catch (error) {
463 throw PrimaryEnvironmentRequestError.fromCause({
464 operation: "list-client-sessions",
465 cause: error,
466 });
467 }
468}
469
470export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
471 try {
472 await runPrimaryHttp(
473 PrimaryEnvironmentHttpClient.pipe(
474 Effect.flatMap((client) =>
475 client.auth.revokeClient({ headers: {}, payload: { sessionId } }),
476 ),
477 ),
478 );
479 } catch (error) {
480 throw PrimaryEnvironmentRequestError.fromCause({
481 operation: "revoke-client-session",
482 sessionId,
483 cause: error,
484 });
485 }
486}
487
488export async function revokeOtherServerClientSessions(): Promise<number> {
489 try {
490 const result = await runPrimaryHttp(
491 PrimaryEnvironmentHttpClient.pipe(
492 Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),
493 ),
494 );
495 return result.revokedCount;
496 } catch (error) {
497 throw PrimaryEnvironmentRequestError.fromCause({
498 operation: "revoke-other-client-sessions",
499 cause: error,
500 });
501 }
502}
503
504export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
505 if (resolvedAuthenticatedGateState?.status === "authenticated") {
506 return resolvedAuthenticatedGateState;
507 }
508
509 if (bootstrapPromise) {
510 return bootstrapPromise;
511 }
512
513 const nextPromise = bootstrapServerAuth();
514 bootstrapPromise = nextPromise;
515 return nextPromise
516 .then((result) => {
517 if (result.status === "authenticated") {
518 resolvedAuthenticatedGateState = result;
519 }
520 return result;
521 })
522 .finally(() => {
523 if (bootstrapPromise === nextPromise) {
524 bootstrapPromise = null;
525 }
526 });
527}
528
529export function __resetServerAuthBootstrapForTests() {
530 bootstrapPromise = null;
531 resolvedAuthenticatedGateState = null;
532}