The best way to control Claude Code, Codex and more from any computer or phone

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