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

pair.test.ts

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