Open History to see the last commit
1import type { DesktopBridge } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
4function jsonResponse(body: unknown, init?: ResponseInit) {
5 return new Response(JSON.stringify(body), {
6 headers: {
7 "content-type": "application/json",
8 },
9 status: 200,
10 ...init,
11 });
12}
13
14type TestWindow = {
15 location: URL;
16 history: {
17 replaceState: (_data: unknown, _unused: string, url: string) => void;
18 };
19 desktopBridge?: DesktopBridge;
20};
21
22function installTestBrowser(url: string) {
23 const testWindow: TestWindow = {
24 location: new URL(url),
25 history: {
26 replaceState: (_data, _unused, nextUrl) => {
27 testWindow.location = new URL(nextUrl, testWindow.location.href);
28 },
29 },
30 };
31
32 vi.stubGlobal("window", testWindow);
33 vi.stubGlobal("document", { title: "T3 Code" });
34
35 return testWindow;
36}
37
38function sessionResponse(body: unknown, init?: ResponseInit) {
39 return jsonResponse(body, init);
40}
41
42describe("resolveInitialServerAuthGateState", () => {
43 beforeEach(() => {
44 vi.restoreAllMocks();
45 vi.useRealTimers();
46 installTestBrowser("http://localhost/");
47 });
48
49 afterEach(async () => {
50 const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
51 __resetServerAuthBootstrapForTests();
52 vi.unstubAllEnvs();
53 vi.useRealTimers();
54 vi.restoreAllMocks();
55 });
56
57 it("reuses an in-flight silent bootstrap attempt", async () => {
58 const fetchMock = vi
59 .fn<typeof fetch>()
60 .mockResolvedValueOnce(
61 sessionResponse({
62 authenticated: false,
63 auth: {
64 policy: "desktop-managed-local",
65 bootstrapMethods: ["desktop-bootstrap"],
66 sessionMethods: ["browser-session-cookie"],
67 sessionCookieName: "t3_session",
68 },
69 }),
70 )
71 .mockResolvedValueOnce(
72 jsonResponse({
73 authenticated: true,
74 sessionMethod: "browser-session-cookie",
75 expiresAt: "2026-04-05T00:00:00.000Z",
76 }),
77 )
78 .mockResolvedValueOnce(
79 sessionResponse({
80 authenticated: true,
81 auth: {
82 policy: "loopback-browser",
83 bootstrapMethods: ["one-time-token"],
84 sessionMethods: ["browser-session-cookie"],
85 sessionCookieName: "t3_session",
86 },
87 sessionMethod: "browser-session-cookie",
88 expiresAt: "2026-04-05T00:00:00.000Z",
89 }),
90 );
91 vi.stubGlobal("fetch", fetchMock);
92
93 const testWindow = installTestBrowser("http://localhost/");
94 testWindow.desktopBridge = {
95 getLocalEnvironmentBootstrap: () => ({
96 label: "Local environment",
97 httpBaseUrl: "http://localhost:3773",
98 wsBaseUrl: "ws://localhost:3773",
99 bootstrapToken: "desktop-bootstrap-token",
100 }),
101 } as DesktopBridge;
102
103 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
104
105 await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
106
107 expect(fetchMock).toHaveBeenCalledTimes(3);
108 expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost:3773/api/auth/session");
109 expect(fetchMock.mock.calls[1]?.[0]).toBe("http://localhost:3773/api/auth/bootstrap");
110 expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");
111 });
112
113 it("uses https fetch urls when the primary environment uses wss", async () => {
114 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
115 sessionResponse({
116 authenticated: false,
117 auth: {
118 policy: "loopback-browser",
119 bootstrapMethods: ["one-time-token"],
120 sessionMethods: ["browser-session-cookie"],
121 sessionCookieName: "t3_session",
122 },
123 }),
124 );
125 vi.stubGlobal("fetch", fetchMock);
126 vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
127 vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
128
129 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
130
131 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
132 status: "requires-auth",
133 auth: {
134 policy: "loopback-browser",
135 bootstrapMethods: ["one-time-token"],
136 sessionMethods: ["browser-session-cookie"],
137 sessionCookieName: "t3_session",
138 },
139 });
140
141 expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/session", {
142 credentials: "include",
143 });
144 });
145
146 it("uses the current origin as an auth proxy base for local dev environments", async () => {
147 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
148 sessionResponse({
149 authenticated: false,
150 auth: {
151 policy: "loopback-browser",
152 bootstrapMethods: ["one-time-token"],
153 sessionMethods: ["browser-session-cookie"],
154 sessionCookieName: "t3_session",
155 },
156 }),
157 );
158 vi.stubGlobal("fetch", fetchMock);
159 installTestBrowser("http://localhost:5735/");
160
161 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
162
163 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
164 status: "requires-auth",
165 auth: {
166 policy: "loopback-browser",
167 bootstrapMethods: ["one-time-token"],
168 sessionMethods: ["browser-session-cookie"],
169 sessionCookieName: "t3_session",
170 },
171 });
172
173 expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/api/auth/session", {
174 credentials: "include",
175 });
176 });
177
178 it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => {
179 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
180 sessionResponse({
181 authenticated: false,
182 auth: {
183 policy: "desktop-managed-local",
184 bootstrapMethods: ["desktop-bootstrap"],
185 sessionMethods: ["browser-session-cookie"],
186 sessionCookieName: "t3_session",
187 },
188 }),
189 );
190 vi.stubGlobal("fetch", fetchMock);
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 } = await import("./environments/primary");
203
204 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
205 status: "requires-auth",
206 auth: {
207 policy: "desktop-managed-local",
208 bootstrapMethods: ["desktop-bootstrap"],
209 sessionMethods: ["browser-session-cookie"],
210 sessionCookieName: "t3_session",
211 },
212 });
213
214 expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:5733/api/auth/session", {
215 credentials: "include",
216 });
217 });
218
219 it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => {
220 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
221 sessionResponse({
222 authenticated: false,
223 auth: {
224 policy: "loopback-browser",
225 bootstrapMethods: ["one-time-token"],
226 sessionMethods: ["browser-session-cookie"],
227 sessionCookieName: "t3_session",
228 },
229 }),
230 );
231 vi.stubGlobal("fetch", fetchMock);
232
233 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
234
235 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
236 status: "requires-auth",
237 auth: {
238 policy: "loopback-browser",
239 bootstrapMethods: ["one-time-token"],
240 sessionMethods: ["browser-session-cookie"],
241 sessionCookieName: "t3_session",
242 },
243 });
244 });
245
246 it("retries transient auth session bootstrap failures after restart", async () => {
247 vi.useFakeTimers();
248 const fetchMock = vi
249 .fn<typeof fetch>()
250 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
251 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
252 .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 }))
253 .mockResolvedValueOnce(
254 sessionResponse({
255 authenticated: false,
256 auth: {
257 policy: "loopback-browser",
258 bootstrapMethods: ["one-time-token"],
259 sessionMethods: ["browser-session-cookie"],
260 sessionCookieName: "t3_session",
261 },
262 }),
263 );
264 vi.stubGlobal("fetch", fetchMock);
265
266 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
267
268 const gateStatePromise = resolveInitialServerAuthGateState();
269 await vi.advanceTimersByTimeAsync(2_000);
270
271 await expect(gateStatePromise).resolves.toEqual({
272 status: "requires-auth",
273 auth: {
274 policy: "loopback-browser",
275 bootstrapMethods: ["one-time-token"],
276 sessionMethods: ["browser-session-cookie"],
277 sessionCookieName: "t3_session",
278 },
279 });
280 expect(fetchMock).toHaveBeenCalledTimes(4);
281 });
282
283 it("takes a pairing token from the location hash and strips it immediately", async () => {
284 const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
285 const { takePairingTokenFromUrl } = await import("./environments/primary");
286
287 expect(takePairingTokenFromUrl()).toBe("pairing-token");
288 expect(testWindow.location.hash).toBe("");
289 expect(testWindow.location.searchParams.get("token")).toBeNull();
290 });
291
292 it("accepts query-string pairing tokens as a backward-compatible fallback", async () => {
293 const testWindow = installTestBrowser("http://localhost/?token=pairing-token");
294 const { takePairingTokenFromUrl } = await import("./environments/primary");
295
296 expect(takePairingTokenFromUrl()).toBe("pairing-token");
297 expect(testWindow.location.searchParams.get("token")).toBeNull();
298 });
299
300 it("allows manual token submission after the initial auth check requires pairing", async () => {
301 const fetchMock = vi
302 .fn<typeof fetch>()
303 .mockResolvedValueOnce(
304 sessionResponse({
305 authenticated: false,
306 auth: {
307 policy: "loopback-browser",
308 bootstrapMethods: ["one-time-token"],
309 sessionMethods: ["browser-session-cookie"],
310 sessionCookieName: "t3_session",
311 },
312 }),
313 )
314 .mockResolvedValueOnce(
315 jsonResponse({
316 authenticated: true,
317 sessionMethod: "browser-session-cookie",
318 expiresAt: "2026-04-05T00:00:00.000Z",
319 }),
320 )
321 .mockResolvedValueOnce(
322 sessionResponse({
323 authenticated: true,
324 auth: {
325 policy: "loopback-browser",
326 bootstrapMethods: ["one-time-token"],
327 sessionMethods: ["browser-session-cookie"],
328 sessionCookieName: "t3_session",
329 },
330 sessionMethod: "browser-session-cookie",
331 expiresAt: "2026-04-05T00:00:00.000Z",
332 }),
333 );
334 vi.stubGlobal("fetch", fetchMock);
335 installTestBrowser("http://localhost/");
336
337 const { resolveInitialServerAuthGateState, submitServerAuthCredential } =
338 await import("./environments/primary");
339
340 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
341 status: "requires-auth",
342 auth: {
343 policy: "loopback-browser",
344 bootstrapMethods: ["one-time-token"],
345 sessionMethods: ["browser-session-cookie"],
346 sessionCookieName: "t3_session",
347 },
348 });
349 await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined();
350 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
351 status: "authenticated",
352 });
353 expect(fetchMock).toHaveBeenCalledTimes(3);
354 });
355
356 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
357 vi.useFakeTimers();
358 const fetchMock = vi
359 .fn<typeof fetch>()
360 .mockResolvedValueOnce(
361 sessionResponse({
362 authenticated: false,
363 auth: {
364 policy: "desktop-managed-local",
365 bootstrapMethods: ["desktop-bootstrap"],
366 sessionMethods: ["browser-session-cookie"],
367 sessionCookieName: "t3_session",
368 },
369 }),
370 )
371 .mockResolvedValueOnce(
372 jsonResponse({
373 authenticated: true,
374 sessionMethod: "browser-session-cookie",
375 expiresAt: "2026-04-05T00:00:00.000Z",
376 }),
377 )
378 .mockResolvedValueOnce(
379 sessionResponse({
380 authenticated: false,
381 auth: {
382 policy: "desktop-managed-local",
383 bootstrapMethods: ["desktop-bootstrap"],
384 sessionMethods: ["browser-session-cookie"],
385 sessionCookieName: "t3_session",
386 },
387 }),
388 )
389 .mockResolvedValueOnce(
390 sessionResponse({
391 authenticated: true,
392 auth: {
393 policy: "desktop-managed-local",
394 bootstrapMethods: ["desktop-bootstrap"],
395 sessionMethods: ["browser-session-cookie"],
396 sessionCookieName: "t3_session",
397 },
398 sessionMethod: "browser-session-cookie",
399 expiresAt: "2026-04-05T00:00:00.000Z",
400 }),
401 );
402 vi.stubGlobal("fetch", fetchMock);
403
404 const testWindow = installTestBrowser("http://localhost/");
405 testWindow.desktopBridge = {
406 getLocalEnvironmentBootstrap: () => ({
407 label: "Local environment",
408 httpBaseUrl: "http://localhost:3773",
409 wsBaseUrl: "ws://localhost:3773",
410 bootstrapToken: "desktop-bootstrap-token",
411 }),
412 } as DesktopBridge;
413
414 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
415
416 const gateStatePromise = resolveInitialServerAuthGateState();
417 await vi.advanceTimersByTimeAsync(100);
418
419 await expect(gateStatePromise).resolves.toEqual({
420 status: "authenticated",
421 });
422 expect(fetchMock).toHaveBeenCalledTimes(4);
423 expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");
424 expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
425 });
426
427 it("memoizes the authenticated gate state after the first successful read", async () => {
428 const fetchMock = vi
429 .fn<typeof fetch>()
430 .mockResolvedValueOnce(
431 sessionResponse({
432 authenticated: true,
433 auth: {
434 policy: "loopback-browser",
435 bootstrapMethods: ["one-time-token"],
436 sessionMethods: ["browser-session-cookie"],
437 sessionCookieName: "t3_session",
438 },
439 sessionMethod: "browser-session-cookie",
440 expiresAt: "2026-04-05T00:00:00.000Z",
441 }),
442 )
443 .mockResolvedValueOnce(
444 sessionResponse({
445 authenticated: false,
446 auth: {
447 policy: "loopback-browser",
448 bootstrapMethods: ["one-time-token"],
449 sessionMethods: ["browser-session-cookie"],
450 sessionCookieName: "t3_session",
451 },
452 }),
453 );
454 vi.stubGlobal("fetch", fetchMock);
455
456 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
457
458 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
459 status: "authenticated",
460 });
461 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
462 status: "authenticated",
463 });
464 expect(fetchMock).toHaveBeenCalledTimes(1);
465 });
466
467 it("creates a pairing credential from the authenticated auth endpoint", async () => {
468 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
469 jsonResponse({
470 id: "pairing-link-1",
471 credential: "pairing-token",
472 label: "Julius iPhone",
473 expiresAt: "2026-04-05T00:00:00.000Z",
474 }),
475 );
476 vi.stubGlobal("fetch", fetchMock);
477
478 const { createServerPairingCredential } = await import("./environments/primary");
479
480 await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({
481 id: "pairing-link-1",
482 credential: "pairing-token",
483 label: "Julius iPhone",
484 expiresAt: "2026-04-05T00:00:00.000Z",
485 });
486 expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", {
487 body: JSON.stringify({ label: "Julius iPhone" }),
488 credentials: "include",
489 headers: {
490 "content-type": "application/json",
491 },
492 method: "POST",
493 });
494 });
495});