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