Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary.
2import * as NodeHttp from "node:http";
3
4import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as NetService from "@t3tools/shared/Net";
8import * as RelayClient from "@t3tools/shared/relayClient";
9import { assert, it } from "@effect/vitest";
10import * as ConfigProvider from "effect/ConfigProvider";
11import * as Console from "effect/Console";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as TestConsole from "effect/testing/TestConsole";
17import { Command } from "effect/cli";
18
19import { makeCli } from "../binCli.ts";
20import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts";
21import {
22 makePersistedServerRuntimeState,
23 persistServerRuntimeState,
24} from "../serverRuntimeState.ts";
25import { acquireRelayClientForLink } from "./connect.ts";
26import { resolveHostCliCommand } from "./invocation.ts";
27
28const managedExecutable = {
29 status: "available",
30 executablePath: "/tmp/cloudflared",
31 source: "managed",
32 version: RelayClient.CLOUDFLARED_VERSION,
33} as const;
34
35it.effect("does not install the relay client when the user declines the managed download", () =>
36 Effect.gen(function* () {
37 let installCalls = 0;
38 const result = yield* acquireRelayClientForLink(
39 {
40 resolve: Effect.succeed({
41 status: "missing",
42 version: RelayClient.CLOUDFLARED_VERSION,
43 }),
44 install: Effect.sync(() => {
45 installCalls += 1;
46 return managedExecutable;
47 }),
48 installWithProgress: () =>
49 Effect.sync(() => {
50 installCalls += 1;
51 return managedExecutable;
52 }),
53 pruneManagedVersions: Effect.void,
54 },
55 () => Effect.succeed(false),
56 () => Effect.void,
57 );
58
59 assert.isTrue(Option.isNone(result));
60 assert.equal(installCalls, 0);
61 }),
62);
63
64it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
65 "t3 connect next steps",
66 (it) => {
67 it.effect.each([
68 { subcommand: "status", hint: "connect link" },
69 { subcommand: "publish", hint: "connect login" },
70 ])("t3 connect $subcommand names `t3 $hint` with --base-dir", ({ subcommand, hint }) =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-hint-test-" });
74
75 yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
76 "connect",
77 subcommand,
78 "--base-dir",
79 baseDir,
80 ]);
81
82 const { command } = yield* resolveHostCliCommand(hint, ["--base-dir", baseDir]);
83 assert.include((yield* TestConsole.logLines).join("\n"), `\`${command}\``);
84 }).pipe(
85 Effect.scoped,
86 Effect.provideService(HostProcess.Environment, {}),
87 Effect.provide(
88 Layer.mergeAll(
89 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
90 Layer.fresh(TestConsole.layer),
91 ),
92 ),
93 ),
94 );
95 },
96);
97
98it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
99 "t3 connect unlink and status",
100 (it) => {
101 const runConnect = (
102 recordedPid: number,
103 options?: {
104 readonly portFreed?: boolean;
105 readonly command?: "unlink" | "status";
106 readonly linkMode?: "managed" | "publish_only";
107 },
108 ) =>
109 Effect.gen(function* () {
110 const requests: Array<string> = [];
111 const warnings: Array<string> = [];
112 const server = yield* Effect.acquireRelease(
113 Effect.callback<NodeHttp.Server>((resume) => {
114 const listening = NodeHttp.createServer((request, response) => {
115 requests.push(`${request.method} ${request.url}`);
116 response.writeHead(200, { "content-type": "application/json" });
117 response.end(JSON.stringify({ ok: true, endpointRuntimeStatus: null }));
118 });
119 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
120 }),
121 (listening) => Effect.sync(() => listening.close()),
122 );
123 const address = server.address();
124 if (address === null || typeof address === "string") {
125 return yield* Effect.die(new Error("Expected a TCP address"));
126 }
127 if (options?.portFreed) {
128 yield* Effect.callback<void>((resume) => {
129 server.close(() => resume(Effect.void));
130 });
131 }
132
133 const fs = yield* FileSystem.FileSystem;
134 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-unlink-test-" });
135 const state = yield* makePersistedServerRuntimeState({
136 config: { host: "127.0.0.1", devUrl: undefined },
137 port: address.port,
138 });
139 yield* persistServerRuntimeState({
140 path: `${baseDir}/userdata/server-runtime.json`,
141 state: { ...state, pid: recordedPid },
142 });
143 if (options?.command === "status") {
144 // Status asks the server for reachability only for a managed link.
145 yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true });
146 yield* fs.writeFileString(
147 `${baseDir}/userdata/secrets/${CLOUD_CLI_DESIRED_LINK_SECRET}.bin`,
148 options.linkMode ?? "managed",
149 );
150 }
151
152 yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
153 "connect",
154 options?.command ?? "unlink",
155 "--base-dir",
156 baseDir,
157 ]).pipe(
158 // TestConsole has no reader for Console.warn.
159 Effect.updateService(Console.Console, (console) => ({
160 ...console,
161 warn: (...args: ReadonlyArray<unknown>) => {
162 warnings.push(args.join(" "));
163 },
164 })),
165 );
166
167 return { requests, warnings, printed: (yield* TestConsole.logLines).join("\n") };
168 }).pipe(
169 Effect.scoped,
170 Effect.provide(
171 Layer.mergeAll(
172 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
173 Layer.fresh(TestConsole.layer),
174 ),
175 ),
176 );
177
178 // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it.
179 const deadPid = 4_194_305;
180
181 it.effect("does not tell the user to restart a server that is gone", () =>
182 Effect.gen(function* () {
183 const { printed, warnings } = yield* runConnect(deadPid, { portFreed: true });
184
185 assert.include(printed, "T3 Connect is disabled locally.");
186 assert.notInclude(warnings.join("\n"), "Restart that server");
187 }),
188 );
189
190 it.effect("warns that a server that is gone may have left its connector running", () =>
191 Effect.gen(function* () {
192 const { warnings } = yield* runConnect(deadPid, { portFreed: true });
193
194 assert.include(warnings.join("\n"), "its cloudflared process may still be running");
195 }),
196 );
197
198 it.effect("does not send a token to whatever took over a dead server's port", () =>
199 Effect.gen(function* () {
200 const { requests } = yield* runConnect(deadPid);
201
202 assert.deepEqual(requests, []);
203 }),
204 );
205
206 it.effect("status does not send a token to whatever took over a dead server's port", () =>
207 Effect.gen(function* () {
208 const { requests } = yield* runConnect(deadPid, { command: "status" });
209
210 assert.deepEqual(requests, []);
211 }),
212 );
213
214 it.effect("status asks a running server to check reachability", () =>
215 Effect.gen(function* () {
216 const { requests } = yield* runConnect(process.pid, { command: "status" });
217
218 assert.deepEqual(requests, ["POST /api/connect/reachability"]);
219 }),
220 );
221
222 it.effect("status does not report a publish-only link as exposed", () =>
223 Effect.gen(function* () {
224 const { printed } = yield* runConnect(process.pid, {
225 command: "status",
226 linkMode: "publish_only",
227 });
228
229 assert.include(printed, "Exposure: publish-only");
230 assert.notInclude(printed, "Other devices can reach this machine");
231 }),
232 );
233
234 it.effect("asks a running server to stop its tunnel", () =>
235 Effect.gen(function* () {
236 const { requests, printed, warnings } = yield* runConnect(process.pid);
237
238 assert.deepEqual(requests, ["POST /api/connect/unlink"]);
239 assert.include(printed, "T3 Connect is disabled locally.");
240 assert.notInclude(warnings.join("\n"), "cloudflared process");
241 }),
242 );
243 },
244);