Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as NetService from "@t3tools/shared/Net";
9import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
10import { LocalServerPairCommandOutput } from "@t3tools/contracts";
11import { assert, describe, expect, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Schema from "effect/Schema";
15import * as TestConsole from "effect/testing/TestConsole";
16import { Command } from "effect/unstable/cli";
17
18import { cli } from "../binCli.ts";
19import {
20 SERVICE_LAUNCHER_CONTEXT_ENV,
21 SERVICE_LAUNCHER_PROTOCOL,
22} from "../cloud/serviceProtocol.ts";
23import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
24import {
25 makePersistedServerRuntimeState,
26 persistServerRuntimeState,
27 type PersistedServerRuntimeState,
28} from "../serverRuntimeState.ts";
29import {
30 DevServerNotProxiableError,
31 resolveDirectPairingBaseUrl,
32 resolveTailscaleLocalTarget,
33} from "./pair.ts";
34
35import packageJson from "../../package.json" with { type: "json" };
36
37const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
38
39const baseState = {
40 version: 1,
41 pid: 123,
42 port: 3_773,
43 origin: "http://127.0.0.1:3773",
44 startedAt: "2026-06-20T00:00:00.000Z",
45} as const satisfies PersistedServerRuntimeState;
46
47describe("pair base URL selection", () => {
48 it("pairs through the dev web origin when the server fronts a dev server", () => {
49 expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
50 "http://localhost:5733/",
51 );
52 });
53
54 it("pairs through the bound host when there is no dev server", () => {
55 expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
56 "http://100.64.0.7:3773",
57 );
58 expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
59 });
60});
61
62describe("pair tailscale local target", () => {
63 it("proxies the dev web port for dev servers", () => {
64 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
65 { localPort: 5_733 },
66 );
67 // A dev server on a non-loopback interface must be proxied at that
68 // interface; tailscale serve defaults to 127.0.0.1 otherwise.
69 expect(
70 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
71 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
72 // URL.hostname keeps IPv6 brackets, so the serve target stays valid.
73 expect(
74 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
75 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
76 });
77
78 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
79 expect(
80 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
81 ).toBeInstanceOf(DevServerNotProxiableError);
82 });
83
84 it("proxies the backend port directly otherwise", () => {
85 expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
86 expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
87 localPort: 3_773,
88 });
89 expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
90 localPort: 3_773,
91 localHost: "192.168.1.42",
92 });
93 });
94});
95
96const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
97
98const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
99 Effect.provide(effect, Layer.mergeAll(CliRuntimeLayer, TestConsole.layer));
100
101// Console output accumulates across CLI runs within a test, and each
102// Console.log call is one entry — so the latest command's output is the last
103// entry, even when it spans many lines.
104const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
105 provideCliTestLayers(
106 Effect.gen(function* () {
107 yield* effect;
108 return (
109 (yield* TestConsole.logLines).findLast(
110 (line): line is string => typeof line === "string",
111 ) ?? ""
112 );
113 }),
114 );
115
116const testDescriptor = {
117 environmentId: "pair-test-environment",
118 label: "pair-test",
119 platform: { os: "linux", arch: "x64" },
120 serverVersion: "0.0.1",
121 capabilities: { repositoryIdentity: true },
122};
123
124const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
125 Effect.acquireUseRelease(
126 Effect.callback<NodeHttp.Server>((resume) => {
127 const server = NodeHttp.createServer((request, response) => {
128 if (request.url === "/.well-known/t3/environment") {
129 response.writeHead(200, { "content-type": "application/json" });
130 response.end(JSON.stringify(testDescriptor));
131 return;
132 }
133 response.writeHead(404);
134 response.end();
135 });
136 server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
137 }),
138 (server) => {
139 const address = server.address();
140 if (address === null || typeof address === "string") {
141 return Effect.die(new Error("Expected a TCP address"));
142 }
143 return run(`http://127.0.0.1:${String(address.port)}`);
144 },
145 (server) => Effect.sync(() => server.close()),
146 );
147
148describe("t3 pair", () => {
149 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
150 withDescriptorServer((origin) =>
151 Effect.gen(function* () {
152 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
153 const port = Number(new URL(origin).port);
154 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
155 yield* persistServerRuntimeState({
156 path: statePath,
157 state: yield* makePersistedServerRuntimeState({
158 config: { host: "127.0.0.1", devUrl: undefined },
159 port,
160 }),
161 });
162
163 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
164
165 assert.include(output, `Pairing with pair-test (${origin})`);
166 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
167 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
168 // Loopback origins are not reachable from a phone; the output must say so.
169 assert.include(output, "only reachable from this machine");
170
171 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
172 assert.isString(token);
173
174 // The token must be in the same store the running server reads.
175 const listed = yield* captureStdout(
176 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
177 );
178 // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
179 const credentials = JSON.parse(listed) as ReadonlyArray<{ readonly label?: string }>;
180 assert.equal(credentials.length, 1);
181 assert.equal(credentials[0]?.label, "t3 pair");
182 }),
183 ).pipe(
184 Effect.provide(NodeServices.layer),
185 Effect.provideService(HostProcessEnvironment, {
186 ...process.env,
187 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
188 protocol: SERVICE_LAUNCHER_PROTOCOL,
189 childVersion: packageJson.version,
190 }),
191 }),
192 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
193 connected: false,
194 send: () => false,
195 on: () => undefined,
196 off: () => undefined,
197 }),
198 ),
199 );
200
201 it.effect("prints one machine-readable object with --json", () =>
202 withDescriptorServer((origin) =>
203 Effect.gen(function* () {
204 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-json-test-"));
205 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
206 yield* persistServerRuntimeState({
207 path: statePath,
208 state: yield* makePersistedServerRuntimeState({
209 config: { host: "127.0.0.1", devUrl: undefined },
210 port: Number(new URL(origin).port),
211 }),
212 });
213
214 const output = yield* captureStdout(
215 runCli(["pair", "--base-dir", baseDir, "--label", "Desktop", "--json"]),
216 );
217 const decoded = yield* Schema.decodeUnknownEffect(
218 Schema.fromJsonString(LocalServerPairCommandOutput),
219 )(output);
220
221 assert.deepEqual(Object.keys(decoded), [
222 "pairingUrl",
223 "token",
224 "expiresAt",
225 "origin",
226 "environmentId",
227 "label",
228 ]);
229 assert.equal(decoded.origin, origin);
230 assert.equal(decoded.environmentId, testDescriptor.environmentId);
231 assert.equal(decoded.label, testDescriptor.label);
232 assert.match(String(decoded.pairingUrl), new RegExp(`^${origin}/pair#token=`));
233 assert.equal(
234 new URL(String(decoded.pairingUrl)).hash.slice("#token=".length),
235 decoded.token,
236 );
237 assert.isFalse(/Pairing with|Note:|[█▀▄]/.test(output));
238 }),
239 ).pipe(Effect.provide(NodeServices.layer)),
240 );
241
242 it.effect("pairs through the recorded dev web URL for dev servers", () =>
243 withDescriptorServer((origin) =>
244 Effect.gen(function* () {
245 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
246 const port = Number(new URL(origin).port);
247 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
248 yield* persistServerRuntimeState({
249 path: statePath,
250 state: yield* makePersistedServerRuntimeState({
251 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
252 port,
253 }),
254 });
255
256 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
257
258 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
259 }),
260 ).pipe(Effect.provide(NodeServices.layer)),
261 );
262
263 it.effect("directs to t3 serve or t3 connect when no server is running", () =>
264 Effect.gen(function* () {
265 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
266
267 const error = yield* provideCliTestLayers(
268 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
269 );
270
271 const rendered = String(
272 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
273 );
274 assert.include(rendered, "No running T3 Code server found.");
275 assert.include(rendered, "npx t3 serve");
276 assert.include(rendered, "npx t3 connect");
277 }).pipe(Effect.provide(NodeServices.layer)),
278 );
279
280 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
281 withDescriptorServer((origin) =>
282 Effect.gen(function* () {
283 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
284 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
285 // The origin answers (another server reused the port), but the pid
286 // that wrote this state file is dead — pairing must not mint a token
287 // into the dead server's database.
288 const state = yield* makePersistedServerRuntimeState({
289 config: { host: "127.0.0.1", devUrl: undefined },
290 port: Number(new URL(origin).port),
291 });
292 yield* persistServerRuntimeState({
293 path: statePath,
294 // pid 2**22 + 1 exceeds any default Linux/macOS pid range.
295 state: { ...state, pid: 4_194_305 },
296 });
297
298 const error = yield* provideCliTestLayers(
299 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
300 );
301
302 const rendered = String(
303 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
304 );
305 assert.include(rendered, "No running T3 Code server found.");
306 }),
307 ).pipe(Effect.provide(NodeServices.layer)),
308 );
309
310 it.effect("ignores stale runtime state pointing at a dead server", () =>
311 Effect.gen(function* () {
312 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
313 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
314 // A port from the dynamic range with nothing listening: the probe fails
315 // fast with ECONNREFUSED and discovery moves on.
316 yield* persistServerRuntimeState({
317 path: statePath,
318 state: yield* makePersistedServerRuntimeState({
319 config: { host: "127.0.0.1", devUrl: undefined },
320 port: 1,
321 }),
322 });
323
324 const error = yield* provideCliTestLayers(
325 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
326 );
327
328 const rendered = String(
329 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
330 );
331 assert.include(rendered, "No running T3 Code server found.");
332 }).pipe(Effect.provide(NodeServices.layer)),
333 );
334});