xonecas.io
64875
Mc

mini-coder / commit b7d2793

refactor: remove Claude Code anthropic OAuth support

xonecas2026-03-30 b7d279391083d34364647ac68b55fbc58260bfb2 parent 0dda74e

16 files changed

AGENTS.md+1−1
@@ -49,7 +49,7 @@ Community oriented — support AGENTS.md and agentskills.io specs, don't introdu
4949 - Skills (`.agents/skills/` and `.claude/skills/`) → https://agentskills.io/client-implementation/adding-skills-support
5050
5151 - Auto discovery of providers via ENV (Example: OPENCODE_API_KEY), or local servers (Example: ollama)
52- - `/login` shows OAuth login status. `/login <provider>` starts browser-based OAuth login. `/logout <provider>` clears saved tokens. Currently supports Anthropic and OpenAI (`openai` uses the Codex / ChatGPT Plus/Pro flow).
52+ - `/login` shows OAuth login status. `/login <provider>` starts browser-based OAuth login. `/logout <provider>` clears saved tokens. Currently supports OpenAI (`openai` uses the Codex / ChatGPT Plus/Pro flow). Anthropic support was removed to comply to their TOS, we can't impersonate claude.
5353 - `/model` (alias `/models`) picks a model from connected providers, including thinking effort if supported. Selection persists across sessions with autocomplete.
5454
5555 - Session management and command to create new/resume/list with local sqlite file.
docs/mini-coder.1.md+1−1
@@ -77,7 +77,7 @@ _prompt_
7777 : Show OAuth login status.
7878
7979 `/login` _provider_
80-: Login via OAuth (opens browser for device flow). Currently supports `anthropic` and `openai`.
80+: Login via OAuth (opens browser for device flow). Currently supports `openai`.
8181
8282 `/logout` _provider_
8383 : Clear saved OAuth tokens.
docs/superpowers/plans/2026-03-30-anthropic-oauth-removal.md+61−0
@@ -0,0 +1,61 @@
1+# Anthropic OAuth Removal Implementation Plan
2+
3+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4+
5+**Goal:** Remove Claude Code subscription OAuth support without affecting Anthropic API-key access or Zen Claude models.
6+
7+**Architecture:** Delete the Anthropic OAuth provider registration and stop consulting Anthropic OAuth state in discovery/model-info paths. Preserve all direct `ANTHROPIC_API_KEY` behavior and Anthropic-family handling needed by Zen and direct API use.
8+
9+**Tech Stack:** Bun, TypeScript, bun:test, SQLite-backed auth storage, AI SDK providers.
10+
11+---
12+
13+### Task 1: Track the work and lock the user-facing contract
14+
15+**Files:**
16+
17+- Modify: `TODO.md`
18+- Reference: `docs/superpowers/specs/2026-03-30-anthropic-oauth-removal-design.md`
19+
20+- [ ] **Step 1: Update TODO.md with active work item**
21+- [ ] **Step 2: Keep TODO.md current as tasks complete**
22+
23+### Task 2: Write failing tests for Anthropic OAuth removal
24+
25+**Files:**
26+
27+- Modify: `src/llm-api/providers-resolve.test.ts`
28+- Modify: `src/llm-api/model-info.test.ts`
29+- Create: `src/session/oauth/auth-storage.test.ts`
30+
31+- [ ] **Step 1: Add a test asserting OAuth providers list only OpenAI**
32+- [ ] **Step 2: Add tests asserting Anthropic discovery requires `ANTHROPIC_API_KEY`**
33+- [ ] **Step 3: Run focused tests to verify they fail for the expected reason**
34+
35+### Task 3: Remove Anthropic OAuth registration and discovery usage
36+
37+**Files:**
38+
39+- Delete: `src/session/oauth/anthropic.ts`
40+- Modify: `src/session/oauth/auth-storage.ts`
41+- Modify: `src/llm-api/providers.ts`
42+- Modify: `src/llm-api/model-info.ts`
43+- Modify: `src/llm-api/model-info-fetch.ts`
44+
45+- [ ] **Step 1: Remove the Anthropic OAuth provider from auth storage**
46+- [ ] **Step 2: Remove Anthropic OAuth-based provider discovery/autodiscovery**
47+- [ ] **Step 3: Remove Anthropic OAuth-based model list fetching**
48+- [ ] **Step 4: Run the focused tests and make them pass**
49+
50+### Task 4: Update CLI/docs and finish verification
51+
52+**Files:**
53+
54+- Modify: `src/cli/commands-help.ts`
55+- Modify: `docs/mini-coder.1.md`
56+- Modify: `TODO.md`
57+
58+- [ ] **Step 1: Remove Anthropic OAuth mentions from help/manpage**
59+- [ ] **Step 2: Run formatting if needed**
60+- [ ] **Step 3: Run focused tests, then broader verification commands**
61+- [ ] **Step 4: Clear the completed TODO item**
docs/superpowers/specs/2026-03-30-anthropic-oauth-removal-design.md+47−0
@@ -0,0 +1,47 @@
1+# Anthropic OAuth Removal Design
2+
3+## Goal
4+
5+Remove Claude Code subscription OAuth support from mini-coder while preserving:
6+
7+- direct Anthropic API key support via `ANTHROPIC_API_KEY`
8+- Anthropic-family models served through Opencode Zen (`zen/claude-*`)
9+
10+## Approved behavior
11+
12+- `anthropic` is removed completely from the user-facing OAuth surface.
13+- `/login anthropic` is no longer supported and behaves like any unknown provider.
14+- `/logout anthropic` is no longer documented or advertised as a supported path.
15+- Existing saved Anthropic OAuth rows in SQLite are ignored; no migration or cleanup is required.
16+- Anthropic remains available through `ANTHROPIC_API_KEY`.
17+- Zen-backed Claude models remain available and unchanged.
18+
19+## Approach
20+
21+Use a narrow OAuth-only removal:
22+
23+1. Remove the Anthropic OAuth provider module and provider registration.
24+2. Stop consulting Anthropic OAuth state during provider discovery and model-info refresh visibility.
25+3. Keep direct Anthropic provider resolution via `ANTHROPIC_API_KEY`.
26+4. Keep Anthropic-family request handling and Zen backend routing unchanged.
27+5. Update tests and docs to match the new OAuth surface.
28+
29+## Files in scope
30+
31+- `src/session/oauth/anthropic.ts` — delete
32+- `src/session/oauth/auth-storage.ts` — unregister Anthropic OAuth
33+- `src/llm-api/providers.ts` — stop treating Anthropic OAuth as connected
34+- `src/llm-api/model-info.ts` — stop treating Anthropic OAuth as a refresh/visibility source
35+- `src/llm-api/model-info-fetch.ts` — stop fetching Anthropic models via OAuth tokens
36+- `src/cli/commands-help.ts` — remove Anthropic OAuth example text
37+- `docs/mini-coder.1.md` — document OpenAI-only OAuth support
38+- tests around provider discovery/model info — update to be deterministic and Anthropic-OAuth-free
39+
40+## Risks and mitigations
41+
42+- Risk: accidentally breaking direct Anthropic API-key support.
43+ - Mitigation: keep direct provider resolver and add/update tests that verify `ANTHROPIC_API_KEY` still wins.
44+- Risk: accidentally breaking Zen Claude behavior.
45+ - Mitigation: avoid touching Anthropic-family routing/caching code used for Zen.
46+- Risk: stale Anthropic OAuth tokens still affecting behavior.
47+ - Mitigation: remove all Anthropic OAuth checks from discovery and model fetching paths.
src/cli/commands-help.ts+1−1
@@ -31,7 +31,7 @@ export function renderHelpCommand(ctx: CommandContext): void {
3131 ["/mcp list", "list MCP servers"],
3232 ["/mcp add <n> <t> [u]", "add an MCP server"],
3333 ["/mcp remove <name>", "remove an MCP server"],
34- ["/login [provider]", "login via OAuth (e.g. anthropic)"],
34+ ["/login [provider]", "login via OAuth (e.g. openai)"],
3535 ["/logout <provider>", "clear OAuth tokens"],
3636 ["/help", "show this help"],
3737 ]);
src/cli/commands-login.ts+11−1
@@ -119,11 +119,21 @@ export function handleLogoutCommand(_ctx: CommandContext, args: string): void {
119119 return;
120120 }
121121
122+ const provider = getOAuthProvider(providerId);
123+ if (!provider) {
124+ writeln(
125+ `${PREFIX.error} unknown provider "${providerId}" — available: ${getOAuthProviders()
126+ .map((p) => p.id)
127+ .join(", ")}`,
128+ );
129+ return;
130+ }
131+
122132 if (!isLoggedIn(providerId)) {
123133 writeln(`${PREFIX.info} ${c.dim("not logged in to")} ${providerId}`);
124134 return;
125135 }
126136
127137 logout(providerId);
128- writeln(`${PREFIX.success} logged out of ${c.cyan(providerId)}`);
138+ writeln(`${PREFIX.success} logged out of ${c.cyan(provider.id)}`);
129139 }
src/llm-api/model-info-fetch.ts+8−26
@@ -185,38 +185,20 @@ async function fetchCodexOAuthModels(
185185 }
186186 }
187187
188-async function getAnthropicAuth(): Promise<{
189- key: string;
190- oauth: boolean;
191-} | null> {
192- const envKey = process.env.ANTHROPIC_API_KEY;
193- if (envKey) return { key: envKey, oauth: false };
194- if (isLoggedIn("anthropic")) {
195- const token = await getAccessToken("anthropic");
196- if (token) return { key: token, oauth: true };
197- }
198- return null;
199-}
200-
201188 async function fetchAnthropicModels(): Promise<
202189 ProviderModelCandidate[] | null
203190 > {
204- const auth = await getAnthropicAuth();
205- if (!auth) return null;
206-
207- const headers: Record<string, string> = {
208- "anthropic-version": "2023-06-01",
209- };
210- if (auth.oauth) {
211- headers.Authorization = `Bearer ${auth.key}`;
212- headers["anthropic-beta"] = "oauth-2025-04-20";
213- } else {
214- headers["x-api-key"] = auth.key;
215- }
191+ const key = process.env.ANTHROPIC_API_KEY;
192+ if (!key) return null;
216193
217194 const payload = await fetchJson(
218195 `${ANTHROPIC_BASE}/v1/models`,
219- { headers },
196+ {
197+ headers: {
198+ "anthropic-version": "2023-06-01",
199+ "x-api-key": key,
200+ },
201+ },
220202 6_000,
221203 );
222204 return processModelsList(payload, "data", "id", (item, modelId) => {
src/llm-api/model-info.test.ts+17−13
@@ -13,36 +13,40 @@ import {
1313 resolveModelInfoFromRows,
1414 } from "./model-info.ts";
1515
16-const anthropicOAuth = isLoggedIn("anthropic");
16+const openAIOAuth = isLoggedIn("openai");
1717
1818 describe("provider sync policy", () => {
1919 test("freshness providers exclude ollama", () => {
20- const expected = ["openai", "google"];
21- if (anthropicOAuth) expected.push("anthropic");
2220 expect(
2321 getRemoteProvidersFromEnv({
2422 OPENAI_API_KEY: "x",
2523 GOOGLE_API_KEY: "y",
2624 }),
27- ).toEqual(expected);
25+ ).toEqual(["openai", "google"]);
2826 });
2927
30- test("refresh providers include ollama", () => {
31- const expected = ["openai"];
32- if (anthropicOAuth) expected.push("anthropic");
33- expected.push("ollama");
34- expect(getProvidersToRefreshFromEnv({ OPENAI_API_KEY: "x" })).toEqual(
35- expected,
36- );
28+ test("refresh providers include anthropic only from env", () => {
29+ expect(getProvidersToRefreshFromEnv({ OPENAI_API_KEY: "x" })).toEqual([
30+ "openai",
31+ "ollama",
32+ ]);
33+
34+ expect(getProvidersToRefreshFromEnv({ ANTHROPIC_API_KEY: "x" })).toEqual([
35+ "anthropic",
36+ ...(openAIOAuth ? ["openai"] : []),
37+ "ollama",
38+ ]);
3739 });
3840
3941 test("snapshot visibility tracks configured providers", () => {
40- // openai visibility depends on env key OR active OAuth login
4142 expect(isProviderVisibleInSnapshot("openai", { OPENAI_API_KEY: "x" })).toBe(
4243 true,
4344 );
45+ expect(isProviderVisibleInSnapshot("anthropic", {})).toBe(false);
46+ expect(
47+ isProviderVisibleInSnapshot("anthropic", { ANTHROPIC_API_KEY: "x" }),
48+ ).toBe(true);
4449 expect(isProviderVisibleInSnapshot("ollama", {})).toBe(true);
45- // Without env or OAuth, zen should not be visible (zen has no OAuth)
4650 expect(isProviderVisibleInSnapshot("zen", {})).toBe(false);
4751 expect(isProviderVisibleInSnapshot("zen", { OPENCODE_API_KEY: "x" })).toBe(
4852 true,
src/llm-api/model-info.ts+3−5
@@ -116,11 +116,9 @@ export function getRemoteProvidersFromEnv(
116116 hasAnyEnvKey(env, entry.envKeys),
117117 ).map((entry) => entry.provider);
118118
119- // Include providers with OAuth login even without env keys
120- for (const p of ["anthropic", "openai"] as const) {
121- if (!providers.includes(p) && isLoggedIn(p)) {
122- providers.push(p);
123- }
119+ // Include providers with OAuth login even without env keys.
120+ if (!providers.includes("openai") && isLoggedIn("openai")) {
121+ providers.push("openai");
124122 }
125123
126124 return providers;
src/llm-api/providers-resolve.test.ts+4−7
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { isLoggedIn } from "../session/oauth/auth-storage.ts";
33 import { autoDiscoverModel, resolveModel } from "./providers.ts";
44
5-const anthropicOAuth = isLoggedIn("anthropic");
5+const openAIOAuth = isLoggedIn("openai");
66
77 const ENV_KEYS = [
88 "OPENCODE_API_KEY",
@@ -49,20 +49,17 @@ describe("autoDiscoverModel", () => {
4949 delete process.env.GOOGLE_API_KEY;
5050 delete process.env.GEMINI_API_KEY;
5151
52- // With OAuth login, anthropic is discovered even without env key
5352 expect(autoDiscoverModel()).toBe(
54- anthropicOAuth ? "anthropic/claude-sonnet-4-6" : "ollama/llama3.2",
53+ openAIOAuth ? "openai/gpt-5.4" : "ollama/llama3.2",
5554 );
5655
5756 process.env.GEMINI_API_KEY = "gem";
5857 expect(autoDiscoverModel()).toBe(
59- anthropicOAuth ? "anthropic/claude-sonnet-4-6" : "google/gemini-3.1-pro",
58+ openAIOAuth ? "openai/gpt-5.4" : "google/gemini-3.1-pro",
6059 );
6160
6261 process.env.OPENAI_API_KEY = "openai";
63- expect(autoDiscoverModel()).toBe(
64- anthropicOAuth ? "anthropic/claude-sonnet-4-6" : "openai/gpt-5.4",
65- );
62+ expect(autoDiscoverModel()).toBe("openai/gpt-5.4");
6663
6764 process.env.ANTHROPIC_API_KEY = "anthropic";
6865 expect(autoDiscoverModel()).toBe("anthropic/claude-sonnet-4-6");
src/llm-api/providers.ts+2−72
@@ -33,38 +33,6 @@ type GoogleProvider = ReturnType<typeof createGoogleGenerativeAI>;
3333 type OpenAICompatProvider = ReturnType<typeof createOpenAICompatible>;
3434 type ModelResolver = (modelId: string) => LanguageModel;
3535
36-/** Betas the AI SDK adds that are not compatible with the OAuth endpoint. */
37-const OAUTH_STRIP_BETAS = new Set<string>();
38-
39-function createOAuthFetch(accessToken: string): ProviderFetch {
40- const oauthFetch = async (
41- input: Parameters<ProviderFetch>[0],
42- init?: Parameters<ProviderFetch>[1],
43- ): Promise<Response> => {
44- let opts = init;
45- if (opts?.headers) {
46- const h = new Headers(
47- opts.headers as ConstructorParameters<typeof Headers>[0],
48- );
49- const beta = h.get("anthropic-beta");
50- if (beta) {
51- const filtered = beta
52- .split(",")
53- .filter((b) => !OAUTH_STRIP_BETAS.has(b))
54- .join(",");
55- h.set("anthropic-beta", filtered);
56- }
57- h.delete("x-api-key");
58- h.set("authorization", `Bearer ${accessToken}`);
59- h.set("user-agent", "claude-cli/2.1.75");
60- h.set("x-app", "cli");
61- opts = { ...opts, headers: Object.fromEntries(h.entries()) };
62- }
63- return fetch(input, opts);
64- };
65- return oauthFetch as ProviderFetch;
66-}
67-
6836 function requireEnv(name: string): string {
6937 const value = process.env[name];
7038 if (!value) throw new Error(`${name} is not set`);
@@ -248,41 +216,10 @@ type AsyncModelResolver = (
248216
249217 const OPENAI_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
250218
251-/** Cache the OAuth-backed Anthropic provider keyed by access token. */
252-let oauthAnthropicCache: { token: string; provider: AnthropicProvider } | null =
253- null;
254-
255219 /** Cache the OAuth-backed OpenAI Codex provider keyed by access token. */
256220 let oauthOpenAICache: { token: string; provider: OpenAIProvider } | null = null;
257221
258-function createOAuthAnthropicProvider(token: string): AnthropicProvider {
259- return createAnthropic({
260- // Use empty apiKey + custom fetch (like opencode) instead of authToken.
261- // The SDK sends x-api-key for apiKey, which we override to Authorization
262- // Bearer in the OAuth fetch wrapper.
263- apiKey: "",
264- fetch: createOAuthFetch(token),
265- headers: {
266- "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
267- },
268- });
269-}
270-
271222 async function resolveAnthropicModel(modelId: string): Promise<LanguageModel> {
272- // OAuth token takes priority over env var
273- if (isLoggedIn("anthropic")) {
274- const token = await getAccessToken("anthropic");
275- if (token) {
276- if (!oauthAnthropicCache || oauthAnthropicCache.token !== token) {
277- oauthAnthropicCache = {
278- token,
279- provider: createOAuthAnthropicProvider(token),
280- };
281- }
282- return oauthAnthropicCache.provider(modelId);
283- }
284- }
285- // Fallback to ANTHROPIC_API_KEY env var
286223 return directProviders.anthropic()(modelId);
287224 }
288225
@@ -322,11 +259,6 @@ export async function resolveModel(
322259 return PROVIDER_MODEL_RESOLVERS[provider](modelId);
323260 }
324261
325-/** Returns true when the Anthropic provider is using an OAuth token. */
326-export function isAnthropicOAuth(): boolean {
327- return isLoggedIn("anthropic");
328-}
329-
330262 interface ConnectedProvider {
331263 name: string;
332264 via: "env" | "oauth";
@@ -336,8 +268,7 @@ interface ConnectedProvider {
336268 export function discoverConnectedProviders(): ConnectedProvider[] {
337269 const result: ConnectedProvider[] = [];
338270 if (process.env.OPENCODE_API_KEY) result.push({ name: "zen", via: "env" });
339- if (isLoggedIn("anthropic")) result.push({ name: "anthropic", via: "oauth" });
340- else if (process.env.ANTHROPIC_API_KEY)
271+ if (process.env.ANTHROPIC_API_KEY)
341272 result.push({ name: "anthropic", via: "env" });
342273 if (isLoggedIn("openai")) result.push({ name: "openai", via: "oauth" });
343274 else if (process.env.OPENAI_API_KEY)
@@ -350,8 +281,7 @@ export function discoverConnectedProviders(): ConnectedProvider[] {
350281
351282 export function autoDiscoverModel(): string {
352283 if (process.env.OPENCODE_API_KEY) return "zen/claude-sonnet-4-6";
353- if (process.env.ANTHROPIC_API_KEY || isLoggedIn("anthropic"))
354- return "anthropic/claude-sonnet-4-6";
284+ if (process.env.ANTHROPIC_API_KEY) return "anthropic/claude-sonnet-4-6";
355285 if (process.env.OPENAI_API_KEY || isLoggedIn("openai"))
356286 return "openai/gpt-5.4";
357287 if (process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY)
src/llm-api/turn-prepare-messages.test.ts+4−11
@@ -39,7 +39,7 @@ function runInHome(
3939 }
4040 }
4141
42-describe("prepareTurnMessages Anthropic OAuth identity handling", () => {
42+describe("prepareTurnMessages ignores stale Anthropic OAuth rows", () => {
4343 let fakeHome = "";
4444
4545 beforeEach(() => {
@@ -51,7 +51,7 @@ describe("prepareTurnMessages Anthropic OAuth identity handling", () => {
5151 rmSync(fakeHome, { recursive: true, force: true });
5252 });
5353
54- test("keeps Claude Code identity on direct Anthropic OAuth, but not on zen/claude", () => {
54+ test("treats direct anthropic and zen/claude the same when an old anthropic oauth row exists", () => {
5555 const result = runInHome(
5656 fakeHome,
5757 `
@@ -89,15 +89,8 @@ describe("prepareTurnMessages Anthropic OAuth identity handling", () => {
8989 expect(result.exitCode).toBe(0);
9090 expect(result.stderr).toBe("");
9191 expect(JSON.parse(result.stdout)).toEqual({
92- anthropicMessages: [
93- {
94- role: "system",
95- content: "You are Claude Code, Anthropic's official CLI for Claude.",
96- },
97- { role: "system", content: "sys" },
98- { role: "user", content: "hi" },
99- ],
100- anthropicSystemPrompt: undefined,
92+ anthropicMessages: [{ role: "user", content: "hi" }],
93+ anthropicSystemPrompt: "sys",
10194 zenMessages: [{ role: "user", content: "hi" }],
10295 zenSystemPrompt: "sys",
10396 });
src/llm-api/turn-prepare-messages.ts+2−28
@@ -5,8 +5,6 @@ import {
55 stripOpenAIHistoryTransforms,
66 stripToolRuntimeInputFields,
77 } from "./history-transforms.ts";
8-import { parseModelString } from "./model-routing.ts";
9-import { isAnthropicOAuth } from "./providers.ts";
108 import type { CoreMessage } from "./turn.ts";
119 import {
1210 applyContextPruning,
@@ -104,35 +102,11 @@ export function prepareTurnMessages(input: {
104102 });
105103 }
106104
107- // 5. OAuth identity: Anthropic OAuth requires the Claude Code identity as
108- // the first system block so the API recognises the client. We inline
109- // both identity and system prompt as messages (identity first) so the
110- // SDK sends them in the correct order on the wire.
111- let finalMessages = compacted;
112- let finalSystemPrompt = systemPrompt;
113- const { provider } = parseModelString(modelString);
114-
115- if (provider === "anthropic" && isAnthropicOAuth()) {
116- const ccIdentity =
117- "You are Claude Code, Anthropic's official CLI for Claude.";
118- const systemMessages: CoreMessage[] = [
119- { role: "system", content: ccIdentity } as CoreMessage,
120- ];
121- if (finalSystemPrompt) {
122- systemMessages.push({
123- role: "system",
124- content: finalSystemPrompt,
125- } as CoreMessage);
126- finalSystemPrompt = undefined;
127- }
128- finalMessages = [...systemMessages, ...finalMessages];
129- }
130-
131105 const wasPruned = postStats.messageCount < preStats.messageCount;
132106
133107 return {
134- messages: finalMessages,
135- systemPrompt: finalSystemPrompt,
108+ messages: compacted,
109+ systemPrompt,
136110 pruned: wasPruned,
137111 prePruneMessageCount: preStats.messageCount,
138112 prePruneTotalBytes: preStats.totalBytes,
src/session/oauth/anthropic.ts+0−182
@@ -1,182 +0,0 @@
1-/**
2- * Anthropic OAuth flow (Claude Pro/Max subscription).
3- *
4- * Uses Authorization Code + PKCE against claude.ai/platform.claude.com.
5- * Starts a local HTTP callback server for the redirect.
6- */
7-
8-import { createServer, type Server } from "node:http";
9-import { generatePKCE } from "./pkce.ts";
10-import type {
11- OAuthCredentials,
12- OAuthLoginCallbacks,
13- OAuthProviderConfig,
14-} from "./types.ts";
15-
16-const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
17-const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
18-const TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
19-const CALLBACK_HOST = "127.0.0.1";
20-const CALLBACK_PORT = 53692;
21-const CALLBACK_PATH = "/callback";
22-const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
23-const SCOPES =
24- "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
25-
26-const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
27-
28-const SUCCESS_HTML = `<!doctype html>
29-<html lang="en"><head><meta charset="utf-8"><title>Authenticated</title></head>
30-<body><p>Authentication successful. Return to your terminal.</p></body></html>`;
31-
32-function startCallbackServer(expectedState: string): Promise<{
33- server: Server;
34- waitForCode: () => Promise<{ code: string; state: string } | null>;
35- cancel: () => void;
36-}> {
37- return new Promise((resolve, reject) => {
38- let result: { code: string; state: string } | null = null;
39- let cancelled = false;
40-
41- const server = createServer((req, res) => {
42- const url = new URL(req.url ?? "", "http://localhost");
43- if (url.pathname !== CALLBACK_PATH) {
44- res.writeHead(404).end("Not found");
45- return;
46- }
47-
48- const code = url.searchParams.get("code");
49- const state = url.searchParams.get("state");
50- const error = url.searchParams.get("error");
51-
52- if (error || !code || !state || state !== expectedState) {
53- res.writeHead(400).end("Authentication failed.");
54- return;
55- }
56-
57- res.writeHead(200, { "Content-Type": "text/html" }).end(SUCCESS_HTML);
58- result = { code, state };
59- });
60-
61- server.on("error", reject);
62- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
63- resolve({
64- server,
65- cancel: () => {
66- cancelled = true;
67- },
68- waitForCode: async () => {
69- const deadline = Date.now() + LOGIN_TIMEOUT_MS;
70- while (!result && !cancelled && Date.now() < deadline) {
71- await new Promise((r) => setTimeout(r, 100));
72- }
73- return result;
74- },
75- });
76- });
77- });
78-}
79-
80-async function postTokenRequest(
81- body: Record<string, string>,
82- label: string,
83-): Promise<OAuthCredentials> {
84- const res = await fetch(TOKEN_URL, {
85- method: "POST",
86- headers: {
87- "Content-Type": "application/json",
88- Accept: "application/json",
89- },
90- body: JSON.stringify(body),
91- signal: AbortSignal.timeout(30_000),
92- });
93-
94- if (!res.ok) {
95- const text = await res.text();
96- throw new Error(`${label} failed (${res.status}): ${text}`);
97- }
98-
99- const data = (await res.json()) as {
100- access_token: string;
101- refresh_token: string;
102- expires_in: number;
103- };
104-
105- return {
106- access: data.access_token,
107- refresh: data.refresh_token,
108- // Expire 5 minutes early to avoid edge cases
109- expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
110- };
111-}
112-
113-function exchangeCode(
114- code: string,
115- state: string,
116- verifier: string,
117-): Promise<OAuthCredentials> {
118- return postTokenRequest(
119- {
120- grant_type: "authorization_code",
121- client_id: CLIENT_ID,
122- code,
123- state,
124- redirect_uri: REDIRECT_URI,
125- code_verifier: verifier,
126- },
127- "Token exchange",
128- );
129-}
130-
131-function refreshAnthropicToken(
132- refreshToken: string,
133-): Promise<OAuthCredentials> {
134- return postTokenRequest(
135- {
136- grant_type: "refresh_token",
137- client_id: CLIENT_ID,
138- refresh_token: refreshToken,
139- },
140- "Token refresh",
141- );
142-}
143-
144-async function loginAnthropic(
145- callbacks: OAuthLoginCallbacks,
146-): Promise<OAuthCredentials> {
147- const { verifier, challenge } = await generatePKCE();
148- const cb = await startCallbackServer(verifier);
149-
150- try {
151- const params = new URLSearchParams({
152- code: "true",
153- client_id: CLIENT_ID,
154- response_type: "code",
155- redirect_uri: REDIRECT_URI,
156- scope: SCOPES,
157- code_challenge: challenge,
158- code_challenge_method: "S256",
159- state: verifier,
160- });
161-
162- callbacks.onOpenUrl(
163- `${AUTHORIZE_URL}?${params}`,
164- "Complete login in your browser.",
165- );
166-
167- const result = await cb.waitForCode();
168- if (!result) throw new Error("Login cancelled or no code received");
169-
170- callbacks.onProgress("Exchanging authorization code for tokens…");
171- return exchangeCode(result.code, result.state, verifier);
172- } finally {
173- cb.server.close();
174- }
175-}
176-
177-export const anthropicOAuth: OAuthProviderConfig = {
178- id: "anthropic",
179- name: "Anthropic (Claude Pro/Max)",
180- login: loginAnthropic,
181- refreshToken: refreshAnthropicToken,
182-};
src/session/oauth/auth-storage.test.ts+21−0
@@ -0,0 +1,21 @@
1+import { describe, expect, test } from "bun:test";
2+import {
3+ getOAuthProvider,
4+ getOAuthProviders,
5+ isLoggedIn,
6+} from "./auth-storage.ts";
7+
8+describe("OAuth provider registry", () => {
9+ test("lists only supported OAuth providers", () => {
10+ expect(getOAuthProviders().map((provider) => provider.id)).toEqual([
11+ "openai",
12+ ]);
13+ expect(getOAuthProvider("openai")?.id).toBe("openai");
14+ expect(getOAuthProvider("anthropic")).toBeUndefined();
15+ });
16+
17+ test("does not expose anthropic login state through the registry", () => {
18+ expect(getOAuthProvider("anthropic")).toBeUndefined();
19+ expect(isLoggedIn("anthropic")).toBe(false);
20+ });
21+});
src/session/oauth/auth-storage.ts+3−4
@@ -5,7 +5,6 @@
55 */
66
77 import { getDb } from "../db/connection.ts";
8-import { anthropicOAuth } from "./anthropic.ts";
98 import { openaiOAuth } from "./openai.ts";
109 import type {
1110 OAuthCredentials,
@@ -22,7 +21,6 @@ interface OAuthTokenRow {
2221 }
2322
2423 const PROVIDERS: ReadonlyMap<string, OAuthProviderConfig> = new Map([
25- [anthropicOAuth.id, anthropicOAuth],
2624 [openaiOAuth.id, openaiOAuth],
2725 ]);
2826
@@ -73,7 +71,7 @@ function isAuthError(err: unknown): boolean {
7371 // ─── Public API ───────────────────────────────────────────────────────────────
7472
7573 export function isLoggedIn(provider: string): boolean {
76- return getStoredToken(provider) !== null;
74+ return PROVIDERS.has(provider) && getStoredToken(provider) !== null;
7775 }
7876
7977 export function listLoggedInProviders(): string[] {
@@ -82,7 +80,8 @@ export function listLoggedInProviders(): string[] {
8280 "SELECT provider FROM oauth_tokens ORDER BY provider",
8381 )
8482 .all()
85- .map((r) => r.provider);
83+ .map((r) => r.provider)
84+ .filter((provider) => PROVIDERS.has(provider));
8685 }
8786
8887 export async function login(