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