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

auth.ts

373 lines10.6 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​
113async function exchangeBootstrapCredential(credential: string): Promise<AuthBootstrapResult> {
114 return retryTransientBootstrap(async () => {
115 const payload: AuthBootstrapInput = { credential };
116 const response = await fetch(resolvePrimaryEnvironmentHttpUrl("/api/auth/bootstrap"), {
117 body: JSON.stringify(payload),
118 credentials: "include",
119 headers: {
120 "content-type": "application/json",
121 },
122 method: "POST",
123 });
124​
125 if (!response.ok) {
126 const message = await response.text();
127 throw new BootstrapHttpError({
128 message: message || `Failed to bootstrap auth session (${response.status}).`,
129 status: response.status,
130 });
131 }
132​
133 return (await response.json()) as AuthBootstrapResult;
134 });
136​
137async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionState> {
138 const startedAt = Date.now();
139​
140 while (true) {
141 const session = await fetchSessionState();
142 if (session.authenticated) {
143 return session;
144 }
145​
146 if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
147 throw new Error("Timed out waiting for authenticated session after bootstrap.");
148 }
149​
150 await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
151 }
153​
154const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
155const BOOTSTRAP_RETRY_TIMEOUT_MS = 15_000;
156const BOOTSTRAP_RETRY_STEP_MS = 500;
157​
158export async function retryTransientBootstrap<T>(operation: () => Promise<T>): Promise<T> {
159 const startedAt = Date.now();
160 while (true) {
161 try {
162 return await operation();
163 } catch (error) {
164 if (!isTransientBootstrapError(error)) {
165 throw error;
166 }
167​
168 if (Date.now() - startedAt >= BOOTSTRAP_RETRY_TIMEOUT_MS) {
169 throw error;
170 }
171​
172 await waitForBootstrapRetry(BOOTSTRAP_RETRY_STEP_MS);
173 }
174 }
176​
177function waitForBootstrapRetry(delayMs: number): Promise<void> {
178 return new Promise((resolve) => {
179 setTimeout(resolve, delayMs);
180 });
182​
183function isTransientBootstrapError(error: unknown): boolean {
184 if (isBootstrapHttpError(error)) {
185 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
186 }
187​
188 if (error instanceof TypeError) {
189 return true;
190 }
191​
192 return error instanceof DOMException && error.name === "AbortError";
194​
195async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
196 const bootstrapCredential = getDesktopBootstrapCredential();
197 const currentSession = await fetchSessionState();
198 if (currentSession.authenticated) {
199 return { status: "authenticated" };
200 }
201​
202 if (!bootstrapCredential) {
203 return {
204 status: "requires-auth",
205 auth: currentSession.auth,
206 };
207 }
208​
209 try {
210 await exchangeBootstrapCredential(bootstrapCredential);
211 await waitForAuthenticatedSessionAfterBootstrap();
212 return { status: "authenticated" };
213 } catch (error) {
214 return {
215 status: "requires-auth",
216 auth: currentSession.auth,
217 errorMessage: error instanceof Error ? error.message : "Authentication failed.",
218 };
219 }
221​
222export async function submitServerAuthCredential(credential: string): Promise<void> {
223 const trimmedCredential = credential.trim();
224 if (!trimmedCredential) {
225 throw new Error("Enter a pairing token to continue.");
226 }
227​
228 resolvedAuthenticatedGateState = null;
229 await exchangeBootstrapCredential(trimmedCredential);
230 bootstrapPromise = null;
231 stripPairingTokenFromUrl();
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;
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>;
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 }
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>;
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 }
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;
344​
345export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
346 if (resolvedAuthenticatedGateState?.status === "authenticated") {
347 return resolvedAuthenticatedGateState;
348 }
349​
350 if (bootstrapPromise) {
351 return bootstrapPromise;
352 }
353​
354 const nextPromise = bootstrapServerAuth();
355 bootstrapPromise = nextPromise;
356 return nextPromise
357 .then((result) => {
358 if (result.status === "authenticated") {
359 resolvedAuthenticatedGateState = result;
360 }
361 return result;
362 })
363 .finally(() => {
364 if (bootstrapPromise === nextPromise) {
365 bootstrapPromise = null;
366 }
367 });
369​
370export function __resetServerAuthBootstrapForTests() {
371 bootstrapPromise = null;
372 resolvedAuthenticatedGateState = null;