The best way to control Claude Code, Codex and more from any computer or phone

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