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/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 layerServerReplying = (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 layerServerReplying({ 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 layerServerReplying({
71 status: 401,
72 contentType: "application/json",
73 body: UNAUTHORIZED_BODY,
74 }),
75 ).pipe(Effect.flip);
76 assert.include(error.detail, "rejected the server password");
77 }),
78 );
79
80 // 1.x rejects a wrong password with an empty 401, which the client cannot decode.
81 it.effect("reports an empty-body 401 as a rejected password", () =>
82 Effect.gen(function* () {
83 const error = yield* verify(layerServerReplying({ status: 401, body: "" })).pipe(Effect.flip);
84 assert.include(error.detail, "rejected the server password");
85 }),
86 );
87
88 it.effect("reports a server error as a server error, not as unreachable", () =>
89 Effect.gen(function* () {
90 for (const status of [500, 502]) {
91 const error = yield* verify(
92 layerServerReplying({ status, contentType: "text/plain", body: "upstream failed" }),
93 ).pipe(Effect.flip);
94 assert.include(error.detail, `returned HTTP ${status}`);
95 }
96 }),
97 );
98
99 // 1.x (and the 2.x web UI on unknown paths) answers /api/info with 200 HTML.
100 it.effect("rejects a server that answers with the web UI's HTML", () =>
101 Effect.gen(function* () {
102 const error = yield* verify(
103 layerServerReplying({ status: 200, contentType: "text/html", body: SPA_BODY }),
104 ).pipe(Effect.flip);
105 assert.include(error.detail, "is not an OpenCode 2 server");
106 }),
107 );
108
109 it.effect("reports an unreachable server as unreachable", () =>
110 Effect.gen(function* () {
111 const error = yield* verify(FetchHttpClient.layer, "http://127.0.0.1:1").pipe(Effect.flip);
112 assert.include(error.detail, "Could not reach the OpenCode server");
113 }),
114 );
115});
116
117describe("OpenCode2Server error details", () => {
118 // `detail` reaches clients through the provider status message, and a
119 // `serverUrl` can carry credentials in its userinfo or query.
120 const serverUrl = "http://user:url-secret@127.0.0.1:1/?token=query-secret";
121 const detailFor = (httpClient: Layer.Layer<HttpClient.HttpClient>) =>
122 Effect.gen(function* () {
123 const server = yield* OpenCode2Server.make({
124 binaryPath: "opencode",
125 serverUrl,
126 serverPassword: "secret",
127 directory: "/project",
128 environment: {},
129 });
130 const error = yield* server.withConnection(() => Effect.void).pipe(Effect.flip);
131 return error.detail;
132 }).pipe(
133 Effect.provide(
134 Layer.mergeAll(
135 OpenCode2Client.layer.pipe(Layer.provide(httpClient)),
136 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
137 ).pipe(Layer.provideMerge(NodeServices.layer)),
138 ),
139 );
140
141 it.effect("never include the server URL", () =>
142 Effect.gen(function* () {
143 const layerHanging = Layer.succeed(
144 HttpClient.HttpClient,
145 HttpClient.make(() => Effect.never),
146 );
147 const timedOut = yield* detailFor(layerHanging).pipe(Effect.forkChild);
148 yield* TestClock.adjust("10 seconds");
149 const details = [
150 yield* detailFor(FetchHttpClient.layer),
151 yield* detailFor(layerServerReplying({ status: 401, body: "" })),
152 yield* detailFor(layerServerReplying({ status: 502, contentType: "text/plain", body: "" })),
153 yield* detailFor(
154 layerServerReplying({ status: 200, contentType: "text/html", body: SPA_BODY }),
155 ),
156 yield* Fiber.join(timedOut),
157 ];
158 assert.deepStrictEqual(details, [
159 "Could not reach the OpenCode server.",
160 "The OpenCode server rejected the server password.",
161 "The OpenCode server returned HTTP 502.",
162 "The server is not an OpenCode 2 server.",
163 "Timed out waiting for the OpenCode server.",
164 ]);
165 for (const detail of details) {
166 assert.notInclude(detail, "url-secret");
167 assert.notInclude(detail, "query-secret");
168 assert.notInclude(detail, "127.0.0.1");
169 }
170 }).pipe(Effect.provide(TestClock.layer())),
171 );
172});
173
174describe("OpenCode2Server passwords", () => {
175 it.effect("generates a distinct 256-bit password per server", () =>
176 Effect.gen(function* () {
177 const first = yield* OpenCode2Server.generatePassword;
178 const second = yield* OpenCode2Server.generatePassword;
179 assert.match(Redacted.value(first), /^[A-Za-z0-9_-]{43}$/);
180 assert.notStrictEqual(Redacted.value(first), Redacted.value(second));
181 assert.notInclude(String(first), Redacted.value(first));
182 }).pipe(Effect.provide(NodeServices.layer)),
183 );
184
185 it("hands the spawned server only the T3 password", () => {
186 const password = Redacted.make("t3-generated");
187 const environment = OpenCode2Server.serverEnvironment(
188 { PATH: "/bin", OPENCODE_SERVER_PASSWORD: "ambient", OPENCODE_PASSWORD: "ambient" },
189 password,
190 );
191 assert.deepStrictEqual(environment, { PATH: "/bin", OPENCODE_PASSWORD: "t3-generated" });
192 });
193});
194
195// Serves /api/info only with the password from OPENCODE_PASSWORD, like 2.x, and
196// prints the 2.x banner (plus the generated-password line 2.x prints when no
197// password is set, which T3 must never need).
198const FAKE_SERVER = `import { createServer } from "node:http";
199const expected = "Basic " + Buffer.from("opencode:" + process.env.OPENCODE_PASSWORD).toString("base64");
200const server = createServer((request, response) => {
201 if (request.headers.authorization !== expected) {
202 response.writeHead(401, { "content-type": "application/json", "www-authenticate": "Basic" });
203 response.end(${JSON.stringify(UNAUTHORIZED_BODY)});
204 return;
205 }
206 response.writeHead(200, { "content-type": "application/json" });
207 response.end(JSON.stringify({ version: "2.0.18", pid: process.pid, urls: [], paths: { tmp: "/tmp" } }));
208});
209server.listen(0, "127.0.0.1", () => {
210 process.stdout.write("server listening on http://127.0.0.1:" + server.address().port + "\\n");
211 process.stdout.write("server password not-the-t3-password\\n");
212});
213`;
214
215describe("OpenCode2Server spawned server", () => {
216 it.live(
217 "is ready once /api/info accepts the generated password",
218 () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const platform = yield* HostProcessPlatform;
223 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode2-fake-" });
224 const isWindows = platform === "win32";
225 const binaryPath = path.join(directory, isWindows ? "opencode.cmd" : "opencode");
226 const scriptPath = path.join(directory, "opencode.mjs");
227 yield* fs.writeFileString(scriptPath, FAKE_SERVER);
228 yield* fs.writeFileString(
229 binaryPath,
230 isWindows
231 ? `@echo off\r\n"${yield* HostProcessExecutablePath}" "${scriptPath}" %*\r\n`
232 : `#!/bin/sh\nexec "${yield* HostProcessExecutablePath}" "${scriptPath}" "$@"\n`,
233 );
234 if (!isWindows) yield* fs.chmod(binaryPath, 0o755);
235
236 const server = yield* OpenCode2Server.make({
237 binaryPath,
238 serverUrl: "",
239 serverPassword: "",
240 directory,
241 environment: { ...(yield* HostProcessEnvironment), OPENCODE_SERVER_PASSWORD: "ambient" },
242 });
243 const first = yield* server.withConnection((connection) => Effect.succeed(connection));
244 const second = yield* server.withConnection((connection) => Effect.succeed(connection));
245 assert.strictEqual(first.version, "2.0.18");
246 assert.strictEqual(first.external, false);
247 assert.strictEqual(second.client, first.client);
248 }).pipe(
249 Effect.scoped,
250 Effect.provide(
251 Layer.mergeAll(
252 OpenCode2Client.layer,
253 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
254 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))),
255 ),
256 ),
257 15_000,
258 );
259});