diff --git a/apps/web/src/app/.well-known/oauth-authorization-server/[...path]/route.ts b/apps/web/src/app/.well-known/oauth-authorization-server/[...path]/route.ts new file mode 100644 index 0000000..384ca83 --- /dev/null +++ b/apps/web/src/app/.well-known/oauth-authorization-server/[...path]/route.ts @@ -0,0 +1,3 @@ +export { GET, OPTIONS } from '../route'; + +export const dynamic = 'force-dynamic'; diff --git a/apps/web/src/app/.well-known/oauth-authorization-server/route.ts b/apps/web/src/app/.well-known/oauth-authorization-server/route.ts new file mode 100644 index 0000000..2af2d39 --- /dev/null +++ b/apps/web/src/app/.well-known/oauth-authorization-server/route.ts @@ -0,0 +1,15 @@ +import { authorizationServerMetadata, CORS_HEADERS } from '@/lib/mcp-oauth'; + +export const dynamic = 'force-dynamic'; + +// RFC 8414 authorization server metadata. The [...path] sibling answers the +// path-suffixed form some clients try first. +export function GET() { + return Response.json(authorizationServerMetadata(), { + headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' }, + }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/.well-known/oauth-protected-resource/[...path]/route.ts b/apps/web/src/app/.well-known/oauth-protected-resource/[...path]/route.ts new file mode 100644 index 0000000..384ca83 --- /dev/null +++ b/apps/web/src/app/.well-known/oauth-protected-resource/[...path]/route.ts @@ -0,0 +1,3 @@ +export { GET, OPTIONS } from '../route'; + +export const dynamic = 'force-dynamic'; diff --git a/apps/web/src/app/.well-known/oauth-protected-resource/route.ts b/apps/web/src/app/.well-known/oauth-protected-resource/route.ts new file mode 100644 index 0000000..611d2fb --- /dev/null +++ b/apps/web/src/app/.well-known/oauth-protected-resource/route.ts @@ -0,0 +1,15 @@ +import { CORS_HEADERS, protectedResourceMetadata } from '@/lib/mcp-oauth'; + +export const dynamic = 'force-dynamic'; + +// RFC 9728 protected-resource metadata for the MCP server at /api/agent/mcp. The +// [...path] sibling answers the path-suffixed form (/.well-known/oauth-protected-resource/api/agent/mcp). +export function GET() { + return Response.json(protectedResourceMetadata(), { + headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' }, + }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/.well-known/openid-configuration/route.ts b/apps/web/src/app/.well-known/openid-configuration/route.ts new file mode 100644 index 0000000..0a4cef0 --- /dev/null +++ b/apps/web/src/app/.well-known/openid-configuration/route.ts @@ -0,0 +1,14 @@ +import { CORS_HEADERS, openidConfiguration } from '@/lib/mcp-oauth'; + +export const dynamic = 'force-dynamic'; + +// For MCP clients that only look for OpenID discovery. No id_token is issued. +export function GET() { + return Response.json(openidConfiguration(), { + headers: { ...CORS_HEADERS, 'cache-control': 'public, max-age=3600' }, + }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/api/agent/mcp/route.test.ts b/apps/web/src/app/api/agent/mcp/route.test.ts index d741e74..965236d 100644 --- a/apps/web/src/app/api/agent/mcp/route.test.ts +++ b/apps/web/src/app/api/agent/mcp/route.test.ts @@ -39,18 +39,27 @@ describe('MCP route (e2e)', () => { authenticateAgentMock.mockResolvedValue({ token: { scopes: ['read', 'trade:crypto'] }, scopes: ['read', 'trade:crypto'], tokenId: 't', userId: 'u', admin: {} }); }); - it('handles initialize without auth and advertises tool capability', async () => { + it('answers initialize without a credential with 401 + WWW-Authenticate (starts OAuth)', async () => { const { POST } = await importRoute(); const res = await POST(rpc('initialize', {}, 1, false) as never); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toContain('resource_metadata="https://b1dz.com/.well-known/oauth-protected-resource"'); + expect(authenticateAgentMock).not.toHaveBeenCalled(); + }); + + it('handles initialize with an agent token and advertises tool capability', async () => { + const { POST } = await importRoute(); + const res = await POST(rpc('initialize', { protocolVersion: '2025-06-18' }) as never); const body = await res.json(); expect(body.result.serverInfo.name).toBe('b1dz-agent'); + expect(body.result.protocolVersion).toBe('2025-06-18'); expect(body.result.capabilities.tools).toBeDefined(); }); it('rejects a bad JSON-RPC envelope with 400', async () => { const { POST } = await importRoute(); const bad = new Request('http://test.local/api/agent/mcp', { - method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ foo: 'bar' }), + method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer b1dz_agent_test' }, body: JSON.stringify({ foo: 'bar' }), }); const res = await POST(bad as never); expect(res.status).toBe(400); @@ -62,6 +71,11 @@ describe('MCP route (e2e)', () => { const body = await res.json(); const names = (body.result.tools as Array<{ name: string }>).map((t) => t.name).sort(); expect(names).toEqual(['get_budget', 'get_portfolio', 'get_quote', 'place_order']); + expect(body.result).toMatchObject({ resultType: 'complete', cacheScope: 'public' }); + expect(typeof body.result.ttlMs).toBe('number'); + const order = body.result.tools.find((t: { name: string }) => t.name === 'place_order'); + expect(order.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true }); + for (const t of body.result.tools) expect(t.title).toBeTruthy(); }); it('401s tool calls without a valid agent token', async () => { @@ -71,6 +85,7 @@ describe('MCP route (e2e)', () => { expect(res.status).toBe(401); const body = await res.json(); expect(body.error.code).toBe(-32001); + expect(res.headers.get('www-authenticate')).toContain('error="invalid_token"'); }); it('routes tools/call place_order through placeAgentOrder', async () => { diff --git a/apps/web/src/app/api/agent/mcp/route.ts b/apps/web/src/app/api/agent/mcp/route.ts index 580075a..c80d9be 100644 --- a/apps/web/src/app/api/agent/mcp/route.ts +++ b/apps/web/src/app/api/agent/mcp/route.ts @@ -1,5 +1,7 @@ import type { NextRequest } from 'next/server'; import { authenticateAgent, type AuthedAgent } from '@/lib/api-auth'; +import { ACCESS_PREFIX, CORS_HEADERS, resolveAccessToken, resourceMetadataUrl, SCOPE } from '@/lib/mcp-oauth'; +import { createAdminSupabase } from '@/lib/supabase'; import { getAgentBudget, getAgentPortfolio, getAgentQuote, placeAgentOrder } from '@/lib/agent-trade'; export const dynamic = 'force-dynamic'; @@ -7,35 +9,51 @@ export const dynamic = 'force-dynamic'; /** * MCP server (the Base-MCP analog) — exposes b1dz crypto trading to external AI * agents (Claude, ChatGPT, any MCP client) as tools, over MCP's JSON-RPC HTTP - * transport. Auth is the same scoped agent token (Authorization: Bearer - * b1dz_agent_…); every tool funnels through the shared policy in agent-trade.ts, - * so trades stay hard-capped by the token's sub-account budget. + * transport. Auth: a scoped agent token (Authorization: Bearer b1dz_agent_…) or + * an OAuth 2.1 access token (b1dz_oat_…, see lib/mcp-oauth.ts) whose grant is + * backed by its own agent token. Either way every tool funnels through the + * shared policy in agent-trade.ts, so trades stay hard-capped by that + * sub-account's budget. + * + * Any request without a valid credential is HTTP 401 with + * `WWW-Authenticate: Bearer resource_metadata=…` (MCP authorization spec), so + * connector UIs (claude.ai, ChatGPT) start OAuth on the first request. */ -const PROTOCOL_VERSION = '2024-11-05'; +/** Newest first; an initialize asking for one of these gets it back, anything else gets the newest. */ +const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']; + +const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const; const TOOLS = [ { name: 'get_budget', + title: 'Get agent budget', description: "Get this agent token's spend budget, amount spent this window, and remaining USD.", inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + annotations: { title: 'Get agent budget', ...READ }, }, { name: 'get_portfolio', + title: 'Get portfolio', description: 'Get the current crypto positions and daily P/L for the linked account.', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + annotations: { title: 'Get portfolio', ...READ }, }, { name: 'get_quote', + title: 'Get quote', description: 'Get the latest known price for a trading pair (e.g. BTC-USD).', inputSchema: { type: 'object', properties: { pair: { type: 'string', description: 'Trading pair, e.g. BTC-USD' } }, required: ['pair'], }, + annotations: { title: 'Get quote', ...READ }, }, { name: 'place_order', + title: 'Place crypto buy', description: 'Place a crypto BUY for the given USD amount, hard-capped by the token budget. Returns accepted/queued; the engine re-checks risk + budget before execution.', inputSchema: { type: 'object', @@ -47,14 +65,37 @@ const TOOLS = [ }, required: ['pair', 'usd'], }, + // Spends real money on an exchange: not read-only, not undoable, reaches outside b1dz. + annotations: { title: 'Place crypto buy', readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, }, ] as const; function rpcResult(id: unknown, result: unknown) { - return Response.json({ jsonrpc: '2.0', id, result }); + return Response.json({ jsonrpc: '2.0', id, result }, { headers: CORS_HEADERS }); } function rpcError(id: unknown, code: number, message: string, httpStatus = 200) { - return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status: httpStatus }); + return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status: httpStatus, headers: CORS_HEADERS }); +} + +/** 401 + the RFC 9728 pointer; `invalid_token` when a credential was sent but did not resolve. */ +function challenge(id: unknown, presented: boolean) { + const parts = [`Bearer resource_metadata="${resourceMetadataUrl()}"`, `scope="${SCOPE}"`]; + if (presented) parts.push('error="invalid_token"', 'error_description="The access token is invalid or expired"'); + return Response.json( + { jsonrpc: '2.0', id, error: { code: -32001, message: 'unauthorized: sign in with OAuth or provide a valid b1dz_agent_ token' } }, + { status: 401, headers: { ...CORS_HEADERS, 'www-authenticate': parts.join(', '), 'cache-control': 'no-store' } }, + ); +} + +function bearer(req: NextRequest): string | null { + const m = /^Bearer\s+(\S+)$/i.exec((req.headers.get('authorization') ?? '').trim()); + return m ? m[1] : null; +} + +/** OAuth access token or b1dz_agent_ key; both resolve to the same AuthedAgent shape. */ +async function principal(req: NextRequest, token: string): Promise { + if (token.startsWith(ACCESS_PREFIX)) return resolveAccessToken(createAdminSupabase(), token); + return authenticateAgent(req); } function toolText(payload: unknown, isError = false) { return { content: [{ type: 'text', text: JSON.stringify(payload) }], isError }; @@ -78,28 +119,30 @@ async function runTool(agent: AuthedAgent, name: string, args: Record null)) as { jsonrpc?: string; id?: unknown; method?: string; params?: Record } | null; + if (!agent) return challenge(msg?.id ?? null, Boolean(token)); if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') { return rpcError(msg?.id ?? null, -32600, 'invalid JSON-RPC request', 400); } - // `initialize` and notifications don't require auth to negotiate; tool calls do. if (msg.method === 'initialize') { + const asked = String(msg.params?.protocolVersion ?? ''); return rpcResult(msg.id, { - protocolVersion: PROTOCOL_VERSION, - capabilities: { tools: {} }, - serverInfo: { name: 'b1dz-agent', version: '1.0.0' }, + protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0], + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: 'b1dz-agent', title: 'b1dz', version: '1.1.0' }, + instructions: + 'b1dz crypto trading for agents. get_budget, get_portfolio and get_quote are read-only. place_order queues a crypto BUY, hard-capped by this connection\'s budget; it fails when the connection has no trading budget.', }); } - if (msg.method === 'notifications/initialized' || msg.method === 'ping') { - return msg.id === undefined ? new Response(null, { status: 202 }) : rpcResult(msg.id, {}); - } - - const agent = await authenticateAgent(req); - if (!agent) return rpcError(msg.id ?? null, -32001, 'unauthorized: provide a valid b1dz_agent_ token', 401); + if (msg.method.startsWith('notifications/')) return new Response(null, { status: 202, headers: CORS_HEADERS }); + if (msg.method === 'ping') return rpcResult(msg.id, {}); if (msg.method === 'tools/list') { - return rpcResult(msg.id, { tools: TOOLS }); + // resultType/ttlMs/cacheScope: required on list results by current MCP clients. + return rpcResult(msg.id, { tools: TOOLS, resultType: 'complete', ttlMs: 300_000, cacheScope: 'public' }); } if (msg.method === 'tools/call') { const name = String(msg.params?.name ?? ''); @@ -114,3 +157,15 @@ export async function POST(req: NextRequest) { return rpcError(msg.id ?? null, -32601, `method not found: ${msg.method}`); } + +/** No server-to-client stream: 401 for anyone signed out (starts OAuth), 405 otherwise. */ +export async function GET(req: NextRequest) { + const token = bearer(req); + const agent = token ? await principal(req, token) : null; + if (!agent) return challenge(null, Boolean(token)); + return new Response(null, { status: 405, headers: { ...CORS_HEADERS, allow: 'POST, OPTIONS' } }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/api/oauth/__tests__/oauth-flow.test.ts b/apps/web/src/app/api/oauth/__tests__/oauth-flow.test.ts new file mode 100644 index 0000000..3ab5216 --- /dev/null +++ b/apps/web/src/app/api/oauth/__tests__/oauth-flow.test.ts @@ -0,0 +1,322 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { NextRequest } from 'next/server'; +import { createHash, randomBytes } from 'node:crypto'; + +// In-memory tables behind a query builder with just the calls lib/mcp-oauth.ts +// makes. Ported from profullstack/threatcrush#450 and smshub#140. +type Row = Record; +const tables: Record = {}; +let cookieUser: string | null = null; +const bearerSessions: Record = {}; + +function builder(table: string) { + const filters: Array<(r: Row) => boolean> = []; + let op: 'select' | 'insert' | 'update' | 'delete' = 'select'; + let payload: Row = {}; + const rows = () => (tables[table] ??= []); + const run = (): Row[] => { + if (op === 'insert') { + const row: Row = { id: randomBytes(8).toString('hex'), created_at: new Date().toISOString(), revoked_at: null, used_at: null, last_used_at: null, ...payload }; + rows().push(row); + return [row]; + } + const matched = rows().filter((r) => filters.every((f) => f(r))); + if (op === 'update') for (const r of matched) Object.assign(r, payload); + if (op === 'delete') tables[table] = rows().filter((r) => !matched.includes(r)); + return matched; + }; + const b = { + insert(p: Row) { op = 'insert'; payload = p; return b; }, + update(p: Row) { op = 'update'; payload = p; return b; }, + delete() { op = 'delete'; return b; }, + select() { return b; }, + order() { return b; }, + eq(col: string, val: unknown) { filters.push((r) => r[col] === val); return b; }, + is(col: string, val: unknown) { filters.push((r) => (r[col] ?? null) === val); return b; }, + gt(col: string, val: string) { filters.push((r) => String(r[col]) > val); return b; }, + gte(col: string, val: string) { filters.push((r) => String(r[col]) >= val); return b; }, + async maybeSingle() { const [r] = run(); return { data: r ?? null, error: null }; }, + async single() { const [r] = run(); return r ? { data: r, error: null } : { data: null, error: { message: 'no rows' } }; }, + then(resolve: (v: { data: Row[]; error: null }) => void) { resolve({ data: run(), error: null }); }, + }; + return b; +} + +const admin = { from: (t: string) => builder(t) }; +const AGENT_KEY = 'b1dz_agent_existingkey'; +const sha = (s: string) => createHash('sha256').update(s).digest('hex'); + +vi.mock('@/lib/supabase', () => ({ + createAdminSupabase: () => admin, + createServerSupabase: async () => ({ + auth: { getUser: async () => ({ data: { user: cookieUser ? { id: cookieUser, email: `${cookieUser}@example.com` } : null } }) }, + }), +})); +// Session auth (cookie or Supabase Bearer JWT) and agent-key auth, against the fake tables. +vi.mock('@/lib/api-auth', () => ({ + authenticate: async (req: Request) => { + const m = /^Bearer\s+(\S+)$/i.exec(req.headers.get('authorization') ?? ''); + if (m) return bearerSessions[m[1]] ? { client: admin, userId: bearerSessions[m[1]], email: null } : null; + return cookieUser ? { client: admin, userId: cookieUser, email: null } : null; + }, + authenticateAgent: async (req: Request) => { + const raw = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, ''); + if (!raw.startsWith('b1dz_agent_')) return null; + const row = (tables.agent_tokens ?? []).find((r) => r.token_hash === sha(raw) && !r.revoked_at); + return row ? { admin, userId: row.user_id, tokenId: row.id, scopes: row.scopes, token: row } : null; + }, + unauthorized: () => new Response(null, { status: 401 }), +})); +const getAgentBudget = vi.fn(async (agent: { tokenId: string; scopes: string[]; token: Row }) => ({ + status: 200, + body: { tokenId: agent.tokenId, scopes: agent.scopes, budgetUsd: Number(agent.token.budget_usd) }, +})); +vi.mock('@/lib/agent-trade', () => ({ + getAgentBudget: (a: never) => getAgentBudget(a), + getAgentPortfolio: async () => ({ status: 200, body: {} }), + getAgentQuote: async () => ({ status: 200, body: {} }), + placeAgentOrder: async () => ({ status: 202, body: {} }), +})); + +process.env.SITE_URL = 'https://b1dz.com'; +const ORIGIN = 'https://b1dz.com'; +const MCP_URL = `${ORIGIN}/api/agent/mcp`; + +const { POST: register } = await import('../register/route'); +const { POST: token } = await import('../token/route'); +const { POST: decide } = await import('../authorize/route'); +const { POST: revoke } = await import('../revoke/route'); +const { POST: mcp, GET: mcpGet } = await import('../../agent/mcp/route'); +const { GET: resourceMeta } = await import('../../../.well-known/oauth-protected-resource/route'); +const { GET: asMeta } = await import('../../../.well-known/oauth-authorization-server/route'); +const oauth = await import('@/lib/mcp-oauth'); + +const CLAUDE = 'https://claude.ai/api/mcp/auth_callback'; +const CHATGPT = 'https://chatgpt.com/connector_platform_oauth_redirect'; +const json = (url: string, body: unknown, headers: Record = {}) => + new NextRequest(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) }); +const tokenReq = (body: Record) => + new NextRequest(`${ORIGIN}/api/oauth/token`, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(body).toString(), + }); +const rpc = (body: unknown, headers: Record = {}) => + new NextRequest(MCP_URL, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) }); + +function pkce() { + const verifier = randomBytes(32).toString('base64url'); + return { verifier, challenge: createHash('sha256').update(verifier).digest('base64url') }; +} + +async function newClient(redirect_uris = [CLAUDE, CHATGPT, 'http://localhost:33418/callback', 'http://127.0.0.1:33418/callback']) { + const res = await register(json(`${ORIGIN}/api/oauth/register`, { client_name: 'Claude', redirect_uris })); + expect(res.status).toBe(201); + return (await res.json()) as { client_id: string; token_endpoint_auth_method: string }; +} + +/** The consent page's JSON decision as the signed-in user (cookie session, same origin). */ +async function authorize(clientId: string, challenge: string, redirect = CLAUDE, extra: Record = {}) { + cookieUser = 'user-1'; + const res = await decide( + json( + `${ORIGIN}/api/oauth/authorize`, + { + response_type: 'code', + client_id: clientId, + redirect_uri: redirect, + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'xyz', + resource: MCP_URL, + approve: true, + ...extra, + }, + { origin: ORIGIN }, + ), + ); + expect(res.status).toBe(200); + const u = new URL(((await res.json()) as { redirect: string }).redirect); + expect(u.searchParams.get('state')).toBe('xyz'); + expect(u.searchParams.get('iss')).toBe(ORIGIN); + return u.searchParams.get('code')!; +} + +async function connect(extra: Record = {}) { + const { client_id } = await newClient(); + const { verifier, challenge } = pkce(); + const code = await authorize(client_id, challenge, CLAUDE, extra); + const res = await token(tokenReq({ grant_type: 'authorization_code', code, code_verifier: verifier, client_id, redirect_uri: CLAUDE })); + expect(res.status).toBe(200); + return { client_id, ...((await res.json()) as { access_token: string; refresh_token: string; expires_in: number; token_type: string }) }; +} + +beforeEach(() => { + for (const k of Object.keys(tables)) delete tables[k]; + for (const k of Object.keys(bearerSessions)) delete bearerSessions[k]; + cookieUser = null; + // An existing agent key, made on /settings before OAuth existed. + tables.agent_tokens = [{ id: 'legacy', user_id: 'user-1', token_hash: sha(AGENT_KEY), scopes: ['read', 'trade:crypto'], budget_usd: 25, budget_window: 'daily', revoked_at: null }]; +}); + +describe('discovery', () => { + it('serves protected-resource metadata whose resource is exactly the MCP URL', async () => { + const r = await resourceMeta().json(); + expect(r.resource).toBe(MCP_URL); + expect(r.authorization_servers[0]).toBe(ORIGIN); + }); + it('serves authorization-server metadata with DCR, S256 and refresh', async () => { + const a = await asMeta().json(); + expect(a).toMatchObject({ + issuer: ORIGIN, + authorization_endpoint: `${ORIGIN}/oauth/authorize`, + token_endpoint: `${ORIGIN}/api/oauth/token`, + registration_endpoint: `${ORIGIN}/api/oauth/register`, + code_challenge_methods_supported: ['S256'], + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], + token_endpoint_auth_methods_supported: ['none'], + authorization_response_iss_parameter_supported: true, + }); + }); +}); + +describe('MCP route auth', () => { + it('answers any request without a credential with 401 + resource_metadata, initialize included', async () => { + for (const res of [await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'initialize' })), await mcpGet(new NextRequest(MCP_URL))]) { + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toContain(`Bearer resource_metadata="${ORIGIN}/.well-known/oauth-protected-resource"`); + } + }); + it('answers a bad credential with 401 invalid_token', async () => { + const res = await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authorization: 'Bearer b1dz_oat_nope' })); + expect(res.status).toBe(401); + expect(res.headers.get('www-authenticate')).toContain('error="invalid_token"'); + }); + it('still accepts an existing b1dz_agent_ key exactly as before', async () => { + const res = await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_budget', arguments: {} } }, { authorization: `Bearer ${AGENT_KEY}` })); + expect(res.status).toBe(200); + const out = JSON.parse(((await res.json()) as { result: { content: Array<{ text: string }> } }).result.content[0].text); + expect(out).toMatchObject({ tokenId: 'legacy', scopes: ['read', 'trade:crypto'], budgetUsd: 25 }); + }); +}); + +describe('dynamic client registration', () => { + it('registers a public client with the claude.ai, chatgpt and loopback redirects', async () => { + const c = await newClient(); + expect(c.client_id).toMatch(/^b1dz_client_[0-9a-f]{32}$/); + expect(c.token_endpoint_auth_method).toBe('none'); + }); + it('refuses confidential clients and non-https redirects', async () => { + const conf = await register(json(`${ORIGIN}/api/oauth/register`, { redirect_uris: [CLAUDE], token_endpoint_auth_method: 'client_secret_basic' })); + expect(conf.status).toBe(400); + const http = await register(json(`${ORIGIN}/api/oauth/register`, { redirect_uris: ['http://evil.example/cb'] })); + expect(((await http.json()) as { error: string }).error).toBe('invalid_redirect_uri'); + }); +}); + +describe('authorization', () => { + it('needs a signed-in user, and refuses a cross-site cookie POST', async () => { + const { client_id } = await newClient(); + const { challenge } = pkce(); + const body = { response_type: 'code', client_id, redirect_uri: CLAUDE, code_challenge: challenge, code_challenge_method: 'S256', approve: true }; + expect((await decide(json(`${ORIGIN}/api/oauth/authorize`, body, { origin: ORIGIN }))).status).toBe(401); + cookieUser = 'user-1'; + expect((await decide(json(`${ORIGIN}/api/oauth/authorize`, body, { origin: 'https://evil.example' }))).status).toBe(401); + }); + it('accepts a Bearer session (headless) and requires PKCE S256', async () => { + bearerSessions['jwt-1'] = 'user-1'; + const { client_id } = await newClient(); + const res = await decide( + json(`${ORIGIN}/api/oauth/authorize`, { response_type: 'code', client_id, redirect_uri: CLAUDE, code_challenge_method: 'plain', approve: true }, { authorization: 'Bearer jwt-1' }), + ); + const u = new URL(((await res.json()) as { redirect: string }).redirect); + expect(u.searchParams.get('error')).toBe('invalid_request'); + expect(u.searchParams.get('iss')).toBe(ORIGIN); + }); + it('sends access_denied back on Deny', async () => { + const { client_id } = await newClient(); + cookieUser = 'user-1'; + const res = await decide( + json(`${ORIGIN}/api/oauth/authorize`, { response_type: 'code', client_id, redirect_uri: CHATGPT, code_challenge: pkce().challenge, code_challenge_method: 'S256', approve: false }, { origin: ORIGIN }), + ); + expect(new URL(((await res.json()) as { redirect: string }).redirect).searchParams.get('error')).toBe('access_denied'); + }); + it('allows a loopback redirect on another port (RFC 8252)', async () => { + const { client_id } = await newClient(); + const code = await authorize(client_id, pkce().challenge, 'http://127.0.0.1:51234/callback'); + expect(code).toBeTruthy(); + }); +}); + +describe('PKCE flow', () => { + it('code -> tokens -> tools/list -> refresh rotation -> revoke', async () => { + const t = await connect(); + expect(t).toMatchObject({ token_type: 'Bearer', expires_in: 3600 }); + expect(t.access_token.startsWith('b1dz_oat_')).toBe(true); + + const list = await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authorization: `Bearer ${t.access_token}` })); + expect(list.status).toBe(200); + const result = ((await list.json()) as { result: { tools: Array<{ name: string; annotations: Record }>; ttlMs: number; cacheScope: string } }).result; + expect(result.tools.map((x) => x.name).sort()).toEqual(['get_budget', 'get_portfolio', 'get_quote', 'place_order']); + expect(result.cacheScope).toBe('public'); + for (const tool of result.tools) expect(typeof tool.annotations.readOnlyHint).toBe('boolean'); + + const r = await token(tokenReq({ grant_type: 'refresh_token', refresh_token: t.refresh_token, client_id: t.client_id })); + expect(r.status).toBe(200); + const t2 = (await r.json()) as { access_token: string; refresh_token: string }; + expect(t2.access_token).not.toBe(t.access_token); + expect((await mcp(rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, { authorization: `Bearer ${t.access_token}` }))).status).toBe(401); + expect((await mcp(rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, { authorization: `Bearer ${t2.access_token}` }))).status).toBe(200); + // Replayed refresh token is refused. + expect((await token(tokenReq({ grant_type: 'refresh_token', refresh_token: t.refresh_token }))).status).toBe(400); + + await revoke(new NextRequest(`${ORIGIN}/api/oauth/revoke`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: `token=${t2.access_token}` })); + expect((await mcp(rpc({ jsonrpc: '2.0', id: 3, method: 'tools/list' }, { authorization: `Bearer ${t2.access_token}` }))).status).toBe(401); + // The grant's agent sub-account is revoked with it; the legacy key is untouched. + expect(tables.agent_tokens.find((x) => x.id !== 'legacy')?.revoked_at).toBeTruthy(); + expect(tables.agent_tokens.find((x) => x.id === 'legacy')?.revoked_at).toBeNull(); + }); + + it('is read-only with no budget unless the user grants one, and never wider than an agent key', async () => { + const ro = await connect(); + const out = async (access: string) => + JSON.parse( + ((await (await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_budget' } }, { authorization: `Bearer ${access}` }))).json()) as { + result: { content: Array<{ text: string }> }; + }).result.content[0].text, + ); + expect(await out(ro.access_token)).toMatchObject({ scopes: ['read'], budgetUsd: 0 }); + const tr = await connect({ trade: true, budget_usd: 40, budget_window: 'weekly' }); + expect(await out(tr.access_token)).toMatchObject({ scopes: ['read', 'trade:crypto'], budgetUsd: 40 }); + // Every grant is its own sub-account bound to the approving user. + const grants = tables.agent_tokens.filter((x) => x.id !== 'legacy'); + expect(grants).toHaveLength(2); + for (const g of grants) expect(g.user_id).toBe('user-1'); + }); + + it('refuses a wrong verifier, a reused code and a mismatched redirect_uri', async () => { + const { client_id } = await newClient(); + const { verifier, challenge } = pkce(); + const code = await authorize(client_id, challenge); + expect((await token(tokenReq({ grant_type: 'authorization_code', code, code_verifier: pkce().verifier, redirect_uri: CLAUDE }))).status).toBe(400); + expect((await token(tokenReq({ grant_type: 'authorization_code', code, code_verifier: verifier, redirect_uri: CLAUDE }))).status).toBe(400); + const code2 = await authorize(client_id, challenge); + expect((await token(tokenReq({ grant_type: 'authorization_code', code: code2, code_verifier: verifier, redirect_uri: CHATGPT }))).status).toBe(400); + }); + + it('ends the grant when its agent token is revoked on /settings', async () => { + const t = await connect(); + for (const g of tables.agent_tokens) if (g.id !== 'legacy') g.revoked_at = new Date().toISOString(); + expect((await mcp(rpc({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, { authorization: `Bearer ${t.access_token}` }))).status).toBe(401); + expect((await token(tokenReq({ grant_type: 'refresh_token', refresh_token: t.refresh_token }))).status).toBe(400); + }); + + it('stores only hashes', async () => { + const t = await connect(); + const dump = JSON.stringify(tables); + expect(dump).not.toContain(t.access_token); + expect(dump).not.toContain(t.refresh_token); + expect(oauth.hashToken(t.access_token)).toHaveLength(64); + }); +}); diff --git a/apps/web/src/app/api/oauth/authorize/route.ts b/apps/web/src/app/api/oauth/authorize/route.ts new file mode 100644 index 0000000..a9e30d6 --- /dev/null +++ b/apps/web/src/app/api/oauth/authorize/route.ts @@ -0,0 +1,63 @@ +import type { NextRequest } from 'next/server'; +import { authenticate } from '@/lib/api-auth'; +import { checkAuthorize, errorRedirect, issueCode, OAuthError, parseGrantLimits, siteOrigin, type AuthorizeParams } from '@/lib/mcp-oauth'; +import { createAdminSupabase } from '@/lib/supabase'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +const NO_STORE = { 'cache-control': 'no-store' }; + +/** + * The decision from the consent page at /oauth/authorize (the advertised + * authorization_endpoint). JSON in, `{ redirect }` out: the page then sends the + * browser there itself, because the site's CSP form-action would block a form + * POST that redirects to claude.ai / chatgpt.com / localhost. + * + * Signed in by EITHER the cookie session (same origin only: Origin header or + * Sec-Fetch-Site) OR `Authorization: Bearer `, + * which a cross-site form cannot attach. Either way: CSRF-safe. + */ +async function signedInUser(req: NextRequest): Promise<{ id: string } | null> { + const hasBearer = /^Bearer\s+\S+$/i.test((req.headers.get('authorization') ?? '').trim()); + if (!hasBearer) { + const origin = req.headers.get('origin'); + const sameOrigin = origin ? origin === siteOrigin() || origin === req.nextUrl.origin : req.headers.get('sec-fetch-site') === 'same-origin'; + if (!sameOrigin) return null; + } + const auth = await authenticate(req); + return auth ? { id: auth.userId } : null; +} + +export async function POST(req: NextRequest) { + let body: AuthorizeParams & { approve?: unknown; trade?: unknown; budget_usd?: unknown; budget_window?: unknown }; + try { + body = (await req.json()) as typeof body; + if (!body || typeof body !== 'object') throw new Error(); + } catch { + return Response.json({ error: 'invalid_request', error_description: 'Send a JSON body' }, { status: 400, headers: NO_STORE }); + } + const approve = body.approve === true || body.approve === 'true' ? true : body.approve === false || body.approve === 'false' ? false : null; + if (approve === null) return Response.json({ error: 'invalid_request', error_description: 'approve is required' }, { status: 400, headers: NO_STORE }); + + const user = await signedInUser(req); + if (!user) return Response.json({ error: 'unauthorized', error_description: 'Sign in to b1dz first' }, { status: 401, headers: NO_STORE }); + + const admin = createAdminSupabase(); + const check = await checkAuthorize(admin, body); + if (!check.ok) { + return 'redirect' in check + ? Response.json({ redirect: check.redirect }, { headers: NO_STORE }) + : Response.json({ error: check.error, error_description: check.description }, { status: 400, headers: NO_STORE }); + } + if (!approve) { + return Response.json({ redirect: errorRedirect(check.redirectUri, 'access_denied', 'The user denied the request', check.state) }, { headers: NO_STORE }); + } + try { + return Response.json({ redirect: await issueCode(admin, check, user.id, parseGrantLimits(body)) }, { headers: NO_STORE }); + } catch (err) { + if (err instanceof OAuthError) return Response.json(err.body(), { status: err.status, headers: NO_STORE }); + console.error('[oauth] authorize failed', (err as Error).message); + return Response.json({ error: 'server_error' }, { status: 500, headers: NO_STORE }); + } +} diff --git a/apps/web/src/app/api/oauth/register/route.ts b/apps/web/src/app/api/oauth/register/route.ts new file mode 100644 index 0000000..72f40e9 --- /dev/null +++ b/apps/web/src/app/api/oauth/register/route.ts @@ -0,0 +1,32 @@ +import type { NextRequest } from 'next/server'; +import { CORS_HEADERS, OAuthError, registerClient } from '@/lib/mcp-oauth'; +import { createAdminSupabase } from '@/lib/supabase'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +// POST /api/oauth/register: RFC 7591 dynamic client registration (public clients only). +export async function POST(req: NextRequest) { + let body: Record; + try { + body = (await req.json()) as Record; + if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error(); + } catch { + return Response.json( + { error: 'invalid_client_metadata', error_description: 'Send the client metadata as a JSON object' }, + { status: 400, headers: CORS_HEADERS }, + ); + } + try { + const client = await registerClient(createAdminSupabase(), body); + return Response.json(client, { status: 201, headers: { ...CORS_HEADERS, 'cache-control': 'no-store' } }); + } catch (err) { + if (err instanceof OAuthError) return Response.json(err.body(), { status: err.status, headers: CORS_HEADERS }); + console.error('[oauth] register failed', (err as Error).message); + return Response.json({ error: 'server_error' }, { status: 500, headers: CORS_HEADERS }); + } +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/api/oauth/revoke/route.ts b/apps/web/src/app/api/oauth/revoke/route.ts new file mode 100644 index 0000000..c27251d --- /dev/null +++ b/apps/web/src/app/api/oauth/revoke/route.ts @@ -0,0 +1,34 @@ +import type { NextRequest } from 'next/server'; +import { CORS_HEADERS, revokeToken } from '@/lib/mcp-oauth'; +import { createAdminSupabase } from '@/lib/supabase'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +// POST /api/oauth/revoke: RFC 7009. Always 200; ends the grant and its agent token. +export async function POST(req: NextRequest) { + const type = req.headers.get('content-type') ?? ''; + let token = ''; + try { + if (type.includes('application/json')) { + const body = (await req.json()) as { token?: unknown }; + token = typeof body?.token === 'string' ? body.token : ''; + } else { + token = new URLSearchParams(await req.text()).get('token') ?? ''; + } + } catch { + /* an unreadable body revokes nothing */ + } + if (token) { + try { + await revokeToken(createAdminSupabase(), token); + } catch (err) { + console.error('[oauth] revoke failed', (err as Error).message); + } + } + return new Response(null, { status: 200, headers: { ...CORS_HEADERS, 'cache-control': 'no-store' } }); +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/api/oauth/token/route.ts b/apps/web/src/app/api/oauth/token/route.ts new file mode 100644 index 0000000..416fc28 --- /dev/null +++ b/apps/web/src/app/api/oauth/token/route.ts @@ -0,0 +1,39 @@ +import type { NextRequest } from 'next/server'; +import { CORS_HEADERS, exchangeCode, OAuthError, refreshTokens } from '@/lib/mcp-oauth'; +import { createAdminSupabase } from '@/lib/supabase'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +const NO_STORE = { ...CORS_HEADERS, 'cache-control': 'no-store', pragma: 'no-cache' }; + +/** The token endpoint takes application/x-www-form-urlencoded (RFC 6749); JSON is accepted too. */ +async function params(req: NextRequest): Promise> { + const type = req.headers.get('content-type') ?? ''; + if (type.includes('application/json')) { + const body = await req.json().catch(() => null); + return body && typeof body === 'object' ? (body as Record) : {}; + } + return Object.fromEntries(new URLSearchParams(await req.text())); +} + +// POST /api/oauth/token: authorization_code (PKCE S256) and refresh_token grants. +export async function POST(req: NextRequest) { + try { + const p = await params(req); + const admin = createAdminSupabase(); + let out; + if (p.grant_type === 'authorization_code') out = await exchangeCode(admin, p); + else if (p.grant_type === 'refresh_token') out = await refreshTokens(admin, p); + else throw new OAuthError('unsupported_grant_type', 'grant_type must be authorization_code or refresh_token'); + return Response.json(out, { headers: NO_STORE }); + } catch (err) { + if (err instanceof OAuthError) return Response.json(err.body(), { status: err.status, headers: NO_STORE }); + console.error('[oauth] token failed', (err as Error).message); + return Response.json({ error: 'server_error' }, { status: 500, headers: NO_STORE }); + } +} + +export function OPTIONS() { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} diff --git a/apps/web/src/app/oauth/authorize/consent-form.tsx b/apps/web/src/app/oauth/authorize/consent-form.tsx new file mode 100644 index 0000000..0507c58 --- /dev/null +++ b/apps/web/src/app/oauth/authorize/consent-form.tsx @@ -0,0 +1,103 @@ +'use client'; +import { useState } from 'react'; + +interface Props { + params: Record; + clientName: string; + clientUri: string | null; + redirectHost: string; + account: string; +} + +/** + * The consent decision. Posts JSON with the cookie session (same origin) and + * then navigates to the returned redirect itself: a form POST that 303s to + * claude.ai / chatgpt.com would be blocked by the site's CSP form-action. + */ +export default function ConsentForm({ params, clientName, clientUri, redirectHost, account }: Props) { + const [trade, setTrade] = useState(false); + const [budget, setBudget] = useState('50'); + const [windowSel, setWindowSel] = useState('daily'); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function decide(approve: boolean) { + setBusy(true); + setError(null); + try { + const res = await fetch('/api/oauth/authorize', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ...params, approve, trade, budget_usd: Number(budget), budget_window: windowSel }), + }); + const data = (await res.json().catch(() => ({}))) as { redirect?: string; error_description?: string; error?: string }; + if (!res.ok || !data.redirect) { + setError(data.error_description || data.error || 'Could not complete the request'); + setBusy(false); + return; + } + window.location.assign(data.redirect); + } catch { + setError('Network error'); + setBusy(false); + } + } + + return ( +
+

