@@ -0,0 +1,182 @@
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+};