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, ORCHESTRATION_PROTOCOL_VERSION } 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 Cause from "effect/Cause";
13import * as ConfigProvider from "effect/ConfigProvider";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Layer from "effect/Layer";
17import * as Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import { FetchHttpClient } from "effect/http";
20import { ChildProcess, ChildProcessSpawner } from "effect/process";
21import * as TestConsole from "effect/testing/TestConsole";
22import { Command, CliError } from "effect/cli";
23
24import { cli } from "../binCli.ts";
25import {
26 SERVICE_LAUNCHER_CONTEXT_ENV,
27 SERVICE_LAUNCHER_PROTOCOL,
28} from "../cloud/serviceProtocol.ts";
29import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
30import {
31 makePersistedServerRuntimeState,
32 persistServerRuntimeState,
33 type PersistedServerRuntimeState,
34} from "../serverRuntimeState.ts";
35import { DevServerNotProxiableError, resolveTailscaleLocalTarget } 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 tailscale local target", () => {
50 it("proxies the dev web port for dev servers", () => {
51 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
52 { localPort: 5_733 },
53 );
54 // tailscale serve defaults to loopback, so non-loopback dev servers need an explicit target.
55 expect(
56 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
57 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
58 expect(
59 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
60 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
61 });
62
63 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
64 expect(
65 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
66 ).toBeInstanceOf(DevServerNotProxiableError);
67 });
68});
69
70const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
71
72const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
73 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
74
75const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
76 provideCliTestLayers(
77 Effect.gen(function* () {
78 yield* effect;
79 return (
80 (yield* TestConsole.logLines).findLast(
81 (line): line is string => typeof line === "string",
82 ) ?? ""
83 );
84 }),
85 );
86
87const testDescriptor = {
88 environmentId: "pair-test-environment",
89 label: "pair-test",
90 platform: { os: "linux", arch: "x64" },
91 serverVersion: "0.0.1",
92 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
93 capabilities: { repositoryIdentity: true },
94};
95
96const withDescriptorServer = <A, E, R>(
97 run: (origin: string) => Effect.Effect<A, E, R>,
98 host = "127.0.0.1",
99 descriptor: object = testDescriptor,
100) =>
101 Effect.acquireUseRelease(
102 Effect.callback<NodeHttp.Server>((resume) => {
103 const server = NodeHttp.createServer((request, response) => {
104 if (request.url === "/.well-known/t3/environment") {
105 response.writeHead(200, { "content-type": "application/json" });
106 response.end(JSON.stringify(descriptor));
107 return;
108 }
109 response.writeHead(404);
110 response.end();
111 });
112 server.listen(0, host, () => resume(Effect.succeed(server)));
113 }),
114 (server) => {
115 const address = server.address();
116 if (address === null || typeof address === "string") {
117 return Effect.die(new Error("Expected a TCP address"));
118 }
119 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
120 },
121 (server) => Effect.sync(() => server.close()),
122 );
123
124describe("t3 pair", () => {
125 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
126 withDescriptorServer(
127 (origin) =>
128 Effect.gen(function* () {
129 const fetch = yield* FetchHttpClient.Fetch;
130 let serving = false;
131 const spawner = ChildProcessSpawner.make((command) =>
132 Effect.gen(function* () {
133 if (!ChildProcess.isStandardCommand(command))
134 return yield* Effect.die("Unexpected pipeline");
135 if (command.args[0] === "serve") {
136 const target = command.args.at(-1)!;
137 const descriptor = yield* Effect.promise(async () =>
138 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
139 );
140 expect(descriptor).toEqual(testDescriptor);
141 serving = true;
142 }
143 return ChildProcessSpawner.makeHandle({
144 pid: ChildProcessSpawner.ProcessId(1),
145 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
146 isRunning: Effect.succeed(false),
147 kill: () => Effect.void,
148 unref: Effect.succeed(Effect.void),
149 stdin: Sink.drain,
150 stdout: Stream.make(
151 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
152 ),
153 stderr: Stream.empty,
154 all: Stream.empty,
155 getInputFd: () => Sink.drain,
156 getOutputFd: () => Stream.empty,
157 });
158 }),
159 );
160
161 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
162 yield* persistServerRuntimeState({
163 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
164 state: yield* makePersistedServerRuntimeState({
165 config: { host: "::1", devUrl: undefined },
166 port: Number(new URL(origin).port),
167 }),
168 });
169 const output = yield* captureStdout(
170 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
171 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
172 Effect.provideService(HostProcess.Platform, "linux"),
173 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
174 if (String(input).startsWith(origin)) return fetch(input, init);
175 assert.equal(
176 String(input),
177 "https://pair-test.tail.ts.net/.well-known/t3/environment",
178 );
179 return serving
180 ? Response.json(testDescriptor)
181 : new Response(null, { status: 503 });
182 }),
183 ),
184 );
185
186 expect(serving).toBe(true);
187 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
188 }),
189 "::1",
190 ).pipe(Effect.provide(NodeServices.layer)),
191 );
192
193 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
194 withDescriptorServer((origin) =>
195 Effect.gen(function* () {
196 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
197 const port = Number(new URL(origin).port);
198 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
199 yield* persistServerRuntimeState({
200 path: statePath,
201 state: yield* makePersistedServerRuntimeState({
202 config: { host: "127.0.0.1", devUrl: undefined },
203 port,
204 }),
205 });
206
207 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
208
209 assert.include(output, `Pairing with pair-test (${origin})`);
210 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
211 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
212 assert.include(output, "only reachable from this machine");
213
214 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
215 assert.isString(token);
216
217 const listed = yield* captureStdout(
218 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
219 );
220 const credentials = JSON.parse(listed) as ReadonlyArray<{
221 readonly label?: string;
222 readonly scopes: ReadonlyArray<string>;
223 }>;
224 assert.equal(credentials.length, 1);
225 assert.equal(credentials[0]?.label, "t3 pair");
226 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
227 }),
228 ).pipe(
229 Effect.provide(NodeServices.layer),
230 Effect.provideService(HostProcess.Environment, {
231 ...process.env,
232 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
233 protocol: SERVICE_LAUNCHER_PROTOCOL,
234 childVersion: packageJson.version,
235 }),
236 }),
237 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
238 connected: false,
239 send: () => false,
240 on: () => undefined,
241 off: () => undefined,
242 }),
243 ),
244 );
245
246 it.effect("pairs through the recorded dev web URL for dev servers", () =>
247 withDescriptorServer((origin) =>
248 Effect.gen(function* () {
249 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
250 const port = Number(new URL(origin).port);
251 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
252 yield* persistServerRuntimeState({
253 path: statePath,
254 state: yield* makePersistedServerRuntimeState({
255 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
256 port,
257 }),
258 });
259
260 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
261
262 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
263 }),
264 ).pipe(Effect.provide(NodeServices.layer)),
265 );
266
267 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
268 withDescriptorServer((origin) =>
269 Effect.gen(function* () {
270 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
271 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
272 const state = yield* makePersistedServerRuntimeState({
273 config: { host: "127.0.0.1", devUrl: undefined },
274 port: Number(new URL(origin).port),
275 });
276 yield* persistServerRuntimeState({
277 path: statePath,
278 state: { ...state, pid: 4_194_305 },
279 });
280
281 const error = yield* provideCliTestLayers(
282 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
283 );
284
285 const rendered = String(
286 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
287 );
288 assert.include(rendered, "No running T3 Code server found.");
289 }),
290 ).pipe(Effect.provide(NodeServices.layer)),
291 );
292
293 // regression: #10516 minting opens the target database with this checkout's
294 // migrations, so a worktree must never fall back to the live install.
295 it.effect("does not fall back to the shared home from a linked worktree", () =>
296 withDescriptorServer((origin) =>
297 Effect.gen(function* () {
298 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-worktree-test-"));
299 const worktree = NodePath.join(root, "worktree");
300 NodeFS.mkdirSync(worktree);
301 NodeFS.writeFileSync(
302 NodePath.join(worktree, ".git"),
303 `gitdir: ${NodePath.join(root, "repo", ".git", "worktrees", "worktree")}\n`,
304 );
305 const sharedHome = NodePath.join(root, "shared");
306 yield* persistServerRuntimeState({
307 path: NodePath.join(sharedHome, "userdata", "server-runtime.json"),
308 state: yield* makePersistedServerRuntimeState({
309 config: { host: "127.0.0.1", devUrl: undefined },
310 port: Number(new URL(origin).port),
311 }),
312 });
313
314 const error = yield* provideCliTestLayers(
315 runCli(["pair"]).pipe(
316 Effect.provideService(HostProcess.WorkingDirectory, worktree),
317 Effect.provide(
318 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOME: sharedHome } })),
319 ),
320 Effect.flip,
321 ),
322 );
323
324 assert.include(String(error), "No running T3 Code server found.");
325 assert.notInclude(String(error), sharedHome);
326 assert.deepEqual(NodeFS.readdirSync(NodePath.join(sharedHome, "userdata")), [
327 "server-runtime.json",
328 ]);
329 }),
330 ).pipe(Effect.provide(NodeServices.layer)),
331 );
332
333 // regression: #15492 an older CLI minted into a V1 database the protocol 2
334 // server never reads, so pairing must refuse before opening the database.
335 it.effect("rejects a server on another protocol before opening its database", () =>
336 withDescriptorServer(
337 (origin) =>
338 Effect.gen(function* () {
339 const baseDir = NodeFS.mkdtempSync(
340 NodePath.join(NodeOS.tmpdir(), "t3-pair-protocol-test-"),
341 );
342 yield* persistServerRuntimeState({
343 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
344 state: yield* makePersistedServerRuntimeState({
345 config: { host: "127.0.0.1", devUrl: undefined },
346 port: Number(new URL(origin).port),
347 }),
348 });
349
350 const exit = yield* provideCliTestLayers(
351 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.exit),
352 );
353
354 assert.deepEqual(NodeFS.readdirSync(NodePath.join(baseDir, "userdata")), [
355 "server-runtime.json",
356 ]);
357 assert.isTrue(Exit.isFailure(exit));
358 if (Exit.isFailure(exit)) {
359 assert.include(String(Cause.squash(exit.cause)), "t3@0.0.45 pair");
360 }
361 }),
362 "127.0.0.1",
363 { ...testDescriptor, serverVersion: "0.0.45", orchestrationProtocolVersion: 1 },
364 ).pipe(Effect.provide(NodeServices.layer)),
365 );
366
367 // Without the capability `tailscale serve` blocks on an enablement URL, so
368 // pairing must stop at status instead of spawning it.
369 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
370 withDescriptorServer((origin) =>
371 Effect.gen(function* () {
372 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
373 yield* persistServerRuntimeState({
374 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
375 state: yield* makePersistedServerRuntimeState({
376 config: { host: "127.0.0.1", devUrl: undefined },
377 port: Number(new URL(origin).port),
378 }),
379 });
380 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
381 const spawner = ChildProcessSpawner.make((command) => {
382 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
383 tailscaleCalls.push(args);
384 const stdout =
385 args[0] === "status"
386 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
387 : "";
388 return Effect.succeed(
389 ChildProcessSpawner.makeHandle({
390 pid: ChildProcessSpawner.ProcessId(1),
391 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
392 isRunning: Effect.succeed(false),
393 kill: () => Effect.void,
394 unref: Effect.succeed(Effect.void),
395 stdin: Sink.drain,
396 stdout: Stream.make(new TextEncoder().encode(stdout)),
397 stderr: Stream.empty,
398 all: Stream.empty,
399 getInputFd: () => Sink.drain,
400 getOutputFd: () => Stream.empty,
401 }),
402 );
403 });
404
405 const error = yield* provideCliTestLayers(
406 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
407 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
408 Effect.flip,
409 ),
410 );
411
412 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
413 assert.include(String(error), "https://login.tailscale.com/admin/dns");
414 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
415 }),
416 ).pipe(Effect.provide(NodeServices.layer)),
417 );
418});
419
420describe("auth scope options", () => {
421 it.effect.each([
422 { group: "pairing", action: "create" },
423 { group: "session", action: "issue" },
424 ] as const)(
425 "issues and persists only the selected scopes for auth $group $action",
426 ({ group, action }) =>
427 Effect.gen(function* () {
428 const baseDir = NodeFS.mkdtempSync(
429 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
430 );
431 const output = yield* captureStdout(
432 runCli([
433 "auth",
434 group,
435 action,
436 "--base-dir",
437 baseDir,
438 "--json",
439 "--scope",
440 "orchestration:read",
441 "--scope",
442 "access:read",
443 "--scope",
444 "orchestration:read",
445 ]),
446 );
447 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
448 const listOutput = yield* captureStdout(
449 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
450 );
451 const listed = JSON.parse(listOutput) as ReadonlyArray<{
452 readonly scopes: ReadonlyArray<string>;
453 }>;
454
455 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
456 assert.lengthOf(listed, 1);
457 assert.deepEqual(listed[0]?.scopes, issued.scopes);
458 }),
459 );
460
461 it.effect.each(
462 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
463 command,
464 label: command.join(" "),
465 })),
466 )("rejects invalid scopes before running $label", ({ command }) =>
467 Effect.gen(function* () {
468 const error = yield* runCli([
469 ...command,
470 "--scope",
471 "orchestration:read",
472 "--scope",
473 "admin",
474 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
475
476 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
477 assert.fail(`Expected ShowHelp, got ${String(error)}`);
478 }
479 assert.deepEqual(error.commandPath, ["t3", ...command]);
480 const scopeError = error.errors[0];
481 if (scopeError?._tag !== "InvalidValue") {
482 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
483 }
484 assert.equal(scopeError.option, "scope");
485 assert.equal(scopeError.value, "admin");
486 }),
487 );
488});