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