Skillfarm / website · skillfarm.ai / src / routes / oauth.tsx
| 1 | import type { Hono } from 'hono'; |
| 2 | import type { AppEnv, Ctx, Env } from '../env'; |
| 3 | import { ipKey, rateLimit } from '../lib/ratelimit'; |
| 4 | import { cleanScopes, createToken, SCOPE_TEXT, SCOPES, type Scope } from '../lib/tokens'; |
| 5 | import { DAY, HttpError, newId, now, randomToken, safeEqual, sha256B64url, sha256Hex } from '../lib/util'; |
| 6 | import { brandMark, icon } from '../views/art'; |
| 7 | import { render } from '../views/layout'; |
| 8 | |
| 9 | /** |
| 10 | * OAuth 2.1 authorization server for MCP clients. |
| 11 | * Public clients only: dynamic registration, authorization code with PKCE (S256), rotating refresh tokens. |
| 12 | * A token can never do more than the person who approved it, and only inside the scopes they approved. |
| 13 | */ |
| 14 | |
| 15 | const ACCESS_TTL = 3600; |
| 16 | const REFRESH_TTL = 60 * DAY; |
| 17 | const CODE_TTL = 300; |
| 18 | const BAD_SCHEMES = new Set(['javascript', 'data', 'vbscript', 'file', 'about', 'blob', 'ws', 'wss', 'ftp', 'mailto', 'tel', 'sms']); |
| 19 | |
| 20 | const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST, OPTIONS', 'access-control-allow-headers': 'content-type, authorization, mcp-protocol-version', 'access-control-max-age': '86400' }; |
| 21 | const NO_STORE = { 'cache-control': 'no-store', pragma: 'no-cache' }; |
| 22 | |
| 23 | type Client = { client_id: string; client_name: string; redirect_uris: string }; |
| 24 | |
| 25 | const origin = (c: Ctx) => new URL(c.req.url).origin; |
| 26 | const isLoopback = (host: string) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]'; |
| 27 | |
| 28 | /** A redirect target we are willing to register. */ |
| 29 | function redirectProblem(uri: unknown): string | null { |
| 30 | if (typeof uri !== 'string' || uri.length > 400) return 'Each redirect URI must be a string under 400 characters.'; |
| 31 | let u: URL; |
| 32 | try { |
| 33 | u = new URL(uri); |
| 34 | } catch { |
| 35 | return 'A redirect URI is not a valid URL.'; |
| 36 | } |
| 37 | if (u.hash) return 'Redirect URIs cannot contain a fragment.'; |
| 38 | if (u.username || u.password) return 'Redirect URIs cannot contain credentials.'; |
| 39 | const scheme = u.protocol.slice(0, -1); |
| 40 | if (scheme === 'https') return null; |
| 41 | if (scheme === 'http') return isLoopback(u.hostname) ? null : 'Plain http redirect URIs are only allowed for localhost.'; |
| 42 | if (BAD_SCHEMES.has(scheme) || !/^[a-z][a-z0-9+.-]{2,40}$/.test(scheme)) return 'That redirect URI scheme is not allowed.'; |
| 43 | return null; |
| 44 | } |
| 45 | |
| 46 | /** Exact match, except that a loopback redirect may use any port (RFC 8252). */ |
| 47 | function redirectMatches(registered: string[], given: string): boolean { |
| 48 | if (registered.includes(given)) return true; |
| 49 | try { |
| 50 | const g = new URL(given); |
| 51 | if (g.protocol !== 'http:' || !isLoopback(g.hostname)) return false; |
| 52 | return registered.some((r) => { |
| 53 | const u = new URL(r); |
| 54 | return u.protocol === 'http:' && isLoopback(u.hostname) && u.hostname === g.hostname && u.pathname === g.pathname && u.search === g.search; |
| 55 | }); |
| 56 | } catch { |
| 57 | return false; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | function redirectLabel(uri: string): string { |
| 62 | try { |
| 63 | const u = new URL(uri); |
| 64 | if (u.protocol === 'https:' || u.protocol === 'http:') return isLoopback(u.hostname) ? 'an app on this computer' : u.host; |
| 65 | return `the ${u.protocol.slice(0, -1)} app on this device`; |
| 66 | } catch { |
| 67 | return 'an unknown address'; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | async function getClient(env: Env, id: string | undefined): Promise<Client | null> { |
| 72 | if (!id || id.length > 80) return null; |
| 73 | return env.DB.prepare('SELECT client_id, client_name, redirect_uris FROM oauth_clients WHERE client_id = ?').bind(id).first<Client>(); |
| 74 | } |
| 75 | |
| 76 | const oauthError = (c: Ctx, status: number, error: string, description: string) => |
| 77 | c.json({ error, error_description: description }, status as 400, { ...CORS, ...NO_STORE }); |
| 78 | |
| 79 | type AuthzParams = { client: Client; redirectUri: string; scopes: Scope[]; state: string; challenge: string }; |
| 80 | |
| 81 | /** Validate an authorization request. Throws a page error when we cannot safely send the person back to the client. */ |
| 82 | async function readAuthz(c: Ctx, get: (k: string) => string | undefined): Promise<AuthzParams | Response> { |
| 83 | const client = await getClient(c.env, get('client_id')); |
| 84 | if (!client) throw new HttpError(400, 'This app is not registered with Skillfarm. Try connecting again from the app.'); |
| 85 | const redirectUri = get('redirect_uri') ?? ''; |
| 86 | const registered = JSON.parse(client.redirect_uris) as string[]; |
| 87 | if (!redirectUri || !redirectMatches(registered, redirectUri)) throw new HttpError(400, 'The app asked to send you to an address it did not register. Nothing was shared.'); |
| 88 | const state = (get('state') ?? '').slice(0, 500); |
| 89 | const back = (error: string, description: string) => { |
| 90 | const u = new URL(redirectUri); |
| 91 | u.searchParams.set('error', error); |
| 92 | u.searchParams.set('error_description', description); |
| 93 | if (state) u.searchParams.set('state', state); |
| 94 | return c.redirect(u.toString()); |
| 95 | }; |
| 96 | if (get('response_type') !== 'code') return back('unsupported_response_type', 'Only the authorization code flow is supported.'); |
| 97 | const challenge = get('code_challenge') ?? ''; |
| 98 | if (get('code_challenge_method') !== 'S256' || !/^[A-Za-z0-9_-]{43,128}$/.test(challenge)) return back('invalid_request', 'PKCE with S256 is required.'); |
| 99 | const asked = get('scope'); |
| 100 | const scopes = asked ? cleanScopes(asked) : [...SCOPES]; |
| 101 | if (!scopes.length) return back('invalid_scope', 'None of the requested scopes are supported.'); |
| 102 | return { client, redirectUri, scopes, state, challenge }; |
| 103 | } |
| 104 | |
| 105 | async function issuePair(env: Env, o: { userId: string; scopes: Scope[]; clientId: string; grantId: string; name: string }) { |
| 106 | const access = await createToken(env, { userId: o.userId, kind: 'access', name: o.name, scopes: o.scopes, clientId: o.clientId, grantId: o.grantId, ttl: ACCESS_TTL }); |
| 107 | const refresh = await createToken(env, { userId: o.userId, kind: 'refresh', name: o.name, scopes: o.scopes, clientId: o.clientId, grantId: o.grantId, ttl: REFRESH_TTL }); |
| 108 | return { access_token: access.token, token_type: 'Bearer', expires_in: ACCESS_TTL, refresh_token: refresh.token, scope: o.scopes.join(' ') }; |
| 109 | } |
| 110 | |
| 111 | export function registerOAuth(app: Hono<AppEnv>) { |
| 112 | const preflight = (c: Ctx) => new Response(null, { status: 204, headers: CORS }); |
| 113 | for (const p of ['/oauth/register', '/oauth/token', '/oauth/revoke', '/.well-known/*']) app.options(p, preflight); |
| 114 | |
| 115 | const serverMeta = (c: Ctx) => { |
| 116 | const base = origin(c); |
| 117 | return c.json( |
| 118 | { |
| 119 | issuer: base, |
| 120 | authorization_endpoint: `${base}/oauth/authorize`, |
| 121 | token_endpoint: `${base}/oauth/token`, |
| 122 | registration_endpoint: `${base}/oauth/register`, |
| 123 | revocation_endpoint: `${base}/oauth/revoke`, |
| 124 | scopes_supported: [...SCOPES], |
| 125 | response_types_supported: ['code'], |
| 126 | response_modes_supported: ['query'], |
| 127 | grant_types_supported: ['authorization_code', 'refresh_token'], |
| 128 | token_endpoint_auth_methods_supported: ['none'], |
| 129 | revocation_endpoint_auth_methods_supported: ['none'], |
| 130 | code_challenge_methods_supported: ['S256'], |
| 131 | service_documentation: `${base}/connect`, |
| 132 | }, |
| 133 | 200, |
| 134 | { ...CORS, 'cache-control': 'public, max-age=3600' }, |
| 135 | ); |
| 136 | }; |
| 137 | app.get('/.well-known/oauth-authorization-server', serverMeta); |
| 138 | app.get('/.well-known/oauth-authorization-server/*', serverMeta); |
| 139 | app.get('/.well-known/openid-configuration', serverMeta); |
| 140 | |
| 141 | const resourceMeta = (c: Ctx) => { |
| 142 | const base = origin(c); |
| 143 | const suffix = c.req.path.replace('/.well-known/oauth-protected-resource', ''); |
| 144 | const resource = suffix === '/mcp/account' ? `${base}/mcp/account` : `${base}/mcp`; |
| 145 | return c.json( |
| 146 | { resource, authorization_servers: [base], scopes_supported: [...SCOPES], bearer_methods_supported: ['header'], resource_name: 'Skillfarm', resource_documentation: `${base}/connect` }, |
| 147 | 200, |
| 148 | { ...CORS, 'cache-control': 'public, max-age=3600' }, |
| 149 | ); |
| 150 | }; |
| 151 | app.get('/.well-known/oauth-protected-resource', resourceMeta); |
| 152 | app.get('/.well-known/oauth-protected-resource/*', resourceMeta); |
| 153 | |
| 154 | // Dynamic client registration (RFC 7591). Clients are public: there is no client secret to leak. |
| 155 | app.post('/oauth/register', async (c) => { |
| 156 | if (!(await rateLimit(c.env, `oauthreg:${await ipKey(c.env, c.req.header('cf-connecting-ip'))}`, 20, 3600))) return oauthError(c, 429, 'too_many_requests', 'Too many registrations from this network. Try again later.'); |
| 157 | let body: Record<string, unknown>; |
| 158 | try { |
| 159 | body = (await c.req.json()) as Record<string, unknown>; |
| 160 | } catch { |
| 161 | return oauthError(c, 400, 'invalid_client_metadata', 'Send the client metadata as JSON.'); |
| 162 | } |
| 163 | const uris = body.redirect_uris; |
| 164 | if (!Array.isArray(uris) || uris.length < 1 || uris.length > 8) return oauthError(c, 400, 'invalid_redirect_uri', 'Register between one and eight redirect URIs.'); |
| 165 | for (const u of uris) { |
| 166 | const problem = redirectProblem(u); |
| 167 | if (problem) return oauthError(c, 400, 'invalid_redirect_uri', problem); |
| 168 | } |
| 169 | const method = body.token_endpoint_auth_method; |
| 170 | if (method !== undefined && method !== 'none') return oauthError(c, 400, 'invalid_client_metadata', 'Only public clients are supported. Set token_endpoint_auth_method to "none".'); |
| 171 | const name = (typeof body.client_name === 'string' ? body.client_name : 'MCP client').replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, 60) || 'MCP client'; |
| 172 | const clientId = `sfc_${randomToken(16)}`; |
| 173 | const ts = now(); |
| 174 | await c.env.DB.prepare('INSERT INTO oauth_clients (client_id, client_name, redirect_uris, created_at) VALUES (?,?,?,?)').bind(clientId, name, JSON.stringify(uris), ts).run(); |
| 175 | return c.json( |
| 176 | { |
| 177 | client_id: clientId, |
| 178 | client_id_issued_at: ts, |
| 179 | client_name: name, |
| 180 | redirect_uris: uris, |
| 181 | grant_types: ['authorization_code', 'refresh_token'], |
| 182 | response_types: ['code'], |
| 183 | token_endpoint_auth_method: 'none', |
| 184 | }, |
| 185 | 201, |
| 186 | { ...CORS, ...NO_STORE }, |
| 187 | ); |
| 188 | }); |
| 189 | |
| 190 | app.get('/oauth/authorize', async (c) => { |
| 191 | const p = await readAuthz(c, (k) => c.req.query(k)); |
| 192 | if (p instanceof Response) return p; |
| 193 | const user = c.get('user'); |
| 194 | const here = new URL(c.req.url); |
| 195 | if (!user) return c.redirect(`/signin?next=${encodeURIComponent(here.pathname + here.search)}`); |
| 196 | const write = p.scopes.includes('skills:write'); |
| 197 | return render( |
| 198 | c, |
| 199 | { title: 'Connect an app', noindex: true, narrow: true }, |
| 200 | <section class="section narrow"> |
| 201 | <div class="card pad auth-card consent"> |
| 202 | <div class="consent-mark">{brandMark(56)}</div> |
| 203 | <h1>Connect {p.client.client_name} to Skillfarm?</h1> |
| 204 | <p class="lede"> |
| 205 | This app wants to use Skillfarm as <strong>@{user.handle}</strong>. It will send you back to {redirectLabel(p.redirectUri)}. |
| 206 | </p> |
| 207 | <ul class="consent-list"> |
| 208 | {p.scopes.map((s) => ( |
| 209 | <li> |
| 210 | {icon('check', 18)} <span>{SCOPE_TEXT[s]}</span> |
| 211 | </li> |
| 212 | ))} |
| 213 | </ul> |
| 214 | <p class="fine"> |
| 215 | {write ? 'Skills shared through this app go to the review queue like any other. ' : ''} |
| 216 | The app never sees your BioLock, and you can disconnect it any time in Settings. Only allow this if you started the connection yourself. |
| 217 | </p> |
| 218 | <form method="post" action="/oauth/authorize" class="form"> |
| 219 | <input type="hidden" name="client_id" value={p.client.client_id} /> |
| 220 | <input type="hidden" name="redirect_uri" value={p.redirectUri} /> |
| 221 | <input type="hidden" name="response_type" value="code" /> |
| 222 | <input type="hidden" name="scope" value={p.scopes.join(' ')} /> |
| 223 | <input type="hidden" name="state" value={p.state} /> |
| 224 | <input type="hidden" name="code_challenge" value={p.challenge} /> |
| 225 | <input type="hidden" name="code_challenge_method" value="S256" /> |
| 226 | <div class="cta-row"> |
| 227 | <button class="btn btn-primary" name="decision" value="allow">Allow</button> |
| 228 | <button class="btn btn-ghost" name="decision" value="deny">Cancel</button> |
| 229 | </div> |
| 230 | </form> |
| 231 | </div> |
| 232 | </section>, |
| 233 | ); |
| 234 | }); |
| 235 | |
| 236 | app.post('/oauth/authorize', async (c) => { |
| 237 | const user = c.get('user'); |
| 238 | if (!user) throw new HttpError(401, 'Sign in first.'); |
| 239 | const form = await c.req.parseBody(); |
| 240 | const get = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : undefined); |
| 241 | const p = await readAuthz(c, get); |
| 242 | if (p instanceof Response) return p; |
| 243 | const back = new URL(p.redirectUri); |
| 244 | if (p.state) back.searchParams.set('state', p.state); |
| 245 | if (get('decision') !== 'allow') { |
| 246 | back.searchParams.set('error', 'access_denied'); |
| 247 | back.searchParams.set('error_description', 'The request was cancelled.'); |
| 248 | return c.redirect(back.toString()); |
| 249 | } |
| 250 | if (!(await rateLimit(c.env, `oauthcode:${user.id}`, 30, 3600))) throw new HttpError(429, 'Too many app connections in one hour. Try again later.'); |
| 251 | const code = `sf_ac_${randomToken(32)}`; |
| 252 | await c.env.DB.prepare('INSERT INTO oauth_codes (code_hash, client_id, user_id, redirect_uri, scopes, code_challenge, expires_at) VALUES (?,?,?,?,?,?,?)') |
| 253 | .bind(await sha256Hex(code), p.client.client_id, user.id, p.redirectUri, p.scopes.join(' '), p.challenge, now() + CODE_TTL) |
| 254 | .run(); |
| 255 | back.searchParams.set('code', code); |
| 256 | return c.redirect(back.toString()); |
| 257 | }); |
| 258 | |
| 259 | app.post('/oauth/token', async (c) => { |
| 260 | if (!(await rateLimit(c.env, `oauthtok:${await ipKey(c.env, c.req.header('cf-connecting-ip'))}`, 120, 60))) return oauthError(c, 429, 'too_many_requests', 'Slow down.'); |
| 261 | let f: Record<string, unknown> = {}; |
| 262 | try { |
| 263 | f = (c.req.header('content-type') ?? '').includes('application/json') ? ((await c.req.json()) as Record<string, unknown>) : await c.req.parseBody(); |
| 264 | } catch { |
| 265 | return oauthError(c, 400, 'invalid_request', 'The request body could not be read.'); |
| 266 | } |
| 267 | const get = (k: string) => (typeof f[k] === 'string' ? (f[k] as string) : ''); |
| 268 | const clientId = get('client_id'); |
| 269 | const ts = now(); |
| 270 | |
| 271 | if (get('grant_type') === 'authorization_code') { |
| 272 | const code = get('code'); |
| 273 | const verifier = get('code_verifier'); |
| 274 | if (!code || !verifier || !clientId) return oauthError(c, 400, 'invalid_request', 'code, code_verifier and client_id are required.'); |
| 275 | // Deleting on read makes the code single use even when two requests race. |
| 276 | const row = await c.env.DB.prepare('DELETE FROM oauth_codes WHERE code_hash = ? RETURNING client_id, user_id, redirect_uri, scopes, code_challenge, expires_at') |
| 277 | .bind(await sha256Hex(code)) |
| 278 | .first<{ client_id: string; user_id: string; redirect_uri: string; scopes: string; code_challenge: string; expires_at: number }>(); |
| 279 | if (!row || row.expires_at < ts) return oauthError(c, 400, 'invalid_grant', 'That code is not valid or has expired.'); |
| 280 | if (row.client_id !== clientId) return oauthError(c, 400, 'invalid_grant', 'That code was issued to a different client.'); |
| 281 | const redirectUri = get('redirect_uri'); |
| 282 | if (redirectUri && redirectUri !== row.redirect_uri) return oauthError(c, 400, 'invalid_grant', 'redirect_uri does not match the authorization request.'); |
| 283 | if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier) || !safeEqual(await sha256B64url(verifier), row.code_challenge)) return oauthError(c, 400, 'invalid_grant', 'The PKCE verifier does not match.'); |
| 284 | const owner = await c.env.DB.prepare('SELECT status FROM users WHERE id = ?').bind(row.user_id).first<{ status: string }>(); |
| 285 | if (owner?.status !== 'active') return oauthError(c, 400, 'invalid_grant', 'This account cannot connect apps.'); |
| 286 | const client = await getClient(c.env, clientId); |
| 287 | const pair = await issuePair(c.env, { userId: row.user_id, scopes: cleanScopes(row.scopes), clientId, grantId: newId(), name: client?.client_name ?? 'MCP client' }); |
| 288 | return c.json(pair, 200, { ...CORS, ...NO_STORE }); |
| 289 | } |
| 290 | |
| 291 | if (get('grant_type') === 'refresh_token') { |
| 292 | const token = get('refresh_token'); |
| 293 | if (!token.startsWith('sf_rt_')) return oauthError(c, 400, 'invalid_grant', 'That refresh token is not valid.'); |
| 294 | const row = await c.env.DB.prepare( |
| 295 | `SELECT t.id, t.user_id, t.scopes, t.client_id, t.grant_id, t.name, t.expires_at, t.revoked_at, u.status FROM api_tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.kind = 'refresh'`, |
| 296 | ) |
| 297 | .bind(await sha256Hex(token)) |
| 298 | .first<{ id: string; user_id: string; scopes: string; client_id: string | null; grant_id: string | null; name: string; expires_at: number | null; revoked_at: number | null; status: string }>(); |
| 299 | if (!row || !row.grant_id || !row.client_id) return oauthError(c, 400, 'invalid_grant', 'That refresh token is not valid.'); |
| 300 | const killGrant = () => c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE grant_id = ? AND revoked_at IS NULL').bind(ts, row.grant_id).run(); |
| 301 | if (row.revoked_at) { |
| 302 | // A refresh token that was already rotated is being replayed: treat the whole connection as stolen. |
| 303 | await killGrant(); |
| 304 | return oauthError(c, 400, 'invalid_grant', 'That refresh token was already used. Connect the app again.'); |
| 305 | } |
| 306 | if ((row.expires_at && row.expires_at < ts) || row.status !== 'active') return oauthError(c, 400, 'invalid_grant', 'That refresh token has expired.'); |
| 307 | if (clientId && clientId !== row.client_id) return oauthError(c, 400, 'invalid_grant', 'That refresh token belongs to a different client.'); |
| 308 | const claimed = await c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL RETURNING id').bind(ts, row.id).first<{ id: string }>(); |
| 309 | if (!claimed) { |
| 310 | await killGrant(); |
| 311 | return oauthError(c, 400, 'invalid_grant', 'That refresh token was already used. Connect the app again.'); |
| 312 | } |
| 313 | await killGrant(); |
| 314 | const held = cleanScopes(row.scopes); |
| 315 | const asked = get('scope') ? cleanScopes(get('scope')).filter((s) => held.includes(s)) : held; |
| 316 | const pair = await issuePair(c.env, { userId: row.user_id, scopes: asked.length ? asked : held, clientId: row.client_id, grantId: row.grant_id, name: row.name }); |
| 317 | return c.json(pair, 200, { ...CORS, ...NO_STORE }); |
| 318 | } |
| 319 | |
| 320 | return oauthError(c, 400, 'unsupported_grant_type', 'Use authorization_code or refresh_token.'); |
| 321 | }); |
| 322 | |
| 323 | // RFC 7009: always answers 200 so a caller cannot probe for valid tokens. |
| 324 | app.post('/oauth/revoke', async (c) => { |
| 325 | let token = ''; |
| 326 | try { |
| 327 | const f = await c.req.parseBody(); |
| 328 | token = typeof f.token === 'string' ? f.token : ''; |
| 329 | } catch { |
| 330 | /* fall through */ |
| 331 | } |
| 332 | if (token.startsWith('sf_at_') || token.startsWith('sf_rt_')) { |
| 333 | const row = await c.env.DB.prepare("SELECT id, grant_id FROM api_tokens WHERE token_hash = ? AND kind IN ('access','refresh')").bind(await sha256Hex(token)).first<{ id: string; grant_id: string | null }>(); |
| 334 | if (row?.grant_id) await c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE grant_id = ? AND revoked_at IS NULL').bind(now(), row.grant_id).run(); |
| 335 | else if (row) await c.env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').bind(now(), row.id).run(); |
| 336 | } |
| 337 | return c.body(null, 200, { ...CORS, ...NO_STORE }); |
| 338 | }); |
| 339 | } |