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