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 NodeCrypto from "@effect/platform-node/NodeCrypto";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { AuthStandardClientScopes, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
10import * as NetService from "@t3tools/shared/Net";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import { assert, describe, expect, it } from "@effect/vitest";
13import * as Cause from "effect/Cause";
14import * as ConfigProvider from "effect/ConfigProvider";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Sink from "effect/Sink";
20import * as Stream from "effect/Stream";
21import { FetchHttpClient } from "effect/http";
22import { ChildProcess, ChildProcessSpawner } from "effect/process";
23import * as TestClock from "effect/testing/TestClock";
24import * as TestConsole from "effect/testing/TestConsole";
25import { Command, CliError } from "effect/cli";
26
27import { cli } from "../binCli.ts";
28import {
29 SERVICE_LAUNCHER_CONTEXT_ENV,
30 SERVICE_LAUNCHER_PROTOCOL,
31} from "../cloud/serviceProtocol.ts";
32import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
33import * as ProcessRunner from "../processRunner.ts";
34import * as ServerOwnership from "../serverOwnership.ts";
35import {
36 makePersistedServerRuntimeState,
37 persistServerRuntimeState,
38 type PersistedServerRuntimeState,
39} from "../serverRuntimeState.ts";
40import { resolveHostCliCommand } from "./invocation.ts";
41import {
42 DevServerNotProxiableError,
43 resolveTailscaleLocalTarget,
44 ServePortOccupiedError,
45 TailscaleServeTargetRefusedError,
46} from "./pair.ts";
47
48import packageJson from "../../package.json" with { type: "json" };
49import { buildPairingAppLink } from "@t3tools/shared/remote";
50
51const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer);
52
53const baseState = {
54 version: 1,
55 pid: 123,
56 port: 3_773,
57 origin: "http://127.0.0.1:3773",
58 startedAt: "2026-06-20T00:00:00.000Z",
59} as const satisfies PersistedServerRuntimeState;
60
61describe("pair tailscale local target", () => {
62 it("proxies the dev web port for dev servers", () => {
63 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
64 { localPort: 5_733 },
65 );
66 // tailscale serve defaults to loopback, so non-loopback dev servers need an explicit target.
67 expect(
68 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
69 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
70 expect(
71 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
72 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
73 // tailscale serve's default target is 127.0.0.1, which misses an IPv6-only listener.
74 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[::1]:5733/" })).toEqual({
75 localPort: 5_733,
76 localHost: "[::1]",
77 });
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
87const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
88
89const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
90 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
91
92const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
93 provideCliTestLayers(
94 Effect.gen(function* () {
95 yield* effect;
96 return (
97 (yield* TestConsole.logLines).findLast(
98 (line): line is string => typeof line === "string",
99 ) ?? ""
100 );
101 }),
102 );
103
104const testDescriptor = {
105 environmentId: "pair-test-environment",
106 label: "pair-test",
107 platform: { os: "linux", arch: "x64" },
108 serverVersion: "0.0.1",
109 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
110 capabilities: { repositoryIdentity: true },
111};
112
113const withDescriptorServer = <A, E, R>(
114 run: (origin: string) => Effect.Effect<A, E, R>,
115 host = "127.0.0.1",
116 descriptor: object = testDescriptor,
117) =>
118 Effect.acquireUseRelease(
119 Effect.callback<NodeHttp.Server>((resume) => {
120 const server = NodeHttp.createServer((request, response) => {
121 if (request.url === "/.well-known/t3/environment") {
122 response.writeHead(200, { "content-type": "application/json" });
123 response.end(JSON.stringify(descriptor));
124 return;
125 }
126 response.writeHead(404);
127 response.end();
128 });
129 server.listen(0, host, () => resume(Effect.succeed(server)));
130 }),
131 (server) => {
132 const address = server.address();
133 if (address === null || typeof address === "string") {
134 return Effect.die(new Error("Expected a TCP address"));
135 }
136 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
137 },
138 (server) => Effect.sync(() => server.close()),
139 );
140
141describe("t3 pair", () => {
142 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
143 withDescriptorServer(
144 (origin) =>
145 Effect.gen(function* () {
146 const fetch = yield* FetchHttpClient.Fetch;
147 let serving = false;
148 const spawner = ChildProcessSpawner.make((command) =>
149 Effect.gen(function* () {
150 if (!ChildProcess.isStandardCommand(command))
151 return yield* Effect.die("Unexpected pipeline");
152 if (command.args[0] === "serve" && command.args[1] === "--bg") {
153 const target = String(command.args.at(-1));
154 const descriptor = yield* Effect.promise(async () =>
155 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
156 );
157 expect(descriptor).toEqual(testDescriptor);
158 serving = true;
159 }
160 return ChildProcessSpawner.makeHandle({
161 pid: ChildProcessSpawner.ProcessId(1),
162 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
163 exitStatus: Effect.succeed({
164 _tag: "Exited",
165 code: ChildProcessSpawner.ExitCode(0),
166 }),
167 isRunning: Effect.succeed(false),
168 kill: () => Effect.void,
169 unref: Effect.succeed(Effect.void),
170 stdin: Sink.drain,
171 stdout: Stream.make(
172 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
173 ),
174 stderr: Stream.empty,
175 all: Stream.empty,
176 getInputFd: () => Sink.drain,
177 getOutputFd: () => Stream.empty,
178 });
179 }),
180 );
181
182 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
183 yield* persistServerRuntimeState({
184 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
185 state: yield* makePersistedServerRuntimeState({
186 config: { host: "::1", devUrl: undefined },
187 port: Number(new URL(origin).port),
188 }),
189 });
190 const output = yield* captureStdout(
191 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
192 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
193 Effect.provideService(HostProcess.Platform, "linux"),
194 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
195 if (String(input).startsWith(origin)) return fetch(input, init);
196 assert.equal(
197 String(input),
198 "https://pair-test.tail.ts.net/.well-known/t3/environment",
199 );
200 return serving
201 ? Response.json(testDescriptor)
202 : new Response(null, { status: 503 });
203 }),
204 ),
205 );
206
207 expect(serving).toBe(true);
208 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
209 }),
210 "::1",
211 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
212 );
213
214 // The MagicDNS probe fails whenever the host cannot reach its own *.ts.net name,
215 // so it cannot be what decides that the port is free.
216 it.effect(
217 "leaves another app's Serve route alone when the host cannot reach its MagicDNS URL",
218 () =>
219 withDescriptorServer((origin) =>
220 // Another live app on loopback; a dead port's route may be taken back.
221 withDescriptorServer((otherAppOrigin) =>
222 Effect.gen(function* () {
223 const fetch = yield* FetchHttpClient.Fetch;
224 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
225 const spawner = ChildProcessSpawner.make((command) => {
226 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
227 tailscaleCalls.push(args);
228 const stdout =
229 args[0] === "status"
230 ? '{"BackendState":"Running","Self":{"DNSName":"host-a.tail.ts.net.","TailscaleIPs":["100.64.0.1"],"CapMap":{"https":null}}}'
231 : args[0] === "serve" && args[1] === "status"
232 ? JSON.stringify({
233 TCP: { "443": { HTTPS: true } },
234 Web: {
235 "host-a.tail.ts.net:443": {
236 Handlers: { "/": { Proxy: otherAppOrigin } },
237 },
238 },
239 })
240 : "";
241 return Effect.succeed(
242 ChildProcessSpawner.makeHandle({
243 pid: ChildProcessSpawner.ProcessId(1),
244 // A recorded takeover fails fast instead of waiting out the HTTPS retries.
245 exitCode: Effect.succeed(
246 ChildProcessSpawner.ExitCode(
247 args[0] === "serve" && args[1] !== "status" ? 1 : 0,
248 ),
249 ),
250 exitStatus: Effect.succeed({
251 _tag: "Exited",
252 code: ChildProcessSpawner.ExitCode(
253 args[0] === "serve" && args[1] !== "status" ? 1 : 0,
254 ),
255 }),
256 isRunning: Effect.succeed(false),
257 kill: () => Effect.void,
258 unref: Effect.succeed(Effect.void),
259 stdin: Sink.drain,
260 stdout: Stream.make(new TextEncoder().encode(stdout)),
261 stderr: Stream.empty,
262 all: Stream.empty,
263 getInputFd: () => Sink.drain,
264 getOutputFd: () => Stream.empty,
265 }),
266 );
267 });
268
269 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-held-"));
270 yield* persistServerRuntimeState({
271 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
272 state: yield* makePersistedServerRuntimeState({
273 config: { host: "127.0.0.1", devUrl: undefined },
274 port: Number(new URL(origin).port),
275 }),
276 });
277
278 const exit = yield* runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
279 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
280 Effect.provideService(HostProcess.Platform, "linux"),
281 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
282 if (String(input).startsWith(origin)) return fetch(input, init);
283 throw new TypeError("getaddrinfo ENOTFOUND host-a.tail.ts.net");
284 }),
285 Effect.exit,
286 );
287
288 assert.deepEqual(
289 tailscaleCalls.filter((args) => args[0] === "serve" && args[1] !== "status"),
290 [],
291 );
292 assert.isTrue(Exit.isFailure(exit));
293 if (Exit.isFailure(exit)) {
294 assert.instanceOf(Cause.squash(exit.cause), ServePortOccupiedError);
295 }
296 }),
297 ),
298 ).pipe(Effect.provide(layerCliRuntime)),
299 );
300
301 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
302 withDescriptorServer((origin) =>
303 Effect.gen(function* () {
304 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
305 const port = Number(new URL(origin).port);
306 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
307 yield* persistServerRuntimeState({
308 path: statePath,
309 state: yield* makePersistedServerRuntimeState({
310 config: { host: "127.0.0.1", devUrl: undefined },
311 port,
312 }),
313 });
314
315 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
316
317 assert.include(output, `Pairing with pair-test (${origin})`);
318 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
319 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
320 assert.include(output, "only reachable from this machine");
321
322 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
323 assert.isString(token);
324 assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${token}`)}`);
325
326 const listed = yield* captureStdout(
327 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
328 );
329 const credentials = JSON.parse(listed) as ReadonlyArray<{
330 readonly label?: string;
331 readonly scopes: ReadonlyArray<string>;
332 }>;
333 assert.equal(credentials.length, 1);
334 assert.equal(credentials[0]?.label, "t3 pair");
335 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
336 }),
337 ).pipe(
338 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
339 Effect.provideService(HostProcess.Environment, {
340 ...process.env,
341 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
342 protocol: SERVICE_LAUNCHER_PROTOCOL,
343 childVersion: packageJson.version,
344 }),
345 }),
346 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
347 connected: false,
348 send: () => false,
349 on: () => undefined,
350 off: () => undefined,
351 }),
352 ),
353 );
354
355 it.effect("pairs through the recorded dev web URL for dev servers", () =>
356 withDescriptorServer((origin) =>
357 Effect.gen(function* () {
358 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
359 const port = Number(new URL(origin).port);
360 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
361 yield* persistServerRuntimeState({
362 path: statePath,
363 state: yield* makePersistedServerRuntimeState({
364 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
365 port,
366 }),
367 });
368
369 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
370
371 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
372 }),
373 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
374 );
375
376 it.effect("refuses --tailscale before turning on Serve when the policy keeps clients local", () =>
377 withDescriptorServer((origin) =>
378 Effect.gen(function* () {
379 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-policy-test-"));
380 const policyPath = NodePath.join(baseDir, "policy.json");
381 NodeFS.writeFileSync(
382 policyPath,
383 JSON.stringify({
384 schemaVersion: 1,
385 organization: "Example Corp",
386 limits: { clients: ["desktop", "local-browser"] },
387 }),
388 );
389 yield* persistServerRuntimeState({
390 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
391 state: yield* makePersistedServerRuntimeState({
392 config: { host: "127.0.0.1", devUrl: undefined },
393 port: Number(new URL(origin).port),
394 }),
395 });
396
397 const error = yield* provideCliTestLayers(
398 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
399 Effect.provideService(
400 ChildProcessSpawner.ChildProcessSpawner,
401 ChildProcessSpawner.make(() => Effect.die("tailscale must not run")),
402 ),
403 Effect.provide(
404 ConfigProvider.layer(
405 ConfigProvider.fromEnv({ env: { T3CODE_DEV_MANAGED_POLICY_PATH: policyPath } }),
406 ),
407 ),
408 Effect.flip,
409 ),
410 );
411
412 assert.include(
413 String(error),
414 "Example Corp's policy does not allow remote clients, so Tailscale Serve cannot be turned on.",
415 );
416 }),
417 ).pipe(Effect.provide(NodeServices.layer)),
418 );
419
420 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
421 withDescriptorServer((origin) =>
422 Effect.gen(function* () {
423 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3 pair pid test-"));
424 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
425 const state = yield* makePersistedServerRuntimeState({
426 config: { host: "127.0.0.1", devUrl: undefined },
427 port: Number(new URL(origin).port),
428 });
429 yield* persistServerRuntimeState({
430 path: statePath,
431 state: { ...state, pid: 4_194_305 },
432 });
433
434 const error = yield* provideCliTestLayers(
435 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
436 );
437
438 const rendered = String(
439 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
440 );
441 assert.include(rendered, "No running T3 Code server found.");
442 for (const subcommand of ["serve", "connect"]) {
443 const { command } = yield* resolveHostCliCommand(subcommand, ["--base-dir", baseDir]);
444 assert.include(rendered, `\`${command}\``);
445 }
446 }),
447 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
448 );
449
450 // regression: #10516 minting opens the target database with this checkout's
451 // migrations, so a worktree must never fall back to the live install.
452 it.effect("does not fall back to the shared home from a linked worktree", () =>
453 withDescriptorServer((origin) =>
454 Effect.gen(function* () {
455 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-worktree-test-"));
456 const worktree = NodePath.join(root, "worktree");
457 NodeFS.mkdirSync(worktree);
458 NodeFS.writeFileSync(
459 NodePath.join(worktree, ".git"),
460 `gitdir: ${NodePath.join(root, "repo", ".git", "worktrees", "worktree")}\n`,
461 );
462 const sharedHome = NodePath.join(root, "shared");
463 yield* persistServerRuntimeState({
464 path: NodePath.join(sharedHome, "userdata", "server-runtime.json"),
465 state: yield* makePersistedServerRuntimeState({
466 config: { host: "127.0.0.1", devUrl: undefined },
467 port: Number(new URL(origin).port),
468 }),
469 });
470
471 const error = yield* provideCliTestLayers(
472 runCli(["pair"]).pipe(
473 Effect.provideService(HostProcess.WorkingDirectory, worktree),
474 Effect.provide(
475 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOME: sharedHome } })),
476 ),
477 Effect.flip,
478 ),
479 );
480
481 assert.include(String(error), "No running T3 Code server found.");
482 assert.notInclude(String(error), sharedHome);
483 assert.deepEqual(NodeFS.readdirSync(NodePath.join(sharedHome, "userdata")), [
484 "server-runtime.json",
485 ]);
486 }),
487 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
488 );
489
490 // regression: #15492 an older CLI minted into a V1 database the protocol 2
491 // server never reads, so pairing must refuse before opening the database.
492 it.effect("rejects a server on another protocol before opening its database", () =>
493 withDescriptorServer(
494 (origin) =>
495 Effect.gen(function* () {
496 const baseDir = NodeFS.mkdtempSync(
497 NodePath.join(NodeOS.tmpdir(), "t3-pair-protocol-test-"),
498 );
499 yield* persistServerRuntimeState({
500 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
501 state: yield* makePersistedServerRuntimeState({
502 config: { host: "127.0.0.1", devUrl: undefined },
503 port: Number(new URL(origin).port),
504 }),
505 });
506
507 const exit = yield* provideCliTestLayers(
508 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.exit),
509 );
510
511 assert.deepEqual(NodeFS.readdirSync(NodePath.join(baseDir, "userdata")), [
512 "server-runtime.json",
513 ]);
514 assert.isTrue(Exit.isFailure(exit));
515 if (Exit.isFailure(exit)) {
516 assert.include(
517 String(Cause.squash(exit.cause)),
518 `t3@0.0.45 pair --base-dir ${baseDir}`,
519 );
520 }
521 }),
522 "127.0.0.1",
523 { ...testDescriptor, serverVersion: "0.0.45", orchestrationProtocolVersion: 1 },
524 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
525 );
526
527 // Without the capability `tailscale serve` blocks on an enablement URL, so
528 // pairing must stop at status instead of spawning it.
529 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
530 withDescriptorServer((origin) =>
531 Effect.gen(function* () {
532 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
533 yield* persistServerRuntimeState({
534 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
535 state: yield* makePersistedServerRuntimeState({
536 config: { host: "127.0.0.1", devUrl: undefined },
537 port: Number(new URL(origin).port),
538 }),
539 });
540 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
541 const spawner = ChildProcessSpawner.make((command) => {
542 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
543 tailscaleCalls.push(args);
544 const stdout =
545 args[0] === "status"
546 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
547 : "";
548 return Effect.succeed(
549 ChildProcessSpawner.makeHandle({
550 pid: ChildProcessSpawner.ProcessId(1),
551 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
552 exitStatus: Effect.succeed({
553 _tag: "Exited",
554 code: ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1),
555 }),
556 isRunning: Effect.succeed(false),
557 kill: () => Effect.void,
558 unref: Effect.succeed(Effect.void),
559 stdin: Sink.drain,
560 stdout: Stream.make(new TextEncoder().encode(stdout)),
561 stderr: Stream.empty,
562 all: Stream.empty,
563 getInputFd: () => Sink.drain,
564 getOutputFd: () => Stream.empty,
565 }),
566 );
567 });
568
569 const error = yield* provideCliTestLayers(
570 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
571 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
572 Effect.flip,
573 ),
574 );
575
576 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
577 assert.include(String(error), "https://login.tailscale.com/admin/dns");
578 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
579 }),
580 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
581 );
582
583 // regression: #35517 - the macOS Tailscale apps refuse Serve targets other than
584 // localhost, 127.0.0.1 and ::1, so a specific bind needs an explanation.
585 it.effect("names the bind address when Tailscale refuses it as a Serve target", () =>
586 Effect.gen(function* () {
587 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-"));
588 yield* persistServerRuntimeState({
589 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
590 state: yield* makePersistedServerRuntimeState({
591 config: { host: "127.0.0.2", devUrl: undefined },
592 port: 3773,
593 }),
594 });
595 const spawner = ChildProcessSpawner.make((command) => {
596 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
597 const serve = args[0] === "serve" && args[1] !== "status";
598 return Effect.succeed(
599 ChildProcessSpawner.makeHandle({
600 pid: ChildProcessSpawner.ProcessId(1),
601 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(serve ? 1 : 0)),
602 exitStatus: Effect.succeed({
603 _tag: "Exited",
604 code: ChildProcessSpawner.ExitCode(serve ? 1 : 0),
605 }),
606 isRunning: Effect.succeed(false),
607 kill: () => Effect.void,
608 unref: Effect.succeed(Effect.void),
609 stdin: Sink.drain,
610 stdout: Stream.make(
611 new TextEncoder().encode(
612 serve
613 ? ""
614 : args[0] === "status"
615 ? '{"Self":{"DNSName":"pair-test.tail.ts.net."}}'
616 : "{}",
617 ),
618 ),
619 stderr: Stream.make(
620 new TextEncoder().encode(
621 serve
622 ? "Warning: the MacOS extension doesn't support connecting to remote destinations from non-default route\n"
623 : "",
624 ),
625 ),
626 all: Stream.empty,
627 getInputFd: () => Sink.drain,
628 getOutputFd: () => Stream.empty,
629 }),
630 );
631 });
632
633 const error = yield* provideCliTestLayers(
634 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
635 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
636 Effect.provideService(HostProcess.Platform, "darwin"),
637 Effect.provideService(FetchHttpClient.Fetch, async (input) => {
638 if (String(input) === "http://127.0.0.2:3773/.well-known/t3/environment") {
639 return Response.json(testDescriptor);
640 }
641 assert.equal(String(input), "https://pair-test.tail.ts.net/.well-known/t3/environment");
642 return new Response(null, { status: 503 });
643 }),
644 Effect.flip,
645 ),
646 );
647
648 assert.instanceOf(error, TailscaleServeTargetRefusedError);
649 assert.include(String(error), "127.0.0.2");
650 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
651 );
652
653 // regression: #37459 - on Linux without an operator, tailscaled refuses Serve config
654 // from a normal user, and the CLI must say how to fix it.
655 it.effect("explains the operator fix when Tailscale denies the Serve config", () =>
656 Effect.gen(function* () {
657 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-"));
658 yield* persistServerRuntimeState({
659 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
660 state: yield* makePersistedServerRuntimeState({
661 config: { host: "127.0.0.1", devUrl: undefined },
662 port: 3773,
663 }),
664 });
665 const spawner = ChildProcessSpawner.make((command) => {
666 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
667 const serve = args[0] === "serve" && args[1] !== "status";
668 return Effect.succeed(
669 ChildProcessSpawner.makeHandle({
670 pid: ChildProcessSpawner.ProcessId(1),
671 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(serve ? 1 : 0)),
672 exitStatus: Effect.succeed({
673 _tag: "Exited",
674 code: ChildProcessSpawner.ExitCode(serve ? 1 : 0),
675 }),
676 isRunning: Effect.succeed(false),
677 kill: () => Effect.void,
678 unref: Effect.succeed(Effect.void),
679 stdin: Sink.drain,
680 stdout: Stream.make(
681 new TextEncoder().encode(
682 serve
683 ? ""
684 : args[0] === "status"
685 ? '{"Self":{"DNSName":"pair-test.tail.ts.net."}}'
686 : "{}",
687 ),
688 ),
689 stderr: Stream.make(
690 new TextEncoder().encode(
691 serve
692 ? "sending serve config: Access denied: serve config denied\n\nUse 'sudo tailscale serve --https=443 --bg http://127.0.0.1:3773'.\nTo not require root, use 'sudo tailscale set --operator=$USER' once.\n"
693 : "",
694 ),
695 ),
696 all: Stream.empty,
697 getInputFd: () => Sink.drain,
698 getOutputFd: () => Stream.empty,
699 }),
700 );
701 });
702
703 const error = yield* provideCliTestLayers(
704 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
705 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
706 Effect.provideService(HostProcess.Platform, "linux"),
707 Effect.provideService(FetchHttpClient.Fetch, async (input) => {
708 if (String(input) === "http://127.0.0.1:3773/.well-known/t3/environment") {
709 return Response.json(testDescriptor);
710 }
711 assert.equal(String(input), "https://pair-test.tail.ts.net/.well-known/t3/environment");
712 return new Response(null, { status: 503 });
713 }),
714 Effect.flip,
715 ),
716 );
717
718 assert.include(String(error), "sudo tailscale set --operator=$USER");
719 assert.notInclude(String(error), "by hand to see why");
720 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
721 );
722});
723
724describe("auth session revoke", () => {
725 // Nothing listens on the recorded port; `server` stubs what fetch meets there instead.
726 it.effect.each([
727 {
728 label: "goes through a running server, which closes open connections",
729 recorded: true,
730 lockHeld: false,
731 server: "answers",
732 outcome: "revoked by server",
733 },
734 {
735 label: "writes the database when no server runs",
736 recorded: false,
737 lockHeld: false,
738 server: "none",
739 outcome: "revoked locally",
740 },
741 {
742 label: "writes the database when the recorded server has stopped",
743 recorded: true,
744 lockHeld: false,
745 server: "none",
746 outcome: "revoked locally",
747 },
748 {
749 label: "changes nothing when a running server refuses the connection",
750 recorded: true,
751 lockHeld: true,
752 server: "none",
753 outcome: "RunningServerUnreachableError",
754 },
755 {
756 label: "does not repeat a change locally when the server stops replying mid-request",
757 recorded: true,
758 lockHeld: false,
759 server: "hangs",
760 outcome: "RunningServerNoReplyError",
761 },
762 {
763 label: "does not repeat a change locally when the server answers with an error",
764 recorded: true,
765 lockHeld: false,
766 server: "fails",
767 outcome: "HttpClientError",
768 },
769 ] as const)("$label", ({ recorded, lockHeld, server, outcome }) =>
770 provideCliTestLayers(
771 Effect.gen(function* () {
772 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-revoke-test-"));
773 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
774 const issued = JSON.parse(
775 yield* captureStdout(
776 runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
777 ),
778 ) as { readonly sessionId: string };
779 if (recorded) {
780 // A port just released has no listener, so connecting to it is refused.
781 const port = yield* (yield* NetService.NetService).reserveLoopbackPort("127.0.0.1");
782 yield* persistServerRuntimeState({
783 path: statePath,
784 // An owner id skips the legacy liveness probe, so only the lock decides.
785 state: {
786 ...baseState,
787 pid: process.pid,
788 ownerId: "test-owner",
789 port,
790 origin: `http://127.0.0.1:${port}`,
791 },
792 });
793 }
794 if (lockHeld) {
795 yield* ServerOwnership.acquireServerOwnership(statePath).pipe(
796 Effect.provide(ProcessRunner.layer),
797 );
798 }
799
800 const requests: Array<{ readonly path: string; readonly body: unknown }> = [];
801 const requestStarted = Promise.withResolvers<void>();
802 const fetch: typeof globalThis.fetch | undefined =
803 server === "answers" || server === "fails"
804 ? async (input, init) => {
805 requests.push({
806 path: new URL(String(input)).pathname,
807 body: JSON.parse(String(init?.body)),
808 });
809 return server === "answers"
810 ? Response.json({ revoked: true })
811 : new Response(null, { status: 502 });
812 }
813 : server === "hangs"
814 ? (_input, init) => {
815 requestStarted.resolve();
816 return new Promise((_resolve, reject) =>
817 init?.signal?.addEventListener("abort", () => reject(init.signal?.reason)),
818 );
819 }
820 : undefined;
821 const revoke = runCli([
822 "auth",
823 "session",
824 "revoke",
825 "--base-dir",
826 baseDir,
827 issued.sessionId,
828 ]);
829 const running = yield* (
830 fetch === undefined
831 ? revoke
832 : revoke.pipe(Effect.provideService(FetchHttpClient.Fetch, fetch))
833 ).pipe(Effect.exit, Effect.forkChild);
834 if (server === "hangs") {
835 yield* Effect.promise(() => requestStarted.promise);
836 yield* TestClock.adjust("30 seconds");
837 }
838 const exit = yield* Fiber.join(running);
839 const listed = JSON.parse(
840 yield* captureStdout(
841 runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
842 ),
843 ) as ReadonlyArray<{ readonly sessionId: string }>;
844
845 assert.deepEqual(
846 requests,
847 server === "answers" || server === "fails"
848 ? [{ path: "/api/auth/clients/revoke", body: { sessionId: issued.sessionId } }]
849 : [],
850 );
851 if (outcome === "revoked by server" || outcome === "revoked locally") {
852 assert.isTrue(Exit.isSuccess(exit));
853 } else {
854 assert.include(Cause.pretty(Exit.isFailure(exit) ? exit.cause : Cause.empty), outcome);
855 }
856 // The stub server revokes nothing, and the CLI's own session is gone either way.
857 assert.deepEqual(
858 listed.map((session) => session.sessionId),
859 outcome === "revoked locally" ? [] : [issued.sessionId],
860 );
861 }).pipe(Effect.scoped),
862 ),
863 );
864});
865
866describe("auth scope options", () => {
867 it.effect.each([
868 { group: "pairing", action: "create" },
869 { group: "session", action: "issue" },
870 ] as const)(
871 "issues and persists only the selected scopes for auth $group $action",
872 ({ group, action }) =>
873 Effect.gen(function* () {
874 const baseDir = NodeFS.mkdtempSync(
875 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
876 );
877 const output = yield* captureStdout(
878 runCli([
879 "auth",
880 group,
881 action,
882 "--base-dir",
883 baseDir,
884 "--json",
885 "--scope",
886 "orchestration:read",
887 "--scope",
888 "access:read",
889 "--scope",
890 "orchestration:read",
891 ]),
892 );
893 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
894 const listOutput = yield* captureStdout(
895 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
896 );
897 const listed = JSON.parse(listOutput) as ReadonlyArray<{
898 readonly scopes: ReadonlyArray<string>;
899 }>;
900
901 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
902 assert.lengthOf(listed, 1);
903 assert.deepEqual(listed[0]?.scopes, issued.scopes);
904 }),
905 );
906
907 it.effect.each(
908 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
909 command,
910 label: command.join(" "),
911 })),
912 )("rejects invalid scopes before running $label", ({ command }) =>
913 Effect.gen(function* () {
914 const error = yield* runCli([
915 ...command,
916 "--scope",
917 "orchestration:read",
918 "--scope",
919 "admin",
920 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
921
922 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
923 assert.fail(`Expected ShowHelp, got ${String(error)}`);
924 }
925 assert.deepEqual(error.commandPath, ["t3", ...command]);
926 const scopeError = error.errors[0];
927 if (scopeError?._tag !== "InvalidValue") {
928 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
929 }
930 assert.equal(scopeError.option, "scope");
931 assert.equal(scopeError.value, "admin");
932 }),
933 );
934});
935
936describe("auth pairing create --base-url", () => {
937 it.effect.each(["192.168.1.5:3773", "localhost:3773", "ftp://localhost:3773"])(
938 "rejects %s before issuing a token",
939 (baseUrl) =>
940 Effect.gen(function* () {
941 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
942 const error = yield* runCli([
943 "auth",
944 "pairing",
945 "create",
946 "--base-dir",
947 baseDir,
948 "--base-url",
949 baseUrl,
950 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
951
952 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
953 assert.fail(`Expected ShowHelp, got ${String(error)}`);
954 }
955 const flagError = error.errors[0];
956 if (flagError?._tag !== "InvalidValue") {
957 assert.fail(`Expected InvalidValue, got ${String(flagError?._tag)}`);
958 }
959 assert.equal(flagError.option, "base-url");
960 assert.equal(flagError.value, baseUrl);
961
962 const listOutput = yield* captureStdout(
963 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
964 );
965 assert.deepEqual(JSON.parse(listOutput), []);
966 }),
967 );
968
969 it.effect.each(["http://192.168.1.5:3773", "https://example.com", "http:localhost:3773"])(
970 "prints a pair URL for %s",
971 (baseUrl) =>
972 Effect.gen(function* () {
973 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
974 const output = yield* captureStdout(
975 runCli([
976 "auth",
977 "pairing",
978 "create",
979 "--base-dir",
980 baseDir,
981 "--base-url",
982 baseUrl,
983 "--json",
984 ]),
985 );
986 const issued = JSON.parse(output) as {
987 readonly credential: string;
988 readonly pairUrl: string;
989 };
990
991 assert.equal(issued.pairUrl, `${new URL(baseUrl).origin}/pair#token=${issued.credential}`);
992 }),
993 );
994});
995
996describe("scripted auth output", () => {
997 it.effect.each(
998 [
999 ["auth", "session", "issue", "--token-only"],
1000 ["auth", "session", "list", "--json"],
1001 ["auth", "pairing", "list", "--json"],
1002 ].map((command) => ({ command, label: command.join(" ") })),
1003 )("prints only the result for $label after removing an abandoned upload", ({ command }) =>
1004 Effect.gen(function* () {
1005 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-quiet-test-"));
1006 const attachmentsDir = NodePath.join(baseDir, "userdata", "attachments");
1007 NodeFS.mkdirSync(attachmentsDir, { recursive: true });
1008 // An abandoned upload makes config resolution log that it removed it.
1009 const abandoned = NodePath.join(attachmentsDir, "abandoned.part");
1010 NodeFS.writeFileSync(abandoned, "");
1011 const jan2020Seconds = 1_577_836_800;
1012 NodeFS.utimesSync(abandoned, jan2020Seconds, jan2020Seconds);
1013 // The sweep reads Clock, so a week past the upload's mtime makes it expired.
1014 yield* TestClock.setTime((jan2020Seconds + 7 * 24 * 60 * 60) * 1000);
1015
1016 const lines = yield* provideCliTestLayers(
1017 Effect.gen(function* () {
1018 yield* runCli([...command, "--base-dir", baseDir]);
1019 return yield* TestConsole.logLines;
1020 }),
1021 );
1022
1023 assert.isFalse(NodeFS.existsSync(abandoned));
1024 assert.lengthOf(lines, 1);
1025 const output = String(lines[0]);
1026 if (command.includes("--json")) {
1027 assert.deepEqual(JSON.parse(output), []);
1028 } else {
1029 assert.match(output.trim(), /^[\w-]+\.[\w-]+/);
1030 }
1031 }),
1032 );
1033});