The best way to control Claude Code, Codex and more from any computer or phone

main
ts 449 lines 15.9 KB
Raw
1 import {
2 EnvironmentAuthInvalidError,
3 type AuthBrowserSessionResult,
4 type AuthCreatePairingCredentialInput,
5 type AuthSessionState,
6 type DesktopBridge,
7 } from "@t3tools/contracts";
8 import { createBrowserHistory } from "@tanstack/react-router";
9 import * as DateTime from "effect/DateTime";
10 import * as Effect from "effect/Effect";
11 import { HttpClientError, HttpClientRequest } from "effect/http";
12 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
14 import { installEnvironmentHttpTest } from "../test/environmentHttpTest";
15 import { __setPrimaryHttpRunnerForTests } from "./lib/runtime";
16
17 type TestWindow = {
18 location: URL;
19 history: {
20 state: unknown;
21 replaceState: (_data: unknown, _unused: string, url?: string) => void;
22 };
23 desktopBridge?: DesktopBridge;
24 };
25
26 const LOOPBACK_AUTH = {
27 policy: "loopback-browser",
28 bootstrapMethods: ["one-time-token"],
29 sessionMethods: ["browser-session-cookie"],
30 sessionCookieName: "t3_session",
31 } as const;
32
33 const DESKTOP_AUTH = {
34 policy: "desktop-managed-local",
35 bootstrapMethods: ["desktop-bootstrap"],
36 sessionMethods: ["browser-session-cookie"],
37 sessionCookieName: "t3_session",
38 } as const;
39
40 const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
41 const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
42 authenticated: false,
43 auth,
44 });
45
46 const authenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
47 authenticated: true,
48 auth,
49 sessionMethod: "browser-session-cookie",
50 expiresAt: SESSION_EXPIRES_AT,
51 });
52
53 const browserSession = (scopes: AuthBrowserSessionResult["scopes"]): AuthBrowserSessionResult => ({
54 authenticated: true,
55 scopes,
56 sessionMethod: "browser-session-cookie",
57 expiresAt: SESSION_EXPIRES_AT,
58 });
59
60 function installTestBrowser(url: string) {
61 const testWindow: TestWindow = {
62 location: new URL(url),
63 history: {
64 state: null,
65 replaceState: (data, _unused, nextUrl) => {
66 testWindow.history.state = data;
67 if (nextUrl !== undefined) {
68 testWindow.location = new URL(nextUrl, testWindow.location.href);
69 }
70 },
71 },
72 };
73
74 vi.stubGlobal("window", testWindow);
75 vi.stubGlobal("document", { title: "T3 Code" });
76
77 return testWindow;
78 }
79
80 function sequence<A>(...values: ReadonlyArray<A>) {
81 let index = 0;
82 return () => values[Math.min(index++, values.length - 1)]!;
83 }
84
85 function createSignal() {
86 let resolve = () => {};
87 const promise = new Promise<void>((resolvePromise) => {
88 resolve = resolvePromise;
89 });
90 return { promise, resolve };
91 }
92
93 let disposeHttpTest: (() => Promise<void>) | undefined;
94
95 async function installAuthApi(input: {
96 readonly session?: () => AuthSessionState;
97 readonly browserSession?: (
98 credential: string,
99 ) => Effect.Effect<AuthBrowserSessionResult, EnvironmentAuthInvalidError>;
100 readonly pairingCredential?: (payload: AuthCreatePairingCredentialInput) => Effect.Effect<{
101 readonly id: string;
102 readonly credential: string;
103 readonly label?: string;
104 readonly expiresAt: DateTime.Utc;
105 }>;
106 }) {
107 const testApi = await installEnvironmentHttpTest({
108 ...(input.session ? { session: () => Effect.succeed(input.session!()) } : {}),
109 ...(input.browserSession
110 ? { browserSession: (payload) => input.browserSession!(payload.credential) }
111 : {}),
112 ...(input.pairingCredential
113 ? { pairingCredential: (payload) => input.pairingCredential!(payload) }
114 : {}),
115 });
116 disposeHttpTest = testApi.dispose;
117 return testApi;
118 }
119
120 describe("resolveInitialServerAuthGateState", () => {
121 beforeEach(() => {
122 vi.restoreAllMocks();
123 vi.useRealTimers();
124 installTestBrowser("http://localhost/");
125 });
126
127 afterEach(async () => {
128 await disposeHttpTest?.();
129 disposeHttpTest = undefined;
130 const { __resetServerAuthBootstrapForTests } = await import("./environments/primary");
131 __resetServerAuthBootstrapForTests();
132 __setPrimaryHttpRunnerForTests();
133 vi.unstubAllEnvs();
134 vi.useRealTimers();
135 vi.restoreAllMocks();
136 });
137
138 it("reuses an in-flight silent bootstrap attempt", async () => {
139 const nextSession = sequence(
140 unauthenticatedSession(DESKTOP_AUTH),
141 authenticatedSession(DESKTOP_AUTH),
142 );
143 const testApi = await installAuthApi({
144 session: nextSession,
145 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
146 });
147
148 const testWindow = installTestBrowser("http://localhost/");
149 testWindow.desktopBridge = {
150 getLocalEnvironmentBootstraps: () => [
151 {
152 id: "primary",
153 label: "Windows",
154 httpBaseUrl: "http://localhost:3773",
155 wsBaseUrl: "ws://localhost:3773",
156 bootstrapToken: "desktop-bootstrap-token",
157 },
158 ],
159 } as unknown as DesktopBridge;
160
161 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
162
163 await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]);
164
165 expect(testApi.calls.session).toBe(2);
166 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
167 });
168
169 it("retries the desktop bootstrap while the backend is still unreachable", async () => {
170 const nextSession = sequence(
171 unauthenticatedSession(DESKTOP_AUTH),
172 authenticatedSession(DESKTOP_AUTH),
173 );
174 const testApi = await installAuthApi({
175 session: nextSession,
176 browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
177 });
178 // What FetchHttpClient yields when nothing listens on the backend port.
179 const connectionRefused = new HttpClientError.HttpClientError({
180 reason: new HttpClientError.TransportError({
181 request: HttpClientRequest.get("http://localhost:3773/api/auth/session"),
182 cause: new TypeError("Failed to fetch"),
183 }),
184 });
185 let unreachableAttempts = 1;
186 __setPrimaryHttpRunnerForTests((effect) => {
187 if (unreachableAttempts > 0) {
188 unreachableAttempts -= 1;
189 return Promise.reject(connectionRefused);
190 }
191 return testApi.run(effect);
192 });
193
194 const testWindow = installTestBrowser("http://localhost/");
195 testWindow.desktopBridge = {
196 getLocalEnvironmentBootstraps: () => [
197 {
198 id: "primary",
199 label: "Local",
200 httpBaseUrl: "http://localhost:3773",
201 wsBaseUrl: "ws://localhost:3773",
202 bootstrapToken: "desktop-bootstrap-token",
203 },
204 ],
205 } as unknown as DesktopBridge;
206
207 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
208
209 vi.useFakeTimers({ toFake: ["setTimeout", "Date"] });
210 await Promise.all([
211 expect(resolveInitialServerAuthGateState()).resolves.toEqual({ status: "authenticated" }),
212 vi.advanceTimersByTimeAsync(1_000),
213 ]);
214 expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
215 });
216
217 it("takes a pairing token from the location hash and strips it immediately", async () => {
218 const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
219 const { takePairingTokenFromUrl } = await import("./environments/primary");
220
221 expect(takePairingTokenFromUrl()).toBe("pairing-token");
222 expect(testWindow.location.hash).toBe("");
223 expect(testWindow.location.searchParams.get("token")).toBeNull();
224 });
225
226 it.each([
227 { suffix: "#token=replacement-token", cached: false },
228 { suffix: "#token=replacement-token", cached: true },
229 { suffix: "?token=replacement-token", cached: true },
230 { suffix: "/#token=replacement-token", cached: true },
231 ])(
232 "re-pairs an authenticated browser with $suffix when cached=$cached",
233 async ({ suffix, cached }) => {
234 let scopes: AuthBrowserSessionResult["scopes"] = ["orchestration:read"];
235 const testApi = await installAuthApi({
236 session: () => ({ ...authenticatedSession(LOOPBACK_AUTH), scopes }),
237 browserSession: () =>
238 Effect.sync(() => {
239 scopes = ["orchestration:read", "orchestration:operate"];
240 return browserSession(scopes);
241 }),
242 });
243 const testWindow = installTestBrowser("http://localhost/");
244 const {
245 resolveInitialServerAuthGateState,
246 submitServerAuthCredential,
247 takePairingTokenFromUrl,
248 } = await import("./environments/primary");
249 const { fetchSessionState } = await import("./environments/primary/auth");
250
251 if (cached) {
252 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
253 status: "authenticated",
254 });
255 }
256
257 testWindow.location = new URL(`http://localhost/pair${suffix}`);
258 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
259 status: "requires-auth",
260 auth: LOOPBACK_AUTH,
261 });
262 expect(testApi.calls.browserSession).toEqual([]);
263
264 const token = takePairingTokenFromUrl();
265 expect(token).toBe("replacement-token");
266 await submitServerAuthCredential(token!);
267
268 expect(testApi.calls.browserSession).toEqual([{ credential: "replacement-token" }]);
269 await expect(fetchSessionState()).resolves.toMatchObject({
270 authenticated: true,
271 scopes: ["orchestration:read", "orchestration:operate"],
272 });
273 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
274 status: "authenticated",
275 });
276 },
277 );
278
279 it.each([false, true])(
280 "keeps rejected replacement pairing open when cached=%s",
281 async (cached) => {
282 const existingSession = {
283 ...authenticatedSession(LOOPBACK_AUTH),
284 scopes: ["orchestration:read"] as const,
285 };
286 const exchangeStarted = createSignal();
287 const finishExchange = createSignal();
288 const testApi = await installAuthApi({
289 session: () => existingSession,
290 browserSession: () =>
291 Effect.gen(function* () {
292 exchangeStarted.resolve();
293 yield* Effect.promise(() => finishExchange.promise);
294 return yield* new EnvironmentAuthInvalidError({
295 code: "auth_invalid",
296 reason: "invalid_credential",
297 traceId: "trace-invalid-replacement",
298 });
299 }),
300 });
301 const testWindow = installTestBrowser("http://localhost/");
302 const {
303 resolveInitialServerAuthGateState,
304 submitServerAuthCredential,
305 takePairingTokenFromUrl,
306 } = await import("./environments/primary");
307 const { fetchSessionState } = await import("./environments/primary/auth");
308 if (cached) {
309 await resolveInitialServerAuthGateState();
310 }
311 testWindow.location = new URL("http://localhost/pair#token=invalid-replacement");
312 const history = createBrowserHistory({
313 window: {
314 get location() {
315 return testWindow.location;
316 },
317 history: testWindow.history,
318 addEventListener() {},
319 removeEventListener() {},
320 },
321 });
322 const gateLoads: Array<ReturnType<typeof resolveInitialServerAuthGateState>> = [];
323 const unsubscribe = history.subscribe(() => {
324 gateLoads.push(resolveInitialServerAuthGateState());
325 });
326 try {
327 const requiresAuth = { status: "requires-auth", auth: LOOPBACK_AUTH };
328 await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
329
330 // Token removal synchronously reloads the TanStack auth gate via replaceState.
331 const pairingHistoryState = history.location.state;
332 const token = takePairingTokenFromUrl();
333 expect(history.location.state).toEqual(pairingHistoryState);
334 expect(gateLoads).toHaveLength(1);
335 await expect(gateLoads[0]).resolves.toEqual(requiresAuth);
336 const rejected = expect(submitServerAuthCredential(token!)).rejects.toMatchObject({
337 _tag: "PrimaryEnvironmentPairingCredentialRejectedError",
338 message: "Invalid pairing token. Check the token and try again.",
339 });
340 await exchangeStarted.promise;
341 await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
342 finishExchange.resolve();
343 await rejected;
344 await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth);
345 expect(testApi.calls.browserSession).toEqual([{ credential: "invalid-replacement" }]);
346 await expect(fetchSessionState()).resolves.toEqual(existingSession);
347
348 testWindow.history.replaceState({}, "", "/");
349 await expect(gateLoads[1]).resolves.toEqual({ status: "authenticated" });
350 testWindow.history.replaceState({}, "", "/pair");
351 await expect(gateLoads[2]).resolves.toEqual({ status: "authenticated" });
352 } finally {
353 finishExchange.resolve();
354 unsubscribe();
355 history.destroy();
356 }
357 },
358 );
359
360 it("makes later callers wait for a URL token that arrives during bootstrap", async () => {
361 let releaseExchange!: () => void;
362 const exchangeRelease = new Promise<void>((resolve) => {
363 releaseExchange = resolve;
364 });
365 let markExchangeStarted!: () => void;
366 const exchangeStarted = new Promise<void>((resolve) => {
367 markExchangeStarted = resolve;
368 });
369 const nextSession = sequence(
370 authenticatedSession(LOOPBACK_AUTH),
371 authenticatedSession(LOOPBACK_AUTH),
372 );
373 const testApi = await installAuthApi({
374 session: nextSession,
375 browserSession: () => {
376 markExchangeStarted();
377 return Effect.promise(() => exchangeRelease).pipe(
378 Effect.andThen(
379 Effect.fail(
380 new EnvironmentAuthInvalidError({
381 code: "auth_invalid",
382 reason: "invalid_credential",
383 traceId: "trace-rejected-queued-credential",
384 }),
385 ),
386 ),
387 );
388 },
389 });
390 const testWindow = installTestBrowser("http://localhost/");
391 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
392
393 const initialBootstrap = resolveInitialServerAuthGateState();
394 testWindow.location = new URL("http://localhost/#token=reusable-token");
395 const explicitPairing = resolveInitialServerAuthGateState();
396 const laterCaller = resolveInitialServerAuthGateState();
397 let laterCallerSettled = false;
398 void laterCaller.then(() => {
399 laterCallerSettled = true;
400 });
401
402 try {
403 await expect(initialBootstrap).resolves.toEqual({ status: "authenticated" });
404 await exchangeStarted;
405 expect(laterCallerSettled).toBe(false);
406 } finally {
407 releaseExchange();
408 }
409
410 const rejectedState = {
411 status: "requires-auth",
412 auth: LOOPBACK_AUTH,
413 errorMessage: "Invalid pairing token. Check the token and try again.",
414 } as const;
415 await expect(explicitPairing).resolves.toEqual(rejectedState);
416 await expect(laterCaller).resolves.toEqual(rejectedState);
417 expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]);
418 expect(testApi.calls.session).toBe(2);
419 });
420
421 it("reports a rejected URL token without caching false success", async () => {
422 const cause = new EnvironmentAuthInvalidError({
423 code: "auth_invalid",
424 reason: "invalid_credential",
425 traceId: "trace-invalid-url-credential",
426 });
427 const nextSession = sequence(
428 authenticatedSession(LOOPBACK_AUTH),
429 unauthenticatedSession(LOOPBACK_AUTH),
430 );
431 const testApi = await installAuthApi({
432 session: nextSession,
433 browserSession: () => Effect.fail(cause),
434 });
435 installTestBrowser("http://localhost/#token=rejected-token");
436 const { resolveInitialServerAuthGateState } = await import("./environments/primary");
437
438 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
439 status: "requires-auth",
440 auth: LOOPBACK_AUTH,
441 errorMessage: "Invalid pairing token. Check the token and try again.",
442 });
443 await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
444 status: "requires-auth",
445 auth: LOOPBACK_AUTH,
446 });
447 expect(testApi.calls.browserSession).toEqual([{ credential: "rejected-token" }]);
448 });
449 });