-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
355 lines (305 loc) · 10 KB
/
worker.js
File metadata and controls
355 lines (305 loc) · 10 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
* GitHub App Token Broker for ai-aligned-gh
*
* Provides user-to-server GitHub tokens via device flow for proper user attribution.
* Actions appear as the user (with app badge), not as the bot.
*
* Setup:
* 1. wrangler secret put GITHUB_CLIENT_ID # From GitHub App settings
* 2. wrangler secret put GITHUB_APP_ID # From GitHub App settings
* 3. wrangler secret put GITHUB_APP_PRIVATE_KEY # From GitHub App settings
* 4. wrangler deploy
*
* Usage with ai-aligned-gh:
* The CLI tool will automatically handle the device flow to get user tokens.
*
* Manual testing:
* # Start device flow
* curl -X POST https://your-worker.workers.dev/user-token/start -d '{"scopes":"repo"}'
* # Go to verification_uri and enter user_code
* # Poll for token
* curl -X POST https://your-worker.workers.dev/user-token/poll -d '{"device_code":"..."}'
*/
import { signJWT } from './jwt-simple.js';
// Handle /user-token/start endpoint
async function handleUserTokenStart(request, env, body) {
const { scopes, redirect_uri } = body;
const clientId = env.GITHUB_CLIENT_ID;
if (!clientId) {
return new Response(JSON.stringify({
error: 'GitHub Client ID not configured'
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
// OAuth endpoints are on github.com, not api.github.com
const url = 'https://github.com/login/device/code';
const params = new URLSearchParams({
client_id: clientId
});
// IMPORTANT: For GitHub Apps, we should NOT send scopes
// GitHub Apps use fine-grained permissions, not OAuth scopes
// The device flow will create a user-to-server token with the app's permissions
// Do NOT send scopes parameter - it would break the GitHub App authentication
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params.toString()
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error_description || data.error || 'Failed to start device flow');
}
// Store device code data in KV for polling (if KV is available)
if (env.DEVICE_CODES) {
await env.DEVICE_CODES.put(data.device_code, JSON.stringify({
...data,
created_at: Date.now(),
redirect_uri
}), {
expirationTtl: data.expires_in
});
} else {
console.warn('DEVICE_CODES KV namespace not configured - device flow will not persist');
}
return new Response(JSON.stringify({
device_code: data.device_code,
user_code: data.user_code,
verification_uri: data.verification_uri,
expires_in: data.expires_in,
interval: data.interval
}), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({
error: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// Note: We do NOT exchange user tokens for installation tokens
// User-to-server tokens (ghu_ prefix) maintain user identity with app badge
// Installation tokens (ghs_ prefix) would show actions as from the bot only
// This is intentionally removed to ensure proper user attribution
// Create JWT for GitHub App authentication
async function createAppJWT(appId, privateKey) {
const now = Math.floor(Date.now() / 1000);
const payload = {
iat: now - 60, // Issued 60 seconds ago to account for clock drift
exp: now + 600, // Expires in 10 minutes
iss: appId // Issuer is the app ID
};
return await signJWT(payload, privateKey);
}
// Handle /user-token/poll endpoint
async function handleUserTokenPoll(request, env, body) {
const { device_code } = body;
if (!device_code) {
return new Response(JSON.stringify({
error: 'device_code is required'
}), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Get device code data from KV (if available)
if (!env.DEVICE_CODES) {
return new Response(JSON.stringify({
error: 'server_error',
error_description: 'Device flow not configured on this server'
}), {
status: 503,
headers: { 'Content-Type': 'application/json' }
});
}
const deviceData = await env.DEVICE_CODES.get(device_code, 'json');
if (!deviceData) {
return new Response(JSON.stringify({
error: 'expired_token',
error_description: 'Device code has expired'
}), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
const clientId = env.GITHUB_CLIENT_ID;
// OAuth endpoints are on github.com, not api.github.com
const url = 'https://github.com/login/oauth/access_token';
const params = new URLSearchParams({
client_id: clientId,
device_code: device_code,
grant_type: 'urn:ietf:params:oauth:grant-type:device_code'
});
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params.toString()
});
const data = await response.json();
if (data.error) {
if (data.error === 'authorization_pending') {
// Still waiting for user authorization
return new Response(JSON.stringify({
error: 'authorization_pending',
error_description: 'User has not yet authorized the request',
interval: deviceData.interval
}), {
status: 202,
headers: { 'Content-Type': 'application/json' }
});
}
if (data.error === 'slow_down') {
// Client is polling too fast
return new Response(JSON.stringify({
error: 'slow_down',
error_description: 'Polling too frequently',
interval: deviceData.interval + 5
}), {
status: 429,
headers: { 'Content-Type': 'application/json' }
});
}
// Other errors
return new Response(JSON.stringify({
error: data.error,
error_description: data.error_description
}), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Success - we have a user-to-server token
// IMPORTANT: Do NOT exchange this for an installation token!
// User-to-server tokens (ghu_ prefix) maintain user identity with app badge
// Installation tokens (ghs_ prefix) would lose user attribution
const finalToken = data.access_token;
// Clean up device code (if KV is available)
if (env.DEVICE_CODES) {
await env.DEVICE_CODES.delete(device_code);
}
// Calculate expiration
const expiresAt = new Date(Date.now() + (data.expires_in || 28800) * 1000).toISOString();
return new Response(JSON.stringify({
access_token: finalToken,
token_type: data.token_type || 'bearer',
expires_at: expiresAt,
scope: data.scope,
app_attribution: finalToken !== data.access_token // Indicate if we got an installation token
}), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store'
}
});
} catch (error) {
return new Response(JSON.stringify({
error: 'server_error',
error_description: error.message
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// Import web flow handlers
import webFlow from './worker-web.js';
// Main request handler
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// Route web flow endpoints to web flow handler
if (url.pathname.startsWith('/auth/')) {
return webFlow.fetch(request, env, ctx);
}
// Allow GET for health check
if (request.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) {
return new Response(JSON.stringify({
status: 'healthy',
service: 'GitHub App Token Broker for ai-aligned-gh',
timestamp: new Date().toISOString(),
endpoints: {
'/user-token/start': 'Start device flow (POST)',
'/user-token/poll': 'Poll device flow (POST)',
'/auth/start': 'Start web flow (POST)',
'/auth/callback': 'OAuth callback (GET)',
'/auth/poll': 'Poll web flow (POST)'
}
}), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
// Only allow POST for other endpoints
if (request.method !== 'POST') {
return new Response(JSON.stringify({
error: 'Method not allowed'
}), {
status: 405,
headers: {
'Content-Type': 'application/json'
}
});
}
// Parse request body
let body;
try {
const rawBody = await request.text();
body = rawBody ? JSON.parse(rawBody) : {};
} catch (error) {
return new Response(JSON.stringify({
error: 'Invalid request body'
}), {
status: 400,
headers: {
'Content-Type': 'application/json'
}
});
}
// Route requests
try {
let response;
switch (url.pathname) {
case '/user-token/start':
response = await handleUserTokenStart(request, env, body);
break;
case '/user-token/poll':
response = await handleUserTokenPoll(request, env, body);
break;
default:
response = new Response(JSON.stringify({
error: 'Not found'
}), {
status: 404,
headers: { 'Content-Type': 'application/json' }
});
}
return response;
} catch (error) {
console.error('Request failed:', error);
return new Response(JSON.stringify({
error: 'Internal server error'
}), {
status: 500,
headers: {
'Content-Type': 'application/json'
}
});
}
}
};