+ Allow {clientName} to use your b1dz account? +

+

+ Signed in as {account}. {clientName} gets its own agent sub-account: it can read your + budget, portfolio and quotes through the b1dz MCP tools. It can place crypto buys only if you give it a trading budget below, and + never more than that budget per window. It shows up with your agent tokens in Settings, where you can change or revoke it. +

+ + {trade && ( +
+ + +
+ )} +

+ After you decide, you go back to {redirectHost}. + {clientUri ? <> Client site: {clientUri} : null} +

+ {error &&
{error}
} +
+ + +
+
+ ); +} diff --git a/apps/web/src/app/oauth/authorize/page.tsx b/apps/web/src/app/oauth/authorize/page.tsx new file mode 100644 index 0000000..99c298c --- /dev/null +++ b/apps/web/src/app/oauth/authorize/page.tsx @@ -0,0 +1,60 @@ +import type { Metadata } from 'next'; +import { redirect } from 'next/navigation'; +import { checkAuthorize, type AuthorizeParams } from '@/lib/mcp-oauth'; +import { createAdminSupabase, createServerSupabase } from '@/lib/supabase'; +import ConsentForm from './consent-form'; + +export const dynamic = 'force-dynamic'; + +export const metadata: Metadata = { + title: 'Connect an app - b1dz', + description: 'Allow an AI app (Claude, ChatGPT, ...) to use your b1dz account through the b1dz MCP server.', + robots: { index: false, follow: false }, +}; + +const FIELDS = ['response_type', 'client_id', 'redirect_uri', 'code_challenge', 'code_challenge_method', 'state', 'scope', 'resource'] as const; + +/** + * OAuth 2.1 authorization endpoint for the MCP server at /api/agent/mcp. Not + * signed in: round trip through /login (password or CoinPay) and back. Signed + * in: name the client, let the user pick read-only or a capped trading budget, + * and post the decision to /api/oauth/authorize. + */ +export default async function OAuthAuthorizePage({ searchParams }: { searchParams: Promise> }) { + const raw = await searchParams; + const params: Record = {}; + for (const f of FIELDS) { + const v = raw[f]; + if (typeof v === 'string') params[f] = v; + } + const check = await checkAuthorize(createAdminSupabase(), params as AuthorizeParams); + if (!check.ok) { + if ('redirect' in check) redirect(check.redirect); + return ( +
+
+

This connection request cannot be used

+

{check.description}

+
+
+ ); + } + + const supabase = await createServerSupabase(); + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) redirect(`/login?next=${encodeURIComponent(`/oauth/authorize?${new URLSearchParams(params).toString()}`)}`); + + return ( +
+ +
+ ); +} diff --git a/apps/web/src/lib/mcp-oauth.ts b/apps/web/src/lib/mcp-oauth.ts new file mode 100644 index 0000000..166330c --- /dev/null +++ b/apps/web/src/lib/mcp-oauth.ts @@ -0,0 +1,522 @@ +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import type { SupabaseClient } from '@supabase/supabase-js'; +import { type AgentBudgetWindow, type AgentScope, type AgentTokenRow } from '@b1dz/core'; +import type { AuthedAgent } from './api-auth'; + +/** + * OAuth 2.1 authorization server for the MCP resource at /api/agent/mcp, per + * the MCP authorization spec: protected-resource metadata (RFC 9728), + * authorization server metadata (RFC 8414), dynamic client registration + * (RFC 7591), the authorization code grant with PKCE S256 only (RFC 9207 `iss` + * on every redirect), and rotating refresh tokens. Public clients only + * (claude.ai, ChatGPT and Claude Code all register as + * `token_endpoint_auth_method: none`). + * + * Every grant is backed by its own agent_tokens row, created when the code is + * exchanged with the scopes, budget and window the user picked on the consent + * screen. An access token therefore resolves to the same AuthedAgent a + * `b1dz_agent_` key does and goes through the same policy (agent-trade.ts): + * never more than an agent key with those limits. It is resolved only by the + * MCP route, so no other API accepts it. Revoking the grant revokes its agent + * token and vice versa. Tables: supabase/migrations/20261111150000_mcp_oauth.sql + * (hashes only). + * + * Ported from ThreatCrush (profullstack/threatcrush#450). + */ + +export const ACCESS_PREFIX = 'b1dz_oat_'; +export const REFRESH_PREFIX = 'b1dz_ort_'; +export const SCOPE = 'mcp'; +export const ACCESS_TTL_S = 3600; +export const REFRESH_TTL_S = 90 * 24 * 3600; +export const CODE_TTL_S = 300; +/** Upper bound for a budget granted from the consent screen; raise it on /settings if you need more. */ +export const MAX_CONSENT_BUDGET_USD = 100_000; + +const env = (name: string) => process.env[name]; + +/** The public origin, read at runtime (Next inlines literal process.env.X at build). */ +export function siteOrigin(): string { + return (env('SITE_URL') || env('NEXT_PUBLIC_SITE_URL') || 'https://b1dz.com').replace(/\/+$/, ''); +} + +export const MCP_PATH = '/api/agent/mcp'; +export const resourceUrl = (origin = siteOrigin()) => `${origin}${MCP_PATH}`; +export const resourceMetadataUrl = (origin = siteOrigin()) => `${origin}/.well-known/oauth-protected-resource`; + +export function protectedResourceMetadata(origin = siteOrigin()) { + return { + resource: resourceUrl(origin), + authorization_servers: [origin], + bearer_methods_supported: ['header'], + scopes_supported: [SCOPE], + resource_name: 'b1dz', + resource_documentation: `${origin}/settings`, + }; +} + +export function authorizationServerMetadata(origin = siteOrigin()) { + return { + issuer: origin, + authorization_endpoint: `${origin}/oauth/authorize`, + token_endpoint: `${origin}/api/oauth/token`, + registration_endpoint: `${origin}/api/oauth/register`, + revocation_endpoint: `${origin}/api/oauth/revoke`, + scopes_supported: [SCOPE], + response_types_supported: ['code'], + response_modes_supported: ['query'], + grant_types_supported: ['authorization_code', 'refresh_token'], + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + revocation_endpoint_auth_methods_supported: ['none'], + authorization_response_iss_parameter_supported: true, + service_documentation: `${origin}/settings`, + }; +} + +/** OpenID-shaped discovery for clients that only look there. No id_token is issued. */ +export function openidConfiguration(origin = siteOrigin()) { + return { + ...authorizationServerMetadata(origin), + subject_types_supported: ['public'], + id_token_signing_alg_values_supported: ['RS256'], + }; +} + +/** CORS for the metadata, registration, token and revoke endpoints: no cookies are involved. */ +export const CORS_HEADERS: Record = { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET, POST, OPTIONS', + 'access-control-allow-headers': 'authorization, content-type, mcp-protocol-version, mcp-session-id', + 'access-control-expose-headers': 'www-authenticate', + 'access-control-max-age': '86400', +}; + +// ─── Secrets ─── + +export const hashToken = (secret: string) => createHash('sha256').update(secret).digest('hex'); +const secret = () => randomBytes(32).toString('base64url'); + +/** base64url(SHA-256(verifier)), constant-time against the stored challenge. */ +export function pkceMatches(verifier: string, challenge: string): boolean { + if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) return false; + const a = Buffer.from(createHash('sha256').update(verifier).digest('base64url')); + const b = Buffer.from(challenge); + return a.length === b.length && timingSafeEqual(a, b); +} + +export const isS256Challenge = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{43}$/.test(v); + +// ─── Redirect URIs ─── + +const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']); + +/** https anywhere (no fragment, no credentials), or http on a loopback host (RFC 8252). */ +export function isAllowedRedirectUri(value: unknown): value is string { + if (typeof value !== 'string' || value.length > 2000) return false; + let u: URL; + try { + u = new URL(value); + } catch { + return false; + } + if (u.hash || u.username || u.password) return false; + if (u.protocol === 'https:') return true; + return u.protocol === 'http:' && LOOPBACK.has(u.hostname); +} + +/** + * Exact match, except that a loopback redirect may use any port (RFC 8252 + * §7.3): Claude Code listens on whichever port is free. + */ +export function redirectUriMatches(registered: string[], asked: string): boolean { + if (registered.includes(asked)) return true; + let a: URL; + try { + a = new URL(asked); + } catch { + return false; + } + if (a.protocol !== 'http:' || !LOOPBACK.has(a.hostname)) return false; + return registered.some((r) => { + try { + const u = new URL(r); + return u.protocol === 'http:' && u.hostname === a.hostname && u.pathname === a.pathname && u.search === a.search; + } catch { + return false; + } + }); +} + +// ─── Errors ─── + +export class OAuthError extends Error { + constructor( + public code: string, + message: string, + public status = 400, + ) { + super(message); + } + body() { + return { error: this.code, error_description: this.message }; + } +} + +// ─── Clients (RFC 7591) ─── + +export interface OAuthClient { + client_id: string; + client_name: string; + redirect_uris: string[]; + client_uri: string | null; + logo_uri: string | null; +} + +// eslint-disable-next-line no-control-regex +const cleanName = (v: unknown) => (typeof v === 'string' ? v.replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, 100) : ''); + +const optionalHttps = (v: unknown) => { + if (typeof v !== 'string') return null; + try { + return new URL(v).protocol === 'https:' ? v.slice(0, 500) : null; + } catch { + return null; + } +}; + +export async function registerClient(admin: SupabaseClient, body: Record) { + const uris = body.redirect_uris; + if (!Array.isArray(uris) || uris.length === 0 || uris.length > 20) { + throw new OAuthError('invalid_redirect_uri', 'redirect_uris must list 1 to 20 URIs'); + } + for (const u of uris) { + if (!isAllowedRedirectUri(u)) { + throw new OAuthError('invalid_redirect_uri', `Not allowed: ${String(u).slice(0, 200)} (https, or http on localhost/127.0.0.1)`); + } + } + const method = body.token_endpoint_auth_method ?? 'none'; + if (method !== 'none') { + throw new OAuthError('invalid_client_metadata', 'Only public clients are supported: token_endpoint_auth_method must be none'); + } + const grants = Array.isArray(body.grant_types) ? body.grant_types.map(String) : ['authorization_code', 'refresh_token']; + if (grants.some((g) => g !== 'authorization_code' && g !== 'refresh_token')) { + throw new OAuthError('invalid_client_metadata', 'grant_types may only be authorization_code and refresh_token'); + } + const types = Array.isArray(body.response_types) ? body.response_types.map(String) : ['code']; + if (types.some((t) => t !== 'code')) throw new OAuthError('invalid_client_metadata', 'response_types may only be code'); + + const row = { + client_id: `b1dz_client_${randomBytes(16).toString('hex')}`, + client_name: cleanName(body.client_name) || 'MCP client', + redirect_uris: [...new Set(uris as string[])], + client_uri: optionalHttps(body.client_uri), + logo_uri: optionalHttps(body.logo_uri), + }; + const { error } = await admin.from('oauth_clients').insert(row); + if (error) throw new OAuthError('server_error', 'Could not register the client', 500); + return { + ...row, + client_id_issued_at: Math.floor(Date.now() / 1000), + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + scope: SCOPE, + }; +} + +export async function getClient(admin: SupabaseClient, clientId: unknown): Promise { + if (typeof clientId !== 'string' || !/^[\w-]{1,100}$/.test(clientId)) return null; + const { data } = await admin + .from('oauth_clients') + .select('client_id, client_name, redirect_uris, client_uri, logo_uri') + .eq('client_id', clientId) + .maybeSingle(); + return (data as OAuthClient | null) ?? null; +} + +// ─── Authorization request ─── + +export interface AuthorizeParams { + response_type?: unknown; + client_id?: unknown; + redirect_uri?: unknown; + code_challenge?: unknown; + code_challenge_method?: unknown; + state?: unknown; + scope?: unknown; + resource?: unknown; +} + +export type AuthorizeCheck = + /** Unknown client or redirect: show the error, never redirect (RFC 6749 §4.1.2.1). */ + | { ok: false; error: string; description: string } + /** The redirect is trusted but the request is bad: send the error back to the client. */ + | { ok: false; redirect: string } + | { ok: true; client: OAuthClient; redirectUri: string; challenge: string; state: string | null; resource: string | null }; + +export function errorRedirect(redirectUri: string, error: string, description: string, state: string | null): string { + const u = new URL(redirectUri); + u.searchParams.set('error', error); + u.searchParams.set('error_description', description); + if (state) u.searchParams.set('state', state); + u.searchParams.set('iss', siteOrigin()); + return u.toString(); +} + +/** The MCP resource, with or without a trailing slash or query. */ +function resourceMatches(value: string): boolean { + try { + const u = new URL(value); + const r = new URL(resourceUrl()); + return u.origin === r.origin && u.pathname.replace(/\/+$/, '') === r.pathname; + } catch { + return false; + } +} + +export async function checkAuthorize(admin: SupabaseClient, p: AuthorizeParams): Promise { + const client = await getClient(admin, p.client_id); + if (!client) return { ok: false, error: 'invalid_client', description: 'Unknown client_id. Remove the connector and add it again.' }; + const redirectUri = + typeof p.redirect_uri === 'string' && p.redirect_uri ? p.redirect_uri : client.redirect_uris.length === 1 ? client.redirect_uris[0] : ''; + if (!redirectUri || !redirectUriMatches(client.redirect_uris, redirectUri)) { + return { ok: false, error: 'invalid_request', description: 'redirect_uri is not registered for this client.' }; + } + const state = typeof p.state === 'string' && p.state ? p.state.slice(0, 1000) : null; + const back = (error: string, description: string) => ({ ok: false as const, redirect: errorRedirect(redirectUri, error, description, state) }); + if (p.response_type !== 'code') return back('unsupported_response_type', 'response_type must be code'); + if (!isS256Challenge(p.code_challenge)) return back('invalid_request', 'PKCE is required: code_challenge (S256)'); + if (p.code_challenge_method !== 'S256') return back('invalid_request', 'code_challenge_method must be S256'); + if (typeof p.scope === 'string' && p.scope.trim() && !p.scope.split(/\s+/).every((s) => s === SCOPE)) { + return back('invalid_scope', `The only scope is ${SCOPE}`); + } + let resource: string | null = null; + if (typeof p.resource === 'string' && p.resource) { + if (!resourceMatches(p.resource)) return back('invalid_target', `resource must be ${resourceUrl()}`); + resource = p.resource; + } + return { ok: true, client, redirectUri, challenge: p.code_challenge, state, resource }; +} + +/** What the user allowed on the consent screen: read-only unless they gave the app a trading budget. */ +export interface GrantLimits { + scopes: AgentScope[]; + budgetUsd: number; + budgetWindow: AgentBudgetWindow; +} + +export const READ_ONLY: GrantLimits = { scopes: ['read'], budgetUsd: 0, budgetWindow: 'daily' }; + +/** Parse the consent form's choices. Anything unexpected falls back to read-only. */ +export function parseGrantLimits(body: { trade?: unknown; budget_usd?: unknown; budget_window?: unknown }): GrantLimits { + const trade = body.trade === true || body.trade === 'true' || body.trade === 'on'; + const budget = Number(body.budget_usd); + const window = ['daily', 'weekly', 'monthly'].includes(String(body.budget_window)) ? (String(body.budget_window) as AgentBudgetWindow) : 'daily'; + if (!trade || !Number.isFinite(budget) || budget <= 0) return { ...READ_ONLY, budgetWindow: window }; + return { scopes: ['read', 'trade:crypto'], budgetUsd: Math.min(Math.round(budget * 100) / 100, MAX_CONSENT_BUDGET_USD), budgetWindow: window }; +} + +/** Issue a single-use code for an approved request; returns the redirect with code + state + iss. */ +export async function issueCode( + admin: SupabaseClient, + check: Extract, + userId: string, + limits: GrantLimits = READ_ONLY, +): Promise { + const code = secret(); + const { error } = await admin.from('oauth_codes').insert({ + code_hash: hashToken(code), + client_id: check.client.client_id, + user_id: userId, + redirect_uri: check.redirectUri, + code_challenge: check.challenge, + scope: SCOPE, + resource: check.resource, + agent_scopes: limits.scopes, + budget_usd: limits.budgetUsd, + budget_window: limits.budgetWindow, + expires_at: new Date(Date.now() + CODE_TTL_S * 1000).toISOString(), + }); + if (error) throw new OAuthError('server_error', 'Could not issue an authorization code', 500); + const u = new URL(check.redirectUri); + u.searchParams.set('code', code); + if (check.state) u.searchParams.set('state', check.state); + u.searchParams.set('iss', siteOrigin()); + return u.toString(); +} + +// ─── Token endpoint ─── + +export interface TokenResponse { + access_token: string; + token_type: 'Bearer'; + expires_in: number; + refresh_token: string; + scope: string; +} + +function newPair() { + const access = ACCESS_PREFIX + secret(); + const refresh = REFRESH_PREFIX + secret(); + const now = Date.now(); + return { + access, + refresh, + row: { + access_hash: hashToken(access), + refresh_hash: hashToken(refresh), + access_expires_at: new Date(now + ACCESS_TTL_S * 1000).toISOString(), + refresh_expires_at: new Date(now + REFRESH_TTL_S * 1000).toISOString(), + }, + }; +} + +const respond = (access: string, refresh: string): TokenResponse => ({ + access_token: access, + token_type: 'Bearer', + expires_in: ACCESS_TTL_S, + refresh_token: refresh, + scope: SCOPE, +}); + +export async function exchangeCode(admin: SupabaseClient, p: Record): Promise { + const code = typeof p.code === 'string' ? p.code : ''; + const verifier = typeof p.code_verifier === 'string' ? p.code_verifier : ''; + if (!code) throw new OAuthError('invalid_request', 'code is required'); + if (!verifier) throw new OAuthError('invalid_request', 'code_verifier is required (PKCE)'); + + // Single use: the conditional update is the guard, so two racing requests cannot both redeem it. + const { data: row } = await admin + .from('oauth_codes') + .update({ used_at: new Date().toISOString() }) + .eq('code_hash', hashToken(code)) + .is('used_at', null) + .gt('expires_at', new Date().toISOString()) + .select('client_id, user_id, redirect_uri, code_challenge, scope, agent_scopes, budget_usd, budget_window') + .maybeSingle(); + if (!row) throw new OAuthError('invalid_grant', 'The authorization code is invalid, expired or already used'); + if (typeof p.client_id === 'string' && p.client_id && p.client_id !== row.client_id) { + throw new OAuthError('invalid_grant', 'The code was issued to another client'); + } + if (p.redirect_uri !== row.redirect_uri) throw new OAuthError('invalid_grant', 'redirect_uri does not match the authorization request'); + if (!pkceMatches(verifier, row.code_challenge)) throw new OAuthError('invalid_grant', 'code_verifier does not match the code_challenge'); + + // The grant's own agent sub-account. Its token_hash is the hash of a secret + // nobody ever sees, so it can only be reached through this grant. + const client = await getClient(admin, row.client_id); + const { data: agentToken, error: agentErr } = await admin + .from('agent_tokens') + .insert({ + user_id: row.user_id, + name: `${client?.client_name ?? 'MCP client'} (connected app)`.slice(0, 80), + token_hash: hashToken(`oauth-grant:${secret()}`), + token_suffix: 'oaut', + scopes: row.agent_scopes ?? ['read'], + budget_usd: Number(row.budget_usd) || 0, + budget_window: row.budget_window ?? 'daily', + allowed_symbols: null, + }) + .select('id') + .single(); + if (agentErr || !agentToken) throw new OAuthError('server_error', 'Could not issue tokens', 500); + + const pair = newPair(); + const { error } = await admin.from('oauth_tokens').insert({ + client_id: row.client_id, + user_id: row.user_id, + agent_token_id: agentToken.id, + scope: row.scope, + ...pair.row, + }); + if (error) { + await admin.from('agent_tokens').delete().eq('id', agentToken.id); + throw new OAuthError('server_error', 'Could not issue tokens', 500); + } + await admin.from('oauth_clients').update({ last_used_at: new Date().toISOString() }).eq('client_id', row.client_id); + return respond(pair.access, pair.refresh); +} + +export async function refreshTokens(admin: SupabaseClient, p: Record): Promise { + const refresh = typeof p.refresh_token === 'string' ? p.refresh_token : ''; + if (!refresh.startsWith(REFRESH_PREFIX)) throw new OAuthError('invalid_grant', 'The refresh token is invalid'); + const oldHash = hashToken(refresh); + const { data: grant } = await admin + .from('oauth_tokens') + .select('id, client_id, agent_token_id') + .eq('refresh_hash', oldHash) + .is('revoked_at', null) + .gt('refresh_expires_at', new Date().toISOString()) + .maybeSingle(); + if (!grant) throw new OAuthError('invalid_grant', 'The refresh token is invalid, expired or revoked'); + if (typeof p.client_id === 'string' && p.client_id && p.client_id !== grant.client_id) { + throw new OAuthError('invalid_grant', 'The refresh token was issued to another client'); + } + // The backing agent token revoked on /settings ends the grant too. + const { data: agentToken } = await admin.from('agent_tokens').select('id').eq('id', grant.agent_token_id).is('revoked_at', null).maybeSingle(); + if (!agentToken) throw new OAuthError('invalid_grant', 'The connection was revoked'); + // Rotate in place, conditional on the old hash: a replayed refresh token loses the race. + const pair = newPair(); + const { data: rotated } = await admin + .from('oauth_tokens') + .update(pair.row) + .eq('id', grant.id) + .eq('refresh_hash', oldHash) + .select('id') + .maybeSingle(); + if (!rotated) throw new OAuthError('invalid_grant', 'The refresh token was already used'); + return respond(pair.access, pair.refresh); +} + +/** RFC 7009: always 200, whether or not the token was known. Ends the whole grant and its agent token. */ +export async function revokeToken(admin: SupabaseClient, token: string): Promise { + const col = token.startsWith(ACCESS_PREFIX) ? 'access_hash' : token.startsWith(REFRESH_PREFIX) ? 'refresh_hash' : null; + if (!col) return; + const now = new Date().toISOString(); + const { data } = await admin + .from('oauth_tokens') + .update({ revoked_at: now }) + .eq(col, hashToken(token)) + .is('revoked_at', null) + .select('agent_token_id') + .maybeSingle(); + if (data?.agent_token_id) { + await admin.from('agent_tokens').update({ revoked_at: now }).eq('id', data.agent_token_id).is('revoked_at', null); + } +} + +// ─── Resolving an access token (MCP route only) ─── + +/** The same AuthedAgent a b1dz_agent_ key resolves to, from the grant's own agent token. Fails closed. */ +export async function resolveAccessToken(admin: SupabaseClient, token: string): Promise { + if (!token.startsWith(ACCESS_PREFIX)) return null; + const { data: grant } = await admin + .from('oauth_tokens') + .select('id, user_id, agent_token_id, last_used_at') + .eq('access_hash', hashToken(token)) + .is('revoked_at', null) + .gt('access_expires_at', new Date().toISOString()) + .maybeSingle(); + if (!grant) return null; + const { data: row } = await admin + .from('agent_tokens') + .select('*') + .eq('id', grant.agent_token_id) + .eq('user_id', grant.user_id) + .is('revoked_at', null) + .maybeSingle(); + if (!row) return null; + // At most one write a minute per grant. + if (!grant.last_used_at || Date.now() - Date.parse(grant.last_used_at) > 60_000) { + const now = new Date().toISOString(); + await admin.from('oauth_tokens').update({ last_used_at: now }).eq('id', grant.id); + await admin.from('agent_tokens').update({ last_used_at: now }).eq('id', row.id); + } + return { + admin, + userId: row.user_id, + tokenId: row.id, + scopes: Array.isArray(row.scopes) ? row.scopes : [], + token: row as AgentTokenRow, + }; +} diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index 1a4d73f..e6b27c9 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -18,6 +18,10 @@ const PUBLIC_PATHS = [ '/install.sh', // Invite landing: /i/ must work signed out. '/i', + // MCP OAuth consent (the page itself sends signed-out users to /login with the + // full query), plus the default OAuth paths an MCP client falls back to: they + // must answer 404, never a 200 HTML login page (breaks the client's JSON parse). + '/oauth', '/register', '/authorize', '/token', ]; const INVITE_PATH = /^\/i\/([A-Za-z0-9-]{12,40})\/?$/; const INVITE_COOKIE = 'b1dz_invite'; // = INVITE_COOKIE in lib/credits.ts (kept local: the proxy stays Edge-safe) diff --git a/supabase/migrations/20261111150000_mcp_oauth.sql b/supabase/migrations/20261111150000_mcp_oauth.sql new file mode 100644 index 0000000..55a482b --- /dev/null +++ b/supabase/migrations/20261111150000_mcp_oauth.sql @@ -0,0 +1,73 @@ +-- OAuth 2.1 for the MCP server at /api/agent/mcp (claude.ai connectors, +-- ChatGPT apps, Claude Code), per the MCP authorization spec. Ported from +-- ThreatCrush (profullstack/threatcrush#450). +-- Created: 2026-11-11 +-- +-- oauth_clients dynamic client registration (RFC 7591): public clients only +-- (token_endpoint_auth_method none), so there is no secret. +-- oauth_codes authorization codes: single use, ~5 minutes, bound to the +-- client, redirect_uri, PKCE S256 challenge and the user, plus +-- the limits the user chose on the consent screen. +-- oauth_tokens one row per grant ("connected app"): the current access and +-- refresh token hashes. A refresh rotates both in place. +-- +-- Every grant is backed by its own agent_tokens row (the same "sub-account" a +-- b1dz_agent_ key is), created when the code is exchanged. So an OAuth access +-- token can do exactly what an agent key with those scopes, budget and window +-- can, never more; it shows up (and can be revoked or re-budgeted) with the +-- user's other agent tokens. Revoking either side ends the grant. +-- +-- Only SHA-256 hashes of codes and tokens are stored. Service role only: RLS +-- on, no policies; every read and write goes through lib/mcp-oauth.ts. + +create table if not exists public.oauth_clients ( + client_id text primary key, + client_name text not null check (length(client_name) between 1 and 200), + redirect_uris text[] not null check (cardinality(redirect_uris) between 1 and 20), + client_uri text, + logo_uri text, + created_at timestamptz not null default now(), + last_used_at timestamptz +); + +create table if not exists public.oauth_codes ( + code_hash text primary key, + client_id text not null references public.oauth_clients(client_id) on delete cascade, + user_id uuid not null references auth.users(id) on delete cascade, + redirect_uri text not null, + code_challenge text not null, + scope text not null default 'mcp', + resource text, + agent_scopes text[] not null default '{read}', + budget_usd numeric not null default 0 check (budget_usd >= 0), + budget_window text not null default 'daily' check (budget_window in ('daily', 'weekly', 'monthly')), + created_at timestamptz not null default now(), + expires_at timestamptz not null, + used_at timestamptz +); +create index if not exists oauth_codes_expires_idx on public.oauth_codes (expires_at); + +create table if not exists public.oauth_tokens ( + id uuid primary key default gen_random_uuid(), + client_id text not null references public.oauth_clients(client_id) on delete cascade, + user_id uuid not null references auth.users(id) on delete cascade, + agent_token_id uuid not null references public.agent_tokens(id) on delete cascade, + scope text not null default 'mcp', + access_hash text not null unique, + refresh_hash text not null unique, + access_expires_at timestamptz not null, + refresh_expires_at timestamptz not null, + created_at timestamptz not null default now(), + last_used_at timestamptz, + revoked_at timestamptz +); +create index if not exists oauth_tokens_user_idx on public.oauth_tokens (user_id); +create index if not exists oauth_tokens_agent_token_idx on public.oauth_tokens (agent_token_id); + +alter table public.oauth_clients enable row level security; +alter table public.oauth_codes enable row level security; +alter table public.oauth_tokens enable row level security; + +-- Supabase grants table privileges to anon/authenticated by default; RLS with +-- no policy already refuses them, this makes it explicit. +revoke all on public.oauth_clients, public.oauth_codes, public.oauth_tokens from anon, authenticated;