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 Layer from "effect/Layer";
18import * as Sink from "effect/Sink";
19import * as Stream from "effect/Stream";
20import { FetchHttpClient } from "effect/http";
21import { ChildProcess, ChildProcessSpawner } from "effect/process";
22import * as TestClock from "effect/testing/TestClock";
23import * as TestConsole from "effect/testing/TestConsole";
24import { Command, CliError } from "effect/cli";
25
26import { cli } from "../binCli.ts";
27import {
28 SERVICE_LAUNCHER_CONTEXT_ENV,
29 SERVICE_LAUNCHER_PROTOCOL,
30} from "../cloud/serviceProtocol.ts";
31import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
32import {
33 makePersistedServerRuntimeState,
34 persistServerRuntimeState,
35 type PersistedServerRuntimeState,
36} from "../serverRuntimeState.ts";
37import { resolveHostCliCommand } from "./invocation.ts";
38import {
39 DevServerNotProxiableError,
40 resolveTailscaleLocalTarget,
41 ServePortOccupiedError,
42} from "./pair.ts";
43
44import packageJson from "../../package.json" with { type: "json" };
45import { buildPairingAppLink } from "@t3tools/shared/remote";
46
47const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer);
48
49const baseState = {
50 version: 1,
51 pid: 123,
52 port: 3_773,
53 origin: "http://127.0.0.1:3773",
54 startedAt: "2026-06-20T00:00:00.000Z",
55} as const satisfies PersistedServerRuntimeState;
56
57describe("pair tailscale local target", () => {
58 it("proxies the dev web port for dev servers", () => {
59 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
60 { localPort: 5_733 },
61 );
62 // tailscale serve defaults to loopback, so non-loopback dev servers need an explicit target.
63 expect(
64 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
65 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
66 expect(
67 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
68 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
69 });
70
71 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
72 expect(
73 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
74 ).toBeInstanceOf(DevServerNotProxiableError);
75 });
76});
77
78const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
79
80const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
81 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
82
83const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
84 provideCliTestLayers(
85 Effect.gen(function* () {
86 yield* effect;
87 return (
88 (yield* TestConsole.logLines).findLast(
89 (line): line is string => typeof line === "string",
90 ) ?? ""
91 );
92 }),
93 );
94
95const testDescriptor = {
96 environmentId: "pair-test-environment",
97 label: "pair-test",
98 platform: { os: "linux", arch: "x64" },
99 serverVersion: "0.0.1",
100 orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
101 capabilities: { repositoryIdentity: true },
102};
103
104const withDescriptorServer = <A, E, R>(
105 run: (origin: string) => Effect.Effect<A, E, R>,
106 host = "127.0.0.1",
107 descriptor: object = testDescriptor,
108) =>
109 Effect.acquireUseRelease(
110 Effect.callback<NodeHttp.Server>((resume) => {
111 const server = NodeHttp.createServer((request, response) => {
112 if (request.url === "/.well-known/t3/environment") {
113 response.writeHead(200, { "content-type": "application/json" });
114 response.end(JSON.stringify(descriptor));
115 return;
116 }
117 response.writeHead(404);
118 response.end();
119 });
120 server.listen(0, host, () => resume(Effect.succeed(server)));
121 }),
122 (server) => {
123 const address = server.address();
124 if (address === null || typeof address === "string") {
125 return Effect.die(new Error("Expected a TCP address"));
126 }
127 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
128 },
129 (server) => Effect.sync(() => server.close()),
130 );
131
132describe("t3 pair", () => {
133 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
134 withDescriptorServer(
135 (origin) =>
136 Effect.gen(function* () {
137 const fetch = yield* FetchHttpClient.Fetch;
138 let serving = false;
139 const spawner = ChildProcessSpawner.make((command) =>
140 Effect.gen(function* () {
141 if (!ChildProcess.isStandardCommand(command))
142 return yield* Effect.die("Unexpected pipeline");
143 if (command.args[0] === "serve" && command.args[1] === "--bg") {
144 const target = String(command.args.at(-1));
145 const descriptor = yield* Effect.promise(async () =>
146 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
147 );
148 expect(descriptor).toEqual(testDescriptor);
149 serving = true;
150 }
151 return ChildProcessSpawner.makeHandle({
152 pid: ChildProcessSpawner.ProcessId(1),
153 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
154 isRunning: Effect.succeed(false),
155 kill: () => Effect.void,
156 unref: Effect.succeed(Effect.void),
157 stdin: Sink.drain,
158 stdout: Stream.make(
159 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
160 ),
161 stderr: Stream.empty,
162 all: Stream.empty,
163 getInputFd: () => Sink.drain,
164 getOutputFd: () => Stream.empty,
165 });
166 }),
167 );
168
169 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
170 yield* persistServerRuntimeState({
171 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
172 state: yield* makePersistedServerRuntimeState({
173 config: { host: "::1", devUrl: undefined },
174 port: Number(new URL(origin).port),
175 }),
176 });
177 const output = yield* captureStdout(
178 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
179 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
180 Effect.provideService(HostProcess.Platform, "linux"),
181 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
182 if (String(input).startsWith(origin)) return fetch(input, init);
183 assert.equal(
184 String(input),
185 "https://pair-test.tail.ts.net/.well-known/t3/environment",
186 );
187 return serving
188 ? Response.json(testDescriptor)
189 : new Response(null, { status: 503 });
190 }),
191 ),
192 );
193
194 expect(serving).toBe(true);
195 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
196 }),
197 "::1",
198 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
199 );
200
201 // The MagicDNS probe fails whenever the host cannot reach its own *.ts.net name,
202 // so it cannot be what decides that the port is free.
203 it.effect(
204 "leaves another app's Serve route alone when the host cannot reach its MagicDNS URL",
205 () =>
206 withDescriptorServer((origin) =>
207 // Another live app on loopback; a dead port's route may be taken back.
208 withDescriptorServer((otherAppOrigin) =>
209 Effect.gen(function* () {
210 const fetch = yield* FetchHttpClient.Fetch;
211 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
212 const spawner = ChildProcessSpawner.make((command) => {
213 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
214 tailscaleCalls.push(args);
215 const stdout =
216 args[0] === "status"
217 ? '{"BackendState":"Running","Self":{"DNSName":"host-a.tail.ts.net.","TailscaleIPs":["100.64.0.1"],"CapMap":{"https":null}}}'
218 : args[0] === "serve" && args[1] === "status"
219 ? JSON.stringify({
220 TCP: { "443": { HTTPS: true } },
221 Web: {
222 "host-a.tail.ts.net:443": {
223 Handlers: { "/": { Proxy: otherAppOrigin } },
224 },
225 },
226 })
227 : "";
228 return Effect.succeed(
229 ChildProcessSpawner.makeHandle({
230 pid: ChildProcessSpawner.ProcessId(1),
231 // A recorded takeover fails fast instead of waiting out the HTTPS retries.
232 exitCode: Effect.succeed(
233 ChildProcessSpawner.ExitCode(
234 args[0] === "serve" && args[1] !== "status" ? 1 : 0,
235 ),
236 ),
237 isRunning: Effect.succeed(false),
238 kill: () => Effect.void,
239 unref: Effect.succeed(Effect.void),
240 stdin: Sink.drain,
241 stdout: Stream.make(new TextEncoder().encode(stdout)),
242 stderr: Stream.empty,
243 all: Stream.empty,
244 getInputFd: () => Sink.drain,
245 getOutputFd: () => Stream.empty,
246 }),
247 );
248 });
249
250 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-held-"));
251 yield* persistServerRuntimeState({
252 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
253 state: yield* makePersistedServerRuntimeState({
254 config: { host: "127.0.0.1", devUrl: undefined },
255 port: Number(new URL(origin).port),
256 }),
257 });
258
259 const exit = yield* runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
260 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
261 Effect.provideService(HostProcess.Platform, "linux"),
262 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
263 if (String(input).startsWith(origin)) return fetch(input, init);
264 throw new TypeError("getaddrinfo ENOTFOUND host-a.tail.ts.net");
265 }),
266 Effect.exit,
267 );
268
269 assert.deepEqual(
270 tailscaleCalls.filter((args) => args[0] === "serve" && args[1] !== "status"),
271 [],
272 );
273 assert.isTrue(Exit.isFailure(exit));
274 if (Exit.isFailure(exit)) {
275 assert.instanceOf(Cause.squash(exit.cause), ServePortOccupiedError);
276 }
277 }),
278 ),
279 ).pipe(Effect.provide(layerCliRuntime)),
280 );
281
282 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
283 withDescriptorServer((origin) =>
284 Effect.gen(function* () {
285 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
286 const port = Number(new URL(origin).port);
287 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
288 yield* persistServerRuntimeState({
289 path: statePath,
290 state: yield* makePersistedServerRuntimeState({
291 config: { host: "127.0.0.1", devUrl: undefined },
292 port,
293 }),
294 });
295
296 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
297
298 assert.include(output, `Pairing with pair-test (${origin})`);
299 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
300 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
301 assert.include(output, "only reachable from this machine");
302
303 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
304 assert.isString(token);
305 assert.include(output, `App link: ${buildPairingAppLink(`${origin}/pair#token=${token}`)}`);
306
307 const listed = yield* captureStdout(
308 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
309 );
310 const credentials = JSON.parse(listed) as ReadonlyArray<{
311 readonly label?: string;
312 readonly scopes: ReadonlyArray<string>;
313 }>;
314 assert.equal(credentials.length, 1);
315 assert.equal(credentials[0]?.label, "t3 pair");
316 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
317 }),
318 ).pipe(
319 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
320 Effect.provideService(HostProcess.Environment, {
321 ...process.env,
322 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
323 protocol: SERVICE_LAUNCHER_PROTOCOL,
324 childVersion: packageJson.version,
325 }),
326 }),
327 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
328 connected: false,
329 send: () => false,
330 on: () => undefined,
331 off: () => undefined,
332 }),
333 ),
334 );
335
336 it.effect("pairs through the recorded dev web URL for dev servers", () =>
337 withDescriptorServer((origin) =>
338 Effect.gen(function* () {
339 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
340 const port = Number(new URL(origin).port);
341 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
342 yield* persistServerRuntimeState({
343 path: statePath,
344 state: yield* makePersistedServerRuntimeState({
345 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
346 port,
347 }),
348 });
349
350 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
351
352 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
353 }),
354 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
355 );
356
357 it.effect("refuses --tailscale before turning on Serve when the policy keeps clients local", () =>
358 withDescriptorServer((origin) =>
359 Effect.gen(function* () {
360 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-policy-test-"));
361 const policyPath = NodePath.join(baseDir, "policy.json");
362 NodeFS.writeFileSync(
363 policyPath,
364 JSON.stringify({
365 schemaVersion: 1,
366 organization: "Example Corp",
367 limits: { clients: ["desktop", "local-browser"] },
368 }),
369 );
370 yield* persistServerRuntimeState({
371 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
372 state: yield* makePersistedServerRuntimeState({
373 config: { host: "127.0.0.1", devUrl: undefined },
374 port: Number(new URL(origin).port),
375 }),
376 });
377
378 const error = yield* provideCliTestLayers(
379 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
380 Effect.provideService(
381 ChildProcessSpawner.ChildProcessSpawner,
382 ChildProcessSpawner.make(() => Effect.die("tailscale must not run")),
383 ),
384 Effect.provide(
385 ConfigProvider.layer(
386 ConfigProvider.fromEnv({ env: { T3CODE_DEV_MANAGED_POLICY_PATH: policyPath } }),
387 ),
388 ),
389 Effect.flip,
390 ),
391 );
392
393 assert.include(
394 String(error),
395 "Example Corp's policy does not allow remote clients, so Tailscale Serve cannot be turned on.",
396 );
397 }),
398 ).pipe(Effect.provide(NodeServices.layer)),
399 );
400
401 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
402 withDescriptorServer((origin) =>
403 Effect.gen(function* () {
404 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3 pair pid test-"));
405 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
406 const state = yield* makePersistedServerRuntimeState({
407 config: { host: "127.0.0.1", devUrl: undefined },
408 port: Number(new URL(origin).port),
409 });
410 yield* persistServerRuntimeState({
411 path: statePath,
412 state: { ...state, pid: 4_194_305 },
413 });
414
415 const error = yield* provideCliTestLayers(
416 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
417 );
418
419 const rendered = String(
420 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
421 );
422 assert.include(rendered, "No running T3 Code server found.");
423 for (const subcommand of ["serve", "connect"]) {
424 const { command } = yield* resolveHostCliCommand(subcommand, ["--base-dir", baseDir]);
425 assert.include(rendered, `\`${command}\``);
426 }
427 }),
428 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
429 );
430
431 // regression: #10516 minting opens the target database with this checkout's
432 // migrations, so a worktree must never fall back to the live install.
433 it.effect("does not fall back to the shared home from a linked worktree", () =>
434 withDescriptorServer((origin) =>
435 Effect.gen(function* () {
436 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-worktree-test-"));
437 const worktree = NodePath.join(root, "worktree");
438 NodeFS.mkdirSync(worktree);
439 NodeFS.writeFileSync(
440 NodePath.join(worktree, ".git"),
441 `gitdir: ${NodePath.join(root, "repo", ".git", "worktrees", "worktree")}\n`,
442 );
443 const sharedHome = NodePath.join(root, "shared");
444 yield* persistServerRuntimeState({
445 path: NodePath.join(sharedHome, "userdata", "server-runtime.json"),
446 state: yield* makePersistedServerRuntimeState({
447 config: { host: "127.0.0.1", devUrl: undefined },
448 port: Number(new URL(origin).port),
449 }),
450 });
451
452 const error = yield* provideCliTestLayers(
453 runCli(["pair"]).pipe(
454 Effect.provideService(HostProcess.WorkingDirectory, worktree),
455 Effect.provide(
456 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_HOME: sharedHome } })),
457 ),
458 Effect.flip,
459 ),
460 );
461
462 assert.include(String(error), "No running T3 Code server found.");
463 assert.notInclude(String(error), sharedHome);
464 assert.deepEqual(NodeFS.readdirSync(NodePath.join(sharedHome, "userdata")), [
465 "server-runtime.json",
466 ]);
467 }),
468 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
469 );
470
471 // regression: #15492 an older CLI minted into a V1 database the protocol 2
472 // server never reads, so pairing must refuse before opening the database.
473 it.effect("rejects a server on another protocol before opening its database", () =>
474 withDescriptorServer(
475 (origin) =>
476 Effect.gen(function* () {
477 const baseDir = NodeFS.mkdtempSync(
478 NodePath.join(NodeOS.tmpdir(), "t3-pair-protocol-test-"),
479 );
480 yield* persistServerRuntimeState({
481 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
482 state: yield* makePersistedServerRuntimeState({
483 config: { host: "127.0.0.1", devUrl: undefined },
484 port: Number(new URL(origin).port),
485 }),
486 });
487
488 const exit = yield* provideCliTestLayers(
489 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.exit),
490 );
491
492 assert.deepEqual(NodeFS.readdirSync(NodePath.join(baseDir, "userdata")), [
493 "server-runtime.json",
494 ]);
495 assert.isTrue(Exit.isFailure(exit));
496 if (Exit.isFailure(exit)) {
497 assert.include(String(Cause.squash(exit.cause)), "t3@0.0.45 pair");
498 }
499 }),
500 "127.0.0.1",
501 { ...testDescriptor, serverVersion: "0.0.45", orchestrationProtocolVersion: 1 },
502 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
503 );
504
505 // Without the capability `tailscale serve` blocks on an enablement URL, so
506 // pairing must stop at status instead of spawning it.
507 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
508 withDescriptorServer((origin) =>
509 Effect.gen(function* () {
510 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
511 yield* persistServerRuntimeState({
512 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
513 state: yield* makePersistedServerRuntimeState({
514 config: { host: "127.0.0.1", devUrl: undefined },
515 port: Number(new URL(origin).port),
516 }),
517 });
518 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
519 const spawner = ChildProcessSpawner.make((command) => {
520 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
521 tailscaleCalls.push(args);
522 const stdout =
523 args[0] === "status"
524 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
525 : "";
526 return Effect.succeed(
527 ChildProcessSpawner.makeHandle({
528 pid: ChildProcessSpawner.ProcessId(1),
529 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
530 isRunning: Effect.succeed(false),
531 kill: () => Effect.void,
532 unref: Effect.succeed(Effect.void),
533 stdin: Sink.drain,
534 stdout: Stream.make(new TextEncoder().encode(stdout)),
535 stderr: Stream.empty,
536 all: Stream.empty,
537 getInputFd: () => Sink.drain,
538 getOutputFd: () => Stream.empty,
539 }),
540 );
541 });
542
543 const error = yield* provideCliTestLayers(
544 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
545 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
546 Effect.flip,
547 ),
548 );
549
550 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
551 assert.include(String(error), "https://login.tailscale.com/admin/dns");
552 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
553 }),
554 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
555 );
556
557 // regression: #35517 - the macOS Tailscale apps refuse Serve targets other than
558 // localhost, 127.0.0.1 and ::1, so a specific bind needs an explanation.
559 it.effect("names the bind address when Tailscale refuses it as a Serve target", () =>
560 withDescriptorServer(
561 (origin) =>
562 Effect.gen(function* () {
563 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-"));
564 yield* persistServerRuntimeState({
565 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
566 state: yield* makePersistedServerRuntimeState({
567 config: { host: "127.0.0.2", devUrl: undefined },
568 port: Number(new URL(origin).port),
569 }),
570 });
571 const spawner = ChildProcessSpawner.make((command) => {
572 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
573 const serve = args[0] === "serve" && args[1] !== "status";
574 return Effect.succeed(
575 ChildProcessSpawner.makeHandle({
576 pid: ChildProcessSpawner.ProcessId(1),
577 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(serve ? 1 : 0)),
578 isRunning: Effect.succeed(false),
579 kill: () => Effect.void,
580 unref: Effect.succeed(Effect.void),
581 stdin: Sink.drain,
582 stdout: Stream.make(
583 new TextEncoder().encode(
584 serve
585 ? ""
586 : args[0] === "serve"
587 ? "{}"
588 : '{"Self":{"DNSName":"pair-test.tail.ts.net."}}',
589 ),
590 ),
591 stderr: Stream.make(
592 new TextEncoder().encode(
593 serve
594 ? "Warning: the MacOS extension doesn't support connecting to remote destinations from non-default route\n"
595 : "",
596 ),
597 ),
598 all: Stream.empty,
599 getInputFd: () => Sink.drain,
600 getOutputFd: () => Stream.empty,
601 }),
602 );
603 });
604
605 const error = yield* provideCliTestLayers(
606 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
607 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
608 Effect.provideService(HostProcess.Platform, "darwin"),
609 Effect.flip,
610 ),
611 );
612
613 assert.include(String(error), "127.0.0.2");
614 }),
615 "127.0.0.2",
616 ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
617 );
618});
619
620describe("auth scope options", () => {
621 it.effect.each([
622 { group: "pairing", action: "create" },
623 { group: "session", action: "issue" },
624 ] as const)(
625 "issues and persists only the selected scopes for auth $group $action",
626 ({ group, action }) =>
627 Effect.gen(function* () {
628 const baseDir = NodeFS.mkdtempSync(
629 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
630 );
631 const output = yield* captureStdout(
632 runCli([
633 "auth",
634 group,
635 action,
636 "--base-dir",
637 baseDir,
638 "--json",
639 "--scope",
640 "orchestration:read",
641 "--scope",
642 "access:read",
643 "--scope",
644 "orchestration:read",
645 ]),
646 );
647 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
648 const listOutput = yield* captureStdout(
649 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
650 );
651 const listed = JSON.parse(listOutput) as ReadonlyArray<{
652 readonly scopes: ReadonlyArray<string>;
653 }>;
654
655 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
656 assert.lengthOf(listed, 1);
657 assert.deepEqual(listed[0]?.scopes, issued.scopes);
658 }),
659 );
660
661 it.effect.each(
662 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
663 command,
664 label: command.join(" "),
665 })),
666 )("rejects invalid scopes before running $label", ({ command }) =>
667 Effect.gen(function* () {
668 const error = yield* runCli([
669 ...command,
670 "--scope",
671 "orchestration:read",
672 "--scope",
673 "admin",
674 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
675
676 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
677 assert.fail(`Expected ShowHelp, got ${String(error)}`);
678 }
679 assert.deepEqual(error.commandPath, ["t3", ...command]);
680 const scopeError = error.errors[0];
681 if (scopeError?._tag !== "InvalidValue") {
682 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
683 }
684 assert.equal(scopeError.option, "scope");
685 assert.equal(scopeError.value, "admin");
686 }),
687 );
688});
689
690describe("auth pairing create --base-url", () => {
691 it.effect.each(["192.168.1.5:3773", "localhost:3773", "ftp://localhost:3773"])(
692 "rejects %s before issuing a token",
693 (baseUrl) =>
694 Effect.gen(function* () {
695 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
696 const error = yield* runCli([
697 "auth",
698 "pairing",
699 "create",
700 "--base-dir",
701 baseDir,
702 "--base-url",
703 baseUrl,
704 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
705
706 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
707 assert.fail(`Expected ShowHelp, got ${String(error)}`);
708 }
709 const flagError = error.errors[0];
710 if (flagError?._tag !== "InvalidValue") {
711 assert.fail(`Expected InvalidValue, got ${String(flagError?._tag)}`);
712 }
713 assert.equal(flagError.option, "base-url");
714 assert.equal(flagError.value, baseUrl);
715
716 const listOutput = yield* captureStdout(
717 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
718 );
719 assert.deepEqual(JSON.parse(listOutput), []);
720 }),
721 );
722
723 it.effect.each(["http://192.168.1.5:3773", "https://example.com", "http:localhost:3773"])(
724 "prints a pair URL for %s",
725 (baseUrl) =>
726 Effect.gen(function* () {
727 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-base-url-test-"));
728 const output = yield* captureStdout(
729 runCli([
730 "auth",
731 "pairing",
732 "create",
733 "--base-dir",
734 baseDir,
735 "--base-url",
736 baseUrl,
737 "--json",
738 ]),
739 );
740 const issued = JSON.parse(output) as {
741 readonly credential: string;
742 readonly pairUrl: string;
743 };
744
745 assert.equal(issued.pairUrl, `${new URL(baseUrl).origin}/pair#token=${issued.credential}`);
746 }),
747 );
748});
749
750describe("scripted auth output", () => {
751 it.effect.each(
752 [
753 ["auth", "session", "issue", "--token-only"],
754 ["auth", "session", "list", "--json"],
755 ["auth", "pairing", "list", "--json"],
756 ].map((command) => ({ command, label: command.join(" ") })),
757 )("prints only the result for $label after removing an abandoned upload", ({ command }) =>
758 Effect.gen(function* () {
759 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cli-quiet-test-"));
760 const attachmentsDir = NodePath.join(baseDir, "userdata", "attachments");
761 NodeFS.mkdirSync(attachmentsDir, { recursive: true });
762 // An abandoned upload makes config resolution log that it removed it.
763 const abandoned = NodePath.join(attachmentsDir, "abandoned.part");
764 NodeFS.writeFileSync(abandoned, "");
765 const jan2020Seconds = 1_577_836_800;
766 NodeFS.utimesSync(abandoned, jan2020Seconds, jan2020Seconds);
767 // The sweep reads Clock, so a week past the upload's mtime makes it expired.
768 yield* TestClock.setTime((jan2020Seconds + 7 * 24 * 60 * 60) * 1000);
769
770 const lines = yield* provideCliTestLayers(
771 Effect.gen(function* () {
772 yield* runCli([...command, "--base-dir", baseDir]);
773 return yield* TestConsole.logLines;
774 }),
775 );
776
777 assert.isFalse(NodeFS.existsSync(abandoned));
778 assert.lengthOf(lines, 1);
779 const output = String(lines[0]);
780 if (command.includes("--json")) {
781 assert.deepEqual(JSON.parse(output), []);
782 } else {
783 assert.match(output.trim(), /^[\w-]+\.[\w-]+/);
784 }
785 }),
786 );
787});