Open History to see the last commit
1import {
2 AuthSessionState as AuthSessionStateSchema,
3 EnvironmentAuthInvalidError,
4 type AuthBrowserSessionResult,
5 type AuthCreatePairingCredentialInput,
6 type AuthSessionState,
7 type DesktopBridge,
8} from "@t3tools/contracts";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as Schema from "effect/Schema";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
14import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
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 encodeAuthSessionState = Schema.encodeSync(AuthSessionStateSchema);
40
41const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
42 authenticated: false,
43 auth,
44});
45
46const authenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
47 authenticated: true,
48 auth,
49 sessionMethod: "browser-session-cookie",
50 expiresAt: SESSION_EXPIRES_AT,
51});
52
53const browserSession = (scopes: AuthBrowserSessionResult["scopes"]): AuthBrowserSessionResult => ({
54 authenticated: true,
55 scopes,
56 sessionMethod: "browser-session-cookie",
57 expiresAt: SESSION_EXPIRES_AT,
58});
59
60function installTestBrowser(url: string) {
61 const testWindow: TestWindow = {
62 location: new URL(url),
63 history: {
64 replaceState: (_data, _unused, nextUrl) => {
65 testWindow.location = new URL(nextUrl, testWindow.location.href);
66 },
67 },
68 };
69
70 vi.stubGlobal("window", testWindow);
71 vi.stubGlobal("document", { title: "T3 Code" });
72
73 return testWindow;
74}
75
76function sequence<A>(...values: ReadonlyArray<A>) {
77 let index = 0;
78 return () => values[Math.min(index++, values.length - 1)]!;
79}
80
81let disposeHttpTest: (() => Promise<void>) | undefined;
82
83async function installAuthApi(input: {
84 readonly session?: () => AuthSessionState;
85 readonly browserSession?: (
86 credential: string,
87 ) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;
88 readonly pairingCredential?: (payload: AuthCreatePairingCredentialInput) => Effect.Effect<{
89 readonly id: string;
90 readonly credential: string;
91 readonly label?: string;
92 readonly expiresAt: DateTime.Utc;
93 }>;
94}) {
95 const testApi = await installEnvironmentHttpTest({
96 ...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),
97 ...(input.browserSession
98 ? { browserSession: (payload) => input.browserSession!(payload.credential) }
99 : {}),
100 ...(input.pairingCredential
101 ? { pairingCredential: (payload) => input.pairingCredential!(payload) }
102 : {}),
103 });
104 disposeHttpTest = testApi.dispose;
105 return testApi;
106}
107
108describe("resolveInitialServerAuthGateState", () => {
109 beforeEach(() => {
110 vi.restoreAllMocks();
111 vi.useRealTimers();
112 installTestBrowser("http://localhost/");
113 });
114
115 afterEach(async () => {
116 await disposeHttpTest?.();
117 disposeHttpTest = undefined;
118 const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
119 __resetServerAuthBootstrapForTests();
120 vi.unstubAllEnvs();
121 vi.useRealTimers();
122 vi.restoreAllMocks();
123 });
124
125 it("reuses an in-flight silent bootstrap attempt", async () => {
126 const nextSession = sequence(
127 unauthenticatedSession(DESKTOP_AUTH),
128 authenticatedSession(DESKTOP_AUTH),
129 );
130 const testApi = await installAuthApi({
131 session: nextSession,
132 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
133 });
134
135 const testWindow = installTestBrowser("http://localhost/");
136 testWindow.desktopBridge = {
137 getLocalEnvironmentBootstrap: () => ({
138 label: "Local environment",
139 httpBaseUrl: "http://localhost:3773",
140 wsBaseUrl: "ws://localhost:3773",
141 bootstrapToken: "desktop-bootstrap-token",
142 }),
143 } as DesktopBridge;
144
145 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
146
147 await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
148
149 expect(testApi.calls.session).toBe(2);
150 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
151 });
152
153 it("uses https urls when the primary environment uses wss", async () => {
154 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
155 vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
156 vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
157
158 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
159 await import("./environments/primary");
160
161 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
162 status: "requires-auth",
163 auth: LOOPBACK_AUTH,
164 });
165 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
166 "https://remote.example.com/api/auth/session",
167 );
168 });
169
170 it("uses the current origin as an auth proxy base for local dev environments", async () => {
171 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
172 installTestBrowser("http://localhost:5735/");
173
174 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
175 await import("./environments/primary");
176
177 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
178 status: "requires-auth",
179 auth: LOOPBACK_AUTH,
180 });
181 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
182 "http://localhost:5735/api/auth/session",
183 );
184 });
185
186 it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => {
187 await installAuthApi({ session: () => unauthenticatedSession(DESKTOP_AUTH) });
188 vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733");
189
190 const testWindow = installTestBrowser("http://127.0.0.1:5733/");
191 testWindow.desktopBridge = {
192 getLocalEnvironmentBootstrap: () => ({
193 label: "Local environment",
194 httpBaseUrl: "http://127.0.0.1:3773",
195 wsBaseUrl: "ws://127.0.0.1:3773",
196 }),
197 } as DesktopBridge;
198
199 const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } =
200 await import("./environments/primary");
201
202 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
203 status: "requires-auth",
204 auth: DESKTOP_AUTH,
205 });
206 expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe(
207 "http://127.0.0.1:5733/api/auth/session",
208 );
209 });
210
211 it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => {
212 await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) });
213 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
214
215 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
216 status: "requires-auth",
217 auth: LOOPBACK_AUTH,
218 });
219 });
220
221 it("retries transient auth session bootstrap failures after restart", async () => {
222 vi.useFakeTimers();
223 const fetchMock = vi
224 .fn<typeof fetch>()
225 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
226 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
227 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
228 .mockResolvedValueOnce(
229 new Response(
230 JSON.stringify(encodeAuthSessionState(unauthenticatedSession(LOOPBACK_AUTH))),
231 { status: 200, headers: { "content-type": "application/json" } },
232 ),
233 );
234 vi.stubGlobal("fetch", fetchMock);
235
236 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
237
238 const gateStatePromise = resolveInitialServerAuthGateState();
239 await vi.advanceTimersByTimeAsync(2_000);
240
241 await expect(gateStatePromise).resolves.toEqual({
242 status: "requires-auth",
243 auth: LOOPBACK_AUTH,
244 });
245 expect(fetchMock).toHaveBeenCalledTimes(4);
246 });
247
248 it("takes a pairing token from the location hash and strips it immediately", async () => {
249 const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
250 const { takePairingTokenFromUrl } = await import("./environments/primary");
251
252 expect(takePairingTokenFromUrl()).toBe("pairing-token");
253 expect(testWindow.location.hash).toBe("");
254 expect(testWindow.location.searchParams.get("token")).toBeNull();
255 });
256
257 it("accepts query-string pairing tokens as a backward-compatible fallback", async () => {
258 const testWindow = installTestBrowser("http://localhost/?token=pairing-token");
259 const { takePairingTokenFromUrl } = await import("./environments/primary");
260
261 expect(takePairingTokenFromUrl()).toBe("pairing-token");
262 expect(testWindow.location.searchParams.get("token")).toBeNull();
263 });
264
265 it("allows manual token submission after the initial auth check requires pairing", async () => {
266 const nextSession = sequence(
267 unauthenticatedSession(LOOPBACK_AUTH),
268 authenticatedSession(LOOPBACK_AUTH),
269 );
270 const testApi = await installAuthApi({
271 session: nextSession,
272 browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
273 });
274 const { resolveInitialServerAuthGateState, submitServerAuthCredential } =
275 await import("./environments/primary");
276
277 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
278 status: "requires-auth",
279 auth: LOOPBACK_AUTH,
280 });
281 await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined();
282 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
283 status: "authenticated",
284 });
285 expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
286 expect(testApi.calls.session).toBe(2);
287 });
288
289 it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
290 const testApi = await installAuthApi({
291 browserSession: () =>
292 Effect.fail(
293 new EnvironmentAuthInvalidError({
294 code: "auth_invalid",
295 reason: "invalid_credential",
296 traceId: "trace-invalid-credential",
297 }),
298 ),
299 });
300
301 const { submitServerAuthCredential } = await import("./environments/primary");
302
303 await expect(submitServerAuthCredential("bad-token")).rejects.toThrow(
304 "Invalid pairing token. Check the token and try again.",
305 );
306 expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
307 });
308
309 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
310 vi.useFakeTimers();
311 const nextSession = sequence(
312 unauthenticatedSession(DESKTOP_AUTH),
313 unauthenticatedSession(DESKTOP_AUTH),
314 authenticatedSession(DESKTOP_AUTH),
315 );
316 const testApi = await installAuthApi({
317 session: nextSession,
318 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
319 });
320
321 const testWindow = installTestBrowser("http://localhost/");
322 testWindow.desktopBridge = {
323 getLocalEnvironmentBootstrap: () => ({
324 label: "Local environment",
325 httpBaseUrl: "http://localhost:3773",
326 wsBaseUrl: "ws://localhost:3773",
327 bootstrapToken: "desktop-bootstrap-token",
328 }),
329 } as DesktopBridge;
330
331 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
332
333 const gateStatePromise = resolveInitialServerAuthGateState();
334 await vi.advanceTimersByTimeAsync(100);
335
336 await expect(gateStatePromise).resolves.toEqual({ status: "authenticated" });
337 expect(testApi.calls.session).toBe(3);
338 });
339
340 it("memoizes the authenticated gate state after the first successful read", async () => {
341 const testApi = await installAuthApi({
342 session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
343 });
344 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
345
346 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
347 status: "authenticated",
348 });
349 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
350 status: "authenticated",
351 });
352 expect(testApi.calls.session).toBe(1);
353 });
354
355 it("creates a pairing credential from the authenticated auth endpoint", async () => {
356 const testApi = await installAuthApi({
357 pairingCredential: (payload) =>
358 Effect.succeed({
359 id: "pairing-link-1",
360 credential: "pairing-token",
361 ...(payload.label === undefined ? {} : { label: payload.label }),
362 expiresAt: SESSION_EXPIRES_AT,
363 }),
364 });
365 const { createServerPairingCredential } = await import("./environments/primary");
366
367 const credential = await createServerPairingCredential({
368 label: "Julius iPhone",
369 scopes: ["orchestration:read"],
370 });
371 expect(credential).toMatchObject({
372 id: "pairing-link-1",
373 credential: "pairing-token",
374 label: "Julius iPhone",
375 });
376 expect(DateTime.formatIso(credential.expiresAt)).toBe("2026-04-05T00:00:00.000Z");
377 expect(testApi.calls.pairingCredential).toEqual([
378 { label: "Julius iPhone", scopes: ["orchestration:read"] },
379 ]);
380 });
381});