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

main
ts 152 lines 5.88 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off globalFetch:off - Tests exercise the real native loopback listener without an OpenAI account.
2 import * as NodeHttp from "node:http";
3 import { describe, expect, it } from "vite-plus/test";
4 import { codexAuthDeliveryUrl, readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
5 import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
6 import { receiveCodexAuthCallback, cancelCodexAuthCallback } from "./CodexAuthCallback.ts";
7
8 // Holds every probe socket until all ports are read, so one call never returns the same port twice.
9 async function freePorts(count: number) {
10 const servers = Array.from({ length: count }, () => NodeHttp.createServer());
11 await Promise.all(
12 servers.map((server) => new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))),
13 );
14 const ports = servers.map((server) => {
15 const address = server.address();
16 if (!address || typeof address === "string") throw new Error("address");
17 return address.port;
18 });
19 await Promise.all(
20 servers.map((server) => new Promise<void>((resolve) => server.close(() => resolve()))),
21 );
22 return ports;
23 }
24 async function freePort() {
25 const [port] = await freePorts(1);
26 return port!;
27 }
28 function request(port: number, state = "a".repeat(43)) {
29 const url = new URL("https://auth.openai.com/api/accounts/authorize");
30 url.search = new URLSearchParams({
31 client_id: "dynamic_agent_client",
32 response_type: "code",
33 redirect_uri: `http://127.0.0.1:${port}/auth/callback`,
34 state,
35 code_challenge_method: "S256",
36 code_challenge: "b".repeat(43),
37 }).toString();
38 return url.toString();
39 }
40 function callback(authorizationUrl: string) {
41 const request = new URL(authorizationUrl);
42 const url = new URL(request.searchParams.get("redirect_uri")!);
43 url.search = new URLSearchParams({
44 state: request.searchParams.get("state")!,
45 code: "test-code",
46 client_id: "oaiapp_test",
47 }).toString();
48 return url.toString();
49 }
50
51 describe("desktop Codex callback helper", () => {
52 it("binds before opening sign-in, ignores a foreign response, and returns only the code callback", async ({
53 onTestFinished,
54 }) => {
55 const authorizationUrl = request(await freePort());
56 const expected = callback(authorizationUrl);
57 const opening = Promise.withResolvers<boolean>();
58 onTestFinished(() => opening.resolve(true));
59 const checkResponse = async () => {
60 const invalid = new URL(expected);
61 invalid.searchParams.set("state", "foreign");
62 expect((await fetch(invalid)).status).toBe(400);
63 const response = await fetch(expected);
64 expect(response.headers.get("cache-control")).toBe("no-store");
65 expect(await response.text()).not.toContain("test-code");
66 };
67 let responseChecked!: Promise<void>;
68 const received = await receiveCodexAuthCallback(authorizationUrl, () => {
69 responseChecked = checkResponse();
70 return responseChecked.then(() => opening.promise);
71 });
72 await responseChecked;
73 expect(received).toBe(expected);
74 });
75 it("returns hosted web to the exact instance and environment without putting the code in its query", async () => {
76 const authorizationUrl = request(await freePort());
77 const expected = callback(authorizationUrl);
78 const input = {
79 authorizationUrl,
80 returnUrl: "https://app.t3.codes/settings/providers?environmentId=remote-one&instanceId=work",
81 environmentId: EnvironmentId.make("remote-one"),
82 instanceId: ProviderInstanceId.make("work"),
83 flowId: "flow-one",
84 };
85 const openBrowser = async () => {
86 const response = await fetch(expected, { redirect: "manual" });
87 expect(response.status).toBe(303);
88 const delivery = response.headers.get("location")!;
89 expect(new URL(delivery).searchParams.has("code")).toBe(false);
90 expect(readCodexAuthDelivery(delivery)?.callbackUrl).toBe(expected);
91 expect(readCodexAuthDelivery(delivery)?.returnUrl).toBe(input.returnUrl);
92 return true;
93 };
94 let opening!: Promise<boolean>;
95 await receiveCodexAuthCallback(
96 authorizationUrl,
97 () => (opening = openBrowser()),
98 (url) => codexAuthDeliveryUrl(input, url),
99 );
100 await opening;
101 });
102 it("cancels and releases its listener so exact-port reauthorization can run again", async ({
103 onTestFinished,
104 signal,
105 }) => {
106 for (const external of [false, true]) {
107 const authorizationUrl = request(await freePort());
108 const abort = new AbortController();
109 const opening = Promise.withResolvers<boolean>();
110 onTestFinished(() => opening.resolve(true));
111 await expect(
112 receiveCodexAuthCallback(
113 authorizationUrl,
114 async () => {
115 if (external) abort.abort();
116 else cancelCodexAuthCallback(authorizationUrl);
117 return opening.promise;
118 },
119 undefined,
120 abort.signal,
121 ),
122 ).rejects.toThrow("cancelled");
123 if (signal.aborted) return;
124 expect(
125 await receiveCodexAuthCallback(authorizationUrl, async () => {
126 await fetch(callback(authorizationUrl));
127 return true;
128 }),
129 ).toBe(callback(authorizationUrl));
130 }
131 });
132 it("allows two accounts to complete independently", async () => {
133 const [portA, portB] = await freePorts(2);
134 const a = request(portA!, "a".repeat(43));
135 const b = request(portB!, "c".repeat(43));
136 const openedA = Promise.withResolvers<void>();
137 const openedB = Promise.withResolvers<void>();
138 const receiveA = receiveCodexAuthCallback(a, async () => {
139 openedA.resolve();
140 await openedB.promise;
141 await fetch(callback(a));
142 return true;
143 });
144 const receiveB = receiveCodexAuthCallback(b, async () => {
145 openedB.resolve();
146 await openedA.promise;
147 await fetch(callback(b));
148 return true;
149 });
150 expect(await Promise.all([receiveA, receiveB])).toEqual([callback(a), callback(b)]);
151 });
152 });