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

auth.ts

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