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

pair.test.ts

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