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

auth.ts

408 lines11.5 KB

1import type {
2 AuthBootstrapInput,
3 AuthBootstrapResult,
4 AuthClientMetadata,
5 AuthCreatePairingCredentialInput,
6 AuthPairingCredentialResult,
7 AuthRevokeClientSessionInput,
8 AuthRevokePairingLinkInput,
9 AuthSessionId,
10 AuthSessionState,
11} from "@t3tools/contracts";
12​
13import {
14 getPairingTokenFromUrl,
15 stripPairingTokenFromUrl as stripPairingTokenUrl,
16} from "../../pairingUrl";
17​
18import { resolvePrimaryEnvironmentHttpUrl } from "./target";
19import * as Data from "effect/Data";
20import * as Predicate from "effect/Predicate";
21​
22export class BootstrapHttpError extends Data.TaggedError("BootstrapHttpError")<{
23 readonly message: string;
24 readonly status: number;
25}> {}
26const isBootstrapHttpError = (u: unknown): u is BootstrapHttpError =>
27 Predicate.isTagged(u, "BootstrapHttpError");
28​
29export interface ServerPairingLinkRecord {
30 readonly id: string;
31 readonly credential: string;
32 readonly role: "owner" | "client";
33 readonly subject: string;
34 readonly label?: string;
35 readonly createdAt: string;
36 readonly expiresAt: string;
38​
39export interface ServerClientSessionRecord {
40 readonly sessionId: AuthSessionId;
41 readonly subject: string;
42 readonly role: "owner" | "client";
43 readonly method: "browser-session-cookie" | "bearer-session-token";
44 readonly client: AuthClientMetadata;
45 readonly issuedAt: string;
46 readonly expiresAt: string;
47 readonly lastConnectedAt: string | null;
48 readonly connected: boolean;
49 readonly current: boolean;
51​
52type ServerAuthGateState =
53 | { status: "authenticated" }
54 | {
55 status: "requires-auth";
56 auth: AuthSessionState["auth"];
57 errorMessage?: string;
58 };
59​
60let bootstrapPromise: Promise<ServerAuthGateState> | null = null;
61let resolvedAuthenticatedGateState: ServerAuthGateState | null = null;
62const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
63const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
64​
65export function peekPairingTokenFromUrl(): string | null {
66 return getPairingTokenFromUrl(new URL(window.location.href));
68​
69export function stripPairingTokenFromUrl() {
70 const url = new URL(window.location.href);
71 const next = stripPairingTokenUrl(url);
72 if (next.toString() === url.toString()) {
73 return;
74 }
75 window.history.replaceState({}, document.title, next.toString());
77​
78export function takePairingTokenFromUrl(): string | null {
79 const token = peekPairingTokenFromUrl();
80 if (!token) {
81 return null;
82 }
83 stripPairingTokenFromUrl();
84 return token;
86​
87function getDesktopBootstrapCredential(): string | null {
88 const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
89 return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
90 ? bootstrap.bootstrapToken
91 : null;
93​
94export async function fetchSessionState(): Promise<AuthSessionState> {
95 return retryTransientBootstrap(async () => {
96 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/session"), {
97 credentials: "include",
98 });
99 if (!response.ok) {
100 throw new BootstrapHttpError({
101 message: `Failed to load server auth session state (${response.status}).`,
102 status: response.status,
103 });
104 }
105 return (await response.json()) as AuthSessionState;
106 });
108​
109async function readErrorMessage(response: Response, fallbackMessage: string): Promise<string> {
110 const text = await response.text();
111 return text || fallbackMessage;
113​
114const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([
115 "Invalid bootstrap credential.",
116 "Unknown bootstrap credential.",
117]);
118​
119function parseBootstrapErrorMessage(message: string): string {
120 const trimmed = message.trim();
121 if (trimmed.length === 0) {
122 return "";
123 }
124​
125 try {
126 const parsed = JSON.parse(trimmed) as {
127 error?: unknown;
128 };
129 if (typeof parsed.error === "string" && parsed.error.trim().length > 0) {
130 return parsed.error.trim();
131 }
132 } catch {
133 // Not JSON; fall back to plain text.
134 }
135​
136 return trimmed;
138​
139function toFriendlyBootstrapErrorMessage(status: number, message: string): string {
140 const parsedMessage = parseBootstrapErrorMessage(message);
141 if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(parsedMessage)) {
142 return "Invalid pairing token. Check the token and try again.";
143 }
144​
145 return parsedMessage;
147​
148async function exchangeBootstrapCredential(credential: string): Promise<AuthBootstrapResult> {
149 return retryTransientBootstrap(async () => {
150 const payload: AuthBootstrapInput = { credential };
151 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/bootstrap"), {
152 body: JSON.stringify(payload),
153 credentials: "include",
154 headers: {
155 "content-type": "application/json",
156 },
157 method: "POST",
158 });
159​
160 if (!response.ok) {
161 const message = toFriendlyBootstrapErrorMessage(response.status, await response.text());
162 throw new BootstrapHttpError({
163 message: message || `Failed to bootstrap auth session (${response.status}).`,
164 status: response.status,
165 });
166 }
167​
168 return (await response.json()) as AuthBootstrapResult;
169 });
171​
172async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
173 const startedAt = Date.now();
174​
175 while (true) {
176 const session = await fetchSessionState();
177 if (session.authenticated) {
178 return session;
179 }
180​
181 if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
182 throw new Error("Timed out waiting for authenticated session after bootstrap.");
183 }
184​
185 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
186 }
188​
189const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
190const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
191const BOOTSTRAP_RETRY_STEP_MS = 500;
192​
193export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
194 const startedAt = Date.now();
195 while (true) {
196 try {
197 return await operation();
198 } catch (error) {
199 if (!isTransientBootstrapError(error)) {
200 throw error;
201 }
202​
203 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
204 throw error;
205 }
206​
207 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
208 }
209 }
211​
212function waitForBootstrapRetry(delayMs: number): Promise<void> {
213 return new Promise((resolve) => {
214 setTimeout(resolve, delayMs);
215 });
217​
218function isTransientBootstrapError(error: unknown): boolean {
219 if (isBootstrapHttpError(error)) {
220 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
221 }
222​
223 if (error instanceof TypeError) {
224 return true;
225 }
226​
227 return error instanceof DOMException && error.name === "AbortError";
229​
230async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
231 const bootstrapCredential = getDesktopBootstrapCredential();
232 const currentSession = await fetchSessionState();
233 if (currentSession.authenticated) {
234 return { status: "authenticated" };
235 }
236​
237 if (!bootstrapCredential) {
238 return {
239 status: "requires-auth",
240 auth: currentSession.auth,
241 };
242 }
243​
244 try {
245 await exchangeBootstrapCredential(bootstrapCredential);
246 await waitForAuthenticatedSessionAfterBootstrap();
247 return { status: "authenticated" };
248 } catch (error) {
249 return {
250 status: "requires-auth",
251 auth: currentSession.auth,
252 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
253 };
254 }
256​
257export async function submitServerAuthCredential(credential: string): Promise<void> {
258 const trimmedCredential = credential.trim();
259 if (!trimmedCredential) {
260 throw new Error("Enter a pairing token to continue.");
261 }
262​
263 resolvedAuthenticatedGateState = null;
264 await exchangeBootstrapCredential(trimmedCredential);
265 bootstrapPromise = null;
266 stripPairingTokenFromUrl();
268​
269export async function createServerPairingCredential(
270 label?: string,
271): Promise<AuthPairingCredentialResult> {
272 const trimmedLabel = label?.trim();
273 const payload: AuthCreatePairingCredentialInput = trimmedLabel ? { label: trimmedLabel } : {};
274 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-token"), {
275 body: JSON.stringify(payload),
276 credentials: "include",
277 headers: {
278 "content-type": "application/json",
279 },
280 method: "POST",
281 });
282​
283 if (!response.ok) {
284 throw new Error(
285 await readErrorMessage(response, `Failed to create pairing credential (${response.status}).`),
286 );
287 }
288​
289 return (await response.json()) as AuthPairingCredentialResult;
291​
292export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
293 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links"), {
294 credentials: "include",
295 });
296​
297 if (!response.ok) {
298 throw new Error(
299 await readErrorMessage(response, `Failed to load pairing links (${response.status}).`),
300 );
301 }
302​
303 return (await response.json()) as ReadonlyArray<ServerPairingLinkRecord>;
305​
306export async function revokeServerPairingLink(id: string): Promise<void> {
307 const payload: AuthRevokePairingLinkInput = { id };
308 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links/revoke"), {
309 body: JSON.stringify(payload),
310 credentials: "include",
311 headers: {
312 "content-type": "application/json",
313 },
314 method: "POST",
315 });
316​
317 if (!response.ok) {
318 throw new Error(
319 await readErrorMessage(response, `Failed to revoke pairing link (${response.status}).`),
320 );
321 }
323​
324export async function listServerClientSessions(): Promise<
325 ReadonlyArray<ServerClientSessionRecord>
326> {
327 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients"), {
328 credentials: "include",
329 });
330​
331 if (!response.ok) {
332 throw new Error(
333 await readErrorMessage(response, `Failed to load paired clients (${response.status}).`),
334 );
335 }
336​
337 return (await response.json()) as ReadonlyArray<ServerClientSessionRecord>;
339​
340export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
341 const payload: AuthRevokeClientSessionInput = { sessionId };
342 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke"), {
343 body: JSON.stringify(payload),
344 credentials: "include",
345 headers: {
346 "content-type": "application/json",
347 },
348 method: "POST",
349 });
350​
351 if (!response.ok) {
352 throw new Error(
353 await readErrorMessage(response, `Failed to revoke client session (${response.status}).`),
354 );
355 }
357​
358export async function revokeOtherServerClientSessions(): Promise<number> {
359 const response = await fetch(
360 resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke-others"),
361 {
362 credentials: "include",
363 method: "POST",
364 },
365 );
366​
367 if (!response.ok) {
368 throw new Error(
369 await readErrorMessage(
370 response,
371 `Failed to revoke other client sessions (${response.status}).`,
372 ),
373 );
374 }
375​
376 const result = (await response.json()) as { revokedCount?: number };
377 return result.revokedCount ?? 0;
379​
380export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
381 if (resolvedAuthenticatedGateState?.status === "authenticated") {
382 return resolvedAuthenticatedGateState;
383 }
384​
385 if (bootstrapPromise) {
386 return bootstrapPromise;
387 }
388​
389 const nextPromise = bootstrapServerAuth();
390 bootstrapPromise = nextPromise;
391 return nextPromise
392 .then((result) => {
393 if (result.status === "authenticated") {
394 resolvedAuthenticatedGateState = result;
395 }
396 return result;
397 })
398 .finally(() => {
399 if (bootstrapPromise === nextPromise) {
400 bootstrapPromise = null;
401 }
402 });
404​
405export function __resetServerAuthBootstrapForTests() {
406 bootstrapPromise = null;
407 resolvedAuthenticatedGateState = null;