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

authBootstrap.test.ts

478 lines16.9 KB

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