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