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