import type { Hono } from 'hono'; import type { AppEnv, Ctx, Env } from '../env'; import { ipKey, rateLimit } from '../lib/ratelimit'; import { cleanScopes, createToken, SCOPE_TEXT, SCOPES, type Scope } from '../lib/tokens'; import { DAY, HttpError, newId, now, randomToken, safeEqual, sha256B64url, sha256Hex } from '../lib/util'; import { brandMark, icon } from '../views/art'; import { render } from '../views/layout'; /** * OAuth 2.1 authorization server for MCP clients. * Public clients only: dynamic registration, authorization code with PKCE (S256), rotating refresh tokens. * A token can never do more than the person who approved it, and only inside the scopes they approved. */ const ACCESS_TTL = 3600; const REFRESH_TTL = 60 * DAY; const CODE_TTL = 300; const BAD_SCHEMES = new Set(['javascript', 'data', 'vbscript', 'file', 'about', 'blob', 'ws', 'wss', 'ftp', 'mailto', 'tel', 'sms']); 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' }; const NO_STORE = { 'cache-control': 'no-store', pragma: 'no-cache' }; type Client = { client_id: string; client_name: string; redirect_uris: string }; const origin = (c: Ctx) => new URL(c.req.url).origin; const isLoopback = (host: string) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]'; /** A redirect target we are willing to register. */ function redirectProblem(uri: unknown): string | null { if (typeof uri !== 'string' || uri.length > 400) return 'Each redirect URI must be a string under 400 characters.'; let u: URL; try { u = new URL(uri); } catch { return 'A redirect URI is not a valid URL.'; } if (u.hash) return 'Redirect URIs cannot contain a fragment.'; if (u.username || u.password) return 'Redirect URIs cannot contain credentials.'; const scheme = u.protocol.slice(0, -1); if (scheme === 'https') return null; if (scheme === 'http') return isLoopback(u.hostname) ? null : 'Plain http redirect URIs are only allowed for localhost.'; if (BAD_SCHEMES.has(scheme) || !/^[a-z][a-z0-9+.-]{2,40}$/.test(scheme)) return 'That redirect URI scheme is not allowed.'; return null; } /** Exact match, except that a loopback redirect may use any port (RFC 8252). */ function redirectMatches(registered: string[], given: string): boolean { if (registered.includes(given)) return true; try { const g = new URL(given); if (g.protocol !== 'http:' || !isLoopback(g.hostname)) return false; return registered.some((r) => { const u = new URL(r); return u.protocol === 'http:' && isLoopback(u.hostname) && u.hostname === g.hostname && u.pathname === g.pathname && u.search === g.search; }); } catch { return false; } } function redirectLabel(uri: string): string { try { const u = new URL(uri); if (u.protocol === 'https:' || u.protocol === 'http:') return isLoopback(u.hostname) ? 'an app on this computer' : u.host; return `the ${u.protocol.slice(0, -1)} app on this device`; } catch { return 'an unknown address'; } } async function getClient(env: Env, id: string | undefined): Promise { if (!id || id.length > 80) return null; return env.DB.prepare('SELECT client_id, client_name, redirect_uris FROM oauth_clients WHERE client_id = ?').bind(id).first(); } const oauthError = (c: Ctx, status: number, error: string, description: string) => c.json({ error, error_description: description }, status as 400, { ...CORS, ...NO_STORE }); type AuthzParams = { client: Client; redirectUri: string; scopes: Scope[]; state: string; challenge: string }; /** Validate an authorization request. Throws a page error when we cannot safely send the person back to the client. */ async function readAuthz(c: Ctx, get: (k: string) => string | undefined): Promise { const client = await getClient(c.env, get('client_id')); if (!client) throw new HttpError(400, 'This app is not registered with Skillfarm. Try connecting again from the app.'); const redirectUri = get('redirect_uri') ?? ''; const registered = JSON.parse(client.redirect_uris) as string[]; 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.'); const state = (get('state') ?? '').slice(0, 500); const back = (error: string, description: string) => { const u = new URL(redirectUri); u.searchParams.set('error', error); u.searchParams.set('error_description', description); if (state) u.searchParams.set('state', state); return c.redirect(u.toString()); }; if (get('response_type') !== 'code') return back('unsupported_response_type', 'Only the authorization code flow is supported.'); const challenge = get('code_challenge') ?? ''; if (get('code_challenge_method') !== 'S256' || !/^[A-Za-z0-9_-]{43,128}$/.test(challenge)) return back('invalid_request', 'PKCE with S256 is required.'); const asked = get('scope'); const scopes = asked ? cleanScopes(asked) : [...SCOPES]; if (!scopes.length) return back('invalid_scope', 'None of the requested scopes are supported.'); return { client, redirectUri, scopes, state, challenge }; } async function issuePair(env: Env, o: { userId: string; scopes: Scope[]; clientId: string; grantId: string; name: string }) { 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 }); 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 }); return { access_token: access.token, token_type: 'Bearer', expires_in: ACCESS_TTL, refresh_token: refresh.token, scope: o.scopes.join(' ') }; } export function registerOAuth(app: Hono) { const preflight = (c: Ctx) => new Response(null, { status: 204, headers: CORS }); for (const p of ['/oauth/register', '/oauth/token', '/oauth/revoke', '/.well-known/*']) app.options(p, preflight); const serverMeta = (c: Ctx) => { const base = origin(c); return c.json( { issuer: base, authorization_endpoint: `${base}/oauth/authorize`, token_endpoint: `${base}/oauth/token`, registration_endpoint: `${base}/oauth/register`, revocation_endpoint: `${base}/oauth/revoke`, scopes_supported: [...SCOPES], response_types_supported: ['code'], response_modes_supported: ['query'], grant_types_supported: ['authorization_code', 'refresh_token'], token_endpoint_auth_methods_supported: ['none'], revocation_endpoint_auth_methods_supported: ['none'], code_challenge_methods_supported: ['S256'], service_documentation: `${base}/connect`, }, 200, { ...CORS, 'cache-control': 'public, max-age=3600' }, ); }; app.get('/.well-known/oauth-authorization-server', serverMeta); app.get('/.well-known/oauth-authorization-server/*', serverMeta); app.get('/.well-known/openid-configuration', serverMeta); const resourceMeta = (c: Ctx) => { const base = origin(c); const suffix = c.req.path.replace('/.well-known/oauth-protected-resource', ''); const resource = suffix === '/mcp/account' ? `${base}/mcp/account` : `${base}/mcp`; return c.json( { resource, authorization_servers: [base], scopes_supported: [...SCOPES], bearer_methods_supported: ['header'], resource_name: 'Skillfarm', resource_documentation: `${base}/connect` }, 200, { ...CORS, 'cache-control': 'public, max-age=3600' }, ); }; app.get('/.well-known/oauth-protected-resource', resourceMeta); app.get('/.well-known/oauth-protected-resource/*', resourceMeta); // Dynamic client registration (RFC 7591). Clients are public: there is no client secret to leak. app.post('/oauth/register', async (c) => { 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.'); let body: Record; try { body = (await c.req.json()) as Record; } catch { return oauthError(c, 400, 'invalid_client_metadata', 'Send the client metadata as JSON.'); } const uris = body.redirect_uris; if (!Array.isArray(uris) || uris.length < 1 || uris.length > 8) return oauthError(c, 400, 'invalid_redirect_uri', 'Register between one and eight redirect URIs.'); for (const u of uris) { const problem = redirectProblem(u); if (problem) return oauthError(c, 400, 'invalid_redirect_uri', problem); } const method = body.token_endpoint_auth_method; if (method !== undefined && method !== 'none') return oauthError(c, 400, 'invalid_client_metadata', 'Only public clients are supported. Set token_endpoint_auth_method to "none".'); const name = (typeof body.client_name === 'string' ? body.client_name : 'MCP client').replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, 60) || 'MCP client'; const clientId = `sfc_${randomToken(16)}`; const ts = now(); 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(); return c.json( { client_id: clientId, client_id_issued_at: ts, client_name: name, redirect_uris: uris, grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', }, 201, { ...CORS, ...NO_STORE }, ); }); app.get('/oauth/authorize', async (c) => { const p = await readAuthz(c, (k) => c.req.query(k)); if (p instanceof Response) return p; const user = c.get('user'); const here = new URL(c.req.url); if (!user) return c.redirect(`/signin?next=${encodeURIComponent(here.pathname + here.search)}`); const write = p.scopes.includes('skills:write'); return render( c, { title: 'Connect an app', noindex: true, narrow: true },
, ); }); app.post('/oauth/authorize', async (c) => { const user = c.get('user'); if (!user) throw new HttpError(401, 'Sign in first.'); const form = await c.req.parseBody(); const get = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : undefined); const p = await readAuthz(c, get); if (p instanceof Response) return p; const back = new URL(p.redirectUri); if (p.state) back.searchParams.set('state', p.state); if (get('decision') !== 'allow') { back.searchParams.set('error', 'access_denied'); back.searchParams.set('error_description', 'The request was cancelled.'); return c.redirect(back.toString()); } if (!(await rateLimit(c.env, `oauthcode:${user.id}`, 30, 3600))) throw new HttpError(429, 'Too many app connections in one hour. Try again later.'); const code = `sf_ac_${randomToken(32)}`; await c.env.DB.prepare('INSERT INTO oauth_codes (code_hash, client_id, user_id, redirect_uri, scopes, code_challenge, expires_at) VALUES (?,?,?,?,?,?,?)') .bind(await sha256Hex(code), p.client.client_id, user.id, p.redirectUri, p.scopes.join(' '), p.challenge, now() + CODE_TTL) .run(); back.searchParams.set('code', code); return c.redirect(back.toString()); }); app.post('/oauth/token', async (c) => { 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.'); let f: Record = {}; try { f = (c.req.header('content-type') ?? '').includes('application/json') ? ((await c.req.json()) as Record) : await c.req.parseBody(); } catch { return oauthError(c, 400, 'invalid_request', 'The request body could not be read.'); } const get = (k: string) => (typeof f[k] === 'string' ? (f[k] as string) : ''); const clientId = get('client_id'); const ts = now(); if (get('grant_type') === 'authorization_code') { const code = get('code'); const verifier = get('code_verifier'); if (!code || !verifier || !clientId) return oauthError(c, 400, 'invalid_request', 'code, code_verifier and client_id are required.'); // Deleting on read makes the code single use even when two requests race. 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') .bind(await sha256Hex(code)) .first<{ client_id: string; user_id: string; redirect_uri: string; scopes: string; code_challenge: string; expires_at: number }>(); if (!row || row.expires_at < ts) return oauthError(c, 400, 'invalid_grant', 'That code is not valid or has expired.'); if (row.client_id !== clientId) return oauthError(c, 400, 'invalid_grant', 'That code was issued to a different client.'); const redirectUri = get('redirect_uri'); if (redirectUri && redirectUri !== row.redirect_uri) return oauthError(c, 400, 'invalid_grant', 'redirect_uri does not match the authorization request.'); 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.'); const owner = await c.env.DB.prepare('SELECT status FROM users WHERE id = ?').bind(row.user_id).first<{ status: string }>(); if (owner?.status !== 'active') return oauthError(c, 400, 'invalid_grant', 'This account cannot connect apps.'); const client = await getClient(c.env, clientId); const pair = await issuePair(c.env, { userId: row.user_id, scopes: cleanScopes(row.scopes), clientId, grantId: newId(), name: client?.client_name ?? 'MCP client' }); return c.json(pair, 200, { ...CORS, ...NO_STORE }); } if (get('grant_type') === 'refresh_token') { const token = get('refresh_token'); if (!token.startsWith('sf_rt_')) return oauthError(c, 400, 'invalid_grant', 'That refresh token is not valid.'); const row = await c.env.DB.prepare( `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'`, ) .bind(await sha256Hex(token)) .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 }>(); if (!row || !row.grant_id || !row.client_id) return oauthError(c, 400, 'invalid_grant', 'That refresh token is not valid.'); 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(); if (row.revoked_at) { // A refresh token that was already rotated is being replayed: treat the whole connection as stolen. await killGrant(); return oauthError(c, 400, 'invalid_grant', 'That refresh token was already used. Connect the app again.'); } if ((row.expires_at && row.expires_at < ts) || row.status !== 'active') return oauthError(c, 400, 'invalid_grant', 'That refresh token has expired.'); if (clientId && clientId !== row.client_id) return oauthError(c, 400, 'invalid_grant', 'That refresh token belongs to a different client.'); 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 }>(); if (!claimed) { await killGrant(); return oauthError(c, 400, 'invalid_grant', 'That refresh token was already used. Connect the app again.'); } await killGrant(); const held = cleanScopes(row.scopes); const asked = get('scope') ? cleanScopes(get('scope')).filter((s) => held.includes(s)) : held; 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 }); return c.json(pair, 200, { ...CORS, ...NO_STORE }); } return oauthError(c, 400, 'unsupported_grant_type', 'Use authorization_code or refresh_token.'); }); // RFC 7009: always answers 200 so a caller cannot probe for valid tokens. app.post('/oauth/revoke', async (c) => { let token = ''; try { const f = await c.req.parseBody(); token = typeof f.token === 'string' ? f.token : ''; } catch { /* fall through */ } if (token.startsWith('sf_at_') || token.startsWith('sf_rt_')) { 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 }>(); 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(); 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(); } return c.body(null, 200, { ...CORS, ...NO_STORE }); }); }