diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e0d443..123b51c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,4 +16,4 @@ jobs: node-version: 22 - run: npm ci - run: npm run typecheck - - run: npm run build + - run: npm test diff --git a/README.md b/README.md index f0122e0..136ca20 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,24 @@ Use your Claude Pro/Max subscription in [OpenCode](https://opencode.ai). If you' ## Install +### OpenCode v2 (recommended) + +Install via CLI: + +```bash +opencode plugin add opencode-claude-bridge +``` + +Or add to `~/.config/opencode/opencode.json`: + +```json +{ + "plugins": ["opencode-claude-bridge"] +} +``` + +### OpenCode v1 (1.18.29 – 1.x) + Add to `~/.config/opencode/opencode.json`: ```json @@ -14,15 +32,12 @@ Add to `~/.config/opencode/opencode.json`: OpenCode auto-installs the plugin from npm on next launch. -If you're logged into the Claude CLI (`claude login`), the plugin auto-syncs your credentials — just select an Anthropic model and start chatting. If not, you'll be prompted to authenticate via browser OAuth or enter an API key. +If you're logged into the Claude CLI (`claude login`), the plugin auto-syncs your credentials — just select an Anthropic model and start chatting. If not, you'll be prompted to authenticate via browser OAuth (or `/connect` → Anthropic) or enter an API key. **Upgrade:** -OpenCode pins the installed version. To upgrade to the latest: - -```bash -cd ~/.cache/opencode && npm install opencode-claude-bridge@latest -``` +- **OpenCode v2:** `opencode plugin update opencode-claude-bridge` +- **OpenCode v1:** `cd ~/.cache/opencode && npm install opencode-claude-bridge@latest` Then restart OpenCode. @@ -34,13 +49,20 @@ git clone https://github.com/dotCipher/opencode-claude-bridge.git ~/opencode-cla cd ~/opencode-claude-bridge && npm install && npm run build ``` -Then reference the full path in your config: - -```json -{ - "plugin": ["/Users/YOU/opencode-claude-bridge/dist/index.js"] -} -``` +Then reference the local path in your config: + +- **OpenCode v2** (must be the **directory**, not `dist/index.js`): + ```json + { + "plugins": ["/Users/YOU/opencode-claude-bridge"] + } + ``` +- **OpenCode v1**: + ```json + { + "plugin": ["/Users/YOU/opencode-claude-bridge/dist/index.js"] + } + ``` ## How the bridge works @@ -145,9 +167,45 @@ SHA256(salt + message[4] + message[7] + message[20] + CLI_VERSION).slice(0, 3) The salt is hardcoded in Claude Code's source. This changes per conversation because the user's message text changes. +## OpenCode v2 compatibility + +OpenCode 2.0 loads plugins through a new contract (`id` + `setup()`), and V1 +hooks never run there — older releases fail with *"Plugin must export a default +definition with an id and an effect or setup function"*. This package supports +both generations from a single entrypoint (`{ id, setup, server }`): + +- **OpenCode ≥ 2.0** — uses `setup()`. + - Registers an OAuth method on the built-in `anthropic` integration with + keychain fast-path, browser PKCE (`mode: "auto"` + remote redirect-URL + paste with CSRF `state` verification), and layered refresh (keychain → + stored → CLI) persisted atomically by OpenCode. + - **Seamless sync:** when no Anthropic connection exists yet (neither a + stored credential nor `ANTHROPIC_API_KEY`) and you are logged into + `claude login`, the bridge automatically persists your keychain credential + on startup so Anthropic models appear immediately without running `/connect`. + Existing API keys are never overridden. + - Rewrites OAuth requests and SSE tool-call responses through + provider-scoped `http.request` / `http.response` and system prompt + (`context`, `compaction`, `generate`, `title`) hooks. Requests to + non-Anthropic hosts or with API-key auth pass through untouched. + - No model injection: the v2 catalog already lists Claude models. + - No inline 429 token rotation: Claude refresh tokens are single-use, so + rotation is restricted to OpenCode's persisted integration `refresh` + callback; OpenCode's native retry policy handles 429 backoff. +- **OpenCode 1.18.29 – 1.x** — uses the V1 `server()` implementation as before. + +> **Note on OpenCode v2's built-in Claude Agent provider:** OpenCode v2 also +> ships a native `claude-agent` provider that shells out to the local `claude` +> CLI binary. Use this bridge if you want direct Anthropic API traffic through +> OpenCode's native `anthropic` provider with Claude Code wire parity, tool +> schema & SSE translation, and seamless coexistence with API-key configs. + +OpenCode < 1.18.29 is not supported by `main` (the `{ id, server }` entrypoint +shape requires 1.18.29); use the 1.10.x releases there. + ## Requirements -- [OpenCode](https://opencode.ai) v1.2+ +- [OpenCode](https://opencode.ai) v1.18.29+ (v2 supported) - For OAuth: [Claude CLI](https://docs.anthropic.com/en/docs/claude-code) installed and logged in (`claude login`) - macOS (Keychain) or Linux (`~/.claude/.credentials.json` fallback) - For API key: just configure a `provider` with `apiKey` in your OpenCode config as usual @@ -240,6 +298,8 @@ Anthropic's own Claude Code docs say third-party integrations should use API key ## Credits +OpenCode v2 plugin port initiated by [@TomasRichtr](https://github.com/TomasRichtr) in [#37](https://github.com/dotCipher/opencode-claude-bridge/pull/37). + Combines approaches from [shahidshabbir-se/opencode-anthropic-oauth](https://github.com/shahidshabbir-se/opencode-anthropic-oauth), [ex-machina-co/opencode-anthropic-auth](https://github.com/ex-machina-co/opencode-anthropic-auth), [vinzabe/PERMANENT-opencode-anthropic-oauth-fix](https://github.com/vinzabe/PERMANENT-opencode-anthropic-oauth-fix), and [lehdqlsl/opencode-claude-auth-sync](https://github.com/lehdqlsl/opencode-claude-auth-sync). ## License diff --git a/package-lock.json b/package-lock.json index 1532948..81fbc3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencode-claude-bridge", - "version": "1.10.12", + "version": "1.11.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencode-claude-bridge", - "version": "1.10.12", + "version": "1.11.0", "license": "MIT", "devDependencies": { "@types/node": "^25.5.0", diff --git a/package.json b/package.json index 669fb18..3426b24 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,16 @@ { "name": "opencode-claude-bridge", - "version": "1.10.12", + "version": "1.11.0", "description": "OpenCode ↔ Claude bridge — keychain sync + PKCE OAuth + request transformation", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, "files": [ "dist" ], diff --git a/src/constants.ts b/src/constants.ts index 3289378..bc0d23c 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -75,11 +75,21 @@ export const USER_AGENT = process.env.ANTHROPIC_USER_AGENT || `claude-cli/${CLI_VERSION} (external, ${ENTRYPOINT})`; -// Exact beta flags from Claude Code 2.1.178 (confirmed via request interception) +// Beta flags matching Claude Code 2.1.x (confirmed via request interception). // oauth-2025-04-20 is added separately only for OAuth auth. +// +// 2026-10-16: added thinking-binding-controls-2026-08-01 (present in Claude +// Code ≥2.1.2xx). It legalizes the `thinking.block_binding` request field, +// which OpenCode v2 sends natively for models flagged +// supportsThinkingBlockBinding (claude-haiku-5-5, opus/sonnet/fable 5.x). +// Without this flag those requests fail validation with: +// "thinking.adaptive.block_binding: Extra inputs are not permitted" +// To refresh this list against a newer Claude Code install: +// grep -aoE '"[a-z]+(-[a-z]+)*-20[0-9]{2}-[0-9]{2}-[0-9]{2}"' \ +// "$(readlink -f "$(command -v claude)")" | sort -u export const BETA_FLAGS = process.env.ANTHROPIC_BETA_FLAGS || - "interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,claude-code-20250219,advisor-tool-2026-03-01,effort-2025-11-24,extended-cache-ttl-2025-04-11"; + "interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,claude-code-20250219,advisor-tool-2026-03-01,effort-2025-11-24,extended-cache-ttl-2025-04-11,thinking-binding-controls-2026-08-01"; export const OAUTH_BETA_FLAG = "oauth-2025-04-20"; diff --git a/src/index.test.ts b/src/index.test.ts index 4922d07..ec20b20 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -17,18 +17,26 @@ import { AGENT_TYPE_OPENCODE_TO_CLAUDE, shouldUseClaudeToolSchemas, } from "./claude-tools.js"; -import { extractOAuthErrorDetail } from "./oauth.js"; +import { + extractOAuthErrorDetail, + parseOAuthRedirect, + startOAuthCallbackServer, + type OAuthTokens, +} from "./oauth.js"; import { selectClaudeCredentials } from "./keychain.js"; import { + createOpenCodeClaudeBridgeV2, default as pluginModule, deriveModelDisplayName, getClaudeToolsForActiveOpenCodeTools, getInboundToolNameMapForActiveOpenCodeTools, + isAnthropicApiUrl, mapOutboundToolName, rewriteSystemBlocksForModel, shouldInjectClaudeTools, stripAssistantPrefillForClaude, stripSystemCacheControl, + type V2PluginContext, } from "./index.js"; import { createSseProcessor, parseSseEvent, buildSseEvent } from "./stream.js"; @@ -1227,17 +1235,786 @@ describe("rewriteSystemBlocksForModel", () => { }); describe("plugin module shape", () => { - it("default-exports { id, server } so opencode's loader recognises it", () => { + it("default-exports { id, setup, server } so opencode's loader recognises it", () => { // A bare function default export sends opencode down its legacy path, where // it calls every named export of this module as a plugin factory — which // crashes on the helpers above and takes the whole plugin down with it. + // `server` keeps the V1 implementation on opencode >= 1.18; `setup` adds + // opencode >= 2, which ignores `server` and never runs V1 hooks. assert.equal(typeof pluginModule, "object"); assert.equal(typeof pluginModule.server, "function"); + assert.equal(typeof pluginModule.setup, "function"); }); it("carries an id, which opencode requires for path-referenced plugins", () => { assert.equal(pluginModule.id, "opencode-claude-bridge"); }); + + it("v2 setup registers the anthropic oauth method override and provider-scoped hooks", async () => { + const registrations: string[] = []; + const methodUpdate = { capture: null as unknown }; + const hooks: Array<{ name: string; options?: { providerID?: string } }> = []; + const ctx = { + integration: { + transform: async (editor: (editor: { + method: { + update(registration: Record): void; + }; + }) => void) => { + editor({ + method: { + update(registration: Record) { + methodUpdate.capture = registration; + registrations.push("integration.transform"); + }, + }, + }); + }, + connection: { + active: async () => undefined, + resolve: async () => undefined, + }, + }, + session: { + hook: async (name: string, _cb: unknown, options?: { providerID?: string }) => { + hooks.push({ name, options }); + registrations.push(`session.hook(${name})`); + }, + }, + }; + const cleanup = await (pluginModule.setup as (c: unknown) => Promise)(ctx); + + const registration = methodUpdate.capture as Record; + assert.equal(registration.integrationID, "anthropic"); + const method = registration.method as Record; + assert.equal(method.id, "oauth"); + assert.equal(method.type, "oauth"); + assert.equal(typeof registration.authorize, "function"); + assert.equal(typeof registration.refresh, "function"); + // The refresh callback must be async — opencode calls .then() on its result + // (a plain-object return crashes the credential resolver). + assert.equal( + (registration.refresh as (...args: unknown[]) => unknown).constructor.name, + "AsyncFunction", + "refresh must be async so opencode can await it", + ); + + assert.deepEqual( + hooks.map((h) => `${h.name}:${h.options?.providerID ?? ""}`).sort(), + [ + "compaction:anthropic", + "context:anthropic", + "generate:anthropic", + "http.request:anthropic", + "http.response:anthropic", + "title:anthropic", + ], + ); + assert.equal(typeof cleanup, "function"); + }); +}); + +describe("isAnthropicApiUrl security", () => { + it("accepts HTTPS anthropic.com and subdomains", () => { + assert.equal(isAnthropicApiUrl("https://api.anthropic.com/v1/messages", undefined), true); + assert.equal(isAnthropicApiUrl("https://anthropic.com/v1/messages", undefined), true); + assert.equal(isAnthropicApiUrl("https://us.api.anthropic.com/v1/messages", undefined), true); + }); + + it("rejects suffix-spoofed domains and plaintext HTTP", () => { + assert.equal(isAnthropicApiUrl("https://evilanthropic.com/v1/messages", undefined), false); + assert.equal(isAnthropicApiUrl("https://anthropic.com.evil.example/v1/messages", undefined), false); + assert.equal(isAnthropicApiUrl("http://api.anthropic.com/v1/messages", undefined), false); + assert.equal(isAnthropicApiUrl("https://api.openai.com/v1/responses", undefined), false); + assert.equal(isAnthropicApiUrl("not-a-url", undefined), false); + }); + + it("allows explicitly configured HTTPS or loopback HTTP ANTHROPIC_BASE_URL only", () => { + assert.equal( + isAnthropicApiUrl("http://127.0.0.1:43210/v1/messages", "http://127.0.0.1:43210"), + true, + ); + assert.equal( + isAnthropicApiUrl("http://127.0.0.1:43210/v1/messages", undefined), + false, + ); + assert.equal( + isAnthropicApiUrl("https://proxy.corp.internal/v1/messages", "https://proxy.corp.internal"), + true, + ); + assert.equal( + isAnthropicApiUrl("http://proxy.corp.internal/v1/messages", "http://proxy.corp.internal"), + false, + ); + assert.equal( + isAnthropicApiUrl("https://other.corp.internal/v1/messages", "https://proxy.corp.internal"), + false, + ); + }); +}); + +describe("OAuth CSRF state & redirect paste security", () => { + it("parseOAuthRedirect accepts matching state and extracts code or error", () => { + assert.deepEqual( + parseOAuthRedirect("http://localhost:9999/callback?code=abc123&state=s-good", "s-good"), + { code: "abc123" }, + ); + assert.deepEqual( + parseOAuthRedirect( + "http://localhost:9999/callback?error=access_denied&error_description=Denied&state=s-good", + "s-good", + ), + { error: "Denied" }, + ); + }); + + it("parseOAuthRedirect rejects mismatched state, malformed URL, or missing code", () => { + assert.throws( + () => parseOAuthRedirect("http://localhost:9999/callback?code=abc&state=wrong", "s-good"), + /different sign-in/, + ); + assert.throws( + () => parseOAuthRedirect("http://localhost:9999/callback?code=abc", "s-good"), + /different sign-in/, + ); + assert.throws( + () => parseOAuthRedirect("not a url", "s-good"), + /full URL/, + ); + assert.throws( + () => parseOAuthRedirect("http://localhost:9999/callback?state=s-good", "s-good"), + /authorization code/, + ); + }); + + it("callback server rejects forged/missing state without aborting legitimate callback", async () => { + const server = await startOAuthCallbackServer(); + try { + const codePromise = server.waitForCode(); + + // Forged request with wrong state gets 400 and does NOT settle the attempt + const forged = await fetch(`http://localhost:${server.port}/callback?code=evil&state=wrong`); + assert.equal(forged.status, 400); + + // Missing state also gets 400 + const missing = await fetch(`http://localhost:${server.port}/callback?code=evil`); + assert.equal(missing.status, 400); + + // Legitimate callback with matching state succeeds + const ok = await fetch( + `http://localhost:${server.port}/callback?code=legit-code&state=${encodeURIComponent(server.state)}`, + ); + assert.equal(ok.status, 200); + assert.equal(await codePromise, "legit-code"); + + // Duplicate callback after settlement gets 409 + const dup = await fetch( + `http://localhost:${server.port}/callback?code=second&state=${encodeURIComponent(server.state)}`, + ); + assert.equal(dup.status, 409); + } finally { + server.close(); + } + }); + + it("callback server submitRedirect settles waitForCode on valid state and rejects bad pastes", async () => { + const server = await startOAuthCallbackServer(); + try { + const codePromise = server.waitForCode(); + + // Bad paste throws without aborting waitForCode + assert.throws( + () => server.submitRedirect("http://localhost:1234/callback?code=evil&state=bad"), + /different sign-in/, + ); + + // Good paste resolves waitForCode + server.submitRedirect( + `http://localhost:${server.port}/callback?code=pasted-code&state=${encodeURIComponent(server.state)}`, + ); + assert.equal(await codePromise, "pasted-code"); + } finally { + server.close(); + } + }); +}); + +// ── Test harness for OpenCode v2 plugin ──────────────────────────── + +type MockV2Options = { + activeConnection?: { type: "credential"; id: string; label?: string; method?: string } | { type: "env"; name: string }; + resolvedCredential?: { type: string; access?: string; refresh?: string; expires?: number; key?: string; methodID?: string }; +}; + +function createMockV2Context(opts: MockV2Options = {}) { + const state = { + activeConnection: opts.activeConnection, + resolvedCredential: opts.resolvedCredential, + }; + const disposed: string[] = []; + const connectCalls: Array<{ integrationID: string; methodID: string; label?: string }> = []; + let oauthRegistration: { + integrationID: string; + method: { id: string; type: "oauth"; label: string }; + authorize: () => Promise; + refresh: (cred: any) => Promise; + } | null = null; + const hooks = new Map any; providerID?: string }>>(); + + const ctx: V2PluginContext = { + integration: { + transform: async (editor) => { + editor({ + method: { + update(registration) { + oauthRegistration = registration; + }, + }, + }); + return { + dispose: async () => { + disposed.push("integration.transform"); + }, + }; + }, + oauth: { + connect: async (input) => { + connectCalls.push(input); + if (oauthRegistration) { + const auth = await oauthRegistration.authorize(); + if (auth.mode === "auto") { + const cred = await auth.callback; + state.activeConnection = { + type: "credential", + id: "cred_bootstrapped", + label: input.label ?? "Claude CLI", + method: "oauth", + }; + state.resolvedCredential = cred; + } + } + return { attemptID: "att_1" }; + }, + }, + connection: { + active: async () => state.activeConnection, + resolve: async () => state.resolvedCredential, + }, + }, + session: { + hook: async (name, cb, options) => { + const list = hooks.get(name) ?? []; + list.push({ cb, providerID: options?.providerID }); + hooks.set(name, list); + return { + dispose: async () => { + disposed.push(`session.hook:${name}`); + }, + }; + }, + }, + }; + + return { + ctx, + state, + disposed, + connectCalls, + getOAuthRegistration: () => oauthRegistration, + triggerHook: async (name: string, event: any) => { + for (const entry of hooks.get(name) ?? []) { + await entry.cb(event); + } + return event; + }, + }; +} + +describe("OpenCode v2 plugin (setup)", () => { + const validTokens: OAuthTokens = { + access: "sk-ant-oat01-valid-token", + refresh: "sk-ant-ort01-valid-refresh", + expires: Date.now() + 3_600_000, + }; + + it("seamlessly bootstraps keychain credentials when no Anthropic connection exists", async () => { + const mock = createMockV2Context(); + let callbackServerStarted = false; + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + startOAuthCallbackServer: async () => { + callbackServerStarted = true; + throw new Error("should not start callback server during keychain bootstrap"); + }, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + + const cleanup = await setup(mock.ctx); + assert.equal(mock.connectCalls.length, 1); + assert.deepEqual(mock.connectCalls[0], { + integrationID: "anthropic", + methodID: "oauth", + label: "Claude CLI", + }); + assert.equal(callbackServerStarted, false); + assert.equal(mock.state.activeConnection?.type, "credential"); + assert.equal(mock.state.resolvedCredential?.type, "oauth"); + assert.equal(mock.state.resolvedCredential?.access, validTokens.access); + + await cleanup(); + assert.ok(mock.disposed.includes("integration.transform")); + assert.ok(mock.disposed.includes("session.hook:http.request")); + assert.ok(mock.disposed.includes("session.hook:http.response")); + assert.ok(mock.disposed.includes("session.hook:context")); + }); + + it("never hijacks an existing env or key Anthropic connection during bootstrap", async () => { + for (const activeConnection of [ + { type: "env" as const, name: "ANTHROPIC_API_KEY" }, + { type: "credential" as const, id: "cred_key", label: "My API Key", method: "key" }, + { type: "credential" as const, id: "cred_oauth", label: "Existing OAuth", method: "oauth" }, + ]) { + const mock = createMockV2Context({ + activeConnection, + resolvedCredential: + activeConnection.type === "credential" && activeConnection.method === "oauth" + ? { type: "oauth", methodID: "oauth", ...validTokens } + : { type: "key", key: "sk-ant-api03-secret" }, + }); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + assert.equal(mock.connectCalls.length, 0); + } + }); + + it("rewrites OAuth requests and translates SSE tool calls while preserving API-key passthrough", async () => { + const mock = createMockV2Context({ + activeConnection: { type: "credential", id: "cred_1", method: "oauth" }, + resolvedCredential: { type: "oauth", methodID: "oauth", ...validTokens }, + }); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => ({ account: { uuid: "acct-uuid-123" } }), + }); + await setup(mock.ctx); + + // 1. OAuth request gets rewritten + const originalBody = JSON.stringify({ + model: "claude-sonnet-4-6", + system: [{ type: "text", text: "You are OpenCode." }], + messages: [{ role: "user", content: "Read README.md please" }], + tools: [ + { + name: "read", + description: "Read file", + input_schema: { type: "object", properties: { filePath: { type: "string" } } }, + }, + ], + }); + const reqEvent = { + request: new Request("https://api.anthropic.com/messages", { + method: "POST", + headers: { + "content-type": "application/json", + authorization: `Bearer ${validTokens.access}`, + "x-api-key": "should-be-stripped", + }, + body: originalBody, + }), + }; + await mock.triggerHook("http.request", reqEvent); + + assert.equal(reqEvent.request.url, "https://api.anthropic.com/v1/messages?beta=true"); + assert.equal(reqEvent.request.headers.get("authorization"), `Bearer ${validTokens.access}`); + assert.equal(reqEvent.request.headers.get("x-api-key"), null); + assert.equal(reqEvent.request.headers.get("x-app"), "cli"); + assert.ok(reqEvent.request.headers.get("anthropic-beta")?.includes("oauth-2025-04-20")); + assert.ok(reqEvent.request.headers.get("anthropic-beta")?.includes("thinking-binding-controls-2026-08-01")); + + const rewrittenBody = JSON.parse(await reqEvent.request.clone().text()); + assert.deepEqual(rewrittenBody.thinking, { type: "adaptive" }); + assert.ok(rewrittenBody.system[0].text.startsWith("x-anthropic-billing-header:")); + assert.equal(rewrittenBody.tools[0].name, "Read"); + assert.ok(rewrittenBody.metadata.user_id.includes("acct-uuid-123")); + + // 2. Concurrent API-key request while OAuth request is still in-flight: + // switch active connection to API key before OAuth response arrives. + mock.state.activeConnection = { type: "credential", id: "cred_key", method: "key" }; + mock.state.resolvedCredential = { type: "key", key: "sk-ant-api03-user-key" }; + + const apiKeyReq = new Request("https://api.anthropic.com/v1/messages", { + method: "POST", + headers: { + "content-type": "application/json", + "x-api-key": "sk-ant-api03-user-key", + }, + body: JSON.stringify({ model: "claude-sonnet-4-6", messages: [{ role: "user", content: "hi" }] }), + }); + const apiKeyReqEvent = { request: apiKeyReq }; + await mock.triggerHook("http.request", apiKeyReqEvent); + // Must NOT hijack via keychain even though validTokens are available! + assert.equal(apiKeyReqEvent.request, apiKeyReq); + assert.equal(apiKeyReqEvent.request.headers.get("x-api-key"), "sk-ant-api03-user-key"); + assert.equal(apiKeyReqEvent.request.headers.get("authorization"), null); + + // 3. Responses arrive out of order: OAuth response MUST still be SSE-translated + // while API-key response MUST pass through untouched (regression for oauthMode race). + const ssePayload = + 'event: content_block_start\n' + + 'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"Read","input":{}}}\n\n' + + 'event: content_block_delta\n' + + 'data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"file_path\\":\\"/tmp/a.txt\\"}"}}\n\n' + + 'event: content_block_stop\n' + + 'data: {"type":"content_block_stop","index":0}\n\n'; + + const oauthResEvent = { + request: reqEvent.request, + response: new Response(ssePayload, { + status: 200, + headers: { "content-type": "text/event-stream" }, + }), + }; + await mock.triggerHook("http.response", oauthResEvent); + const oauthOut = await oauthResEvent.response.text(); + assert.ok(oauthOut.includes('"name":"read"'), "OAuth SSE tool name should map Read -> read"); + assert.ok(oauthOut.includes("filePath"), "OAuth SSE args should map file_path -> filePath"); + + const apiKeyRes = new Response(ssePayload, { + status: 200, + headers: { "content-type": "text/event-stream" }, + }); + const apiKeyResEvent = { request: apiKeyReqEvent.request, response: apiKeyRes }; + await mock.triggerHook("http.response", apiKeyResEvent); + assert.equal(apiKeyResEvent.response, apiKeyRes, "API-key response must not be wrapped"); + }); + + it("never rewrites non-Anthropic hosts or cleartext HTTP even with OAuth active", async () => { + const mock = createMockV2Context({ + activeConnection: { type: "credential", id: "cred_1", method: "oauth" }, + resolvedCredential: { type: "oauth", methodID: "oauth", ...validTokens }, + }); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + configuredBaseUrl: undefined, + }); + await setup(mock.ctx); + + for (const badUrl of [ + "https://evilanthropic.com/v1/messages", + "http://api.anthropic.com/v1/messages", + "https://api.openai.com/v1/responses", + ]) { + const req = new Request(badUrl, { method: "POST", body: "{}" }); + const event = { request: req }; + await mock.triggerHook("http.request", event); + assert.equal(event.request, req, `must not rewrite ${badUrl}`); + assert.equal(event.request.headers.get("authorization"), null); + } + }); + + it("never hijacks x-api-key header requests when no integration connection exists", async () => { + const mock = createMockV2Context(); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + // Simulate no oauth.connect so activeConnection remains undefined + delete (mock.ctx.integration as { oauth?: unknown }).oauth; + await setup(mock.ctx); + + const req = new Request("https://api.anthropic.com/v1/messages", { + method: "POST", + headers: { "x-api-key": "sk-ant-api03-direct" }, + body: "{}", + }); + const event = { request: req }; + await mock.triggerHook("http.request", event); + assert.equal(event.request, req); + assert.equal(event.request.headers.get("x-api-key"), "sk-ant-api03-direct"); + }); + + it("system prompt hooks inject Claude prefix in OAuth mode and skip in API-key mode", async () => { + const mock = createMockV2Context({ + activeConnection: { type: "credential", id: "cred_1", method: "oauth" }, + resolvedCredential: { type: "oauth", methodID: "oauth", ...validTokens }, + }); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => validTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + + for (const hookName of ["context", "compaction", "generate", "title"]) { + const event = { + system: [{ type: "text", text: "Base prompt", metadata: { tag: "keep" } }], + }; + await mock.triggerHook(hookName, event); + assert.ok(event.system[0].text.startsWith("You are a Claude agent, built on Anthropic's Claude Agent SDK.\n\nBase prompt")); + assert.deepEqual(event.system[0].metadata, { tag: "keep" }); + + // Idempotent on second call + await mock.triggerHook(hookName, event); + assert.equal(event.system[0].text.match(/Claude Agent SDK/g)?.length, 1); + } + + // Non-text first SystemPart is preserved instead of overwritten + const nonTextEvent = { + system: [{ type: "image", data: "abc" } as Record], + }; + await mock.triggerHook("context", nonTextEvent); + assert.equal(nonTextEvent.system.length, 2); + assert.equal(nonTextEvent.system[0].type, "text"); + assert.equal(nonTextEvent.system[1].type, "image"); + + // Switch to API-key mode: system prompt must not be mutated + mock.state.activeConnection = { type: "env", name: "ANTHROPIC_API_KEY" }; + mock.state.resolvedCredential = { type: "key", key: "sk-ant-api03-key" }; + const apiKeyEvent = { system: [{ type: "text", text: "Clean prompt" }] }; + await mock.triggerHook("context", apiKeyEvent); + assert.equal(apiKeyEvent.system[0].text, "Clean prompt"); + }); + + it("interactive authorize supports mode:auto with submit paste and code fallback", async () => { + const mock = createMockV2Context(); + let closed = false; + let submittedUrl = ""; + let resolveCode!: (code: string) => void; + const exchanged: Array<{ code: string; verifier: string; redirectUri?: string }> = []; + + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => null, + startOAuthCallbackServer: async () => ({ + url: "https://claude.ai/oauth/authorize?state=s1", + manualUrl: "https://claude.ai/oauth/authorize?manual=1", + verifier: "v-pkce", + state: "s1", + port: 43210, + waitForCode: () => new Promise((res) => { resolveCode = res; }), + submitRedirect: (redirectUrl: string) => { + submittedUrl = redirectUrl; + resolveCode("pasted-auth-code"); + }, + close: () => { + closed = true; + }, + }), + exchangeCodeForTokens: (code, verifier, redirectUri) => { + exchanged.push({ code, verifier, redirectUri }); + return validTokens; + }, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + + const reg = mock.getOAuthRegistration()!; + const auth = await reg.authorize(); + assert.equal(auth.mode, "auto"); + assert.equal(auth.url, "https://claude.ai/oauth/authorize?state=s1"); + assert.equal(typeof auth.submit, "function"); + + await auth.submit("http://localhost:43210/callback?code=pasted-auth-code&state=s1"); + const cred = await auth.callback; + assert.equal(submittedUrl, "http://localhost:43210/callback?code=pasted-auth-code&state=s1"); + assert.equal(closed, true); + assert.deepEqual(exchanged, [ + { code: "pasted-auth-code", verifier: "v-pkce", redirectUri: "http://localhost:43210/callback" }, + ]); + assert.equal(cred.type, "oauth"); + assert.equal(cred.methodID, "oauth"); + assert.equal(cred.access, validTokens.access); + }); + + it("interactive authorize falls back to mode:code when callback server cannot bind", async () => { + const mock = createMockV2Context(); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => null, + startOAuthCallbackServer: async () => { + throw new Error("EACCES"); + }, + createAuthorizationRequest: () => ({ + url: "https://claude.ai/oauth/authorize?state=s-manual", + verifier: "v-manual", + state: "s-manual", + }), + exchangeCodeForTokens: (code, verifier) => ({ + access: `tok:${code}:${verifier}`, + refresh: "ref", + expires: Date.now() + 3_600_000, + }), + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + + const reg = mock.getOAuthRegistration()!; + const auth = await reg.authorize(); + assert.equal(auth.mode, "code"); + await assert.rejects( + () => auth.callback("https://platform.claude.com/oauth/code/callback?code=bad&state=wrong"), + /different sign-in/, + ); + const cred = await auth.callback( + "https://platform.claude.com/oauth/code/callback?code=good-code&state=s-manual", + ); + assert.equal(cred.access, "tok:good-code:v-manual"); + }); + + it("refresh callback persists updated tokens and throws cleanly when all layers fail", async () => { + let nextTokens: OAuthTokens | null = { + access: "sk-ant-oat01-refreshed", + refresh: "sk-ant-ort01-refreshed", + expires: Date.now() + 7_200_000, + }; + const mock = createMockV2Context(); + const setup = createOpenCodeClaudeBridgeV2({ + getClaudeTokens: () => null, + refreshTokensLayered: () => nextTokens, + readCachedClaudePromptCache: () => null, + fetchOAuthProfile: async () => null, + }); + await setup(mock.ctx); + + const reg = mock.getOAuthRegistration()!; + const refreshed = await reg.refresh({ + type: "oauth", + methodID: "oauth", + access: "old", + refresh: "old-ref", + expires: 1, + }); + assert.equal(refreshed.access, "sk-ant-oat01-refreshed"); + assert.equal(refreshed.methodID, "oauth"); + + nextTokens = null; + await assert.rejects( + () => reg.refresh({ type: "oauth", methodID: "oauth", access: "old", refresh: "old-ref", expires: 1 }), + /All Claude OAuth refresh layers failed/, + ); + }); +}); + +describe("OpenCode v1 plugin (server)", () => { + it("system transform prefixes anthropic system prompts and ignores other providers", async () => { + const v1 = await pluginModule.server({ + client: { auth: { set: async () => {} } }, + }); + const transform = v1["experimental.chat.system.transform"]; + + const nonAnthropic = { system: ["Keep untouched"] }; + transform({ model: { providerID: "openai" } }, nonAnthropic); + assert.deepEqual(nonAnthropic.system, ["Keep untouched"]); + + const anthropic = { system: ["Base prompt"] }; + transform({ model: { providerID: "anthropic" } }, anthropic); + assert.ok(anthropic.system[0].startsWith("You are a Claude agent, built on Anthropic's Claude Agent SDK.\n\nBase prompt")); + + // Idempotent + transform({ model: { providerID: "anthropic" } }, anthropic); + assert.equal(anthropic.system[0].match(/Claude Agent SDK/g)?.length, 1); + }); + + it("auth.loader passes through API-key auth without installing a custom fetch", async () => { + const savedApiKey = process.env.ANTHROPIC_API_KEY; + try { + const v1 = await pluginModule.server({ + client: { auth: { set: async () => {} } }, + }); + const provider = { models: {} as Record> }; + const result = await v1.auth.loader( + async () => ({ type: "apikey", access: "sk-ant-api03-v1-key" }), + provider, + ); + assert.equal(result.fetch, undefined); + assert.equal(process.env.ANTHROPIC_API_KEY, "sk-ant-api03-v1-key"); + } finally { + if (savedApiKey === undefined) delete process.env.ANTHROPIC_API_KEY; + else process.env.ANTHROPIC_API_KEY = savedApiKey; + } + }); + + it("auth.loader injects Claude models and rewrites OAuth fetch + SSE responses", async () => { + const savedApiKey = process.env.ANTHROPIC_API_KEY; + const savedFetch = globalThis.fetch; + try { + const v1 = await pluginModule.server({ + client: { auth: { set: async () => {} } }, + }); + + const provider = { models: {} as Record> }; + const oauthAuth = { + type: "oauth", + access: "sk-ant-oat01-v1-token", + refresh: "sk-ant-ort01-v1-refresh", + expires: Date.now() + 3_600_000, + }; + const loaderResult = await v1.auth.loader(async () => oauthAuth, provider); + assert.ok("claude-sonnet-4-6" in provider.models, "should inject ANTHROPIC_MODELS"); + assert.equal(typeof loaderResult.fetch, "function"); + + let capturedUrl = ""; + let capturedHeaders: Record = {}; + let capturedBody = ""; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/api/oauth/profile")) { + return new Response(JSON.stringify({ account: { uuid: "v1-acct-uuid" } }), { status: 200 }); + } + capturedUrl = url; + capturedHeaders = (init?.headers ?? {}) as Record; + capturedBody = String(init?.body ?? ""); + const sse = + 'event: content_block_start\n' + + 'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"Read","input":{}}}\n\n' + + 'event: content_block_delta\n' + + 'data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"file_path\\":\\"/tmp/v1.txt\\"}"}}\n\n' + + 'event: content_block_stop\n' + + 'data: {"type":"content_block_stop","index":0}\n\n'; + return new Response(sse, { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + + const res = await loaderResult.fetch!("https://api.anthropic.com/messages", { + method: "POST", + headers: { "content-type": "application/json", "x-api-key": "oauth-placeholder" }, + body: JSON.stringify({ + model: "claude-sonnet-4-6", + messages: [{ role: "user", content: "Hello" }], + tools: [ + { + name: "read", + description: "Read file", + input_schema: { type: "object", properties: { filePath: { type: "string" } } }, + }, + ], + }), + }); + + assert.equal(capturedUrl, "https://api.anthropic.com/v1/messages?beta=true"); + assert.equal(capturedHeaders["authorization"], "Bearer sk-ant-oat01-v1-token"); + assert.equal(capturedHeaders["x-api-key"], undefined); + assert.ok(capturedHeaders["anthropic-beta"]?.includes("thinking-binding-controls-2026-08-01")); + const parsedOut = JSON.parse(capturedBody); + assert.equal(parsedOut.tools[0].name, "Read"); + + const text = await res.text(); + assert.ok(text.includes('"name":"read"')); + assert.ok(text.includes("filePath")); + } finally { + globalThis.fetch = savedFetch; + if (savedApiKey === undefined) delete process.env.ANTHROPIC_API_KEY; + else process.env.ANTHROPIC_API_KEY = savedApiKey; + } + }); }); describe("selectClaudeCredentials", () => { diff --git a/src/index.ts b/src/index.ts index d9fcaac..77b1e1a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,8 +6,10 @@ import { createAuthorizationRequest, exchangeCodeForTokens, parseAuthCode, + parseOAuthRedirect, refreshTokens, startOAuthCallbackServer, + type OAuthTokens, } from "./oauth.js"; import { getClaudeTokens, readClaudeCredentials } from "./keychain.js"; import { @@ -347,11 +349,17 @@ async function storeAuth( }); } -/** Layered token refresh: valid keychain access → stored refresh → CLI refresh token. */ -async function refreshAuth( +/** + * Layered token refresh WITHOUT persistence: valid keychain access → stored + * refresh token → CLI refresh token. Returns the fresh token set, or null when + * no layer produced one. Throws with the last error detail when a refresh was + * attempted and failed. Persistence is the caller's job: the V1 plugin writes + * to opencode's auth store via `refreshAuth`; the V2 plugin returns the tokens + * from its integration `refresh` callback so opencode itself persists them. + */ +function refreshTokensLayered( auth: AuthType, - client: PluginClient, -): Promise { +): { access: string; refresh: string; expires: number } | null { type Tokens = { access: string; refresh: string; expires: number }; let fresh: Tokens | null = null; const errors: string[] = []; @@ -390,6 +398,21 @@ async function refreshAuth( } } + if (fresh) return fresh; + + if (errors.length > 0) { + throw new Error(errors[errors.length - 1]); + } + + return null; +} + +/** Layered token refresh + persist to opencode's auth store (V1 loader path). */ +async function refreshAuth( + auth: AuthType, + client: PluginClient, +): Promise { + const fresh = refreshTokensLayered(auth); if (fresh) { await storeAuth(client, fresh); auth.access = fresh.access; @@ -397,16 +420,19 @@ async function refreshAuth( auth.expires = fresh.expires; return fresh.access; } - - if (errors.length > 0) { - throw new Error(errors[errors.length - 1]); - } - return null; } /** Best-effort browser open — tries multiple methods on each platform. */ function openBrowser(url: string): void { + // Only open valid HTTPS URLs to prevent command/scheme injection. + try { + const parsed = new URL(url); + if (parsed.protocol !== "https:") return; + } catch { + return; + } + (async () => { const { execFileSync } = await import("node:child_process"); @@ -415,9 +441,17 @@ function openBrowser(url: string): void { const attempts: Array<[string, () => void]> = [ ["launchctl asuser", () => execFileSync("/bin/launchctl", ["asuser", uid, "/usr/bin/open", url], { timeout: 5000 })], ["open", () => execFileSync("/usr/bin/open", [url], { timeout: 3000 })], - ["osascript", () => execFileSync("/usr/bin/osascript", ["-e", `open location "${url}"`], { timeout: 3000 })], + [ + "osascript", + () => + execFileSync( + "/usr/bin/osascript", + ["-e", "on run argv", "-e", "open location (item 1 of argv)", "-e", "end run", "--", url], + { timeout: 3000 }, + ), + ], ]; - for (const [name, attempt] of attempts) { + for (const [, attempt] of attempts) { try { attempt(); break; } catch {} } @@ -429,7 +463,7 @@ function openBrowser(url: string): void { ["xdg-open", () => execFileSync("/usr/bin/xdg-open", [url], { timeout: 3000 })], ["open", () => execFileSync("/usr/bin/open", [url], { timeout: 3000 })], ]; - for (const [name, attempt] of attempts) { + for (const [, attempt] of attempts) { try { attempt(); break; } catch {} } @@ -603,6 +637,250 @@ async function fetchOAuthProfile(accessToken: string): Promise | null; +}; + +/** /messages → /v1/messages and ?beta=true, matching Claude Code's URLs. */ +function normalizeAnthropicApiUrl(rawUrl: string): string { + let requestUrl: URL | null = null; + try { + requestUrl = new URL(rawUrl); + } catch {} + + if (requestUrl?.pathname === "/messages") { + requestUrl.pathname = "/v1/messages"; + } + if (requestUrl?.pathname === "/v1/messages" && !requestUrl.searchParams.has("beta")) { + requestUrl.searchParams.set("beta", "true"); + } + return requestUrl?.toString() ?? rawUrl; +} + +/** + * Mutate a parsed /v1/messages body in place to match Claude Code's wire + * format: adaptive thinking, context management, billing metadata, system + * prompt shaping, Claude tool schemas, and outbound tool-name/argument + * translation. Returns the inbound tool-name map to use when translating the + * response (differs from the static map when Claude schemas were injected). + */ +async function transformClaudeRequestBody( + parsed: any, + opts: { + requestUrl: string; + accessToken: string; + sessionId: string; + deviceId: string; + cachedClaudePromptCache: ClaudeSystemPromptCache | null; + cachedClaudeSystem: NonNullable | null; + }, +): Promise<{ inboundToolNameMap: Record }> { + let inboundToolNameMap = INBOUND_TOOL_NAME_MAP; + + // Only inject adaptive thinking for models that support it. + // Use an explicit allowlist — haiku and older sonnet variants + // (e.g. claude-sonnet-4-5) reject the field entirely. + // claude-sonnet-4-6 and claude-opus-4-x are confirmed to support + // interleaved-thinking-2025-05-14. + const THINKING_MODELS = [ + "claude-opus-4", + "claude-sonnet-4-6", + ]; + const supportsThinking = parsed.model && + THINKING_MODELS.some((m: string) => parsed.model.includes(m)); + if (!parsed.thinking && supportsThinking) { + parsed.thinking = { type: "adaptive" }; + } + + // Anthropic requires temperature=1 when thinking is enabled/adaptive + const thinkingType = parsed.thinking?.type; + if ( + (thinkingType === "enabled" || thinkingType === "adaptive") && + parsed.temperature !== undefined && + parsed.temperature !== 1 + ) { + parsed.temperature = 1; + } + + if (!parsed.system) parsed.system = []; + if (Array.isArray(parsed.messages)) { + parsed.messages = stripAssistantPrefillForClaude(parsed.messages); + } + // context_management and output_config.effort are only + // supported by thinking-capable models. Sending them to + // haiku (used for title generation) produces a 400. + if (supportsThinking) { + if (!parsed.context_management) { + parsed.context_management = { + edits: [{ type: CLEAR_THINKING_TYPE, keep: "all" }], + }; + } + if (!parsed.output_config) { + parsed.output_config = { effort: DEFAULT_EFFORT }; + } + } + + const profile = opts.accessToken + ? await fetchOAuthProfile(opts.accessToken) + : null; + if (!parsed.metadata) parsed.metadata = {}; + if (!parsed.metadata.user_id && profile?.account?.uuid) { + parsed.metadata.user_id = JSON.stringify({ + device_id: opts.deviceId, + account_uuid: profile.account.uuid, + session_id: opts.sessionId, + }); + } + + // Compute dynamic fingerprint from the first user message + // (matches Claude Code's per-request fingerprint behavior). + let dynamicFingerprint: string | undefined; + if (parsed.messages && Array.isArray(parsed.messages)) { + const firstText = extractFirstUserMessageText(parsed.messages); + if (firstText) { + dynamicFingerprint = computeFingerprint(firstText); + } + } + + // Inject billing header as first system block (required for OAuth). + const hasBilling = parsed.system.some( + (s: { text?: string }) => + s.text?.startsWith("x-anthropic-billing-header:"), + ); + let billingHeader = buildBillingHeader(opts.sessionId, opts.cachedClaudePromptCache, dynamicFingerprint); + if (!hasBilling) { + parsed.system.unshift({ + type: "text", + text: billingHeader, + }); + } else { + billingHeader = parsed.system[0]?.text || billingHeader; + } + + // If we have a locally captured Claude Code system prompt, prefer it. + if (opts.cachedClaudeSystem) { + const rewritten = rewriteSystemBlocksForModel( + opts.cachedClaudeSystem, + typeof parsed.model === "string" ? parsed.model : undefined, + ); + parsed.system = [ + { type: "text", text: billingHeader }, + ...rewritten, + ]; + } else if (parsed.system && Array.isArray(parsed.system)) { + // Otherwise keep the existing prompt but shape it closer to Claude Code. + parsed.system = normalizeSystemBlocks(parsed.system); + } + parsed.system = stripSystemCacheControl(parsed.system); + + // Keep OpenCode's default tool schemas for non-Claude targets. + // Claude wire schemas are only useful for Anthropic-native + // requests or Claude-family models on Anthropic-compatible + // routers such as OpenRouter. + if (shouldInjectClaudeTools({ model: parsed.model, requestUrl: opts.requestUrl, tools: parsed.tools })) { + inboundToolNameMap = getInboundToolNameMapForActiveOpenCodeTools(parsed.tools); + parsed.tools = getClaudeToolsForActiveOpenCodeTools(parsed.tools); + } + delete parsed.tool_choice; + + // Normalize message content blocks: + // - Translate tool names (OpenCode → Claude Code) + // - Translate tool_use input arguments (camelCase → snake_case) + // - Clean up text blocks + if (parsed.messages && Array.isArray(parsed.messages)) { + for (const msg of parsed.messages) { + if (!Array.isArray(msg.content)) continue; + for (const block of msg.content) { + if (block.type === "text" && typeof block.text === "string") { + block.text = maybeUnquoteText(block.text); + delete block.cache_control; + } + if (block.type === "tool_use" && block.name) { + block.name = mapOutboundToolName(block.name); + // Consolidated OpenCode → Claude argument translation: + // key renames, Agent/AskUserQuestion/Skill/WebFetch/TodoWrite + // field bridging. Mirrors translateToolArgsJsonString + // (inbound) so round-trips preserve meaning. See + // translateArgsOpencodeToClaude in claude-tools.ts. + if (block.input && typeof block.input === "object") { + block.input = translateArgsOpencodeToClaude( + block.name, + block.input as Record, + ); + } + } + // tool_result blocks reference tool names via tool_use_id, + // no name translation needed here. + } + } + } + + return { inboundToolNameMap }; +} + +/** + * Stream a response through the SSE processor so Claude-style tool names and + * arguments are translated back to OpenCode on assembled content_block_stop + * payloads. Buffers input_json_delta fragments per content-block index, which + * avoids chunk-boundary corruption that regex-on-raw-bytes can't handle. + */ +function wrapAnthropicResponseWithSse( + response: Response, + inboundToolNameMap: Record, +): Response { + if (!response.body) return response; + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + + const processor = createSseProcessor({ + inboundToolNameMap, + translateToolArgs: translateToolArgsJsonString, + }); + + return new Response( + new ReadableStream({ + start(controller) { + // Use start() with an async loop rather than pull(): + // Bun's ReadableStream doesn't reliably re-invoke pull() + // when the handler resolves without enqueuing (which + // happens while we're buffering input_json_delta + // fragments), so pull() can stall the stream. + (async () => { + try { + while (true) { + const { done, value } = await reader.read(); + if (done) { + const decodedTail = decoder.decode(); + if (decodedTail) { + const out = processor.feedChunk(decodedTail); + if (out) controller.enqueue(encoder.encode(out)); + } + const tail = processor.flush(); + if (tail) controller.enqueue(encoder.encode(tail)); + controller.close(); + return; + } + const out = processor.feedChunk(decoder.decode(value, { stream: true })); + if (out) controller.enqueue(encoder.encode(out)); + } + } catch (e) { + controller.error(e); + } + })(); + }, + }), + { status: response.status, statusText: response.statusText, headers: response.headers }, + ); +} + const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { // Save and clear ANTHROPIC_API_KEY so SDK doesn't bypass our fetch. // Restored if OAuth isn't active (API key providers still work). @@ -738,166 +1016,25 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { ); } catch {} - // Only inject adaptive thinking for models that support it. - // Use an explicit allowlist — haiku and older sonnet variants - // (e.g. claude-sonnet-4-5) reject the field entirely. - // claude-sonnet-4-6 and claude-opus-4-x are confirmed to support - // interleaved-thinking-2025-05-14. - const THINKING_MODELS = [ - "claude-opus-4", - "claude-sonnet-4-6", - ]; - const supportsThinking = parsed.model && - THINKING_MODELS.some((m: string) => parsed.model.includes(m)); - if (!parsed.thinking && supportsThinking) { - parsed.thinking = { type: "adaptive" }; - } - - // Anthropic requires temperature=1 when thinking is enabled/adaptive - const thinkingType = parsed.thinking?.type; - if ( - (thinkingType === "enabled" || thinkingType === "adaptive") && - parsed.temperature !== undefined && - parsed.temperature !== 1 - ) { - parsed.temperature = 1; - } - - if (!parsed.system) parsed.system = []; - if (Array.isArray(parsed.messages)) { - parsed.messages = stripAssistantPrefillForClaude(parsed.messages); - } - // context_management and output_config.effort are only - // supported by thinking-capable models. Sending them to - // haiku (used for title generation) produces a 400. - if (supportsThinking) { - if (!parsed.context_management) { - parsed.context_management = { - edits: [{ type: CLEAR_THINKING_TYPE, keep: "all" }], - }; - } - if (!parsed.output_config) { - parsed.output_config = { effort: DEFAULT_EFFORT }; - } - } - - const profile = auth.access - ? await fetchOAuthProfile(auth.access) - : null; - if (!parsed.metadata) parsed.metadata = {}; - if (!parsed.metadata.user_id && profile?.account?.uuid) { - parsed.metadata.user_id = JSON.stringify({ - device_id: deviceId, - account_uuid: profile.account.uuid, - session_id: sessionId, - }); - } - - // Compute dynamic fingerprint from the first user message - // (matches Claude Code's per-request fingerprint behavior). - let dynamicFingerprint: string | undefined; - if (parsed.messages && Array.isArray(parsed.messages)) { - const firstText = extractFirstUserMessageText(parsed.messages); - if (firstText) { - dynamicFingerprint = computeFingerprint(firstText); - } - } - - // Inject billing header as first system block (required for OAuth). - const hasBilling = parsed.system.some( - (s: { text?: string }) => - s.text?.startsWith("x-anthropic-billing-header:"), - ); - let billingHeader = buildBillingHeader(sessionId, cachedClaudePromptCache, dynamicFingerprint); - if (!hasBilling) { - parsed.system.unshift({ - type: "text", - text: billingHeader, - }); - } else { - billingHeader = parsed.system[0]?.text || billingHeader; - } - - // If we have a locally captured Claude Code system prompt, prefer it. - if (cachedClaudeSystem) { - const rewritten = rewriteSystemBlocksForModel( - cachedClaudeSystem, - typeof parsed.model === "string" ? parsed.model : undefined, - ); - parsed.system = [ - { type: "text", text: billingHeader }, - ...rewritten, - ]; - } else if (parsed.system && Array.isArray(parsed.system)) { - // Otherwise keep the existing prompt but shape it closer to Claude Code. - parsed.system = normalizeSystemBlocks(parsed.system); - } - parsed.system = stripSystemCacheControl(parsed.system); - - // Keep OpenCode's default tool schemas for non-Claude targets. - // Claude wire schemas are only useful for Anthropic-native - // requests or Claude-family models on Anthropic-compatible - // routers such as OpenRouter. - if (shouldInjectClaudeTools({ model: parsed.model, requestUrl, tools: parsed.tools })) { - inboundToolNameMap = getInboundToolNameMapForActiveOpenCodeTools(parsed.tools); - parsed.tools = getClaudeToolsForActiveOpenCodeTools(parsed.tools); - } - delete parsed.tool_choice; - - // Normalize message content blocks: - // - Translate tool names (OpenCode → Claude Code) - // - Translate tool_use input arguments (camelCase → snake_case) - // - Clean up text blocks - if (parsed.messages && Array.isArray(parsed.messages)) { - for (const msg of parsed.messages) { - if (!Array.isArray(msg.content)) continue; - for (const block of msg.content) { - if (block.type === "text" && typeof block.text === "string") { - block.text = maybeUnquoteText(block.text); - delete block.cache_control; - } - if (block.type === "tool_use" && block.name) { - block.name = mapOutboundToolName(block.name); - // Consolidated OpenCode → Claude argument translation: - // key renames, Agent/AskUserQuestion/Skill/WebFetch/TodoWrite - // field bridging. Mirrors translateToolArgsJsonString - // (inbound) so round-trips preserve meaning. See - // translateArgsOpencodeToClaude in claude-tools.ts. - if (block.input && typeof block.input === "object") { - block.input = translateArgsOpencodeToClaude( - block.name, - block.input as Record, - ); - } - } - // tool_result blocks reference tool names via tool_use_id, - // no name translation needed here. - } - } - } - + const result = await transformClaudeRequestBody(parsed, { + requestUrl, + accessToken: accessToken || "", + sessionId, + deviceId, + cachedClaudePromptCache, + cachedClaudeSystem, + }); + inboundToolNameMap = result.inboundToolNameMap; body = JSON.stringify(parsed); } catch {} } // ── URL: add ?beta=true ── - let requestUrl: URL | null = null; - try { - requestUrl = new URL( - typeof input === "string" ? input - : input instanceof URL ? input.toString() - : input.url, - ); - } catch {} - - if (requestUrl?.pathname === "/messages") { - requestUrl.pathname = "/v1/messages"; - } - if (requestUrl?.pathname === "/v1/messages" && !requestUrl.searchParams.has("beta")) { - requestUrl.searchParams.set("beta", "true"); - } - const finalUrl = requestUrl?.toString() - ?? (input instanceof Request ? input.url : String(input)); + const finalUrl = normalizeAnthropicApiUrl( + typeof input === "string" ? input + : input instanceof URL ? input.toString() + : input.url, + ); // ── Request (with 429 auto-refresh retry) ── const outHeaders: Record = {}; @@ -938,52 +1075,7 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { } // ── Map Claude-style tool names and arguments back to OpenCode ── - if (!response.body) return response; - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - const encoder = new TextEncoder(); - - // Parse SSE events on \n\n boundaries, buffer tool_use - // input_json_delta fragments per content-block index, and - // translate the assembled JSON once at content_block_stop. - // This avoids chunk-boundary corruption (e.g. "file_" + "path" - // split across TCP chunks) that regex-on-raw-bytes can't - // handle. See src/stream.ts for the processor implementation. - const processor = createSseProcessor({ - inboundToolNameMap, - translateToolArgs: translateToolArgsJsonString, - }); - - return new Response( - new ReadableStream({ - start(controller) { - // Use start() with an async loop rather than pull(): - // Bun's ReadableStream doesn't reliably re-invoke pull() - // when the handler resolves without enqueuing (which - // happens while we're buffering input_json_delta - // fragments), so pull() can stall the stream. - (async () => { - try { - while (true) { - const { done, value } = await reader.read(); - if (done) { - const tail = processor.flush(); - if (tail) controller.enqueue(encoder.encode(tail)); - controller.close(); - return; - } - const out = processor.feedChunk(decoder.decode(value, { stream: true })); - if (out) controller.enqueue(encoder.encode(out)); - } - } catch (e) { - controller.error(e); - } - })(); - }, - }), - { status: response.status, statusText: response.statusText, headers: response.headers }, - ); + return wrapAnthropicResponseWithSse(response, inboundToolNameMap); }, }; }, @@ -1135,15 +1227,600 @@ const OpenCodeClaudeBridge = async ({ client }: { client: PluginClient }) => { }; }; +// ── OpenCode v2 plugin ───────────────────────────────────────────── +// opencode ≥ 2.0 loads plugins through a different contract: the default +// export must carry an `id` plus a `setup(ctx)` (Promise) or `effect(ctx)` +// (Effect) function, and V1 hooks never run. The `server()` shape keeps the +// V1 implementation working on opencode ≥ 1.18.29; `setup` adds v2 by mapping +// the same behavior onto the v2 APIs: +// +// V1 → V2 +// auth.loader (custom fetch) → session.hook("http.request") +// auth.loader (response wrapping) → session.hook("http.response") +// auth.methods (OAuth) → integration.transform, method +// override on `anthropic` with +// authorize + refresh callbacks +// keychain bootstrap at init → integration.oauth.connect (when +// no anthropic connection exists) +// auth.methods (API key) → native /connect (passthrough) +// experimental.chat.system.transform → session.hook("context" | +// "compaction" | "generate" | "title") +// +// Deliberate divergences from the V1 implementation under v2: +// - No model injection: the v2 models.dev catalog already lists Claude +// models and a stored OAuth credential activates the provider. +// - No inline 429 refresh-retry: Claude refresh tokens are single-use, so +// rotating them anywhere but the integration `refresh` callback (whose +// result opencode persists) would invalidate the stored token. opencode's +// native retry policy handles 429 backoff. +// - Rewrites apply strictly to HTTPS anthropic.com hosts (plus an explicitly +// configured HTTPS or loopback ANTHROPIC_BASE_URL); the v2 hooks observe +// every HTTP request for the provider, while the V1 fetch wrapper sat +// inside the provider SDK. + +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]); + +/** + * Strictly verify that a request URL targets Anthropic's HTTPS API (or an + * explicitly configured HTTPS / loopback `ANTHROPIC_BASE_URL` proxy) before + * attaching an OAuth bearer token or rewriting the payload. + * + * Prevents suffix-spoofing (e.g. `evilanthropic.com`) and plaintext HTTP + * token downgrade. + */ +export function isAnthropicApiUrl( + url: string, + configuredBaseUrl: string | undefined = process.env.ANTHROPIC_BASE_URL, +): boolean { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return false; + } + + const host = parsed.hostname.toLowerCase(); + if ( + parsed.protocol === "https:" && + (host === "anthropic.com" || host.endsWith(".anthropic.com")) + ) { + return true; + } + + if (configuredBaseUrl) { + try { + const base = new URL(configuredBaseUrl); + const baseHost = base.hostname.toLowerCase(); + const allowedScheme = + base.protocol === "https:" || + (base.protocol === "http:" && LOOPBACK_HOSTS.has(baseHost)); + if (allowedScheme && parsed.origin === base.origin) { + return true; + } + } catch {} + } + + return false; +} + +type V2OAuthCredential = { + type: "oauth"; + methodID: string; + access: string; + refresh: string; + expires: number; +}; + +type V2OAuthAuthorization = { + url: string; + instructions: string; + expiresAt?: number; +} & ( + | { + mode: "auto"; + callback: Promise; + submit?: (redirect: string) => Promise; + } + | { + mode: "code"; + callback: (code: string) => Promise; + } +); + +type V2ConnectionInfo = + | { type: "credential"; id: string; label?: string; method?: string } + | { type: "env"; name: string }; + +type V2Registration = { + dispose?: () => Promise | void; +}; + +// Structural subset of @opencode/plugin's Context (v2.3.x), kept local so the +// published package stays zero-dependency with a self-contained index.d.ts. +export type V2PluginContext = { + integration: { + transform: ( + editor: (editor: { + method: { + update(registration: { + integrationID: string; + method: { id: string; type: "oauth"; label: string }; + authorize: () => Promise; + refresh: ( + credential: V2OAuthCredential, + ) => Promise; + }): void; + }; + }) => void, + ) => Promise; + oauth?: { + connect: (input: { + integrationID: string; + methodID: string; + label?: string; + }) => Promise; + }; + connection: { + active: (integrationID: string) => Promise; + resolve: ( + connection: V2ConnectionInfo, + ) => Promise< + | { + type?: string; + access?: string; + refresh?: string; + expires?: number; + key?: string; + methodID?: string; + } + | undefined + >; + }; + }; + session: { + hook: ( + name: string, + callback: (event: any) => void | Promise, + options?: { providerID?: string }, + ) => Promise; + }; +}; + +export type V2BridgeDeps = { + getClaudeTokens?: typeof getClaudeTokens; + refreshTokensLayered?: typeof refreshTokensLayered; + startOAuthCallbackServer?: typeof startOAuthCallbackServer; + createAuthorizationRequest?: typeof createAuthorizationRequest; + exchangeCodeForTokens?: typeof exchangeCodeForTokens; + readCachedClaudePromptCache?: typeof readCachedClaudePromptCache; + fetchOAuthProfile?: typeof fetchOAuthProfile; + configuredBaseUrl?: string; +}; + +const V2_SYSTEM_HOOKS = ["context", "compaction", "generate", "title"] as const; + +export function createOpenCodeClaudeBridgeV2(deps: V2BridgeDeps = {}) { + const readTokens = deps.getClaudeTokens ?? getClaudeTokens; + const runLayeredRefresh = deps.refreshTokensLayered ?? refreshTokensLayered; + const startCallback = deps.startOAuthCallbackServer ?? startOAuthCallbackServer; + const createAuthReq = deps.createAuthorizationRequest ?? createAuthorizationRequest; + const exchangeCode = deps.exchangeCodeForTokens ?? exchangeCodeForTokens; + const readPromptCache = deps.readCachedClaudePromptCache ?? readCachedClaudePromptCache; + const getProfile = deps.fetchOAuthProfile ?? fetchOAuthProfile; + + return async function setup(ctx: V2PluginContext): Promise<() => Promise> { + const sessionId = SESSION_ID || randomUUID(); + const deviceId = getStableDeviceId(); + const cachedClaudePromptCache = readPromptCache(); + const cachedClaudeSystem = cachedClaudePromptCache?.system || null; + const state: AnthropicRequestState = { + sessionId, + deviceId, + cachedClaudePromptCache, + cachedClaudeSystem, + }; + + const registrations: V2Registration[] = []; + const activeServers = new Set<() => void>(); + const track = (reg: V2Registration | void) => { + if (reg && typeof reg.dispose === "function") registrations.push(reg); + }; + + // One-shot token handoff used exclusively by startup keychain bootstrap so + // `oauth.connect` never spawns a callback server or opens a browser. + let bootstrapTokens: OAuthTokens | null = null; + + // Per-request inbound tool-name map, computed during the request rewrite. + // Keyed weakly on the rewritten Request (which the response event carries), + // so concurrent OAuth and API-key requests never race on shared state. + const inboundMaps = new WeakMap>(); + + const toOAuthCredential = (tokens: OAuthTokens): V2OAuthCredential => ({ + type: "oauth", + methodID: "oauth", + access: tokens.access, + refresh: tokens.refresh, + expires: tokens.expires, + }); + + /** + * Resolve whether Anthropic is currently operating in OAuth mode and, if + * so, return the access token to use. Strictly returns null whenever an + * API key (`env` connection, `key` credential, or `x-api-key` header) is + * active so API-key users are never hijacked by a local Claude CLI login. + */ + async function resolveAccessToken(request?: Request): Promise { + const authHeader = request?.headers?.get?.("authorization"); + const hasBearer = + typeof authHeader === "string" && + authHeader.startsWith("Bearer ") && + authHeader.length > 7; + const hasApiKeyHeader = Boolean(request?.headers?.get?.("x-api-key")); + + let activeConnection: V2ConnectionInfo | undefined; + try { + activeConnection = await ctx.integration.connection.active("anthropic"); + } catch { + activeConnection = undefined; + } + + if (activeConnection) { + // Explicit env var (e.g. ANTHROPIC_API_KEY) — never hijack with OAuth. + if (activeConnection.type === "env") { + return null; + } + try { + const credential = await ctx.integration.connection.resolve(activeConnection); + if (!credential) { + // Credential exists but couldn't resolve — fall back to request Bearer only. + return hasBearer ? authHeader.slice(7) : null; + } + if (credential.type !== "oauth") { + // Stored API key or external credential — passthrough untouched. + return null; + } + if (hasBearer) { + return authHeader.slice(7); + } + if ( + credential.access && + (typeof credential.expires !== "number" || + credential.expires === 0 || + credential.expires > Date.now()) + ) { + return credential.access; + } + return null; + } catch { + return hasBearer ? authHeader.slice(7) : null; + } + } + + // No active integration connection. + // Respect an explicit x-api-key header (e.g. custom provider config). + if (hasApiKeyHeader && !hasBearer) { + return null; + } + if (hasBearer) { + return authHeader.slice(7); + } + + // Fallback when no connection or API key exists at all: read valid + // non-expired Claude CLI keychain tokens without rotating refresh tokens. + try { + const tokens = readTokens({ refreshExpired: false }); + if (tokens?.access && tokens.expires > Date.now()) return tokens.access; + } catch {} + return null; + } + + // ── Auth: register the `oauth` method on the `anthropic` integration so + // `/connect`, startup keychain sync, and automatic refresh all go through + // the bridge's layered refresh and persist credentials atomically. + track( + await ctx.integration.transform((editor) => { + editor.method.update({ + integrationID: "anthropic", + method: { id: "oauth", type: "oauth", label: "Claude Pro / Max (OAuth)" }, + async authorize(): Promise { + // 1. Startup keychain bootstrap handoff (one-shot, no browser/server) + if (bootstrapTokens) { + const tokens = bootstrapTokens; + bootstrapTokens = null; + return { + url: "", + instructions: "Connected via Claude CLI keychain.", + mode: "auto", + callback: Promise.resolve(toOAuthCredential(tokens)), + }; + } + + // 2. Interactive fast-path: auto-bootstrap from Claude CLI keychain + try { + const tokens = readTokens({ refreshExpired: false }); + if (tokens) { + return { + url: "", + instructions: + "Connected via Claude CLI keychain — no browser needed.", + mode: "auto", + callback: Promise.resolve(toOAuthCredential(tokens)), + }; + } + } catch {} + + // 3. Localhost PKCE callback server with v2-native `mode: "auto"` + // and `submit` paste support (for SSH/remote environments). + // OpenCode's client handles opening `url`, so we do NOT invoke + // `openBrowser` here (avoids duplicate tabs and remote failures). + let callbackServer: Awaited> | null = null; + try { + callbackServer = await startCallback(); + } catch (err) { + console.error(`[opencode-oauth] Failed to start callback server: ${err}`); + } + + if (callbackServer) { + const server = callbackServer; + const redirectUri = `http://localhost:${server.port}/callback`; + activeServers.add(server.close); + const callback = (async () => { + try { + const code = await server.waitForCode(); + const tokens = exchangeCode(code, server.verifier, redirectUri); + return toOAuthCredential(tokens); + } finally { + activeServers.delete(server.close); + server.close(); + } + })(); + return { + url: server.url, + instructions: + "Complete authorization in your browser. If the redirect cannot reach this machine, paste the full redirect URL from your browser's address bar.", + mode: "auto", + callback, + submit: async (redirect: string) => { + server.submitRedirect(redirect); + }, + }; + } + + // 4. Fallback: environments where localhost binding is unavailable. + const { url, verifier, state: oauthState } = createAuthReq(); + return { + url, + instructions: `After authorizing in your browser, paste the authorization code below:\n${url}`, + mode: "code", + callback: async (rawInput: string) => { + const trimmed = rawInput.trim(); + let code: string; + if (/^https?:\/\//i.test(trimmed)) { + const parsed = parseOAuthRedirect(trimmed, oauthState); + if ("error" in parsed) { + throw new Error(`OAuth error: ${parsed.error}`); + } + code = parsed.code; + } else { + code = parseAuthCode(trimmed); + } + if (!code) { + throw new Error("No authorization code received"); + } + return toOAuthCredential(exchangeCode(code, verifier)); + }, + }; + }, + async refresh(credential) { + // Layered refresh (keychain → stored → CLI). MUST return a promise: + // opencode awaits it and persists the resolved credential under a + // cross-process lock. Never refresh outside this callback — Claude + // refresh tokens are single-use. + const fresh = runLayeredRefresh(credential); + if (!fresh) { + throw new Error( + "All Claude OAuth refresh layers failed. Run `claude login` or reconnect 'Claude Pro / Max (OAuth)'.", + ); + } + return toOAuthCredential(fresh); + }, + }); + }), + ); + + // ── Seamless zero-config keychain bootstrap ── + // OpenCode v2 only exposes catalog providers with at least one connection. + // When no Anthropic connection exists yet (neither stored credential nor + // ANTHROPIC_API_KEY env var) and the user already ran `claude login`, + // persist the keychain credential once via our registered OAuth method so + // Anthropic appears immediately without requiring `/connect`. + if (ctx.integration.oauth?.connect) { + try { + const existing = await ctx.integration.connection.active("anthropic"); + if (!existing) { + const tokens = readTokens({ refreshExpired: false }); + if (tokens) { + bootstrapTokens = tokens; + try { + await ctx.integration.oauth.connect({ + integrationID: "anthropic", + methodID: "oauth", + label: "Claude CLI", + }); + } finally { + bootstrapTokens = null; + } + } + } + } catch (err) { + console.error(`[opencode-claude-bridge] Keychain bootstrap skipped: ${err}`); + } + } + + // ── System prompt prefix (v2 replacement of + // experimental.chat.system.transform) ── + // Registered on all four session request kinds so primary turns, + // compaction, generate, and title requests match V1 behavior — gated on + // OAuth mode so API-key traffic keeps an unmodified system prompt. + const prependClaudePrefix = async (event: { + system: Array<{ type?: string; text?: string; [k: string]: unknown }>; + }) => { + if (!(await resolveAccessToken())) return; + if ( + event.system.some( + (s) => typeof s?.text === "string" && s.text.includes(CLAUDE_PREFIX), + ) + ) { + return; + } + if (event.system.length > 0 && event.system[0]?.type === "text") { + event.system[0] = { + ...event.system[0], + text: `${CLAUDE_PREFIX}\n\n${event.system[0].text ?? ""}`, + }; + } else { + event.system.unshift({ type: "text", text: CLAUDE_PREFIX }); + } + }; + + for (const hookName of V2_SYSTEM_HOOKS) { + track( + await ctx.session.hook(hookName, prependClaudePrefix, { + providerID: "anthropic", + }), + ); + } + + // ── Wire rewrite (v2 replacement of the auth.loader fetch, request phase) ── + track( + await ctx.session.hook( + "http.request", + async (event: { request: Request }) => { + const request = event.request; + if (!isAnthropicApiUrl(request.url, deps.configuredBaseUrl)) return; + const accessToken = await resolveAccessToken(request); + if (!accessToken) return; // API-key or unauthenticated — passthrough + + try { + // ── Headers ── + const headers = new Headers(); + if (request.headers) mergeHeaders(headers, request.headers); + headers.set("authorization", `Bearer ${accessToken}`); + headers.delete("x-api-key"); + headers.delete("x-session-affinity"); + headers.delete("x-session-id"); + if (!headers.has("accept")) headers.set("accept", "application/json"); + headers.set("user-agent", USER_AGENT); + headers.set("x-app", "cli"); + headers.set("x-claude-code-session-id", sessionId); + headers.set("anthropic-version", ANTHROPIC_VERSION); + headers.set("anthropic-dangerous-direct-browser-access", "true"); + for (const [k, v] of Object.entries(STAINLESS_HEADERS)) headers.set(k, v); + if (!headers.has("x-stainless-retry-count")) headers.set("x-stainless-retry-count", "0"); + if (!headers.has("x-stainless-timeout")) headers.set("x-stainless-timeout", "600"); + headers.set("anthropic-beta", buildBetaFlags(headers.get("anthropic-beta") || "")); + + // ── Body ── + let body: string | null = null; + let inboundToolNameMap = INBOUND_TOOL_NAME_MAP; + if (request.method !== "GET" && request.method !== "HEAD") { + try { + body = await request.clone().text(); + } catch { + body = null; + } + } + if (body) { + try { + const parsed = JSON.parse(body); + const profile = await getProfile(accessToken); + if (!parsed.metadata) parsed.metadata = {}; + if (!parsed.metadata.user_id && profile?.account?.uuid) { + parsed.metadata.user_id = JSON.stringify({ + device_id: state.deviceId, + account_uuid: profile.account.uuid, + session_id: state.sessionId, + }); + } + const result = await transformClaudeRequestBody(parsed, { + requestUrl: request.url, + accessToken: "", // profile already populated above via injectable getProfile + sessionId: state.sessionId, + deviceId: state.deviceId, + cachedClaudePromptCache: state.cachedClaudePromptCache, + cachedClaudeSystem: state.cachedClaudeSystem, + }); + inboundToolNameMap = result.inboundToolNameMap; + body = JSON.stringify(parsed); + } catch {} + } + + const finalUrl = normalizeAnthropicApiUrl(request.url); + const rewritten = new Request(finalUrl, { + method: request.method, + headers, + ...(body !== null ? { body } : {}), + signal: request.signal, + }); + inboundMaps.set(rewritten, inboundToolNameMap); + event.request = rewritten; + } catch (err) { + console.error(`[opencode-claude-bridge] request rewrite failed, sending original: ${err}`); + } + }, + { providerID: "anthropic" }, + ), + ); + + // ── SSE tool-name/argument translation (response phase) ── + track( + await ctx.session.hook( + "http.response", + (event: { request: Request; response: Response }) => { + const inboundToolNameMap = inboundMaps.get(event.request); + if (!inboundToolNameMap) return; // Not OAuth-rewritten — passthrough + try { + event.response = wrapAnthropicResponseWithSse(event.response, inboundToolNameMap); + } catch (err) { + console.error(`[opencode-claude-bridge] response wrap failed: ${err}`); + } + }, + { providerID: "anthropic" }, + ), + ); + + return async () => { + for (const close of activeServers) { + try { + close(); + } catch {} + } + activeServers.clear(); + for (const reg of registrations.splice(0).reverse()) { + try { + await reg.dispose?.(); + } catch {} + } + }; + }; +} + +const OpenCodeClaudeBridgeV2 = { + setup: createOpenCodeClaudeBridgeV2(), +}; + /** * opencode plugin module. * - * The `{ id, server }` shape is what opencode's plugin loader looks for. A bare - * function default export makes it fall back to its legacy path, which treats - * every named export of this module as a plugin factory and invokes it with - * `(input, options)` — crashing on the helpers exported here for tests. + * `{ id, server }` is the entrypoint opencode ≥ 1.18 loads; `id` + `setup` is + * what opencode ≥ 2.0 requires (there it ignores `server` and never runs V1 + * hooks). A bare function default export makes older loaders fall back to + * their legacy path, which treats every named export of this module as a + * plugin factory and invokes it with `(input, options)` — crashing on the + * helpers exported here for tests. */ export default { id: PLUGIN_ID, + setup: OpenCodeClaudeBridgeV2.setup, server: OpenCodeClaudeBridge, }; diff --git a/src/oauth.ts b/src/oauth.ts index 2acdb23..8de4c82 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -1,4 +1,4 @@ -import { randomBytes, createHash } from "node:crypto"; +import { randomBytes, createHash, timingSafeEqual } from "node:crypto"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { execFileSync } from "node:child_process"; import { @@ -29,6 +29,12 @@ export interface OAuthCallbackServer { port: number; /** Wait for the authorization code to arrive via localhost redirect. Resolves with the code. */ waitForCode: () => Promise; + /** + * Accept a pasted redirect URL (for remote/SSH environments where the + * browser cannot reach localhost). Validates `state` identically to the + * browser callback; throws on invalid paste without aborting the attempt. + */ + submitRedirect: (redirectUrl: string) => void; /** Stop the callback server. */ close: () => void; } @@ -37,6 +43,45 @@ function base64url(buf: Buffer): string { return buf.toString("base64url").replace(/=+$/, ""); } +function safeEqual(a: string, b: string): boolean { + const bufA = Buffer.from(a, "utf8"); + const bufB = Buffer.from(b, "utf8"); + if (bufA.length !== bufB.length) return false; + return timingSafeEqual(bufA, bufB); +} + +/** + * Validate and extract the authorization code (or OAuth error) from a pasted + * redirect URL, enforcing CSRF `state` equality. Throws a user-facing error + * if the paste is malformed, belongs to a different sign-in, or lacks a code. + */ +export function parseOAuthRedirect( + raw: string, + expectedState: string, +): { code: string } | { error: string } { + const value = raw.trim(); + let parsed: URL; + try { + parsed = new URL(value); + } catch { + throw new Error("Paste the full URL from the browser's address bar"); + } + const receivedState = parsed.searchParams.get("state"); + if (!receivedState || !safeEqual(receivedState, expectedState)) { + throw new Error("This URL belongs to a different sign-in"); + } + const error = + parsed.searchParams.get("error_description") || parsed.searchParams.get("error"); + if (error) { + return { error }; + } + const code = parsed.searchParams.get("code"); + if (!code) { + throw new Error("The URL does not contain an authorization code"); + } + return { code }; +} + function sleep(ms: number): void { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } @@ -142,10 +187,11 @@ function parseTokenResponse(status: number, body: string, label: string): OAuthT */ function buildAuthUrls( port: number, + pkce?: { verifier: string; challenge: string; state: string }, ): { automaticUrl: string; manualUrl: string; verifier: string; state: string } { - const verifier = base64url(randomBytes(64)); - const challenge = base64url(createHash("sha256").update(verifier).digest()); - const state = base64url(randomBytes(32)); + const verifier = pkce?.verifier ?? base64url(randomBytes(64)); + const challenge = pkce?.challenge ?? base64url(createHash("sha256").update(verifier).digest()); + const state = pkce?.state ?? base64url(randomBytes(32)); const automaticRedirectUri = `http://localhost:${port}/callback`; @@ -181,6 +227,11 @@ function buildAuthUrls( */ export function startOAuthCallbackServer(): Promise { return new Promise((resolve, reject) => { + const verifier = base64url(randomBytes(64)); + const challenge = base64url(createHash("sha256").update(verifier).digest()); + const state = base64url(randomBytes(32)); + + let settled = false; let codeResolve: ((code: string) => void) | null = null; let codeReject: ((err: Error) => void) | null = null; const codePromise = new Promise((res, rej) => { @@ -188,28 +239,57 @@ export function startOAuthCallbackServer(): Promise { codeReject = rej; }); + const settleCode = (code: string): boolean => { + if (settled) return false; + settled = true; + codeResolve?.(code); + return true; + }; + + const settleError = (err: Error): boolean => { + if (settled) return false; + settled = true; + codeReject?.(err); + return true; + }; + const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); const server = createServer((req: IncomingMessage, res: ServerResponse) => { - const url = new URL(req.url || "/", `http://localhost`); + const url = new URL(req.url || "/", "http://localhost"); if (url.pathname === "/callback") { + const receivedState = url.searchParams.get("state"); + if (!receivedState || !safeEqual(receivedState, state)) { + // Reject forged/mismatched-state requests without aborting the + // legitimate in-flight authorization attempt. + res.writeHead(400, { "Content-Type": "text/html" }); + res.end("

Authorization failed

Invalid OAuth state.

"); + return; + } + + if (settled) { + res.writeHead(409, { "Content-Type": "text/plain" }); + res.end("OAuth callback already received"); + return; + } + const code = url.searchParams.get("code"); const error = url.searchParams.get("error"); if (error) { const desc = url.searchParams.get("error_description") || error; - res.writeHead(200, { "Content-Type": "text/html" }); + res.writeHead(400, { "Content-Type": "text/html" }); res.end(`

Authorization failed

${escapeHtml(desc)}

You can close this window.

`); - codeReject?.(new Error(`OAuth error: ${desc}`)); + settleError(new Error(`OAuth error: ${desc}`)); return; } if (code) { res.writeHead(200, { "Content-Type": "text/html" }); - res.end(`

Authorization successful

You can close this window and return to OpenCode.

`); - codeResolve?.(code); + res.end("

Authorization successful

You can close this window and return to OpenCode.

"); + settleCode(code); return; } @@ -224,20 +304,22 @@ export function startOAuthCallbackServer(): Promise { // Timeout: close the server after 5 minutes if no code arrives const timeout = setTimeout(() => { - codeReject?.(new Error("OAuth callback timed out after 5 minutes")); + settleError(new Error("OAuth callback timed out after 5 minutes")); server.close(); }, 5 * 60 * 1000); + timeout.unref?.(); // Listen on port 0 = OS assigns an ephemeral port server.listen(0, "localhost", () => { const addr = server.address(); if (!addr || typeof addr === "string") { + clearTimeout(timeout); reject(new Error("Failed to get server address")); return; } const port = addr.port; - const { automaticUrl, manualUrl, verifier, state } = buildAuthUrls(port); + const { automaticUrl, manualUrl } = buildAuthUrls(port, { verifier, challenge, state }); resolve({ url: automaticUrl, @@ -246,6 +328,14 @@ export function startOAuthCallbackServer(): Promise { state, port, waitForCode: () => codePromise, + submitRedirect: (redirectUrl: string) => { + const parsed = parseOAuthRedirect(redirectUrl, state); + if ("error" in parsed) { + settleError(new Error(`OAuth error: ${parsed.error}`)); + return; + } + settleCode(parsed.code); + }, close: () => { clearTimeout(timeout); server.close(); @@ -254,6 +344,7 @@ export function startOAuthCallbackServer(): Promise { }); server.on("error", (err) => { + clearTimeout(timeout); reject(err); }); });