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 { AuthStandardClientScopes } from "@t3tools/contracts";
9import * as NetService from "@t3tools/shared/Net";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { assert, describe, expect, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as TestConsole from "effect/testing/TestConsole";
17import { Command, CliError } from "effect/cli";
18import { ChildProcessSpawner } from "effect/process";
19
20import { cli } from "../binCli.ts";
21import {
22 SERVICE_LAUNCHER_CONTEXT_ENV,
23 SERVICE_LAUNCHER_PROTOCOL,
24} from "../cloud/serviceProtocol.ts";
25import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
26import {
27 makePersistedServerRuntimeState,
28 persistServerRuntimeState,
29 type PersistedServerRuntimeState,
30} from "../serverRuntimeState.ts";
31import {
32 DevServerNotProxiableError,
33 resolveDirectPairingBaseUrl,
34 resolveTailscaleLocalTarget,
35} from "./pair.ts";
36
37import packageJson from "../../package.json" with { type: "json" };
38
39const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
40
41const baseState = {
42 version: 1,
43 pid: 123,
44 port: 3_773,
45 origin: "http://127.0.0.1:3773",
46 startedAt: "2026-06-20T00:00:00.000Z",
47} as const satisfies PersistedServerRuntimeState;
48
49describe("pair base URL selection", () => {
50 it("pairs through the dev web origin when the server fronts a dev server", () => {
51 expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
52 "http://localhost:5733/",
53 );
54 });
55
56 it("pairs through the bound host when there is no dev server", () => {
57 expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
58 "http://100.64.0.7:3773",
59 );
60 expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
61 });
62});
63
64describe("pair tailscale local target", () => {
65 it("proxies the dev web port for dev servers", () => {
66 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
67 { localPort: 5_733 },
68 );
69 // A dev server on a non-loopback interface must be proxied at that
70 // interface; tailscale serve defaults to 127.0.0.1 otherwise.
71 expect(
72 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
73 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
74 // URL.hostname keeps IPv6 brackets, so the serve target stays valid.
75 expect(
76 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
77 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
78 });
79
80 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
81 expect(
82 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
83 ).toBeInstanceOf(DevServerNotProxiableError);
84 });
85
86 it("proxies the backend port directly otherwise", () => {
87 expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
88 expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
89 localPort: 3_773,
90 });
91 expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
92 localPort: 3_773,
93 localHost: "192.168.1.42",
94 });
95 });
96});
97
98const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
99
100const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
101 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
102
103const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
104 provideCliTestLayers(
105 Effect.gen(function* () {
106 yield* effect;
107 return (
108 (yield* TestConsole.logLines).findLast(
109 (line): line is string => typeof line === "string",
110 ) ?? ""
111 );
112 }),
113 );
114
115const testDescriptor = {
116 environmentId: "pair-test-environment",
117 label: "pair-test",
118 platform: { os: "linux", arch: "x64" },
119 serverVersion: "0.0.1",
120 capabilities: { repositoryIdentity: true },
121};
122
123const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
124 Effect.acquireUseRelease(
125 Effect.callback<NodeHttp.Server>((resume) => {
126 const server = NodeHttp.createServer((request, response) => {
127 if (request.url === "/.well-known/t3/environment") {
128 response.writeHead(200, { "content-type": "application/json" });
129 response.end(JSON.stringify(testDescriptor));
130 return;
131 }
132 response.writeHead(404);
133 response.end();
134 });
135 server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
136 }),
137 (server) => {
138 const address = server.address();
139 if (address === null || typeof address === "string") {
140 return Effect.die(new Error("Expected a TCP address"));
141 }
142 return run(`http://127.0.0.1:${String(address.port)}`);
143 },
144 (server) => Effect.sync(() => server.close()),
145 );
146
147describe("t3 pair", () => {
148 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
149 withDescriptorServer((origin) =>
150 Effect.gen(function* () {
151 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
152 const port = Number(new URL(origin).port);
153 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
154 yield* persistServerRuntimeState({
155 path: statePath,
156 state: yield* makePersistedServerRuntimeState({
157 config: { host: "127.0.0.1", devUrl: undefined },
158 port,
159 }),
160 });
161
162 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
163
164 assert.include(output, `Pairing with pair-test (${origin})`);
165 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
166 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
167 assert.include(output, "only reachable from this machine");
168
169 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
170 assert.isString(token);
171
172 const listed = yield* captureStdout(
173 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
174 );
175 const credentials = JSON.parse(listed) as ReadonlyArray<{
176 readonly label?: string;
177 readonly scopes: ReadonlyArray<string>;
178 }>;
179 assert.equal(credentials.length, 1);
180 assert.equal(credentials[0]?.label, "t3 pair");
181 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
182 }),
183 ).pipe(
184 Effect.provide(NodeServices.layer),
185 Effect.provideService(HostProcess.Environment, {
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("mints a pairing grant with only the selected scopes", () =>
202 withDescriptorServer((origin) =>
203 Effect.gen(function* () {
204 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-scopes-test-"));
205 yield* persistServerRuntimeState({
206 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
207 state: yield* makePersistedServerRuntimeState({
208 config: { host: "127.0.0.1", devUrl: undefined },
209 port: Number(new URL(origin).port),
210 }),
211 });
212
213 yield* captureStdout(
214 runCli([
215 "pair",
216 "--base-dir",
217 baseDir,
218 "--scope",
219 "orchestration:read",
220 "--scope",
221 "relay:read",
222 "--scope",
223 "orchestration:read",
224 ]),
225 );
226 const listed = yield* captureStdout(
227 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
228 );
229 const credentials = JSON.parse(listed) as ReadonlyArray<{
230 readonly scopes: ReadonlyArray<string>;
231 }>;
232 assert.lengthOf(credentials, 1);
233 assert.deepEqual(credentials[0]?.scopes, ["orchestration:read", "relay:read"]);
234 }),
235 ).pipe(Effect.provide(NodeServices.layer)),
236 );
237
238 it.effect("pairs through the recorded dev web URL for dev servers", () =>
239 withDescriptorServer((origin) =>
240 Effect.gen(function* () {
241 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
242 const port = Number(new URL(origin).port);
243 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
244 yield* persistServerRuntimeState({
245 path: statePath,
246 state: yield* makePersistedServerRuntimeState({
247 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
248 port,
249 }),
250 });
251
252 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
253
254 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
255 }),
256 ).pipe(Effect.provide(NodeServices.layer)),
257 );
258
259 it.effect("directs to t3 serve or t3 connect when no server is running", () =>
260 Effect.gen(function* () {
261 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
262
263 const error = yield* provideCliTestLayers(
264 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
265 );
266
267 const rendered = String(
268 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
269 );
270 assert.include(rendered, "No running T3 Code server found.");
271 assert.include(rendered, "npx t3 serve");
272 assert.include(rendered, "npx t3 connect");
273 }).pipe(Effect.provide(NodeServices.layer)),
274 );
275
276 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
277 withDescriptorServer((origin) =>
278 Effect.gen(function* () {
279 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
280 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
281 const state = yield* makePersistedServerRuntimeState({
282 config: { host: "127.0.0.1", devUrl: undefined },
283 port: Number(new URL(origin).port),
284 });
285 yield* persistServerRuntimeState({
286 path: statePath,
287 state: { ...state, pid: 4_194_305 },
288 });
289
290 const error = yield* provideCliTestLayers(
291 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
292 );
293
294 const rendered = String(
295 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
296 );
297 assert.include(rendered, "No running T3 Code server found.");
298 }),
299 ).pipe(Effect.provide(NodeServices.layer)),
300 );
301
302 it.effect("ignores stale runtime state pointing at a dead server", () =>
303 Effect.gen(function* () {
304 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
305 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
306 yield* persistServerRuntimeState({
307 path: statePath,
308 state: yield* makePersistedServerRuntimeState({
309 config: { host: "127.0.0.1", devUrl: undefined },
310 port: 1,
311 }),
312 });
313
314 const error = yield* provideCliTestLayers(
315 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
316 );
317
318 const rendered = String(
319 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
320 );
321 assert.include(rendered, "No running T3 Code server found.");
322 }).pipe(Effect.provide(NodeServices.layer)),
323 );
324
325 // Without the capability `tailscale serve` blocks on an enablement URL, so
326 // pairing must stop at status instead of spawning it.
327 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
328 withDescriptorServer((origin) =>
329 Effect.gen(function* () {
330 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
331 yield* persistServerRuntimeState({
332 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
333 state: yield* makePersistedServerRuntimeState({
334 config: { host: "127.0.0.1", devUrl: undefined },
335 port: Number(new URL(origin).port),
336 }),
337 });
338 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
339 const spawner = ChildProcessSpawner.make((command) => {
340 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
341 tailscaleCalls.push(args);
342 const stdout =
343 args[0] === "status"
344 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
345 : "";
346 return Effect.succeed(
347 ChildProcessSpawner.makeHandle({
348 pid: ChildProcessSpawner.ProcessId(1),
349 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
350 isRunning: Effect.succeed(false),
351 kill: () => Effect.void,
352 unref: Effect.succeed(Effect.void),
353 stdin: Sink.drain,
354 stdout: Stream.make(new TextEncoder().encode(stdout)),
355 stderr: Stream.empty,
356 all: Stream.empty,
357 getInputFd: () => Sink.drain,
358 getOutputFd: () => Stream.empty,
359 }),
360 );
361 });
362
363 const error = yield* provideCliTestLayers(
364 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
365 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
366 Effect.flip,
367 ),
368 );
369
370 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
371 assert.include(String(error), "https://login.tailscale.com/admin/dns");
372 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
373 }),
374 ).pipe(Effect.provide(NodeServices.layer)),
375 );
376});
377
378describe("auth scope options", () => {
379 it.effect.each([
380 { group: "pairing", action: "create" },
381 { group: "session", action: "issue" },
382 ] as const)(
383 "issues and persists only the selected scopes for auth $group $action",
384 ({ group, action }) =>
385 Effect.gen(function* () {
386 const baseDir = NodeFS.mkdtempSync(
387 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
388 );
389 const output = yield* captureStdout(
390 runCli([
391 "auth",
392 group,
393 action,
394 "--base-dir",
395 baseDir,
396 "--json",
397 "--scope",
398 "orchestration:read",
399 "--scope",
400 "access:read",
401 "--scope",
402 "orchestration:read",
403 ]),
404 );
405 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
406 const listOutput = yield* captureStdout(
407 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
408 );
409 const listed = JSON.parse(listOutput) as ReadonlyArray<{
410 readonly scopes: ReadonlyArray<string>;
411 }>;
412
413 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
414 assert.lengthOf(listed, 1);
415 assert.deepEqual(listed[0]?.scopes, issued.scopes);
416 }),
417 );
418
419 it.effect.each(
420 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
421 command,
422 label: command.join(" "),
423 })),
424 )("rejects invalid scopes before running $label", ({ command }) =>
425 Effect.gen(function* () {
426 const error = yield* runCli([
427 ...command,
428 "--scope",
429 "orchestration:read",
430 "--scope",
431 "admin",
432 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
433
434 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
435 assert.fail(`Expected ShowHelp, got ${String(error)}`);
436 }
437 assert.deepEqual(error.commandPath, ["t3", ...command]);
438 const scopeError = error.errors[0];
439 if (scopeError?._tag !== "InvalidValue") {
440 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
441 }
442 assert.equal(scopeError.option, "scope");
443 assert.equal(scopeError.value, "admin");
444 }),
445 );
446});