-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.ts
More file actions
268 lines (227 loc) · 7.57 KB
/
index.ts
File metadata and controls
268 lines (227 loc) · 7.57 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
265
266
267
268
#!/usr/bin/env bun
import { randomBytes, createHash } from 'node:crypto';
import { writeFile, readFile, unlink } from 'node:fs/promises';
// Constants
const OAUTH_AUTHORIZE_URL = 'https://claude.ai/oauth/authorize';
const OAUTH_TOKEN_URL = 'https://console.anthropic.com/v1/oauth/token';
const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
const REDIRECT_URI = 'https://console.anthropic.com/oauth/code/callback';
const STATE_FILE = 'claude_oauth_state.json';
const CREDENTIALS_FILE = 'credentials.json';
// Types
interface StateData {
state: string;
code_verifier: string;
timestamp: number;
expires_at: number;
}
interface TokenResponse {
access_token: string;
refresh_token: string;
expires_in: number;
scope?: string;
}
interface ClaudeOAuthCredentials {
accessToken: string;
refreshToken: string;
expiresAt: number;
scopes: string[];
isMax: boolean;
}
interface CredentialsFile {
claudeAiOauth: ClaudeOAuthCredentials;
}
/**
* Saves OAuth state data to a JSON file for later verification
*/
async function saveState(state: string, codeVerifier: string): Promise<void> {
const stateData: StateData = {
state,
code_verifier: codeVerifier,
timestamp: Math.floor(Date.now() / 1000),
expires_at: Math.floor(Date.now() / 1000) + 600 // 10 minutes
};
try {
await writeFile(STATE_FILE, JSON.stringify(stateData, null, 2));
} catch (error) {
console.warn(`Warning: Could not save state file: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Generates an OAuth login URL for Claude Code authentication
*/
export async function generateLoginUrl(): Promise<string> {
// Generate secure random values
const state = randomBytes(32).toString('hex');
const codeVerifier = randomBytes(32).toString('base64url');
// Create PKCE code challenge
const codeChallenge = createHash('sha256')
.update(codeVerifier)
.digest('base64url');
// Save state and code verifier for verification later
await saveState(state, codeVerifier);
// Build OAuth URL
const params = new URLSearchParams({
code: 'true',
client_id: CLIENT_ID,
response_type: 'code',
redirect_uri: REDIRECT_URI,
scope: 'org:create_api_key user:profile user:inference',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
state
});
const url = `${OAUTH_AUTHORIZE_URL}?${params.toString()}`;
console.log(url);
return url;
}
/**
* Loads previously saved OAuth state from file
*/
export async function loadState(): Promise<StateData | null> {
try {
const data = await readFile(STATE_FILE, 'utf-8');
return JSON.parse(data);
} catch (error) {
return null;
}
}
/**
* Verifies that the saved state is still valid (not expired)
*/
export async function verifyState(): Promise<boolean> {
const stateData = await loadState();
if (!stateData) {
console.error('Error: No state file found. Please run the login process again.');
return false;
}
const currentTime = Math.floor(Date.now() / 1000);
if (currentTime > stateData.expires_at) {
console.error('Error: State has expired (older than 10 minutes)');
return false;
}
return true;
}
/**
* Exchanges authorization code for access and refresh tokens
*/
export async function exchangeCode(authorizationCode: string): Promise<ClaudeOAuthCredentials | null> {
// Clean up the authorization code in case it has URL fragments
const cleanedCode = authorizationCode.split('#')[0]?.split('&')[0] ?? authorizationCode;
// Load state to get code_verifier
const stateData = await loadState();
if (!stateData) {
console.error('Error: Could not load state data');
return null;
}
const params = {
grant_type: 'authorization_code',
client_id: CLIENT_ID,
code: cleanedCode,
redirect_uri: REDIRECT_URI,
code_verifier: stateData.code_verifier,
state: stateData.state
};
try {
const response = await fetch(OAUTH_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9',
'Referer': 'https://claude.ai/',
'Origin': 'https://claude.ai'
},
body: JSON.stringify(params)
});
if (!response.ok) {
const errorText = await response.text();
console.error(`Error response: ${response.status} - ${errorText}`);
return null;
}
const data = await response.json() as TokenResponse;
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: (Math.floor(Date.now() / 1000) + data.expires_in) * 1000,
scopes: data.scope ? data.scope.split(' ') : ['user:inference', 'user:profile'],
isMax: true
};
} catch (error) {
console.error(`Error making token request: ${error instanceof Error ? error.message : String(error)}`);
return null;
}
}
/**
* Saves OAuth credentials to a JSON file
*/
export async function saveCredentials(tokens: ClaudeOAuthCredentials): Promise<boolean> {
const credentials: CredentialsFile = {
claudeAiOauth: tokens
};
try {
await writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2));
return true;
} catch (error) {
console.error(`Error saving credentials: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
/**
* Removes the state file after successful authentication
*/
export async function cleanupState(): Promise<void> {
try {
await unlink(STATE_FILE);
} catch (error) {
console.warn(`Warning: Could not clean up state file: ${error instanceof Error ? error.message : String(error)}`);
}
}
// CLI handling
if (import.meta.main) {
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
console.log(`Usage: ${process.argv[1]} [authorization_code]`);
console.log('');
console.log(' Without code: Generates an OAuth login URL for Claude Code authentication');
console.log(' With code: Completes OAuth login and exchanges code for tokens');
console.log('');
console.log('Arguments:');
console.log(' authorization_code The code received from the OAuth callback');
console.log('');
console.log('Options:');
console.log(' --help, -h Show this help message');
process.exit(0);
}
const authorizationCode = args[0];
if (authorizationCode) {
// Code exchange flow
if (!await verifyState()) {
console.error('Error: Invalid or expired state. Please run the login process again.');
process.exit(1);
}
console.log('Exchanging authorization code for tokens...');
const tokens = await exchangeCode(authorizationCode);
if (tokens) {
console.log('\nOAuth token exchange successful!');
console.log(`Received scopes: ${tokens.scopes.join(', ')}`);
// Save OAuth credentials
if (await saveCredentials(tokens)) {
await cleanupState();
console.log('\n=== SUCCESS ===');
console.log('OAuth login successful!');
console.log(`Credentials saved to: ${CREDENTIALS_FILE}`);
console.log(`Token expires at: ${new Date(tokens.expiresAt).toLocaleString()}`);
console.log('===============');
// Success - exit code 0 will be handled by GitHub Action
process.exit(0);
}
}
console.error('Login failed!');
process.exit(1);
} else {
// URL generation flow
await generateLoginUrl();
}
}