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

authBootstrap.test.ts

450 lines16.0 KB

1import {
2 EnvironmentAuthInvalidError,
3 type AuthBrowserSessionResult,
4 type AuthCreatePairingCredentialInput,
5 type AuthSessionState,
6 type DesktopBridge,
7} from "@t3tools/contracts";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import { HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12​
13import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
14import { __setPrimaryHttpRunnerForTests, type PrimaryHttpEffectRunner } from "./lib/runtime";
15​
16type TestWindow = {
17 location: URL;
18 history: {
19 replaceState: (_data: unknown, _unused: string, url: string) => void;
20 };
21 desktopBridge?: DesktopBridge;
22};
23​
24const LOOPBACK_AUTH = {
25 policy: "loopback-browser",
26 bootstrapMethods: ["one-time-token"],
27 sessionMethods: ["browser-session-cookie"],
28 sessionCookieName: "t3_session",
29} as const;
30​
31const DESKTOP_AUTH = {
32 policy: "desktop-managed-local",
33 bootstrapMethods: ["desktop-bootstrap"],
34 sessionMethods: ["browser-session-cookie"],
35 sessionCookieName: "t3_session",
36} as const;
37​
38const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
39const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
40 authenticated: false,
41 auth,
42});
43​
44const authenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
45 authenticated: true,
46 auth,
47 sessionMethod: "browser-session-cookie",
48 expiresAt: SESSION_EXPIRES_AT,
49});
50​
51const browserSession = (scopes: AuthBrowserSessionResult["scopes"]): AuthBrowserSessionResult => ({
52 authenticated: true,
53 scopes,
54 sessionMethod: "browser-session-cookie",
55 expiresAt: SESSION_EXPIRES_AT,
56});
57​
58function installTestBrowser(url: string) {
59 const testWindow: TestWindow = {
60 location: new URL(url),
61 history: {
62 replaceState: (_data, _unused, nextUrl) => {
63 testWindow.location = new URL(nextUrl, testWindow.location.href);
64 },
65 },
66 };
67​
68 vi.stubGlobal("window", testWindow);
69 vi.stubGlobal("document", { title: "T3 Code" });
70​
71 return testWindow;
73​
74function installDesktopBootstrap() {
75 const testWindow = installTestBrowser("http://localhost/");
76 testWindow.desktopBridge = {
77 getLocalEnvironmentBootstrap: () => ({
78 label: "Local environment",
79 httpBaseUrl: "http://localhost:3773",
80 wsBaseUrl: "ws://localhost:3773",
81 bootstrapToken: "desktop-bootstrap-token",
82 }),
83 } as DesktopBridge;
85​
86function sequence<A>(...values: ReadonlyArray<A>) {
87 let index = 0;
88 return () => values[Math.min(index++, values.length - 1)]!;
90​
91let disposeHttpTest: (() => Promise<void>) | undefined;
92​
93async function installAuthApi(input: {
94 readonly session?: () => AuthSessionState;
95 readonly browserSession?: (
96 credential: string,
97 ) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;
98 readonly pairingCredential?: (payload: AuthCreatePairingCredentialInput) => Effect.Effect<{
99 readonly id: string;
100 readonly credential: string;
101 readonly label?: string;
102 readonly expiresAt: DateTime.Utc;
103 }>;
104}) {
105 const testApi = await installEnvironmentHttpTest({
106 ...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),
107 ...(input.browserSession
108 ? { browserSession: (payload) => input.browserSession!(payload.credential) }
109 : {}),
110 ...(input.pairingCredential
111 ? { pairingCredential: (payload) => input.pairingCredential!(payload) }
112 : {}),
113 });
114 disposeHttpTest = testApi.dispose;
115 return testApi;
117​
118describe("resolveInitialServerAuthGateState", () => {
119 beforeEach(() => {
120 vi.restoreAllMocks();
121 vi.useRealTimers();
122 installTestBrowser("http://localhost/");
123 });
124​
125 afterEach(async () => {
126 await disposeHttpTest?.();
127 disposeHttpTest = undefined;
128 const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
129 __resetServerAuthBootstrapForTests();
130 __setPrimaryHttpRunnerForTests();
131 vi.unstubAllEnvs();
132 vi.useRealTimers();
133 vi.restoreAllMocks();
134 });
135​
136 it("reuses an in-flight silent bootstrap attempt", async () => {
137 const nextSession = sequence(
138 unauthenticatedSession(DESKTOP_AUTH),
139 authenticatedSession(DESKTOP_AUTH),
140 );
141 const testApi = await installAuthApi({
142 session: nextSession,
143 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
144 });
145​
146 installDesktopBootstrap();
147​
148 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
149​
150 await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
151​
152 expect(testApi.calls.session).toBe(2);
153 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
154 });
155​
156 it("uses https urls when the primary environment uses wss", async () => {
157 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
158 vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
159 vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
160​
161 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
162 await import("./environments/primary");
163​
164 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
165 status: "requires-auth",
166 auth: LOOPBACK_AUTH,
167 });
168 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
169 "https://remote.example.com/api/auth/session",
170 );
171 });
172​
173 it("uses the current origin as an auth proxy base for local dev environments", async () => {
174 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
175 installTestBrowser("http://localhost:5735/");
176​
177 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
178 await import("./environments/primary");
179​
180 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
181 status: "requires-auth",
182 auth: LOOPBACK_AUTH,
183 });
184 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
185 "http://localhost:5735/api/auth/session",
186 );
187 });
188​
189 it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => {
190 await installAuthApi({ session: () => unauthenticatedSession(DESKTOP_AUTH) });
191 vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733");
192​
193 const testWindow = installTestBrowser("http://127.0.0.1:5733/");
194 testWindow.desktopBridge = {
195 getLocalEnvironmentBootstrap: () => ({
196 label: "Local environment",
197 httpBaseUrl: "http://127.0.0.1:3773",
198 wsBaseUrl: "ws://127.0.0.1:3773",
199 }),
200 } as DesktopBridge;
201​
202 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
203 await import("./environments/primary");
204​
205 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
206 status: "requires-auth",
207 auth: DESKTOP_AUTH,
208 });
209 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
210 "http://127.0.0.1:5733/api/auth/session",
211 );
212 });
213​
214 it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => {
215 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
216 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
217​
218 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
219 status: "requires-auth",
220 auth: LOOPBACK_AUTH,
221 });
222 });
223​
224 it("retries transient auth session bootstrap failures after restart", async () => {
225 vi.useFakeTimers();
226 let attempts = 0;
227 const request = HttpClientRequest.get("http://localhost/api/auth/session");
228 const response = HttpClientResponse.fromWeb(
229 request,
230 new Response("Bad Gateway", { status: 502 }),
231 );
232 const runner: PrimaryHttpEffectRunner = async <A>() => {
233 attempts += 1;
234 if (attempts < 4) {
235 throw new HttpClientError.HttpClientError({
236 reason: new HttpClientError.StatusCodeError({ request, response }),
237 });
238 }
239 return unauthenticatedSession(LOOPBACK_AUTH) as A;
240 };
241 __setPrimaryHttpRunnerForTests(runner);
242​
243 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
244​
245 const gateStatePromise = resolveInitialServerAuthGateState();
246 await vi.advanceTimersByTimeAsync(2_000);
247​
248 await expect(gateStatePromise).resolves.toEqual({
249 status: "requires-auth",
250 auth: LOOPBACK_AUTH,
251 });
252 expect(attempts).toBe(4);
253 });
254​
255 it("takes a pairing token from the location hash and strips it immediately", async () => {
256 const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
257 const { takePairingTokenFromUrl } = await import("./environments/primary");
258​
259 expect(takePairingTokenFromUrl()).toBe("pairing-token");
260 expect(testWindow.location.hash).toBe("");
261 expect(testWindow.location.searchParams.get("token")).toBeNull();
262 });
263​
264 it("accepts query-string pairing tokens as a backward-compatible fallback", async () => {
265 const testWindow = installTestBrowser("http://localhost/?token=pairing-token");
266 const { takePairingTokenFromUrl } = await import("./environments/primary");
267​
268 expect(takePairingTokenFromUrl()).toBe("pairing-token");
269 expect(testWindow.location.searchParams.get("token")).toBeNull();
270 });
271​
272 it("allows manual token submission after the initial auth check requires pairing", async () => {
273 const nextSession = sequence(
274 unauthenticatedSession(LOOPBACK_AUTH),
275 authenticatedSession(LOOPBACK_AUTH),
276 );
277 const testApi = await installAuthApi({
278 session: nextSession,
279 browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
280 });
281 const { resolveInitialServerAuthGateState, submitServerAuthCredential } =
282 await import("./environments/primary");
283​
284 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
285 status: "requires-auth",
286 auth: LOOPBACK_AUTH,
287 });
288 await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined();
289 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
290 status: "authenticated",
291 });
292 expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
293 expect(testApi.calls.session).toBe(2);
294 });
295​
296 it("rejects a blank pairing token with a structured validation error", async () => {
297 const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
298 await import("./environments/primary/auth");
299​
300 const error = await submitServerAuthCredential(" ").then(
301 () => null,
302 (failure: unknown) => failure,
303 );
304​
305 expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
306 expect(error).toMatchObject({
307 _tag: "PrimaryEnvironmentPairingCredentialRequiredError",
308 providedLength: 3,
309 message: "Enter a pairing token to continue.",
310 });
311 });
312​
313 it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
314 const cause = new EnvironmentAuthInvalidError({
315 code: "auth_invalid",
316 reason: "invalid_credential",
317 traceId: "trace-invalid-credential",
318 });
319 const testApi = await installAuthApi({
320 browserSession: () => Effect.fail(cause),
321 });
322​
323 const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
324 await import("./environments/primary");
325​
326 const error = await submitServerAuthCredential("bad-token").then(
327 () => null,
328 (failure: unknown) => failure,
329 );
330 expect(error).toMatchObject({
331 _tag: "PrimaryEnvironmentPairingCredentialRejectedError",
332 providedLength: 9,
333 message: "Invalid pairing token. Check the token and try again.",
334 });
335 expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
336 if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
337 throw new Error("Expected a structured rejected pairing credential error.");
338 }
339 expect(error.cause).toMatchObject({
340 _tag: "EnvironmentAuthInvalidError",
341 code: "auth_invalid",
342 reason: "invalid_credential",
343 traceId: "trace-invalid-credential",
344 });
345 expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
346 });
347​
348 it("derives primary request messages from structural request context", async () => {
349 const cause = new Error("private transport detail");
350 const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
351 const error = PrimaryEnvironmentRequestError.fromCause({
352 operation: "list-pairing-links",
353 cause,
354 });
355​
356 expect(error.status).toBe(500);
357 expect(error.cause).toBe(cause);
358 expect(error.message).toBe(
359 "Primary environment request failed during list-pairing-links (HTTP 500).",
360 );
361 expect(error.message).not.toContain(cause.message);
362 });
363​
364 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
365 vi.useFakeTimers();
366 const nextSession = sequence(
367 unauthenticatedSession(DESKTOP_AUTH),
368 unauthenticatedSession(DESKTOP_AUTH),
369 authenticatedSession(DESKTOP_AUTH),
370 );
371 const testApi = await installAuthApi({
372 session: nextSession,
373 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
374 });
375​
376 installDesktopBootstrap();
377​
378 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
379​
380 const gateStatePromise = resolveInitialServerAuthGateState();
381 await vi.advanceTimersByTimeAsync(100);
382​
383 await expect(gateStatePromise).resolves.toEqual({ status: "authenticated" });
384 expect(testApi.calls.session).toBe(3);
385 });
386​
387 it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
388 vi.useFakeTimers();
389 const testApi = await installAuthApi({
390 session: () => unauthenticatedSession(DESKTOP_AUTH),
391 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
392 });
393​
394 installDesktopBootstrap();
395​
396 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
397​
398 const gateStatePromise = resolveInitialServerAuthGateState();
399 await vi.advanceTimersByTimeAsync(2_000);
400​
401 await expect(gateStatePromise).resolves.toEqual({
402 status: "requires-auth",
403 auth: DESKTOP_AUTH,
404 errorMessage: "Timed out waiting for authenticated session after bootstrap.",
405 });
406 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
407 });
408​
409 it("memoizes the authenticated gate state after the first successful read", async () => {
410 const testApi = await installAuthApi({
411 session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
412 });
413 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
414​
415 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
416 status: "authenticated",
417 });
418 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
419 status: "authenticated",
420 });
421 expect(testApi.calls.session).toBe(1);
422 });
423​
424 it("creates a pairing credential from the authenticated auth endpoint", async () => {
425 const testApi = await installAuthApi({
426 pairingCredential: (payload) =>
427 Effect.succeed({
428 id: "pairing-link-1",
429 credential: "pairing-token",
430 ...(payload.label === undefined ? {} : { label: payload.label }),
431 expiresAt: SESSION_EXPIRES_AT,
432 }),
433 });
434 const { createServerPairingCredential } = await import("./environments/primary");
435​
436 const credential = await createServerPairingCredential({
437 label: "Julius iPhone",
438 scopes: ["orchestration:read"],
439 });
440 expect(credential).toMatchObject({
441 id: "pairing-link-1",
442 credential: "pairing-token",
443 label: "Julius iPhone",
444 });
445 expect(DateTime.formatIso(credential.expiresAt)).toBe("2026-04-05T00:00:00.000Z");
446 expect(testApi.calls.pairingCredential).toEqual([
447 { label: "Julius iPhone", scopes: ["orchestration:read"] },
448 ]);
449 });
450});