Open History to see the last commit
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;
72}
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;
87}
88
89function sequence<A>(...values: ReadonlyArray<A>) {
90 let index = 0;
91 return () => values[Math.min(index++, values.length - 1)]!;
92}
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;
119}
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("keeps manual token submission pending until the session is authenticated", async () => {
314 vi.useFakeTimers();
315 let authenticated = false;
316 let settled = false;
317 try {
318 const testApi = await installAuthApi({
319 session: () =>
320 authenticated
321 ? authenticatedSession(LOOPBACK_AUTH)
322 : unauthenticatedSession(LOOPBACK_AUTH),
323 browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
324 });
325 const { submitServerAuthCredential } = await import("./environments/primary");
326
327 const submission = submitServerAuthCredential("retry-token").finally(() => {
328 settled = true;
329 });
330 await vi.advanceTimersByTimeAsync(0);
331
332 expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
333 expect(testApi.calls.session).toBe(1);
334 expect(settled).toBe(false);
335
336 authenticated = true;
337 await vi.advanceTimersByTimeAsync(100);
338 await expect(submission).resolves.toBeUndefined();
339 expect(testApi.calls.session).toBe(2);
340 } finally {
341 vi.useRealTimers();
342 }
343 });
344
345 it("fails manual token submission when the session is not established", async () => {
346 vi.useFakeTimers();
347 try {
348 const testApi = await installAuthApi({
349 session: () => unauthenticatedSession(LOOPBACK_AUTH),
350 browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
351 });
352 const { PrimaryEnvironmentAuthSessionTimeoutError, submitServerAuthCredential } =
353 await import("./environments/primary/auth");
354
355 const submission = submitServerAuthCredential("retry-token");
356 const failure = submission.then(
357 () => null,
358 (error: unknown) => error,
359 );
360 await vi.advanceTimersByTimeAsync(2_000);
361
362 await expect(failure).resolves.toBeInstanceOf(PrimaryEnvironmentAuthSessionTimeoutError);
363 expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
364 expect(testApi.calls.session).toBeGreaterThan(1);
365 } finally {
366 vi.useRealTimers();
367 }
368 });
369
370 it("rejects a blank pairing token with a structured validation error", async () => {
371 const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
372 await import("./environments/primary/auth");
373
374 const error = await submitServerAuthCredential(" ").then(
375 () => null,
376 (failure: unknown) => failure,
377 );
378
379 expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
380 expect(error).toMatchObject({
381 _tag: "PrimaryEnvironmentPairingCredentialRequiredError",
382 providedLength: 3,
383 message: "Enter a pairing token to continue.",
384 });
385 });
386
387 it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
388 const cause = new EnvironmentAuthInvalidError({
389 code: "auth_invalid",
390 reason: "invalid_credential",
391 traceId: "trace-invalid-credential",
392 });
393 const testApi = await installAuthApi({
394 browserSession: () => Effect.fail(cause),
395 });
396
397 const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
398 await import("./environments/primary");
399
400 const error = await submitServerAuthCredential("bad-token").then(
401 () => null,
402 (failure: unknown) => failure,
403 );
404 expect(error).toMatchObject({
405 _tag: "PrimaryEnvironmentPairingCredentialRejectedError",
406 providedLength: 9,
407 message: "Invalid pairing token. Check the token and try again.",
408 });
409 expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
410 if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
411 throw new Error("Expected a structured rejected pairing credential error.");
412 }
413 expect(error.cause).toMatchObject({
414 _tag: "EnvironmentAuthInvalidError",
415 code: "auth_invalid",
416 reason: "invalid_credential",
417 traceId: "trace-invalid-credential",
418 });
419 expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
420 });
421
422 it("derives primary request messages from structural request context", async () => {
423 const cause = new Error("private transport detail");
424 const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
425 const error = PrimaryEnvironmentRequestError.fromCause({
426 operation: "list-pairing-links",
427 cause,
428 });
429
430 expect(error.status).toBe(500);
431 expect(error.cause).toBe(cause);
432 expect(error.message).toBe(
433 "Primary environment request failed during list-pairing-links (HTTP 500).",
434 );
435 expect(error.message).not.toContain(cause.message);
436 });
437
438 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
439 vi.useFakeTimers();
440 const nextSession = sequence(
441 unauthenticatedSession(DESKTOP_AUTH),
442 unauthenticatedSession(DESKTOP_AUTH),
443 authenticatedSession(DESKTOP_AUTH),
444 );
445 const testApi = await installAuthApi({
446 session: nextSession,
447 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
448 });
449
450 const testWindow = installTestBrowser("http://localhost/");
451 testWindow.desktopBridge = {
452 getLocalEnvironmentBootstraps: () => [
453 {
454 id: "primary",
455 label: "Windows",
456 httpBaseUrl: "http://localhost:3773",
457 wsBaseUrl: "ws://localhost:3773",
458 bootstrapToken: "desktop-bootstrap-token",
459 },
460 ],
461 } as unknown as DesktopBridge;
462
463 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
464
465 const gateStatePromise = resolveInitialServerAuthGateState();
466 await vi.advanceTimersByTimeAsync(100);
467
468 await expect(gateStatePromise).resolves.toEqual({ status: "authenticated" });
469 expect(testApi.calls.session).toBe(3);
470 });
471
472 it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
473 vi.useFakeTimers();
474 const testApi = await installAuthApi({
475 session: () => unauthenticatedSession(DESKTOP_AUTH),
476 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
477 });
478
479 installDesktopBootstrap();
480
481 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
482
483 const gateStatePromise = resolveInitialServerAuthGateState();
484 await vi.advanceTimersByTimeAsync(2_000);
485
486 await expect(gateStatePromise).resolves.toEqual({
487 status: "requires-auth",
488 auth: DESKTOP_AUTH,
489 errorMessage: "Timed out waiting for authenticated session after bootstrap.",
490 });
491 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
492 });
493
494 it("memoizes the authenticated gate state after the first successful read", async () => {
495 const testApi = await installAuthApi({
496 session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
497 });
498 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
499
500 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
501 status: "authenticated",
502 });
503 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
504 status: "authenticated",
505 });
506 expect(testApi.calls.session).toBe(1);
507 });
508
509 it("exchanges a URL token when the browser already has a session", async () => {
510 const testApi = await installAuthApi({
511 session: () => authenticatedSession(LOOPBACK_AUTH),
512 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
513 });
514 const testWindow = installTestBrowser("http://localhost/#token=reusable-token");
515 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
516
517 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
518 status: "authenticated",
519 });
520
521 expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]);
522 expect(testWindow.location.hash).toBe("");
523 });
524
525 it("exchanges an explicit pair link after caching an authenticated state", async () => {
526 const testApi = await installAuthApi({
527 session: () => authenticatedSession(LOOPBACK_AUTH),
528 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
529 });
530 const testWindow = installTestBrowser("http://localhost/");
531 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
532
533 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
534 status: "authenticated",
535 });
536 testWindow.location = new URL("http://localhost/pair#token=reusable-token");
537
538 await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
539
540 expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]);
541 expect(testApi.calls.session).toBe(3);
542 });
543
544 it("makes later callers wait for a URL token that arrives during bootstrap", async () => {
545 let releaseExchange!: () => void;
546 const exchangeRelease = new Promise<void>((resolve) => {
547 releaseExchange = resolve;
548 });
549 let markExchangeStarted!: () => void;
550 const exchangeStarted = new Promise<void>((resolve) => {
551 markExchangeStarted = resolve;
552 });
553 const nextSession = sequence(
554 authenticatedSession(LOOPBACK_AUTH),
555 authenticatedSession(LOOPBACK_AUTH),
556 );
557 const testApi = await installAuthApi({
558 session: nextSession,
559 browserSession: () => {
560 markExchangeStarted();
561 return Effect.promise(() => exchangeRelease).pipe(
562 Effect.andThen(
563 Effect.fail(
564 new EnvironmentAuthInvalidError({
565 code: "auth_invalid",
566 reason: "invalid_credential",
567 traceId: "trace-rejected-queued-credential",
568 }),
569 ),
570 ),
571 );
572 },
573 });
574 const testWindow = installTestBrowser("http://localhost/");
575 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
576
577 const initialBootstrap = resolveInitialServerAuthGateState();
578 testWindow.location = new URL("http://localhost/pair#token=reusable-token");
579 const explicitPairing = resolveInitialServerAuthGateState();
580 const laterCaller = resolveInitialServerAuthGateState();
581 let laterCallerSettled = false;
582 void laterCaller.then(() => {
583 laterCallerSettled = true;
584 });
585
586 try {
587 await expect(initialBootstrap).resolves.toEqual({ status: "authenticated" });
588 await exchangeStarted;
589 expect(laterCallerSettled).toBe(false);
590 } finally {
591 releaseExchange();
592 }
593
594 const rejectedState = {
595 status: "requires-auth",
596 auth: LOOPBACK_AUTH,
597 errorMessage: "Invalid pairing token. Check the token and try again.",
598 } as const;
599 await expect(explicitPairing).resolves.toEqual(rejectedState);
600 await expect(laterCaller).resolves.toEqual(rejectedState);
601 expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]);
602 expect(testApi.calls.session).toBe(2);
603 });
604
605 it("does not exchange a token during an ordinary authenticated load", async () => {
606 const testApi = await installAuthApi({
607 session: () => authenticatedSession(LOOPBACK_AUTH),
608 browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
609 });
610 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
611
612 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
613 status: "authenticated",
614 });
615
616 expect(testApi.calls.browserSession).toEqual([]);
617 });
618
619 it("reports a rejected URL token without caching false success", async () => {
620 const cause = new EnvironmentAuthInvalidError({
621 code: "auth_invalid",
622 reason: "invalid_credential",
623 traceId: "trace-invalid-url-credential",
624 });
625 const nextSession = sequence(
626 authenticatedSession(LOOPBACK_AUTH),
627 unauthenticatedSession(LOOPBACK_AUTH),
628 );
629 const testApi = await installAuthApi({
630 session: nextSession,
631 browserSession: () => Effect.fail(cause),
632 });
633 installTestBrowser("http://localhost/#token=rejected-token");
634 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
635
636 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
637 status: "requires-auth",
638 auth: LOOPBACK_AUTH,
639 errorMessage: "Invalid pairing token. Check the token and try again.",
640 });
641 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
642 status: "requires-auth",
643 auth: LOOPBACK_AUTH,
644 });
645 expect(testApi.calls.browserSession).toEqual([{ credential: "rejected-token" }]);
646 });
647
648 it("creates a pairing credential from the authenticated auth endpoint", async () => {
649 const testApi = await installAuthApi({
650 pairingCredential: (payload) =>
651 Effect.succeed({
652 id: "pairing-link-1",
653 credential: "pairing-token",
654 ...(payload.label === undefined ? {} : { label: payload.label }),
655 expiresAt: SESSION_EXPIRES_AT,
656 }),
657 });
658 const { createServerPairingCredential } = await import("./environments/primary");
659
660 const credential = await createServerPairingCredential({
661 label: "Julius iPhone",
662 scopes: ["orchestration:read"],
663 });
664 expect(credential).toMatchObject({
665 id: "pairing-link-1",
666 credential: "pairing-token",
667 label: "Julius iPhone",
668 });
669 expect(DateTime.formatIso(credential.expiresAt)).toBe("2026-04-05T00:00:00.000Z");
670 expect(testApi.calls.pairingCredential).toEqual([
671 { label: "Julius iPhone", scopes: ["orchestration:read"] },
672 ]);
673 });
674});