forked from jinzhongjia/opencode-anthropic-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
264 lines (249 loc) · 8.24 KB
/
index.mjs
File metadata and controls
264 lines (249 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { generatePKCE } from "@openauthjs/openauth/pkce";
const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
/**
* @param {"max" | "console"} mode
*/
async function authorize(mode) {
const pkce = await generatePKCE();
const url = new URL(
`https://${mode === "console" ? "console.anthropic.com" : "claude.ai"}/oauth/authorize`,
import.meta.url,
);
url.searchParams.set("code", "true");
url.searchParams.set("client_id", CLIENT_ID);
url.searchParams.set("response_type", "code");
url.searchParams.set(
"redirect_uri",
"https://console.anthropic.com/oauth/code/callback",
);
url.searchParams.set(
"scope",
"org:create_api_key user:profile user:inference",
);
url.searchParams.set("code_challenge", pkce.challenge);
url.searchParams.set("code_challenge_method", "S256");
url.searchParams.set("state", pkce.verifier);
return {
url: url.toString(),
verifier: pkce.verifier,
};
}
/**
* @param {string} code
* @param {string} verifier
*/
async function exchange(code, verifier) {
const splits = code.split("#");
const result = await fetch("https://console.anthropic.com/v1/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: splits[0],
state: splits[1],
grant_type: "authorization_code",
client_id: CLIENT_ID,
redirect_uri: "https://console.anthropic.com/oauth/code/callback",
code_verifier: verifier,
}),
});
if (!result.ok)
return {
type: "failed",
};
const json = await result.json();
return {
type: "success",
refresh: json.refresh_token,
access: json.access_token,
expires: Date.now() + json.expires_in * 1000,
};
}
/**
* @type {import('@opencode-ai/plugin').Plugin}
*/
export async function AnthropicAuthPlugin({ client }) {
return {
auth: {
provider: "anthropic",
async loader(getAuth, provider) {
const auth = await getAuth();
if (auth.type === "oauth") {
// zero out cost for max plan
for (const model of Object.values(provider.models)) {
model.cost = {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
};
}
return {
apiKey: "",
/**
* @param {any} input
* @param {any} init
*/
async fetch(input, init) {
const auth = await getAuth();
if (auth.type !== "oauth") return fetch(input, init);
if (!auth.access || auth.expires < Date.now()) {
const response = await fetch(
"https://console.anthropic.com/v1/oauth/token",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "refresh_token",
refresh_token: auth.refresh,
client_id: CLIENT_ID,
}),
},
);
if (!response.ok) {
throw new Error(`Token refresh failed: ${response.status}`);
}
const json = await response.json();
await client.auth.set({
path: {
id: "anthropic",
},
body: {
type: "oauth",
refresh: json.refresh_token,
access: json.access_token,
expires: Date.now() + json.expires_in * 1000,
},
});
auth.access = json.access_token;
}
// Add oauth-2025-04-20 beta to whatever betas are already present
const incomingBeta = init.headers?.["anthropic-beta"] || "";
const incomingBetasList = incomingBeta
.split(",")
.map((b) => b.trim())
.filter(Boolean);
// Add oauth beta and deduplicate
const mergedBetas = [
...new Set([
"oauth-2025-04-20",
"claude-code-20250219",
"interleaved-thinking-2025-05-14",
"fine-grained-tool-streaming-2025-05-14",
...incomingBetasList,
]),
].join(",");
const headers = {
...init.headers,
authorization: `Bearer ${auth.access}`,
"anthropic-beta": mergedBetas,
};
delete headers["x-api-key"];
const TOOL_PREFIX = "oc_";
let body = init.body;
if (body && typeof body === "string") {
try {
const parsed = JSON.parse(body);
if (parsed.tools && Array.isArray(parsed.tools)) {
parsed.tools = parsed.tools.map((tool) => ({
...tool,
name: tool.name ? `${TOOL_PREFIX}${tool.name}` : tool.name,
}));
body = JSON.stringify(parsed);
}
} catch (e) {
// ignore parse errors
}
}
const response = await fetch(input, {
...init,
body,
headers,
});
// Transform streaming response to rename tools back
if (response.body) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const stream = new ReadableStream({
async pull(controller) {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
let text = decoder.decode(value, { stream: true });
text = text.replace(/"name"\s*:\s*"oc_([^"]+)"/g, '"name": "$1"');
controller.enqueue(encoder.encode(text));
},
});
return new Response(stream, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
return response;
},
};
}
return {};
},
methods: [
{
label: "Claude Pro/Max",
type: "oauth",
authorize: async () => {
const { url, verifier } = await authorize("max");
return {
url: url,
instructions: "Paste the authorization code here: ",
method: "code",
callback: async (code) => {
const credentials = await exchange(code, verifier);
return credentials;
},
};
},
},
{
label: "Create an API Key",
type: "oauth",
authorize: async () => {
const { url, verifier } = await authorize("console");
return {
url: url,
instructions: "Paste the authorization code here: ",
method: "code",
callback: async (code) => {
const credentials = await exchange(code, verifier);
if (credentials.type === "failed") return credentials;
const result = await fetch(
`https://api.anthropic.com/api/oauth/claude_cli/create_api_key`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${credentials.access}`,
},
},
).then((r) => r.json());
return { type: "success", key: result.raw_key };
},
};
},
},
{
provider: "anthropic",
label: "Manually enter API Key",
type: "api",
},
],
},
};
}