Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 HostProcessEnvironment,
5 HostProcessExecutablePath,
6 HostProcessPlatform,
7} from "@t3tools/shared/hostProcess";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Redacted from "effect/Redacted";
14import * as TestClock from "effect/testing/TestClock";
15import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";
16import { describe } from "vite-plus/test";
17
18import * as OpenCodeRuntime from "../opencodeRuntime.ts";
19import * as OpenCodeServerLedger from "../OpenCodeServerLedger.ts";
20import * as OpenCode2Client from "./OpenCode2Client.ts";
21import * as OpenCode2Server from "./OpenCode2Server.ts";
22
23// Shapes and content types observed on `opencode serve` 2.0.18 (pid and port replaced). 1.x
24// answers /api/info with its web UI: 200 text/html.
25const INFO_BODY =
26 '{"version":"2.0.18","pid":4242,"urls":["http://127.0.0.1:4096"],"paths":{"tmp":"/tmp/opencode"}}';
27const UNAUTHORIZED_BODY = '{"_tag":"UnauthorizedError","message":"Authentication required"}';
28const SPA_BODY = "<!doctype html><html><head><title>OpenCode</title></head></html>";
29
30const serverReplying = (reply: {
31 readonly status: number;
32 readonly contentType?: string;
33 readonly body: string;
34}) =>
35 Layer.succeed(
36 HttpClient.HttpClient,
37 HttpClient.make((request) =>
38 Effect.succeed(
39 HttpClientResponse.fromWeb(
40 request,
41 new Response(reply.body, {
42 status: reply.status,
43 headers: reply.contentType === undefined ? {} : { "content-type": reply.contentType },
44 }),
45 ),
46 ),
47 ),
48 );
49
50const verify = (httpClient: Layer.Layer<HttpClient.HttpClient>, url = "http://127.0.0.1:4096") =>
51 Effect.gen(function* () {
52 const opencode = yield* OpenCode2Client.OpenCode2Client;
53 const { client } = yield* opencode.connect({ baseUrl: url, password: "secret" });
54 return yield* OpenCode2Server.verifyServer(client);
55 }).pipe(Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(httpClient))));
56
57describe("OpenCode2Server.verifyServer", () => {
58 it.effect("returns the version of an authenticated OpenCode 2 server", () =>
59 Effect.gen(function* () {
60 const version = yield* verify(
61 serverReplying({ status: 200, contentType: "application/json", body: INFO_BODY }),
62 );
63 assert.strictEqual(version, "2.0.18");
64 }),
65 );
66
67 it.effect("reports a rejected password, not a wrong server", () =>
68 Effect.gen(function* () {
69 const error = yield* verify(
70 serverReplying({ status: 401, contentType: "application/json", body: UNAUTHORIZED_BODY }),
71 ).pipe(Effect.flip);
72 assert.include(error.detail, "rejected the server password");
73 }),
74 );
75
76 // 1.x rejects a wrong password with an empty 401, which the client cannot decode.
77 it.effect("reports an empty-body 401 as a rejected password", () =>
78 Effect.gen(function* () {
79 const error = yield* verify(serverReplying({ status: 401, body: "" })).pipe(Effect.flip);
80 assert.include(error.detail, "rejected the server password");
81 }),
82 );
83
84 it.effect("reports a server error as a server error, not as unreachable", () =>
85 Effect.gen(function* () {
86 for (const status of [500, 502]) {
87 const error = yield* verify(
88 serverReplying({ status, contentType: "text/plain", body: "upstream failed" }),
89 ).pipe(Effect.flip);
90 assert.include(error.detail, `returned HTTP ${status}`);
91 }
92 }),
93 );
94
95 // 1.x (and the 2.x web UI on unknown paths) answers /api/info with 200 HTML.
96 it.effect("rejects a server that answers with the web UI's HTML", () =>
97 Effect.gen(function* () {
98 const error = yield* verify(
99 serverReplying({ status: 200, contentType: "text/html", body: SPA_BODY }),
100 ).pipe(Effect.flip);
101 assert.include(error.detail, "is not an OpenCode 2 server");
102 }),
103 );
104
105 it.effect("reports an unreachable server as unreachable", () =>
106 Effect.gen(function* () {
107 const error = yield* verify(FetchHttpClient.layer, "http://127.0.0.1:1").pipe(Effect.flip);
108 assert.include(error.detail, "Could not reach the OpenCode server");
109 }),
110 );
111});
112
113describe("OpenCode2Server error details", () => {
114 // `detail` reaches clients through the provider status message, and a
115 // `serverUrl` can carry credentials in its userinfo or query.
116 const serverUrl = "http://user:url-secret@127.0.0.1:1/?token=query-secret";
117 const detailFor = (httpClient: Layer.Layer<HttpClient.HttpClient>) =>
118 Effect.gen(function* () {
119 const server = yield* OpenCode2Server.make({
120 binaryPath: "opencode",
121 serverUrl,
122 serverPassword: "secret",
123 directory: "/project",
124 environment: {},
125 });
126 const error = yield* server.withConnection(() => Effect.void).pipe(Effect.flip);
127 return error.detail;
128 }).pipe(
129 Effect.provide(
130 Layer.mergeAll(
131 OpenCode2Client.layer.pipe(Layer.provide(httpClient)),
132 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
133 ).pipe(Layer.provideMerge(NodeServices.layer)),
134 ),
135 );
136
137 it.effect("never include the server URL", () =>
138 Effect.gen(function* () {
139 const hanging = Layer.succeed(
140 HttpClient.HttpClient,
141 HttpClient.make(() => Effect.never),
142 );
143 const timedOut = yield* detailFor(hanging).pipe(Effect.forkChild);
144 yield* TestClock.adjust("10 seconds");
145 const details = [
146 yield* detailFor(FetchHttpClient.layer),
147 yield* detailFor(serverReplying({ status: 401, body: "" })),
148 yield* detailFor(serverReplying({ status: 502, contentType: "text/plain", body: "" })),
149 yield* detailFor(serverReplying({ status: 200, contentType: "text/html", body: SPA_BODY })),
150 yield* Fiber.join(timedOut),
151 ];
152 assert.deepStrictEqual(details, [
153 "Could not reach the OpenCode server.",
154 "The OpenCode server rejected the server password.",
155 "The OpenCode server returned HTTP 502.",
156 "The server is not an OpenCode 2 server.",
157 "Timed out waiting for the OpenCode server.",
158 ]);
159 for (const detail of details) {
160 assert.notInclude(detail, "url-secret");
161 assert.notInclude(detail, "query-secret");
162 assert.notInclude(detail, "127.0.0.1");
163 }
164 }).pipe(Effect.provide(TestClock.layer())),
165 );
166});
167
168describe("OpenCode2Server passwords", () => {
169 it.effect("generates a distinct 256-bit password per server", () =>
170 Effect.gen(function* () {
171 const first = yield* OpenCode2Server.generatePassword;
172 const second = yield* OpenCode2Server.generatePassword;
173 assert.match(Redacted.value(first), /^[A-Za-z0-9_-]{43}$/);
174 assert.notStrictEqual(Redacted.value(first), Redacted.value(second));
175 assert.notInclude(String(first), Redacted.value(first));
176 }).pipe(Effect.provide(NodeServices.layer)),
177 );
178
179 it("hands the spawned server only the T3 password", () => {
180 const password = Redacted.make("t3-generated");
181 const environment = OpenCode2Server.serverEnvironment(
182 { PATH: "/bin", OPENCODE_SERVER_PASSWORD: "ambient", OPENCODE_PASSWORD: "ambient" },
183 password,
184 );
185 assert.deepStrictEqual(environment, { PATH: "/bin", OPENCODE_PASSWORD: "t3-generated" });
186 });
187});
188
189// Serves /api/info only with the password from OPENCODE_PASSWORD, like 2.x, and
190// prints the 2.x banner (plus the generated-password line 2.x prints when no
191// password is set, which T3 must never need).
192const FAKE_SERVER = `import { createServer } from "node:http";
193const expected = "Basic " + Buffer.from("opencode:" + process.env.OPENCODE_PASSWORD).toString("base64");
194const server = createServer((request, response) => {
195 if (request.headers.authorization !== expected) {
196 response.writeHead(401, { "content-type": "application/json", "www-authenticate": "Basic" });
197 response.end(${JSON.stringify(UNAUTHORIZED_BODY)});
198 return;
199 }
200 response.writeHead(200, { "content-type": "application/json" });
201 response.end(JSON.stringify({ version: "2.0.18", pid: process.pid, urls: [], paths: { tmp: "/tmp" } }));
202});
203server.listen(0, "127.0.0.1", () => {
204 process.stdout.write("server listening on http://127.0.0.1:" + server.address().port + "\\n");
205 process.stdout.write("server password not-the-t3-password\\n");
206});
207`;
208
209describe("OpenCode2Server spawned server", () => {
210 it.live(
211 "is ready once /api/info accepts the generated password",
212 () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const platform = yield* HostProcessPlatform;
217 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode2-fake-" });
218 const isWindows = platform === "win32";
219 const binaryPath = path.join(directory, isWindows ? "opencode.cmd" : "opencode");
220 const scriptPath = path.join(directory, "opencode.mjs");
221 yield* fs.writeFileString(scriptPath, FAKE_SERVER);
222 yield* fs.writeFileString(
223 binaryPath,
224 isWindows
225 ? `@echo off\r\n"${yield* HostProcessExecutablePath}" "${scriptPath}" %*\r\n`
226 : `#!/bin/sh\nexec "${yield* HostProcessExecutablePath}" "${scriptPath}" "$@"\n`,
227 );
228 if (!isWindows) yield* fs.chmod(binaryPath, 0o755);
229
230 const server = yield* OpenCode2Server.make({
231 binaryPath,
232 serverUrl: "",
233 serverPassword: "",
234 directory,
235 environment: { ...(yield* HostProcessEnvironment), OPENCODE_SERVER_PASSWORD: "ambient" },
236 });
237 const first = yield* server.withConnection((connection) => Effect.succeed(connection));
238 const second = yield* server.withConnection((connection) => Effect.succeed(connection));
239 assert.strictEqual(first.version, "2.0.18");
240 assert.strictEqual(first.external, false);
241 assert.strictEqual(second.client, first.client);
242 }).pipe(
243 Effect.scoped,
244 Effect.provide(
245 Layer.mergeAll(
246 OpenCode2Client.layer,
247 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
248 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))),
249 ),
250 ),
251 15_000,
252 );
253});