Public: anyone can read this; the crew can change it.

GET /plugins/opencode/forge.ts serves the OpenCode plugin from the repository's file, and the release image carries it #10274

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/10198-get-plugins-opencode-forge-ts-serves-the → main 2 commits fork

  • Merged. mason/10198-get-plugins-opencode-forge-ts-serves-the was merged into main as d7f940b.

Review

Sign in to review this change.
8 files changed +110 −5
Dockerfile +2
@@ -21,6 +21,8 @@ COPY src ./src
2121 COPY docs/PRINCIPLES.md ./docs/PRINCIPLES.md
2222 # The design principles a src/web/ review is held to (src/crew/design_principles.ts).
2323 COPY docs/DESIGN.md ./docs/DESIGN.md
24 # The OpenCode plugin the forge serves at /plugins/opencode/forge.ts (src/http/plugin_routes.ts).
25 COPY plugins/opencode ./plugins/opencode
2426 # src/ alone: nothing under it imports scripts/ or test/ (test/src-imports.test.ts),
2527 # and the boot proof below fails the build if that ever stops being so (#2652).
2628
plugins/opencode/README.md +2 −2
@@ -1,8 +1,8 @@
11 # forge for OpenCode
22
3 Copy `forge.ts` into `.opencode/plugin/` (or list this package under `plugin`
3 Fetch `forge.ts` into `.opencode/plugin/` (or list this package under `plugin`
44 in `opencode.json`), and set `FORGE_URL` and `FORGE_TOKEN` (make the token at `/settings/tokens` on the forge, which shows the line with its own address filled in):
5 `mkdir -p .opencode/plugin && cp plugins/opencode/forge.ts .opencode/plugin/ && FORGE_URL=<url> FORGE_TOKEN=<token> opencode`. It registers the
5 `mkdir -p .opencode/plugin && curl -fsSo .opencode/plugin/forge.ts <forge>/plugins/opencode/forge.ts && FORGE_URL=<forge> FORGE_TOKEN=<token> opencode`, where `<forge>` is the forge's own origin (it serves this file). It registers the
66 forge's MCP server and the `forge` command: `new`, `tell`, `status`, `decide`, `plan`,
77 `preview`, `pulls`, `runs`, `log`, `asked`.
88 `/forge plan` shows the planner's next wave (the first wave-proposal row of `asks`);
src/core/reserved.ts +1
@@ -108,6 +108,7 @@ export const SYSTEM_NAMES: readonly string[] = [
108108 "runs",
109109 "search",
110110 "settings",
111 "plugins",
111112 "signin",
112113 "signup",
113114 "sitemap.xml",
src/http/plugin_routes.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * `GET /plugins/opencode/forge.ts` (#10198): the OpenCode plugin, the bytes of
3 * the repository's own `plugins/opencode/forge.ts`, so a user connects with
4 * one curl. Read once at boot; the ETag is the bytes' hash, and a matching
5 * `If-None-Match` is a 304. The securityFloor is set on every response by the
6 * server, as for any route. `plugins` is a reserved name (src/core/reserved.ts).
7 */
8
9 import { readFileSync } from "node:fs";
10 import { join } from "node:path";
11 import type { Handler } from "./context.ts";
12 import { holds, weakEtag } from "./etag.ts";
13 import type { Router } from "./router.ts";
14
15 const FILE = join(import.meta.dir, "../../plugins/opencode/forge.ts");
16
17 /** The one-line install: the forge's own origin, no trailing slash. */
18 export function opencodeInstall(origin: string): string {
19 return `mkdir -p .opencode/plugin && curl -fsSo .opencode/plugin/forge.ts ${origin.replace(/\/+$/, "")}/plugins/opencode/forge.ts`;
20 }
21
22 const bytes = readFileSync(FILE);
23 const etag = weakEtag(bytes.toString("utf8"));
24 const headers = {
25 "content-type": "text/plain; charset=utf-8",
26 "cache-control": "public, max-age=300",
27 etag,
28 };
29
30 export const opencodePlugin: Handler = (ctx) =>
31 holds(ctx.request, etag)
32 ? new Response(null, { status: 304, headers: { etag, "cache-control": headers["cache-control"] } })
33 : new Response(ctx.request.method === "HEAD" ? null : bytes, { headers });
34
35 export function pluginRoutes(router: Router<Handler>): void {
36 router.add("GET", "/plugins/opencode/forge.ts", opencodePlugin);
37 }
src/http/server.ts +3
@@ -34,6 +34,7 @@ import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke }
3434 import { allFlowsPage } from "../web/pages/flows-all.ts";
3535 import { measureSubmit } from "./measure.ts";
3636 import { settingsRoutes } from "./settings_routes.ts";
37 import { pluginRoutes } from "./plugin_routes.ts";
3738 import { pinnedRoutes } from "./pinned_routes.ts";
3839 import { boardsAsk, boardsPage } from "../web/pages/boards.ts";
3940 import { boardNew, boardPin, boardPost, pinPost } from "../web/pages/boards-edit.ts";
@@ -917,6 +918,8 @@ export function buildRouter(): Router<Handler> {
917918 // Every /settings… page, in its own module (settings_routes.ts); literal, above /:owner.
918919 // The usage page is handed the pattern list, so settings_routes.ts never imports server.ts.
919920 settingsRoutes(router, knownPatterns);
921 // The OpenCode plugin file (#10198); literal, above /:owner.
922 pluginRoutes(router);
920923 // The Deploy to… page for a pinned forge (#8744); literal, above /:owner.
921924 pinnedRoutes(router);
922925 // Each THREATS.md protection against the last gate; literal, above /:owner.
src/web/pages/account.ts +2 −1
@@ -43,6 +43,7 @@ import {
4343 import { endAccountSession } from "../../actions/signins.ts";
4444 import { listSessions, type SessionInfo } from "../../core/sessions.ts";
4545 import { ADMIN_TOKEN_WORDS, type TokenScope } from "../../core/tokens.ts";
46 import { opencodeInstall } from "../../http/plugin_routes.ts";
4647 import type { CommitEmail, User } from "../../core/users.ts";
4748 import { isStandInEmail } from "../../core/users.ts";
4849 import { cookieValue, isAccountItself, type Ctx } from "../../http/context.ts";
@@ -594,7 +595,7 @@ export function connectCard(ctx: Ctx, token: string | undefined): Html {
594595 <p class="small">OpenCode</p>
595596 ${copyField(
596597 "connect-opencode",
597 `mkdir -p .opencode/plugin && cp plugins/opencode/forge.ts .opencode/plugin/ && ${env} opencode`,
598 `${opencodeInstall(url)} && ${env} opencode`,
598599 "OpenCode command",
599600 "Copy command",
600601 )}`,
test/connect-harness.test.ts +2 −2
@@ -27,7 +27,7 @@ afterAll(async () => {
2727 });
2828
2929 const value = (html: string, id: string) =>
30 new RegExp(`id="${id}"[^>]*value="([^"]*)"`).exec(html)?.[1]?.replaceAll("&lt;", "<").replaceAll("&gt;", ">") ?? "";
30 new RegExp(`id="${id}"[^>]*value="([^"]*)"`).exec(html)?.[1]?.replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">") ?? "";
3131
3232 test("lines use the forge's address, a placeholder, then the minted token once", async () => {
3333 const signup = await fetch(`${base}/signup`, {
@@ -41,7 +41,7 @@ test("lines use the forge's address, a placeholder, then the minted token once",
4141 const before = await (await fetch(`${base}/settings/tokens`, { headers: { cookie } })).text();
4242 expect(before).toContain("Connect your harness");
4343 expect(value(before, "connect-claude")).toBe(`FORGE_URL=${url} FORGE_TOKEN=<token> claude --plugin-dir plugins/claude-code`);
44 expect(value(before, "connect-opencode")).toContain(`FORGE_URL=${url} FORGE_TOKEN=<token> opencode`);
44 expect(value(before, "connect-opencode")).toBe(`mkdir -p .opencode/plugin && curl -fsSo .opencode/plugin/forge.ts ${url}/plugins/opencode/forge.ts && FORGE_URL=${url} FORGE_TOKEN=<token> opencode`);
4545
4646 const made = await fetch(`${base}/settings/tokens`, {
4747 method: "POST",
test/plugin-routes.test.ts added +61
@@ -0,0 +1,61 @@
1 /** /plugins/opencode/forge.ts serves the repository's plugin file (#10198). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { readFileSync } from "node:fs";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { reservedName } from "../src/core/reserved.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { quietLogs } from "./helpers/globals.ts";
11
12 quietLogs();
13
14 const ROOT = join(import.meta.dir, "..");
15 let dir: string;
16 let app: App;
17 let servers: Servers;
18
19 beforeAll(async () => {
20 dir = await mkdtemp(join(tmpdir(), "plugin-routes-"));
21 app = createApp({ dataDir: dir, port: 0 });
22 servers = await serve(app);
23 });
24 afterAll(async () => {
25 servers.stop();
26 app.close();
27 await rm(dir, { recursive: true, force: true });
28 });
29
30 test("200: the file's bytes, as text/plain, with an ETag and the security floor", async () => {
31 const res = await fetch(`${servers.url}/plugins/opencode/forge.ts`);
32 expect(res.status).toBe(200);
33 expect(res.headers.get("content-type")).toBe("text/plain; charset=utf-8");
34 expect(res.headers.get("etag")).toBeTruthy();
35 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
36 expect(res.headers.get("referrer-policy")).toBeTruthy();
37 expect(res.headers.get("content-security-policy")).toBeTruthy();
38 expect(await res.text()).toBe(readFileSync(join(ROOT, "plugins/opencode/forge.ts"), "utf8"));
39 });
40
41 test("304: a matching If-None-Match has no body", async () => {
42 const first = await fetch(`${servers.url}/plugins/opencode/forge.ts`);
43 const etag = first.headers.get("etag")!;
44 const again = await fetch(`${servers.url}/plugins/opencode/forge.ts`, { headers: { "if-none-match": etag } });
45 expect(again.status).toBe(304);
46 expect(await again.text()).toBe("");
47 const other = await fetch(`${servers.url}/plugins/opencode/forge.ts`, { headers: { "if-none-match": 'W/"nope"' } });
48 expect(other.status).toBe(200);
49 });
50
51 test("`plugins` is a reserved name", () => {
52 expect(reservedName(app.db, "plugins")).toBeDefined();
53 });
54
55 test("the Dockerfile copies plugins/opencode", () => {
56 const copies = readFileSync(join(ROOT, "Dockerfile"), "utf8")
57 .split("\n")
58 .filter((l) => l.startsWith("COPY ") && !l.includes("--from"))
59 .flatMap((l) => l.trim().split(/\s+/).slice(1, -1).map((p) => p.replace(/\/$/, "")));
60 expect(copies).toContain("plugins/opencode");
61 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs