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