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("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
357 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
358 jsonResponse(
359 {
360 error: "Invalid bootstrap credential.",
361 },
362 {
363 status: 401,
364 },
365 ),
366 );
367 vi.stubGlobal("fetch", fetchMock);
368
369 const { submitServerAuthCredential } = await import("./environments/primary");
370
371 await expect(submitServerAuthCredential("bad-token")).rejects.toThrow(
372 "Invalid pairing token. Check the token and try again.",
373 );
374 expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/bootstrap", {
375 body: JSON.stringify({ credential: "bad-token" }),
376 credentials: "include",
377 headers: {
378 "content-type": "application/json",
379 },
380 method: "POST",
381 });
382 });
383
384 it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
385 vi.useFakeTimers();
386 const fetchMock = vi
387 .fn<typeof fetch>()
388 .mockResolvedValueOnce(
389 sessionResponse({
390 authenticated: false,
391 auth: {
392 policy: "desktop-managed-local",
393 bootstrapMethods: ["desktop-bootstrap"],
394 sessionMethods: ["browser-session-cookie"],
395 sessionCookieName: "t3_session",
396 },
397 }),
398 )
399 .mockResolvedValueOnce(
400 jsonResponse({
401 authenticated: true,
402 sessionMethod: "browser-session-cookie",
403 expiresAt: "2026-04-05T00:00:00.000Z",
404 }),
405 )
406 .mockResolvedValueOnce(
407 sessionResponse({
408 authenticated: false,
409 auth: {
410 policy: "desktop-managed-local",
411 bootstrapMethods: ["desktop-bootstrap"],
412 sessionMethods: ["browser-session-cookie"],
413 sessionCookieName: "t3_session",
414 },
415 }),
416 )
417 .mockResolvedValueOnce(
418 sessionResponse({
419 authenticated: true,
420 auth: {
421 policy: "desktop-managed-local",
422 bootstrapMethods: ["desktop-bootstrap"],
423 sessionMethods: ["browser-session-cookie"],
424 sessionCookieName: "t3_session",
425 },
426 sessionMethod: "browser-session-cookie",
427 expiresAt: "2026-04-05T00:00:00.000Z",
428 }),
429 );
430 vi.stubGlobal("fetch", fetchMock);
431
432 const testWindow = installTestBrowser("http://localhost/");
433 testWindow.desktopBridge = {
434 getLocalEnvironmentBootstrap: () => ({
435 label: "Local environment",
436 httpBaseUrl: "http://localhost:3773",
437 wsBaseUrl: "ws://localhost:3773",
438 bootstrapToken: "desktop-bootstrap-token",
439 }),
440 } as DesktopBridge;
441
442 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
443
444 const gateStatePromise = resolveInitialServerAuthGateState();
445 await vi.advanceTimersByTimeAsync(100);
446
447 await expect(gateStatePromise).resolves.toEqual({
448 status: "authenticated",
449 });
450 expect(fetchMock).toHaveBeenCalledTimes(4);
451 expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session");
452 expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session");
453 });
454
455 it("memoizes the authenticated gate state after the first successful read", async () => {
456 const fetchMock = vi
457 .fn<typeof fetch>()
458 .mockResolvedValueOnce(
459 sessionResponse({
460 authenticated: true,
461 auth: {
462 policy: "loopback-browser",
463 bootstrapMethods: ["one-time-token"],
464 sessionMethods: ["browser-session-cookie"],
465 sessionCookieName: "t3_session",
466 },
467 sessionMethod: "browser-session-cookie",
468 expiresAt: "2026-04-05T00:00:00.000Z",
469 }),
470 )
471 .mockResolvedValueOnce(
472 sessionResponse({
473 authenticated: false,
474 auth: {
475 policy: "loopback-browser",
476 bootstrapMethods: ["one-time-token"],
477 sessionMethods: ["browser-session-cookie"],
478 sessionCookieName: "t3_session",
479 },
480 }),
481 );
482 vi.stubGlobal("fetch", fetchMock);
483
484 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
485
486 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
487 status: "authenticated",
488 });
489 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
490 status: "authenticated",
491 });
492 expect(fetchMock).toHaveBeenCalledTimes(1);
493 });
494
495 it("creates a pairing credential from the authenticated auth endpoint", async () => {
496 const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(
497 jsonResponse({
498 id: "pairing-link-1",
499 credential: "pairing-token",
500 label: "Julius iPhone",
501 expiresAt: "2026-04-05T00:00:00.000Z",
502 }),
503 );
504 vi.stubGlobal("fetch", fetchMock);
505
506 const { createServerPairingCredential } = await import("./environments/primary");
507
508 await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({
509 id: "pairing-link-1",
510 credential: "pairing-token",
511 label: "Julius iPhone",
512 expiresAt: "2026-04-05T00:00:00.000Z",
513 });
514 expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", {
515 body: JSON.stringify({ label: "Julius iPhone" }),
516 credentials: "include",
517 headers: {
518 "content-type": "application/json",
519 },
520 method: "POST",
521 });
522 });
523});