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

pair.test.ts

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