|
1 | | -// Example: https://claude.ai/oauth/authorize?code=true&client_id=9d1c250a-e61b-44d9-88ed-5944d1962f5e&response_type=code&redirect_uri=https%3A%2F%2Fconsole.anthropic.com%2Foauth%2Fcode%2Fcallback&scope=org%3Acreate_api_key+user%3Aprofile+user%3Ainference&code_challenge=MdFtFgFap23AWDSN0oa3-eaKjQRFE4CaEhXx8M9fHZg&code_challenge_method=S256&state=rKLtaDzm88GSwekyEqdi0wXX-YqIr13tSzYymSzpvfs |
2 | | - |
3 | 1 | import { generatePKCE } from "@openauthjs/openauth/pkce" |
4 | 2 | import { Global } from "../global" |
5 | 3 | import path from "path" |
6 | 4 |
|
7 | 5 | export namespace AuthAnthropic { |
| 6 | + const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" |
| 7 | + |
8 | 8 | export async function authorize() { |
9 | 9 | const pkce = await generatePKCE() |
10 | 10 | const url = new URL("https://claude.ai/oauth/authorize", import.meta.url) |
@@ -48,14 +48,30 @@ export namespace AuthAnthropic { |
48 | 48 | await Bun.write(path.join(Global.Path.data, "anthropic.json"), result) |
49 | 49 | } |
50 | 50 |
|
51 | | - export async function load() { |
| 51 | + export async function access() { |
52 | 52 | const file = Bun.file(path.join(Global.Path.data, "anthropic.json")) |
53 | 53 | if (!(await file.exists())) return |
54 | 54 | const result = await file.json() |
55 | | - return { |
56 | | - accessToken: result.access_token as string, |
57 | | - refreshToken: result.refresh_token as string, |
58 | | - } |
| 55 | + const refresh = result.refresh_token |
| 56 | + const now = Date.now() |
| 57 | + const response = await fetch( |
| 58 | + "https://console.anthropic.com/v1/oauth/token", |
| 59 | + { |
| 60 | + method: "POST", |
| 61 | + headers: { |
| 62 | + "Content-Type": "application/json", |
| 63 | + }, |
| 64 | + body: JSON.stringify({ |
| 65 | + grant_type: "refresh_token", |
| 66 | + refresh_token: refresh, |
| 67 | + client_id: CLIENT_ID, |
| 68 | + }), |
| 69 | + }, |
| 70 | + ) |
| 71 | + if (!response.ok) return |
| 72 | + const json = await response.json() |
| 73 | + await Bun.write(file, JSON.stringify(json)) |
| 74 | + return json.access_token as string |
59 | 75 | } |
60 | 76 |
|
61 | 77 | export class ExchangeFailed extends Error { |
|
0 commit comments