Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pair.test.ts

518 lines19.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
2import * as NodeHttp from "node:http";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { AuthStandardClientScopes } from "@t3tools/contracts";
9import * as NetService from "@t3tools/shared/Net";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { assert, describe, expect, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import { FetchHttpClient } from "effect/http";
17import { ChildProcess, ChildProcessSpawner } from "effect/process";
18import * as TestConsole from "effect/testing/TestConsole";
19import { Command, CliError } from "effect/cli";
20​
21import { cli } from "../binCli.ts";
22import {
23 SERVICE_LAUNCHER_CONTEXT_ENV,
24 SERVICE_LAUNCHER_PROTOCOL,
25} from "../cloud/serviceProtocol.ts";
26import * as ServiceLauncherClient from "../cloud/serviceLauncherClient.ts";
27import {
28 makePersistedServerRuntimeState,
29 persistServerRuntimeState,
30 type PersistedServerRuntimeState,
31} from "../serverRuntimeState.ts";
32import {
33 DevServerNotProxiableError,
34 resolveDirectPairingBaseUrl,
35 resolveTailscaleLocalTarget,
36} from "./pair.ts";
37​
38import packageJson from "../../package.json" with { type: "json" };
39​
40const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
41​
42const baseState = {
43 version: 1,
44 pid: 123,
45 port: 3_773,
46 origin: "http://127.0.0.1:3773",
47 startedAt: "2026-06-20T00:00:00.000Z",
48} as const satisfies PersistedServerRuntimeState;
49​
50describe("pair base URL selection", () => {
51 it("pairs through the dev web origin when the server fronts a dev server", () => {
52 expect(resolveDirectPairingBaseUrl({ ...baseState, devUrl: "http://localhost:5733/" })).toBe(
53 "http://localhost:5733/",
54 );
55 });
56​
57 it("pairs through the bound host when there is no dev server", () => {
58 expect(resolveDirectPairingBaseUrl({ ...baseState, host: "100.64.0.7" })).toBe(
59 "http://100.64.0.7:3773",
60 );
61 expect(resolveDirectPairingBaseUrl(baseState)).toBe("http://localhost:3773");
62 });
63});
64​
65describe("pair tailscale local target", () => {
66 it("proxies the dev web port for dev servers", () => {
67 expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
68 { localPort: 5_733 },
69 );
70 // A dev server on a non-loopback interface must be proxied at that
71 // interface; tailscale serve defaults to 127.0.0.1 otherwise.
72 expect(
73 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://192.168.1.10:5733/" }),
74 ).toEqual({ localPort: 5_733, localHost: "192.168.1.10" });
75 // URL.hostname keeps IPv6 brackets, so the serve target stays valid.
76 expect(
77 resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://[fd7a:115c::1]:5733/" }),
78 ).toEqual({ localPort: 5_733, localHost: "[fd7a:115c::1]" });
79 });
80​
81 it("rejects HTTPS dev URLs, which tailscale serve cannot proxy", () => {
82 expect(
83 resolveTailscaleLocalTarget({ ...baseState, devUrl: "https://localhost:5733/" }),
84 ).toBeInstanceOf(DevServerNotProxiableError);
85 });
86​
87 it("proxies the backend port directly otherwise", () => {
88 expect(resolveTailscaleLocalTarget(baseState)).toEqual({ localPort: 3_773 });
89 expect(resolveTailscaleLocalTarget({ ...baseState, host: "0.0.0.0" })).toEqual({
90 localPort: 3_773,
91 });
92 expect(resolveTailscaleLocalTarget({ ...baseState, host: "192.168.1.42" })).toEqual({
93 localPort: 3_773,
94 localHost: "192.168.1.42",
95 });
96 });
97});
98​
99const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
100​
101const provideCliTestLayers = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
102 Effect.provide(effect, Layer.mergeAll(layerCliRuntime, TestConsole.layer));
103​
104const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
105 provideCliTestLayers(
106 Effect.gen(function* () {
107 yield* effect;
108 return (
109 (yield* TestConsole.logLines).findLast(
110 (line): line is string => typeof line === "string",
111 ) ?? ""
112 );
113 }),
114 );
115​
116const testDescriptor = {
117 environmentId: "pair-test-environment",
118 label: "pair-test",
119 platform: { os: "linux", arch: "x64" },
120 serverVersion: "0.0.1",
121 capabilities: { repositoryIdentity: true },
122};
123​
124const withDescriptorServer = <A, E, R>(
125 run: (origin: string) => Effect.Effect<A, E, R>,
126 host = "127.0.0.1",
127) =>
128 Effect.acquireUseRelease(
129 Effect.callback<NodeHttp.Server>((resume) => {
130 const server = NodeHttp.createServer((request, response) => {
131 if (request.url === "/.well-known/t3/environment") {
132 response.writeHead(200, { "content-type": "application/json" });
133 response.end(JSON.stringify(testDescriptor));
134 return;
135 }
136 response.writeHead(404);
137 response.end();
138 });
139 server.listen(0, host, () => resume(Effect.succeed(server)));
140 }),
141 (server) => {
142 const address = server.address();
143 if (address === null || typeof address === "string") {
144 return Effect.die(new Error("Expected a TCP address"));
145 }
146 return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
147 },
148 (server) => Effect.sync(() => server.close()),
149 );
150​
151describe("t3 pair", () => {
152 it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
153 withDescriptorServer(
154 (origin) =>
155 Effect.gen(function* () {
156 const fetch = yield* FetchHttpClient.Fetch;
157 let serving = false;
158 const spawner = ChildProcessSpawner.make((command) =>
159 Effect.gen(function* () {
160 if (!ChildProcess.isStandardCommand(command))
161 return yield* Effect.die("Unexpected pipeline");
162 if (command.args[0] === "serve") {
163 const target = command.args.at(-1)!;
164 const descriptor = yield* Effect.promise(async () =>
165 (await fetch(new URL("/.well-known/t3/environment", target))).json(),
166 );
167 expect(descriptor).toEqual(testDescriptor);
168 serving = true;
169 }
170 return ChildProcessSpawner.makeHandle({
171 pid: ChildProcessSpawner.ProcessId(1),
172 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
173 isRunning: Effect.succeed(false),
174 kill: () => Effect.void,
175 unref: Effect.succeed(Effect.void),
176 stdin: Sink.drain,
177 stdout: Stream.make(
178 new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
179 ),
180 stderr: Stream.empty,
181 all: Stream.empty,
182 getInputFd: () => Sink.drain,
183 getOutputFd: () => Stream.empty,
184 });
185 }),
186 );
187​
188 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
189 yield* persistServerRuntimeState({
190 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
191 state: yield* makePersistedServerRuntimeState({
192 config: { host: "::1", devUrl: undefined },
193 port: Number(new URL(origin).port),
194 }),
195 });
196 const output = yield* captureStdout(
197 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
198 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
199 Effect.provideService(HostProcess.Platform, "linux"),
200 Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
201 if (String(input).startsWith(origin)) return fetch(input, init);
202 assert.equal(
203 String(input),
204 "https://pair-test.tail.ts.net/.well-known/t3/environment",
205 );
206 return serving
207 ? Response.json(testDescriptor)
208 : new Response(null, { status: 503 });
209 }),
210 ),
211 );
212​
213 expect(serving).toBe(true);
214 assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
215 }),
216 "::1",
217 ).pipe(Effect.provide(NodeServices.layer)),
218 );
219​
220 it.effect("mints a token and prints a QR pairing URL for a live server", () =>
221 withDescriptorServer((origin) =>
222 Effect.gen(function* () {
223 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-test-"));
224 const port = Number(new URL(origin).port);
225 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
226 yield* persistServerRuntimeState({
227 path: statePath,
228 state: yield* makePersistedServerRuntimeState({
229 config: { host: "127.0.0.1", devUrl: undefined },
230 port,
231 }),
232 });
233​
234 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
235​
236 assert.include(output, `Pairing with pair-test (${origin})`);
237 assert.include(output, `Pairing URL: ${origin}/pair#token=`);
238 assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
239 assert.include(output, "only reachable from this machine");
240​
241 const token = /#token=([A-Z2-9]+)/.exec(output)?.[1];
242 assert.isString(token);
243​
244 const listed = yield* captureStdout(
245 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
246 );
247 const credentials = JSON.parse(listed) as ReadonlyArray<{
248 readonly label?: string;
249 readonly scopes: ReadonlyArray<string>;
250 }>;
251 assert.equal(credentials.length, 1);
252 assert.equal(credentials[0]?.label, "t3 pair");
253 assert.deepEqual(credentials[0]?.scopes, AuthStandardClientScopes);
254 }),
255 ).pipe(
256 Effect.provide(NodeServices.layer),
257 Effect.provideService(HostProcess.Environment, {
258 ...process.env,
259 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
260 protocol: SERVICE_LAUNCHER_PROTOCOL,
261 childVersion: packageJson.version,
262 }),
263 }),
264 Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, {
265 connected: false,
266 send: () => false,
267 on: () => undefined,
268 off: () => undefined,
269 }),
270 ),
271 );
272​
273 it.effect("mints a pairing grant with only the selected scopes", () =>
274 withDescriptorServer((origin) =>
275 Effect.gen(function* () {
276 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-scopes-test-"));
277 yield* persistServerRuntimeState({
278 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
279 state: yield* makePersistedServerRuntimeState({
280 config: { host: "127.0.0.1", devUrl: undefined },
281 port: Number(new URL(origin).port),
282 }),
283 });
284​
285 yield* captureStdout(
286 runCli([
287 "pair",
288 "--base-dir",
289 baseDir,
290 "--scope",
291 "orchestration:read",
292 "--scope",
293 "relay:read",
294 "--scope",
295 "orchestration:read",
296 ]),
297 );
298 const listed = yield* captureStdout(
299 runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
300 );
301 const credentials = JSON.parse(listed) as ReadonlyArray<{
302 readonly scopes: ReadonlyArray<string>;
303 }>;
304 assert.lengthOf(credentials, 1);
305 assert.deepEqual(credentials[0]?.scopes, ["orchestration:read", "relay:read"]);
306 }),
307 ).pipe(Effect.provide(NodeServices.layer)),
308 );
309​
310 it.effect("pairs through the recorded dev web URL for dev servers", () =>
311 withDescriptorServer((origin) =>
312 Effect.gen(function* () {
313 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-dev-test-"));
314 const port = Number(new URL(origin).port);
315 const statePath = NodePath.join(baseDir, "dev", "server-runtime.json");
316 yield* persistServerRuntimeState({
317 path: statePath,
318 state: yield* makePersistedServerRuntimeState({
319 config: { host: undefined, devUrl: new URL("http://localhost:5733") },
320 port,
321 }),
322 });
323​
324 const output = yield* captureStdout(runCli(["pair", "--base-dir", baseDir]));
325​
326 assert.include(output, "Pairing URL: http://localhost:5733/pair#token=");
327 }),
328 ).pipe(Effect.provide(NodeServices.layer)),
329 );
330​
331 it.effect("directs to t3 serve or t3 connect when no server is running", () =>
332 Effect.gen(function* () {
333 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));
334​
335 const error = yield* provideCliTestLayers(
336 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
337 );
338​
339 const rendered = String(
340 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
341 );
342 assert.include(rendered, "No running T3 Code server found.");
343 assert.include(rendered, "npx t3 serve");
344 assert.include(rendered, "npx t3 connect");
345 }).pipe(Effect.provide(NodeServices.layer)),
346 );
347​
348 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
349 withDescriptorServer((origin) =>
350 Effect.gen(function* () {
351 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-pid-test-"));
352 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
353 const state = yield* makePersistedServerRuntimeState({
354 config: { host: "127.0.0.1", devUrl: undefined },
355 port: Number(new URL(origin).port),
356 });
357 yield* persistServerRuntimeState({
358 path: statePath,
359 state: { ...state, pid: 4_194_305 },
360 });
361​
362 const error = yield* provideCliTestLayers(
363 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
364 );
365​
366 const rendered = String(
367 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
368 );
369 assert.include(rendered, "No running T3 Code server found.");
370 }),
371 ).pipe(Effect.provide(NodeServices.layer)),
372 );
373​
374 it.effect("ignores stale runtime state pointing at a dead server", () =>
375 Effect.gen(function* () {
376 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-stale-test-"));
377 const statePath = NodePath.join(baseDir, "userdata", "server-runtime.json");
378 yield* persistServerRuntimeState({
379 path: statePath,
380 state: yield* makePersistedServerRuntimeState({
381 config: { host: "127.0.0.1", devUrl: undefined },
382 port: 1,
383 }),
384 });
385​
386 const error = yield* provideCliTestLayers(
387 runCli(["pair", "--base-dir", baseDir]).pipe(Effect.flip),
388 );
389​
390 const rendered = String(
391 typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
392 );
393 assert.include(rendered, "No running T3 Code server found.");
394 }).pipe(Effect.provide(NodeServices.layer)),
395 );
396​
397 // Without the capability `tailscale serve` blocks on an enablement URL, so
398 // pairing must stop at status instead of spawning it.
399 it.effect("explains a tailnet without HTTPS serve instead of running tailscale serve", () =>
400 withDescriptorServer((origin) =>
401 Effect.gen(function* () {
402 const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-test-"));
403 yield* persistServerRuntimeState({
404 path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
405 state: yield* makePersistedServerRuntimeState({
406 config: { host: "127.0.0.1", devUrl: undefined },
407 port: Number(new URL(origin).port),
408 }),
409 });
410 const tailscaleCalls: Array<ReadonlyArray<string>> = [];
411 const spawner = ChildProcessSpawner.make((command) => {
412 const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
413 tailscaleCalls.push(args);
414 const stdout =
415 args[0] === "status"
416 ? `{"Self":{"DNSName":"pair-test.invalid.","CapMap":{"funnel":null}}}`
417 : "";
418 return Effect.succeed(
419 ChildProcessSpawner.makeHandle({
420 pid: ChildProcessSpawner.ProcessId(1),
421 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(args[0] === "status" ? 0 : 1)),
422 isRunning: Effect.succeed(false),
423 kill: () => Effect.void,
424 unref: Effect.succeed(Effect.void),
425 stdin: Sink.drain,
426 stdout: Stream.make(new TextEncoder().encode(stdout)),
427 stderr: Stream.empty,
428 all: Stream.empty,
429 getInputFd: () => Sink.drain,
430 getOutputFd: () => Stream.empty,
431 }),
432 );
433 });
434​
435 const error = yield* provideCliTestLayers(
436 runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
437 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
438 Effect.flip,
439 ),
440 );
441​
442 assert.include(String(error), "Tailscale Serve is not enabled on your tailnet.");
443 assert.include(String(error), "https://login.tailscale.com/admin/dns");
444 assert.deepEqual(tailscaleCalls, [["status", "--json"]]);
445 }),
446 ).pipe(Effect.provide(NodeServices.layer)),
447 );
448});
449​
450describe("auth scope options", () => {
451 it.effect.each([
452 { group: "pairing", action: "create" },
453 { group: "session", action: "issue" },
454 ] as const)(
455 "issues and persists only the selected scopes for auth $group $action",
456 ({ group, action }) =>
457 Effect.gen(function* () {
458 const baseDir = NodeFS.mkdtempSync(
459 NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-scopes-test-"),
460 );
461 const output = yield* captureStdout(
462 runCli([
463 "auth",
464 group,
465 action,
466 "--base-dir",
467 baseDir,
468 "--json",
469 "--scope",
470 "orchestration:read",
471 "--scope",
472 "access:read",
473 "--scope",
474 "orchestration:read",
475 ]),
476 );
477 const issued = JSON.parse(output) as { readonly scopes: ReadonlyArray<string> };
478 const listOutput = yield* captureStdout(
479 runCli(["auth", group, "list", "--base-dir", baseDir, "--json"]),
480 );
481 const listed = JSON.parse(listOutput) as ReadonlyArray<{
482 readonly scopes: ReadonlyArray<string>;
483 }>;
484​
485 assert.deepEqual(issued.scopes, ["orchestration:read", "access:read"]);
486 assert.lengthOf(listed, 1);
487 assert.deepEqual(listed[0]?.scopes, issued.scopes);
488 }),
489 );
490​
491 it.effect.each(
492 [["pair"], ["auth", "pairing", "create"], ["auth", "session", "issue"]].map((command) => ({
493 command,
494 label: command.join(" "),
495 })),
496 )("rejects invalid scopes before running $label", ({ command }) =>
497 Effect.gen(function* () {
498 const error = yield* runCli([
499 ...command,
500 "--scope",
501 "orchestration:read",
502 "--scope",
503 "admin",
504 ]).pipe(Effect.provide(layerCliRuntime), Effect.flip);
505​
506 if (!CliError.isCliError(error) || error._tag !== "ShowHelp") {
507 assert.fail(`Expected ShowHelp, got ${String(error)}`);
508 }
509 assert.deepEqual(error.commandPath, ["t3", ...command]);
510 const scopeError = error.errors[0];
511 if (scopeError?._tag !== "InvalidValue") {
512 assert.fail(`Expected InvalidValue, got ${String(scopeError?._tag)}`);
513 }
514 assert.equal(scopeError.option, "scope");
515 assert.equal(scopeError.value, "admin");
516 }),
517 );
518});