-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path[action].js
More file actions
223 lines (183 loc) · 8.56 KB
/
Copy path[action].js
File metadata and controls
223 lines (183 loc) · 8.56 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
// GitHub OAuth social connect.
// Routes: /api/auth/github/connect — redirect to GitHub OAuth
// /api/auth/github/callback — exchange code, store encrypted token
// /api/auth/github/status — connection status for the signed-in user
import { webcrypto } from 'node:crypto';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { cors, json, redirect, error, wrap, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
// ── Key derivation (HKDF from JWT_SECRET, info = 'github-token') ──────────────
async function deriveKey() {
const raw = new TextEncoder().encode(env.JWT_SECRET);
const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
return subtle.deriveKey(
{
name: 'HKDF',
hash: 'SHA-256',
salt: new TextEncoder().encode('github-token'),
info: new Uint8Array(0),
},
base,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
}
async function encryptToken(plaintext) {
const key = await deriveKey();
const iv = new Uint8Array(12);
(globalThis.crypto || webcrypto).getRandomValues(iv);
const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));
const buf = new Uint8Array(iv.length + ct.byteLength);
buf.set(iv, 0);
buf.set(new Uint8Array(ct), iv.length);
return Buffer.from(buf).toString('base64');
}
// ── CSRF state (HMAC-signed payload) ─────────────────────────────────────────
async function makeState(payload) {
const data = Buffer.from(JSON.stringify(payload)).toString('base64url');
const sig = await hmacSha256(env.JWT_SECRET, data);
return `${data}.${sig}`;
}
async function verifyState(state) {
const dotIdx = state.lastIndexOf('.');
if (dotIdx < 0) throw Object.assign(new Error('invalid state'), { status: 400 });
const data = state.slice(0, dotIdx);
const sig = state.slice(dotIdx + 1);
const expected = await hmacSha256(env.JWT_SECRET, data);
if (!constantTimeEquals(sig, expected)) throw Object.assign(new Error('invalid state signature'), { status: 400 });
return JSON.parse(Buffer.from(data, 'base64url').toString());
}
// ── connect ───────────────────────────────────────────────────────────────────
async function handleConnect(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!env.GITHUB_OAUTH_CLIENT_ID) {
return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');
}
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const session = await getSessionUser(req);
if (!session) return error(res, 401, 'unauthorized', 'sign in required');
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agent_id') || '';
const state = await makeState({ userId: session.id, agentId, ts: Date.now() });
const redirectUri = `${env.APP_ORIGIN}/api/auth/github/callback`;
const ghUrl = new URL('https://github.com/login/oauth/authorize');
ghUrl.searchParams.set('client_id', env.GITHUB_OAUTH_CLIENT_ID);
ghUrl.searchParams.set('redirect_uri', redirectUri);
ghUrl.searchParams.set('scope', 'read:user,public_repo');
ghUrl.searchParams.set('state', state);
return redirect(res, ghUrl.toString());
}
// ── callback ──────────────────────────────────────────────────────────────────
async function handleCallback(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!env.GITHUB_OAUTH_CLIENT_ID || !env.GITHUB_OAUTH_CLIENT_SECRET) {
return error(res, 501, 'not_configured', 'GitHub OAuth is not configured');
}
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const url = new URL(req.url, 'http://x');
const code = url.searchParams.get('code');
const stateParam = url.searchParams.get('state');
const ghError = url.searchParams.get('error');
if (ghError) {
return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=denied`);
}
if (!code || !stateParam) return error(res, 400, 'bad_request', 'missing code or state');
let stateData;
try {
stateData = await verifyState(stateParam);
} catch {
return error(res, 400, 'invalid_state', 'invalid or tampered state parameter');
}
if (Date.now() - stateData.ts > 10 * 60 * 1000) {
return error(res, 400, 'state_expired', 'OAuth state has expired — please try again');
}
// Session-bind: if a session is active it must match the state's userId so a
// state token can't be replayed by a different user in their browser session.
const callbackSession = await getSessionUser(req).catch(() => null);
if (callbackSession && callbackSession.id !== stateData.userId) {
return error(res, 403, 'session_mismatch', 'OAuth state does not match the current session');
}
// Exchange code for access token
const tokenRes = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: { accept: 'application/json', 'content-type': 'application/json' },
body: JSON.stringify({
client_id: env.GITHUB_OAUTH_CLIENT_ID,
client_secret: env.GITHUB_OAUTH_CLIENT_SECRET,
code,
redirect_uri: `${env.APP_ORIGIN}/api/auth/github/callback`,
}),
});
if (!tokenRes.ok) {
return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);
}
const tokenData = await tokenRes.json();
if (tokenData.error || !tokenData.access_token) {
return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);
}
// Fetch GitHub user profile
const profileRes = await fetch('https://api.github.com/user', {
headers: {
authorization: `token ${tokenData.access_token}`,
'user-agent': 'three.ws/1.0',
},
});
if (!profileRes.ok) {
return redirect(res, `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=error`);
}
const profile = await profileRes.json();
const encryptedToken = await encryptToken(tokenData.access_token);
await sql`
INSERT INTO social_connections (user_id, provider, provider_uid, username, access_token, scopes)
VALUES (
${stateData.userId},
'github',
${String(profile.id)},
${profile.login},
${encryptedToken},
${tokenData.scope || 'read:user,public_repo'}
)
ON CONFLICT (user_id, provider) DO UPDATE SET
provider_uid = EXCLUDED.provider_uid,
username = EXCLUDED.username,
access_token = EXCLUDED.access_token,
scopes = EXCLUDED.scopes,
connected_at = now()
`;
const dest = stateData.agentId
? `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=connected&agent_id=${encodeURIComponent(stateData.agentId)}`
: `${env.APP_ORIGIN}/settings?tab=connected-accounts&github=connected`;
return redirect(res, dest);
}
// ── status ────────────────────────────────────────────────────────────────────
async function handleStatus(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
const session = await getSessionUser(req);
if (!session) return error(res, 401, 'unauthorized', 'sign in required');
const [row] = await sql`
SELECT username, connected_at FROM social_connections
WHERE user_id = ${session.id} AND provider = 'github'
`;
if (!row) return json(res, 200, { connected: false });
return json(res, 200, {
connected: true,
username: row.username,
connected_at: row.connected_at,
});
}
// ── dispatch ──────────────────────────────────────────────────────────────────
export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const action = url.searchParams.get('action') || url.pathname.split('/').filter(Boolean).pop();
if (action === 'connect') return handleConnect(req, res);
if (action === 'callback') return handleCallback(req, res);
if (action === 'status') return handleStatus(req, res);
return error(res, 404, 'not_found', 'unknown github auth action');
});