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

auth.ts

359 lines10.1 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;
60const AUTH_SESSION_ESTABLISH_TIMEOUT_MS = 2_000;
61const AUTH_SESSION_ESTABLISH_STEP_MS = 100;
62​
63export function peekPairingTokenFromUrl(): string | null {
64 return getPairingTokenFromUrl(new URL(window.location.href));
66​
67export function stripPairingTokenFromUrl() {
68 const url = new URL(window.location.href);
69 const next = stripPairingTokenUrl(url);
70 if (next.toString() === url.toString()) {
71 return;
72 }
73 window.history.replaceState({}, document.title, next.toString());
75​
76export function takePairingTokenFromUrl(): string | null {
77 const token = peekPairingTokenFromUrl();
78 if (!token) {
79 return null;
80 }
81 stripPairingTokenFromUrl();
82 return token;
84​
85function getDesktopBootstrapCredential(): string | null {
86 const bootstrap = window.desktopBridge?.getLocalEnvironmentBootstrap();
87 return typeof bootstrap?.bootstrapToken === "string" && bootstrap.bootstrapToken.length > 0
88 ? bootstrap.bootstrapToken
89 : null;
91​
92export async function fetchSessionState(): Promise<AuthSessionState> {
93 return retryTransientBootstrap(async () => {
94 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/session"), {
95 credentials: "include",
96 });
97 if (!response.ok) {
98 throw new BootstrapHttpError({
99 message: `Failed to load server auth session state (${response.status}).`,
100 status: response.status,
101 });
102 }
103 return (await response.json()) as AuthSessionState;
104 });
106​
107async function readErrorMessage(response: Response, fallbackMessage: string): Promise<string> {
108 const text = await response.text();
109 return text || fallbackMessage;
111​
112async function exchangeBootstrapCredential(credential: string): Promise<AuthBootstrapResult> {
113 return retryTransientBootstrap(async () => {
114 const payload: AuthBootstrapInput = { credential };
115 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/bootstrap"), {
116 body: JSON.stringify(payload),
117 credentials: "include",
118 headers: {
119 "content-type": "application/json",
120 },
121 method: "POST",
122 });
123​
124 if (!response.ok) {
125 const message = await response.text();
126 throw new BootstrapHttpError({
127 message: message || `Failed to bootstrap auth session (${response.status}).`,
128 status: response.status,
129 });
130 }
131​
132 return (await response.json()) as AuthBootstrapResult;
133 });
135​
136async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
137 const startedAt = Date.now();
138​
139 while (true) {
140 const session = await fetchSessionState();
141 if (session.authenticated) {
142 return session;
143 }
144​
145 if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
146 throw new Error("Timed out waiting for authenticated session after bootstrap.");
147 }
148​
149 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
150 }
152​
153const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
154const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
155const BOOTSTRAP_RETRY_STEP_MS = 500;
156​
157export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
158 const startedAt = Date.now();
159 while (true) {
160 try {
161 return await operation();
162 } catch (error) {
163 if (!isTransientBootstrapError(error)) {
164 throw error;
165 }
166​
167 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
168 throw error;
169 }
170​
171 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
172 }
173 }
175​
176function waitForBootstrapRetry(delayMs: number): Promise<void> {
177 return new Promise((resolve) => {
178 setTimeout(resolve, delayMs);
179 });
181​
182function isTransientBootstrapError(error: unknown): boolean {
183 if (isBootstrapHttpError(error)) {
184 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
185 }
186​
187 if (error instanceof TypeError) {
188 return true;
189 }
190​
191 return error instanceof DOMException && error.name === "AbortError";
193​
194async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
195 const bootstrapCredential = getDesktopBootstrapCredential();
196 const currentSession = await fetchSessionState();
197 if (currentSession.authenticated) {
198 return { status: "authenticated" };
199 }
200​
201 if (!bootstrapCredential) {
202 return {
203 status: "requires-auth",
204 auth: currentSession.auth,
205 };
206 }
207​
208 try {
209 await exchangeBootstrapCredential(bootstrapCredential);
210 await waitForAuthenticatedSessionAfterBootstrap();
211 return { status: "authenticated" };
212 } catch (error) {
213 return {
214 status: "requires-auth",
215 auth: currentSession.auth,
216 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
217 };
218 }
220​
221export async function submitServerAuthCredential(credential: string): Promise<void> {
222 const trimmedCredential = credential.trim();
223 if (!trimmedCredential) {
224 throw new Error("Enter a pairing token to continue.");
225 }
226​
227 await exchangeBootstrapCredential(trimmedCredential);
228 bootstrapPromise = null;
229 stripPairingTokenFromUrl();
231​
232export async function createServerPairingCredential(
233 label?: string,
234): Promise<AuthPairingCredentialResult> {
235 const trimmedLabel = label?.trim();
236 const payload: AuthCreatePairingCredentialInput = trimmedLabel ? { label: trimmedLabel } : {};
237 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-token"), {
238 body: JSON.stringify(payload),
239 credentials: "include",
240 headers: {
241 "content-type": "application/json",
242 },
243 method: "POST",
244 });
245​
246 if (!response.ok) {
247 throw new Error(
248 await readErrorMessage(response, `Failed to create pairing credential (${response.status}).`),
249 );
250 }
251​
252 return (await response.json()) as AuthPairingCredentialResult;
254​
255export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPairingLinkRecord>> {
256 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links"), {
257 credentials: "include",
258 });
259​
260 if (!response.ok) {
261 throw new Error(
262 await readErrorMessage(response, `Failed to load pairing links (${response.status}).`),
263 );
264 }
265​
266 return (await response.json()) as ReadonlyArray<ServerPairingLinkRecord>;
268​
269export async function revokeServerPairingLink(id: string): Promise<void> {
270 const payload: AuthRevokePairingLinkInput = { id };
271 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/pairing-links/revoke"), {
272 body: JSON.stringify(payload),
273 credentials: "include",
274 headers: {
275 "content-type": "application/json",
276 },
277 method: "POST",
278 });
279​
280 if (!response.ok) {
281 throw new Error(
282 await readErrorMessage(response, `Failed to revoke pairing link (${response.status}).`),
283 );
284 }
286​
287export async function listServerClientSessions(): Promise<
288 ReadonlyArray<ServerClientSessionRecord>
289> {
290 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients"), {
291 credentials: "include",
292 });
293​
294 if (!response.ok) {
295 throw new Error(
296 await readErrorMessage(response, `Failed to load paired clients (${response.status}).`),
297 );
298 }
299​
300 return (await response.json()) as ReadonlyArray<ServerClientSessionRecord>;
302​
303export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {
304 const payload: AuthRevokeClientSessionInput = { sessionId };
305 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke"), {
306 body: JSON.stringify(payload),
307 credentials: "include",
308 headers: {
309 "content-type": "application/json",
310 },
311 method: "POST",
312 });
313​
314 if (!response.ok) {
315 throw new Error(
316 await readErrorMessage(response, `Failed to revoke client session (${response.status}).`),
317 );
318 }
320​
321export async function revokeOtherServerClientSessions(): Promise<number> {
322 const response = await fetch(
323 resolvePrimaryEnvironmentHttpUrl("/api/auth/clients/revoke-others"),
324 {
325 credentials: "include",
326 method: "POST",
327 },
328 );
329​
330 if (!response.ok) {
331 throw new Error(
332 await readErrorMessage(
333 response,
334 `Failed to revoke other client sessions (${response.status}).`,
335 ),
336 );
337 }
338​
339 const result = (await response.json()) as { revokedCount?: number };
340 return result.revokedCount ?? 0;
342​
343export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
344 if (bootstrapPromise) {
345 return bootstrapPromise;
346 }
347​
348 const nextPromise = bootstrapServerAuth();
349 bootstrapPromise = nextPromise;
350 return nextPromise.finally(() => {
351 if (bootstrapPromise === nextPromise) {
352 bootstrapPromise = null;
353 }
354 });
356​
357export function __resetServerAuthBootstrapForTests() {
358 bootstrapPromise = null;