Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions pm-stack/dispatch/src/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,24 @@ export class OpenCodeClient {
} catch {
throw new OpenCodeError(`opencode auth file unreadable: ${this.authFile}`);
}
const data = JSON.parse(raw) as { password?: string };
if (!data.password) throw new OpenCodeError("opencode auth file carries no password");
// The parse and the shape are part of the boundary (#7085): a
// truncated/mid-write state file, a non-object document, or a
// non-string password must surface as an OpenCodeError naming the
// problem - never a raw Type/SyntaxError, and never a credential
// silently coerced from a number or object.
let parsedAuth: unknown;
try {
parsedAuth = JSON.parse(raw);
} catch {
throw new OpenCodeError(`opencode auth file is not valid JSON: ${this.authFile}`);
}
if (typeof parsedAuth !== "object" || parsedAuth === null || Array.isArray(parsedAuth)) {
throw new OpenCodeError(`opencode auth file does not hold a JSON object: ${this.authFile}`);
}
const data = parsedAuth as { password?: unknown };
if (typeof data.password !== "string" || !data.password) {
throw new OpenCodeError("opencode auth file carries no password");
}
return `Basic ${Buffer.from(`opencode:${data.password}`).toString("base64")}`;
}

Expand All @@ -41,7 +57,12 @@ export class OpenCodeClient {
throw new OpenCodeError(`opencode ${method} ${path} failed (HTTP ${res.status}): ${text.slice(0, 200)}`);
}
if (!text.trim()) return null;
const parsed: unknown = JSON.parse(text);
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
throw new OpenCodeError(`opencode ${method} ${path} returned a non-JSON response (HTTP ${res.status})`);
}
// The v2 API wraps responses in a {data: …} envelope.
if (typeof parsed === "object" && parsed !== null && "data" in parsed) {
return (parsed as { data: unknown }).data;
Expand Down
104 changes: 104 additions & 0 deletions pm-stack/dispatch/test/opencode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { OpenCodeClient, OpenCodeError } from "../src/opencode.ts";

// Pinning tests for #7085: the OpenCode client parses two JSON inputs —
// the server state/auth file and every 2xx response body. Both parses
// are boundary validations: wrong-shape or malformed input must surface
// as OpenCodeError, never a raw Type/SyntaxError, and a non-string
// password must never be coerced into the Basic credential.

let mode: "ok" | "nonjson" = "ok";
let lastAuth = "";
let server: ReturnType<typeof Bun.serve>;
let baseUrl = "";
let dir = "";

function authFile(name: string, content: string): string {
const path = join(dir, name);
writeFileSync(path, content);
return path;
}

beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), "dispatch-opencode-test-"));
server = Bun.serve({
port: 0,
fetch(req) {
lastAuth = req.headers.get("authorization") ?? "";
if (mode === "nonjson") {
return new Response("<html>not json</html>", { status: 200, headers: { "content-type": "text/html" } });
}
return Response.json({ data: { id: "sess-control" } });
},
});
baseUrl = `http://127.0.0.1:${server.port}`;
});

afterAll(() => {
server.stop(true);
rmSync(dir, { recursive: true, force: true });
});

async function create(file: string) {
const client = new OpenCodeClient(baseUrl, file);
return client.createSession({ directory: "/tmp", title: "t", model: null });
}

describe("OpenCodeClient auth file boundary (#7085)", () => {
test("control: a valid auth file resolves and sends the password verbatim", async () => {
mode = "ok";
const session = await create(authFile("valid.json", JSON.stringify({ password: "pw123" })));
expect(session.id).toBe("sess-control");
expect(Buffer.from(lastAuth.replace("Basic ", ""), "base64").toString()).toBe("opencode:pw123");
});

test("control: an object without a password yields the no-password OpenCodeError", async () => {
await expect(create(authFile("empty.json", "{}"))).rejects.toThrow(OpenCodeError);
await expect(create(authFile("empty.json", "{}"))).rejects.toThrow(/carries no password/);
});

test("a null auth file is an OpenCodeError, not a raw TypeError", async () => {
const err = await create(authFile("null.json", "null")).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
expect(String((err as Error).message)).toContain("does not hold a JSON object");
});

test("an array auth file is an OpenCodeError, not a raw error", async () => {
const err = await create(authFile("array.json", "[]")).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
});

test("a malformed auth file is an OpenCodeError, not a raw SyntaxError", async () => {
const err = await create(authFile("bad.json", "{not json")).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
expect(String((err as Error).message)).toContain("not valid JSON");
});

test("a numeric password is rejected, never coerced into the credential", async () => {
lastAuth = "";
const err = await create(authFile("num.json", JSON.stringify({ password: 12345 }))).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
expect(lastAuth).toBe("");
});

test("an object password is rejected, never sent as [object Object]", async () => {
lastAuth = "";
const err = await create(authFile("obj.json", JSON.stringify({ password: { x: 1 } }))).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
expect(lastAuth).toBe("");
});
});

describe("OpenCodeClient response body boundary (#7085)", () => {
test("a non-JSON 200 body is an OpenCodeError, not a raw SyntaxError", async () => {
mode = "nonjson";
const err = await create(authFile("valid2.json", JSON.stringify({ password: "pw123" }))).catch((e: unknown) => e);
expect(err).toBeInstanceOf(OpenCodeError);
expect(String((err as Error).message)).toContain("non-JSON response");
mode = "ok";
});
});
Loading