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" };
38import { buildPairingAppLink } from "@t3tools/shared/remote";
39
40const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
41
42const baseState = {
43 version: 1,
44 pid: 123,
45 port: 3_773,
46 origin: "http://127.0.0.1:3773",
47 startedAt: "2026-06-20T00:00:00.000Z",
48} as const satisfies PersistedServerRuntimeState;
49
50describe("pair tailscale local target", () => {
51 it("proxies the dev web port for dev servers", () => {
52 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
53 { localPort: 5_733 },
54 );
55 // tailscale serve defaults to loopback, so non-loopback dev servers need an explicit target.
56 expect(
57 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
58 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
59 expect(
60 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
61 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
62 });
63
64 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
65 expect(
66 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
67 ).toBeInstanceOf(DevServerNotProxiableError);
68 });
69});
70
71const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
72
73const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
74 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
75
76const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
77 provideCliTestLayers(
78 Effect.gen(function* () {
79 yield* effect;
80 return (
81 (yield* TestConsole.logLines).findLast(
82 (line): line is string => typeof line === "string",
83 ) ?? ""
84 );
85 }),
86 );
87
88const testDescriptor = {
89 environmentId: "pair-test-environment",
90 label: "pair-test",
91 platform: { os: "linux", arch: "x64" },
92 serverVersion: "0.0.1",
93 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
94 capabilities: { repositoryIdentity: true },
95};
96
97const withDescriptorServer = <A, E, R>(
98 run: (origin: string) => Effect.Effect<A, E, R>,
99 host = "127.0.0.1",
100 descriptor: object = testDescriptor,
101) =>
102 Effect.acquireUseRelease(
103 Effect.callback<NodeHttp.Server>((resume) => {
104 const server = NodeHttp.createServer((request, response) => {
105 if (request.url === "/.well-known/t3/environment") {
106 response.writeHead(200, { "content-type": "application/json" });
107 response.end(JSON.stringify(descriptor));
108 return;
109 }
110 response.writeHead(404);
111 response.end();
112 });
113 server.listen(0, host, () => resume(Effect.succeed(server)));
114 }),
115 (server) => {
116 const address = server.address();
117 if (address === null || typeof address === "string") {
118 return Effect.die(new Error("Expected a TCP address"));
119 }
120 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
121 },
122 (server) => Effect.sync(() => server.close()),
123 );
124
125describe("t3 pair", () => {
126 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
127 withDescriptorServer(
128 (origin) =>
129 Effect.gen(function* () {
130 const fetch = yield* FetchHttpClient.Fetch;
131 let serving = false;
132 const spawner = ChildProcessSpawner.make((command) =>
133 Effect.gen(function* () {
134 if (!ChildProcess.isStandardCommand(command))
135 return yield* Effect.die("Unexpected pipeline");
136 if (command.args[0] === "serve") {
137 const target = command.args.at(-1)!;
138 const descriptor = yield* Effect.promise(async () =>
139 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
140 );
141 expect(descriptor).toEqual(testDescriptor);
142 serving = true;
143 }
144 return ChildProcessSpawner.makeHandle({
145 pid: ChildProcessSpawner.ProcessId(1),
146 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
147 isRunning: Effect.succeed(false),
148 kill: () => Effect.void,
149 unref: Effect.succeed(Effect.void),
150 stdin: Sink.drain,
151 stdout: Stream.make(
152 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
153 ),
154 stderr: Stream.empty,
155 all: Stream.empty,
156 getInputFd: () => Sink.drain,
157 getOutputFd: () => Stream.empty,
158 });
159 }),
160 );
161
162 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
163 yield* persistServerRuntimeState({
164 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
165 state: yield* makePersistedServerRuntimeState({
166 config: { host: "::1", devUrl: undefined },
167 port: Number(new URL(origin).port),
168 }),
169 });
170 const output = yield* captureStdout(
171 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
172 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
173 Effect.provideService(HostProcess.Platform, "linux"),
174 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
175 if (String(input).startsWith(origin)) return fetch(input, init);
176 assert.equal(
177 String(input),
178 "https://pair-test.tail.ts.net/.well-known/t3/environment",
179 );
180 return serving
181 ? Response.json(testDescriptor)
182 : new Response(null, { status: 503 });
183 }),
184 ),
185 );
186
187 expect(serving).toBe(true);
188 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
189 }),
190 "::1",
191 ).pipe(Effect.provide(NodeServices.layer)),
192 );
193
194 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
195 withDescriptorServer((origin) =>
196 Effect.gen(function* () {
197 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
198 const port = Number(new URL(origin).port);
199 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
200 yield* persistServerRuntimeState({
201 path: statePath,
202 state: yield* makePersistedServerRuntimeState({
203 config: { host: "127.0.0.1", devUrl: undefined },
204 port,
205 }),
206 });
207
208 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
209
210 assert.include(output, `Pairing with pair-test (${origin})`);
211 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
212 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
213 assert.include(output, "only reachable from this machine");
214
215 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
216 assert.isString(token);
217 assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${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});
491
492describe("auth pairing create --base-url", () => {
493 it.effect.each(["192.168.1.5:3773", "localhost:3773", "ftp://localhost:3773"])(
494 "rejects %s before issuing a token",
495 (baseUrl) =>
496 Effect.gen(function* () {
497 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
498 const error = yield* runCli([
499 "auth",
500 "pairing",
501 "create",
502 "--base-dir",
503 baseDir,
504 "--base-url",
505 baseUrl,
506 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
507
508 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
509 assert.fail(`Expected ShowHelp, got ${String(error)}`);
510 }
511 const flagError = error.errors[0];
512 if (flagError?._tag !== "InvalidValue") {
513 assert.fail(`Expected InvalidValue, got ${String(flagError?._tag)}`);
514 }
515 assert.equal(flagError.option, "base-url");
516 assert.equal(flagError.value, baseUrl);
517
518 const listOutput = yield* captureStdout(
519 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
520 );
521 assert.deepEqual(JSON.parse(listOutput), []);
522 }),
523 );
524
525 it.effect.each(["http://192.168.1.5:3773", "https://example.com", "http:localhost:3773"])(
526 "prints a pair URL for %s",
527 (baseUrl) =>
528 Effect.gen(function* () {
529 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
530 const output = yield* captureStdout(
531 runCli([
532 "auth",
533 "pairing",
534 "create",
535 "--base-dir",
536 baseDir,
537 "--base-url",
538 baseUrl,
539 "--json",
540 ]),
541 );
542 const issued = JSON.parse(output) as {
543 readonly credential: string;
544 readonly pairUrl: string;
545 };
546
547 assert.equal(issued.pairUrl, `${new URL(baseUrl).origin}/pair#token=${issued.credential}`);
548 }),
549 );
550});