Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

auth.ts

413 lines12.6 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import type {
3 AuthBrowserSessionResult,
4 AuthClientMetadata,
5 AuthConnectDeviceRequest,
6 AuthEnvironmentScope,
7 ServerAuthSessionMethod,
8 AuthSessionId,
9 AuthSessionState,
10} from "@t3tools/contracts";
11import { EnvironmentHttpCommonError, PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
12import type { EnvironmentHttpCommonError as EnvironmentHttpCommonErrorType } from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import { HttpClientError } from "effect/http";
16​
17import {
18 getPairingTokenFromUrl,
19 stripPairingTokenFromUrl as stripPairingTokenUrl,
20} from "@t3tools/shared/remote";
21​
22import { PrimaryEnvironmentHttpClient } from "./httpClient";
23import { runPrimaryHttp } from "../../lib/runtime";
24import { msg } from "gt-react";
25import { m } from "../../i18n/messages";
26​
27const PrimaryEnvironmentRequestOperation = Schema.Literals([
28 "fetch-session-state",
29 "exchange-bootstrap-credential",
30 "fetch-environment-descriptor",
31 "create-pairing-credential",
32 "list-pairing-links",
33 "revoke-pairing-link",
34 "list-client-sessions",
35 "revoke-client-session",
36 "revoke-other-client-sessions",
37]);
38type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
39​
40export class PrimaryEnvironmentRequestError extends Schema.TaggedError<PrimaryEnvironmentRequestError>()(
41 "PrimaryEnvironmentRequestError",
42 {
43 operation: PrimaryEnvironmentRequestOperation,
44 status: Schema.Number,
45 pairingLinkId: Schema.optional(Schema.String),
46 sessionId: Schema.optional(Schema.String),
47 cause: Schema.Defect(),
48 },
49) {
50 static fromCause(input: {
51 readonly operation: PrimaryEnvironmentRequestOperation;
52 readonly cause: unknown;
53 readonly pairingLinkId?: string;
54 readonly sessionId?: string;
55 }): PrimaryEnvironmentRequestError {
56 const status = readHttpApiStatus(input.cause) ?? 500;
57 return new PrimaryEnvironmentRequestError({
58 operation: input.operation,
59 status,
60 ...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
61 ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
62 cause: input.cause,
63 });
64 }
65​
66 override get message(): string {
67 return m(
68 msg`Primary environment request failed during ${{ operation: this.operation }} (HTTP ${{ status: this.status }}).`,
69 );
70 }
72​
73const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
74​
75export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRejectedError>()(
76 "PrimaryEnvironmentPairingCredentialRejectedError",
77 {
78 providedLength: Schema.Number,
79 cause: Schema.Defect(),
80 },
81) {
82 override get message(): string {
83 return m(msg("Invalid pairing token. Check the token and try again."));
84 }
86​
87export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedError<PrimaryEnvironmentAuthSessionTimeoutError>()(
88 "PrimaryEnvironmentAuthSessionTimeoutError",
89 {
90 timeoutMs: Schema.Number,
91 elapsedMs: Schema.Number,
92 },
93) {
94 override get message(): string {
95 return m(msg("Timed out waiting for authenticated session after bootstrap."));
96 }
98​
99export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedError<PrimaryEnvironmentPairingCredentialRequiredError>()(
100 "PrimaryEnvironmentPairingCredentialRequiredError",
101 {
102 providedLength: Schema.Number,
103 },
104) {
105 override get message(): string {
106 return m(msg("Enter a pairing token to continue."));
107 }
109​
110const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
111​
112export interface ServerPairingLinkRecord {
113 readonly id: string;
114 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
115 readonly subject: string;
116 readonly label?: string;
117 readonly createdAt: string;
118 readonly expiresAt: string;
119 readonly connectDeviceRequest?: AuthConnectDeviceRequest;
121​
122export interface ServerClientSessionRecord {
123 readonly sessionId: AuthSessionId;
124 readonly subject: string;
125 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
126 readonly method: ServerAuthSessionMethod;
127 readonly client: AuthClientMetadata;
128 readonly issuedAt: string;
129 readonly expiresAt: string;
130 readonly lastConnectedAt: string | null;
131 readonly connected: boolean;
132 readonly current: boolean;
134​
135type ServerAuthGateState =
136 | { status: "authenticated" }
137 | {
138 status: "requires-auth";
139 auth: AuthSessionState["auth"];
140 errorMessage?: string;
141 };
142​
143let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
144let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
145let explicitPairingRequested = false;
146const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
147const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
148​
149export function peekPairingTokenFromUrl(): string | null {
150 return getPairingTokenFromUrl(new URL(window.location.href));
152​
153export function stripPairingTokenFromUrl() {
154 const url = new URL(window.location.href);
155 const next = stripPairingTokenUrl(url);
156 if (next.toString() === url.toString()) {
157 return;
158 }
159 window.history.replaceState(window.history.state, document.title, next.toString());
161​
162export function takePairingTokenFromUrl(): string | null {
163 const token = peekPairingTokenFromUrl();
164 if (!token) {
165 return null;
166 }
167 stripPairingTokenFromUrl();
168 return token;
170​
171function getDesktopBootstrapCredential(): string | null {
172 // DesktopBackendConfiguration gives primary and WSL the same bootstrap token.
173 const bootstraps = window.desktopBridge?.getLocalEnvironmentBootstraps() ?? [];
174 const primary = bootstraps.find((entry) => entry.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
175 return typeof primary?.bootstrapToken === "string" && primary.bootstrapToken.length > 0
176 ? primary.bootstrapToken
177 : null;
179​
180export async function fetchSessionState(): Promise<AuthSessionState> {
181 return retryTransientBootstrap(async () => {
182 try {
183 return await runPrimaryHttp(
184 PrimaryEnvironmentHttpClient.pipe(
185 Effect.flatMap((client) => client.auth.session({ headers: {} })),
186 ),
187 );
188 } catch (error) {
189 throw PrimaryEnvironmentRequestError.fromCause({
190 operation: "fetch-session-state",
191 cause: error,
192 });
193 }
194 });
196​
197function readHttpApiStatus(error: unknown): number | null {
198 if (isEnvironmentHttpCommonError(error)) {
199 return readEnvironmentHttpErrorStatus(error);
200 }
201 return HttpClientError.isHttpClientError(error) && error.response !== undefined
202 ? error.response.status
203 : null;
205​
206function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType): number {
207 switch (error._tag) {
208 case "EnvironmentRequestInvalidError":
209 return 400;
210 case "EnvironmentAuthInvalidError":
211 return 401;
212 case "EnvironmentScopeRequiredError":
213 case "EnvironmentOperationForbiddenError":
214 case "EnvironmentConnectApprovalPendingError":
215 return 403;
216 case "EnvironmentResourceNotFoundError":
217 return 404;
218 case "EnvironmentInternalError":
219 return 500;
220 }
222​
223async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
224 return retryTransientBootstrap(async () => {
225 try {
226 return await runPrimaryHttp(
227 PrimaryEnvironmentHttpClient.pipe(
228 Effect.flatMap((client) => client.auth.browserSession({ payload: { credential } })),
229 ),
230 );
231 } catch (error) {
232 if (
233 isEnvironmentHttpCommonError(error) &&
234 error._tag === "EnvironmentAuthInvalidError" &&
235 error.reason === "invalid_credential"
236 ) {
237 throw new PrimaryEnvironmentPairingCredentialRejectedError({
238 providedLength: credential.length,
239 cause: error,
240 });
241 }
242 throw PrimaryEnvironmentRequestError.fromCause({
243 operation: "exchange-bootstrap-credential",
244 cause: error,
245 });
246 }
247 });
249​
250async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
251 const startedAt = Date.now();
252​
253 while (true) {
254 const session = await fetchSessionState();
255 if (session.authenticated) {
256 return session;
257 }
258​
259 const elapsedMs = Date.now() - startedAt;
260 if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
261 throw new PrimaryEnvironmentAuthSessionTimeoutError({
262 timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
263 elapsedMs,
264 });
265 }
266​
267 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
268 }
270​
271const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
272const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
273const BOOTSTRAP_RETRY_STEP_MS = 500;
274​
275async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
276 const startedAt = Date.now();
277 while (true) {
278 try {
279 return await operation();
280 } catch (error) {
281 if (!isTransientBootstrapError(error)) {
282 throw error;
283 }
284​
285 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
286 throw error;
287 }
288​
289 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
290 }
291 }
293​
294function waitForBootstrapRetry(delayMs: number): Promise<void> {
295 return new Promise((resolve) => {
296 setTimeout(resolve, delayMs);
297 });
299​
300function isTransientBootstrapError(error: unknown): boolean {
301 if (isPrimaryEnvironmentRequestError(error)) {
302 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status) || isTransportError(error.cause);
303 }
304​
305 if (error instanceof TypeError) {
306 return true;
307 }
308​
309 return error instanceof DOMException && error.name === "AbortError";
311​
312function isTransportError(error: unknown): boolean {
313 return HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError";
315​
316async function bootstrapServerAuth(urlCredential: string | null): Promise<ServerAuthGateState> {
317 const currentSession = await fetchSessionState();
318 if (currentSession.authenticated && !urlCredential) {
319 return { status: "authenticated" };
320 }
321​
322 const bootstrapCredential = urlCredential ?? getDesktopBootstrapCredential();
323 if (!bootstrapCredential) {
324 return {
325 status: "requires-auth",
326 auth: currentSession.auth,
327 };
328 }
329​
330 try {
331 await exchangeBootstrapCredential(bootstrapCredential);
332 await waitForAuthenticatedSessionAfterBootstrap();
333 return { status: "authenticated" };
334 } catch (error) {
335 return {
336 status: "requires-auth",
337 auth: currentSession.auth,
338 errorMessage: thrownErrorMessage(error, m) ?? m(msg("Authentication failed.")),
339 };
340 }
342​
343export async function submitServerAuthCredential(credential: string): Promise<void> {
344 const trimmedCredential = credential.trim();
345 if (!trimmedCredential) {
346 throw new PrimaryEnvironmentPairingCredentialRequiredError({
347 providedLength: credential.length,
348 });
349 }
350​
351 resolvedAuthenticatedGateState = null;
352 await exchangeBootstrapCredential(trimmedCredential);
353 await waitForAuthenticatedSessionAfterBootstrap();
354 resolvedAuthenticatedGateState = { status: "authenticated" };
355 bootstrapPromise = null;
356 explicitPairingRequested = false;
357 stripPairingTokenFromUrl();
359​
360export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
361 // Preserve explicit grant replacement across the auth-gate reload triggered by token removal.
362 if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {
363 explicitPairingRequested = false;
364 } else if (peekPairingTokenFromUrl()) {
365 explicitPairingRequested = true;
366 }
367 if (explicitPairingRequested) {
368 const currentSession = await fetchSessionState();
369 return { status: "requires-auth", auth: currentSession.auth };
370 }
371​
372 const urlCredential = takePairingTokenFromUrl();
373 const previousPromise = bootstrapPromise;
374 if (urlCredential) {
375 resolvedAuthenticatedGateState = null;
376 } else {
377 if (previousPromise) {
378 return previousPromise;
379 }
380​
381 if (resolvedAuthenticatedGateState?.status === "authenticated") {
382 return resolvedAuthenticatedGateState;
383 }
384 }
385​
386 const nextPromise = previousPromise
387 ? previousPromise
388 .catch(() => undefined)
389 .then(() => {
390 resolvedAuthenticatedGateState = null;
391 return bootstrapServerAuth(urlCredential);
392 })
393 : bootstrapServerAuth(urlCredential);
394 bootstrapPromise = nextPromise;
395 return nextPromise
396 .then((result) => {
397 if (bootstrapPromise === nextPromise && result.status === "authenticated") {
398 resolvedAuthenticatedGateState = result;
399 }
400 return result;
401 })
402 .finally(() => {
403 if (bootstrapPromise === nextPromise) {
404 bootstrapPromise = null;
405 }
406 });
408​
409export function __resetServerAuthBootstrapForTests() {
410 bootstrapPromise = null;
411 resolvedAuthenticatedGateState = null;
412 explicitPairingRequested = false;