diff --git a/apps/mobile/app/settings/ai/mcp.tsx b/apps/mobile/app/settings/ai/mcp.tsx index c929c792..8ffaaee6 100644 --- a/apps/mobile/app/settings/ai/mcp.tsx +++ b/apps/mobile/app/settings/ai/mcp.tsx @@ -49,6 +49,9 @@ export default function McpConnectionsScreen() { const stored = useQuery(api.mcpOAuth.getSettings, live ? {} : 'skip'); const updateSettings = useMutation(api.mcpOAuth.updateSettings); const updateScopes = useMutation(api.mcpOAuth.updateGrantScopes); + const scopeUpdates = React.useRef( + new Map }>(), + ); const [settings, setSettings] = React.useState(stored); const [open, setOpen] = React.useState(null); React.useEffect(() => { @@ -146,14 +149,28 @@ export default function McpConnectionsScreen() { title={`Change ${SCOPES[scope]!.toLowerCase()}`} checked={grant.scopes.includes(scope)} disabled={!live} - onChange={(next) => - void updateScopes({ - grantId: grant.id as Id<'mcpOAuthGrants'>, - scopes: next - ? [...grant.scopes, scope] - : grant.scopes.filter((item) => item !== scope), - }) - } + onChange={(next) => { + const grantId = String(grant.id); + let update = scopeUpdates.current.get(grantId); + if (!update) { + update = { scopes: [...grant.scopes], pending: Promise.resolve() }; + scopeUpdates.current.set(grantId, update); + } + const scopes = next + ? [...new Set([...update.scopes, scope])] + : update.scopes.filter((item) => item !== scope); + update.scopes = scopes; + const pending = update.pending + .catch(() => undefined) + .then(() => + updateScopes({ + grantId: grant.id as Id<'mcpOAuthGrants'>, + scopes, + }), + ); + update.pending = pending; + void pending.catch(() => {}); + }} /> )), }>(), + ); const [settings, setSettings] = React.useState(stored); const [open, setOpen] = React.useState(null); const [query, setQuery] = React.useState(''); @@ -213,14 +216,27 @@ export function McpConnectionsClient({ tools }: { tools: readonly McpToolSummary checked={on} disabled={!live} onChange={async (next) => { + const grantId = String(grant.id); + let update = scopeUpdates.current.get(grantId); + if (!update) { + update = { scopes: [...grant.scopes], pending: Promise.resolve() }; + scopeUpdates.current.set(grantId, update); + } const scopes = next - ? [...grant.scopes, item.scope] - : grant.scopes.filter((scope) => scope !== item.scope); + ? [...new Set([...update.scopes, item.scope])] + : update.scopes.filter((scope) => scope !== item.scope); + update.scopes = scopes; + const pending = update.pending + .catch(() => undefined) + .then(() => + updateScopes({ + grantId: grant.id as Id<'mcpOAuthGrants'>, + scopes, + }), + ); + update.pending = pending; try { - await updateScopes({ - grantId: grant.id as Id<'mcpOAuthGrants'>, - scopes, - }); + await pending; } catch { setMessage('Could not update permissions.'); } diff --git a/apps/web/app/mcp/authorize/screen.tsx b/apps/web/app/mcp/authorize/screen.tsx index c061a73c..6e91ff84 100644 --- a/apps/web/app/mcp/authorize/screen.tsx +++ b/apps/web/app/mcp/authorize/screen.tsx @@ -6,7 +6,7 @@ import { useConvexAuth, useAuthToken } from '@convex-dev/auth/react'; import { useMutation, useQuery } from 'convex/react'; import { api } from '@convex/_generated/api'; import { Button, ThemeProvider } from '@finapp/ui/web'; -import { authorizationDenialUrl, currentIssuer } from '@finapp/mcp/authorizationCallback'; +import { authorizationDenialUrl } from '@finapp/mcp/authorizationCallback'; type AuthorizationRequest = { clientId: string; @@ -106,6 +106,18 @@ export function McpAuthorizeScreen() { setPending(true); setError(''); try { + const metadataResponse = await fetch('/.well-known/oauth-authorization-server', { + cache: 'no-store', + }); + if (!metadataResponse.ok) throw new Error('Could not verify Finapp’s authorization issuer.'); + const metadata = (await metadataResponse.json()) as { issuer?: unknown }; + if (typeof metadata.issuer !== 'string') { + throw new Error('Could not verify Finapp’s authorization issuer.'); + } + const configuredIssuer = new URL(metadata.issuer); + if (configuredIssuer.origin !== metadata.issuer) { + throw new Error('Could not verify Finapp’s authorization issuer.'); + } const code = await createCode({ clientId: request.clientId, redirectUri: request.redirectUri, @@ -115,7 +127,7 @@ export function McpAuthorizeScreen() { const callback = new URL(request.redirectUri); callback.searchParams.set('code', code); callback.searchParams.set('state', request.state); - callback.searchParams.set('iss', currentIssuer()); + callback.searchParams.set('iss', configuredIssuer.origin); window.location.assign(callback.toString()); } catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not authorize this connection.'); diff --git a/apps/web/app/mcp/route.ts b/apps/web/app/mcp/route.ts index 653a27ca..06a81afa 100644 --- a/apps/web/app/mcp/route.ts +++ b/apps/web/app/mcp/route.ts @@ -99,9 +99,7 @@ export async function POST(request: Request) { .query(api.mcpOAuth.accessPolicy, { grantId: principal.grantId as never }) .catch(() => null); if (!policy) return withCors(unauthorized(), request); - const scopes = policy.scopes.filter( - (scope) => principal.scopes.includes(scope) || scope === 'finapp:read', - ); + const scopes = policy.scopes; const server = createMcpServer(client, scopes, principal.grantId, policy.settings); const transport = new WebStandardStreamableHTTPServerTransport({ diff --git a/apps/web/app/oauth/token/route.ts b/apps/web/app/oauth/token/route.ts index 69cf15f6..28a0416a 100644 --- a/apps/web/app/oauth/token/route.ts +++ b/apps/web/app/oauth/token/route.ts @@ -1,7 +1,7 @@ -import { api } from '@convex/_generated/api'; +import { api, internal } from '@convex/_generated/api'; import { decodeJwt } from 'jose'; import { readClientCredentials } from '@convex/shared/mcpClients'; -import { convexClient, mcpResourceUrl, prepareMcpAccessTokenSigner } from '@finapp/mcp/oauth'; +import { convexAdminClient, mcpResourceUrl, prepareMcpAccessTokenSigner } from '@finapp/mcp/oauth'; export const runtime = 'nodejs'; @@ -41,7 +41,10 @@ export async function POST(request: Request) { } const form = new URLSearchParams(new TextDecoder().decode(bytes.subarray(0, byteLength))); const grantType = form.get('grant_type'); - const credentials = readClientCredentials(request.headers.get('authorization'), form); + const authorization = request.headers.get('authorization'); + const credentials = readClientCredentials(authorization, form); + if (authorization && !/^Basic /i.test(authorization)) + return Response.json({ error: 'invalid_request' }, { status: 400 }); if ('error' in credentials) return Response.json( { error: credentials.error }, @@ -68,6 +71,17 @@ export async function POST(request: Request) { if (!clientId) return Response.json({ error: 'invalid_request' }, { status: 400 }); if (grantType !== 'authorization_code' && grantType !== 'refresh_token') return Response.json({ error: 'unsupported_grant_type' }, { status: 400 }); + const rawScope = grantType === 'refresh_token' ? form.get('scope') : null; + const requestedScopes = + rawScope === null ? undefined : [...new Set(rawScope.split(/\s+/).filter(Boolean))]; + if ( + requestedScopes && + (requestedScopes.length === 0 || + requestedScopes.length > 5 || + !requestedScopes.includes('finapp:read')) + ) { + return Response.json({ error: 'invalid_scope' }, { status: 400 }); + } const resource = form.get('resource'); let signAccessToken: Awaited>; try { @@ -81,8 +95,8 @@ export async function POST(request: Request) { type Grant = { userId: string; grantId: string; scopes: string[]; refreshToken: string }; let grant: Grant; - const client = convexClient(); try { + const client = convexAdminClient(); if (grantType === 'authorization_code') { const code = form.get('code'); const redirectUri = form.get('redirect_uri'); @@ -95,29 +109,54 @@ export async function POST(request: Request) { ...args, clientAssertion: credentials.clientAssertion, }) - : await client.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + : await client.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { ...args, ...(credentials.clientSecret ? { clientSecret: credentials.clientSecret } : {}), + authTransport: + credentials.via === 'basic' ? 'basic' : credentials.via === 'post' ? 'post' : 'none', }); } else { const refreshToken = form.get('refresh_token'); if (!refreshToken) return Response.json({ error: 'invalid_request' }, { status: 400 }); + if (credentials.clientAssertion && requestedScopes) { + const scopes = await client.query(api.mcpOAuth.refreshTokenScopes, { + refreshToken, + clientId, + }); + if (requestedScopes.some((scope) => !scopes.includes(scope))) + return Response.json({ error: 'invalid_scope' }, { status: 400 }); + } grant = credentials.clientAssertion ? await client.action(api.mcpOAuthActions.refreshWithClientAssertion, { refreshToken, clientId, clientAssertion: credentials.clientAssertion, }) - : await client.mutation(api.mcpOAuth.refreshAccessGrant, { + : await client.mutation(internal.mcpOAuth.refreshAccessGrant, { refreshToken, clientId, ...(credentials.clientSecret ? { clientSecret: credentials.clientSecret } : {}), + authTransport: + credentials.via === 'basic' ? 'basic' : credentials.via === 'post' ? 'post' : 'none', + ...(requestedScopes ? { requestedScopes } : {}), }); + if (credentials.clientAssertion && requestedScopes) { + const scopes = await client.mutation(api.mcpOAuth.restrictRefreshGrantScopes, { + refreshToken: grant.refreshToken, + clientId, + requestedScopes, + }); + grant = { ...grant, scopes }; + } } } catch (cause) { const message = cause instanceof Error ? cause.message : ''; if (message.includes('INVALID_CLIENT')) return invalidClient(); - return Response.json({ error: 'invalid_grant' }, { status: 400 }); + if (message.includes('INVALID_SCOPE')) + return Response.json({ error: 'invalid_scope' }, { status: 400 }); + if (message.includes('INVALID_GRANT')) + return Response.json({ error: 'invalid_grant' }, { status: 400 }); + return Response.json({ error: 'server_error' }, { status: 503 }); } try { diff --git a/convex/mcpOAuth.ts b/convex/mcpOAuth.ts index a52bc002..dd12436d 100644 --- a/convex/mcpOAuth.ts +++ b/convex/mcpOAuth.ts @@ -37,6 +37,17 @@ function base64url(bytes: Uint8Array): string { function isAllowedScope(scope: string): boolean { return Object.hasOwn(allowedScopes, scope); } +function validateRefreshScopes(scopes: string[], grantScopes: string[]): string[] { + const uniqueScopes = [...new Set(scopes)]; + if ( + uniqueScopes.length < 1 || + uniqueScopes.length > 5 || + !uniqueScopes.includes('finapp:read') || + uniqueScopes.some((scope) => !isAllowedScope(scope) || !grantScopes.includes(scope)) + ) + throw new Error('INVALID_SCOPE'); + return uniqueScopes; +} function randomCode(): string { const bytes = crypto.getRandomValues(new Uint8Array(32)); @@ -79,6 +90,11 @@ async function findClient(ctx: { db: QueryCtx['db'] }, clientId: string) { .withIndex('by_client_id', (index) => index.eq('clientId', clientId)) .unique(); } +// Client transport detected by the OAuth token endpoint. +const clientAuthTransport = v.union(v.literal('none'), v.literal('basic'), v.literal('post')); + +const refreshScopes = v.optional(v.array(v.string())); + const tokenAuthMethod = v.union( v.literal('none'), @@ -206,7 +222,7 @@ export const deleteMyClient = mutation({ const grants = await ctx.db .query('mcpOAuthGrants') .withIndex('by_client', (index) => index.eq('clientId', clientId)) - .take(500); + .collect(); const now = Date.now(); for (const grant of grants) if (grant.revokedAt === undefined) await ctx.db.patch(grant._id, { revokedAt: now }); @@ -337,11 +353,20 @@ export const createAuthorizationCode = mutation({ async function authenticateClient( ctx: MutationCtx, clientId: string, - credentials: { clientSecret?: string; assertionVerified: boolean }, + credentials: { + clientSecret?: string; + assertionVerified: boolean; + authTransport?: 'none' | 'basic' | 'post'; + }, ) { const client = await findClient(ctx, clientId); if (!client) throw new Error('INVALID_CLIENT'); const method = clientMethod(client); + const transportMatches = + (method === 'none' && credentials.authTransport === 'none') || + (method === 'client_secret_basic' && credentials.authTransport === 'basic') || + (method === 'client_secret_post' && credentials.authTransport === 'post'); + if (method !== 'private_key_jwt' && !transportMatches) throw new Error('INVALID_CLIENT'); if (method === 'private_key_jwt') { if (!credentials.assertionVerified) throw new Error('INVALID_CLIENT'); } else if (isConfidentialSecretMethod(method)) { @@ -374,7 +399,11 @@ const exchangeArgs = { async function exchangeCode( ctx: MutationCtx, args: { code: string; clientId: string; redirectUri: string; codeVerifier: string }, - credentials: { clientSecret?: string; assertionVerified: boolean }, + credentials: { + clientSecret?: string; + assertionVerified: boolean; + authTransport?: 'none' | 'basic' | 'post'; + }, ) { if ( !/^[a-f\d]{64}$/.test(args.code) || @@ -428,11 +457,15 @@ async function exchangeCode( return { userId: code.userId, scopes: code.scopes, grantId, refreshToken }; } -/** Code exchange for public (`none`) and secret (`client_secret_*`) clients. */ -export const exchangeAuthorizationCode = mutation({ - args: { ...exchangeArgs, clientSecret: v.optional(v.string()) }, - handler: async (ctx, { clientSecret, ...args }) => - exchangeCode(ctx, args, { clientSecret, assertionVerified: false }), +/** Code exchange for public and secret clients after token-route authentication. */ +export const exchangeAuthorizationCode = internalMutation({ + args: { + ...exchangeArgs, + clientSecret: v.optional(v.string()), + authTransport: v.optional(clientAuthTransport), + }, + handler: async (ctx, { clientSecret, authTransport, ...args }) => + exchangeCode(ctx, args, { clientSecret, authTransport, assertionVerified: false }), }); /** Code exchange after the action verified a `private_key_jwt` client assertion. */ @@ -446,8 +479,12 @@ export const exchangeAuthorizationCodeWithAssertion = internalMutation({ async function refreshGrant( ctx: MutationCtx, - args: { refreshToken: string; clientId: string }, - credentials: { clientSecret?: string; assertionVerified: boolean }, + args: { refreshToken: string; clientId: string; requestedScopes?: string[] }, + credentials: { + clientSecret?: string; + assertionVerified: boolean; + authTransport?: 'none' | 'basic' | 'post'; + }, ) { if (!args.refreshToken || args.refreshToken.length > 256 || !isValidClientId(args.clientId)) throw new Error('INVALID_GRANT'); @@ -466,15 +503,79 @@ async function refreshGrant( throw new Error('INVALID_GRANT'); const user = await ctx.db.get(grant.userId); if (!user || user.deletedAt !== undefined) throw new Error('INVALID_GRANT'); + const scopes = validateRefreshScopes(args.requestedScopes ?? grant.scopes, grant.scopes); + if (args.requestedScopes) await ctx.db.patch(grant._id, { scopes }); const refreshToken = await issueRefreshToken(ctx, grant._id); - return { userId: grant.userId, scopes: grant.scopes, grantId: grant._id, refreshToken }; + return { userId: grant.userId, scopes, grantId: grant._id, refreshToken }; } -/** Refresh-token grant (rotating) for public and secret clients. */ -export const refreshAccessGrant = mutation({ - args: { refreshToken: v.string(), clientId: v.string(), clientSecret: v.optional(v.string()) }, - handler: async (ctx, { clientSecret, ...args }) => - refreshGrant(ctx, args, { clientSecret, assertionVerified: false }), +/** Refresh-token grant after token-route authentication. */ +export const refreshAccessGrant = internalMutation({ + args: { + refreshToken: v.string(), + clientId: v.string(), + clientSecret: v.optional(v.string()), + authTransport: v.optional(clientAuthTransport), + requestedScopes: refreshScopes, + }, + handler: async (ctx, { clientSecret, authTransport, ...args }) => + refreshGrant(ctx, args, { clientSecret, authTransport, assertionVerified: false }), +}); +/** Looks up the current scope ceiling for a refresh token without rotating it. */ +export const refreshTokenScopes = query({ + args: { refreshToken: v.string(), clientId: v.string() }, + handler: async (ctx, { refreshToken, clientId }) => { + if (!refreshToken || refreshToken.length > 256 || !isValidClientId(clientId)) + throw new Error('INVALID_GRANT'); + const refreshTokenHash = await hash(refreshToken); + const grant = await ctx.db + .query('mcpOAuthGrants') + .withIndex('by_refresh_hash', (index) => index.eq('refreshTokenHash', refreshTokenHash)) + .unique(); + if ( + !grant || + grant.clientId !== clientId || + grant.revokedAt !== undefined || + (grant.refreshExpiresAt ?? 0) <= Date.now() + ) + throw new Error('INVALID_GRANT'); + const user = await ctx.db.get(grant.userId); + if (!user || user.deletedAt !== undefined) throw new Error('INVALID_GRANT'); + return grant.scopes; + }, +}); + +/** Applies a validated scope subset to a private-key client's live grant after rotation. */ +export const restrictRefreshGrantScopes = mutation({ + args: { + refreshToken: v.string(), + clientId: v.string(), + requestedScopes: v.array(v.string()), + }, + handler: async (ctx, { refreshToken, clientId, requestedScopes }) => { + if (!refreshToken || refreshToken.length > 256 || !isValidClientId(clientId)) + throw new Error('INVALID_GRANT'); + const refreshTokenHash = await hash(refreshToken); + const grant = await ctx.db + .query('mcpOAuthGrants') + .withIndex('by_refresh_hash', (index) => index.eq('refreshTokenHash', refreshTokenHash)) + .unique(); + if ( + !grant || + grant.clientId !== clientId || + grant.revokedAt !== undefined || + (grant.refreshExpiresAt ?? 0) <= Date.now() + ) + throw new Error('INVALID_GRANT'); + const user = await ctx.db.get(grant.userId); + if (!user || user.deletedAt !== undefined) throw new Error('INVALID_GRANT'); + const currentSubset = [...new Set(requestedScopes)].filter((scope) => + grant.scopes.includes(scope), + ); + const scopes = validateRefreshScopes(currentSubset, grant.scopes); + await ctx.db.patch(grant._id, { scopes }); + return scopes; + }, }); export const refreshAccessGrantWithAssertion = internalMutation({ diff --git a/packages/mcp/src/oauth.ts b/packages/mcp/src/oauth.ts index 8e1a36f9..29df60f6 100644 --- a/packages/mcp/src/oauth.ts +++ b/packages/mcp/src/oauth.ts @@ -1,4 +1,5 @@ import { ConvexHttpClient } from 'convex/browser'; +import type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'; import { exportJWK, importPKCS8, importSPKI, jwtVerify, SignJWT } from 'jose'; import type { JWTPayload } from 'jose'; import { MCP_CONVEX_AUDIENCE } from '../../../convex/shared/mcpAuth'; @@ -38,6 +39,26 @@ export function convexClient(): ConvexHttpClient { return new ConvexHttpClient(mcpConvexUrl()); } +type InternalMutationClient = ConvexHttpClient & { + setAdminAuth(token: string): void; + mutation>( + mutation: Mutation, + args: FunctionArgs, + ): Promise>; +}; + +/** Admin-authenticated client for trusted server-only operations. */ +export function convexAdminClient(): InternalMutationClient { + const deployKey = process.env.CONVEX_DEPLOY_KEY?.trim(); + if (!deployKey) throw new Error('CONVEX_DEPLOY_KEY is required'); + const client = new ConvexHttpClient(mcpConvexUrl()); + const adminClient = client as unknown as InternalMutationClient; + if (typeof adminClient.setAdminAuth !== 'function') + throw new Error('The Convex SDK does not support admin authentication'); + adminClient.setAdminAuth(deployKey); + return adminClient; +} + export async function mcpBackendClient(principal: McpPrincipal): Promise { const client = convexClient(); const context = await signingContext(); diff --git a/packages/mcp/src/tools/finance.ts b/packages/mcp/src/tools/finance.ts index 841f9323..fad761ed 100644 --- a/packages/mcp/src/tools/finance.ts +++ b/packages/mcp/src/tools/finance.ts @@ -230,10 +230,12 @@ export const financeTools: ToolFactory = (client) => [ name: 'finapp.finance.transactions.delete', title: 'Delete transaction (to Trash)', description: - 'Delete one personal transaction. It moves to Trash and can be restored with finapp.finance.trash.restore, so no confirmation is needed. Group expenses use finapp.groups.expenses.delete.', + 'Delete one personal transaction after explicit user confirmation. It moves to Trash and can be restored with finapp.finance.trash.restore. Group expenses use finapp.groups.expenses.delete.', scope: 'finapp:write:finance', + destructive: true, input: { transactionId: docId('Transaction'), + confirm: confirm('delete this transaction'), clientMutationId: mutationId, }, run: (args) => diff --git a/packages/mcp/src/tools/personal.ts b/packages/mcp/src/tools/personal.ts index 08023664..b4d8fa75 100644 --- a/packages/mcp/src/tools/personal.ts +++ b/packages/mcp/src/tools/personal.ts @@ -167,14 +167,16 @@ export const personalTools: ToolFactory = (client) => [ name: 'finapp.personal.notifications.summary', title: 'Notification status', description: - 'Your unread notification count and which notification categories are on. unreadCapped=true means only the newest 500 notifications were counted.', + 'Your unread notification count and which notification categories are on. When unreadCapped is true, the count covers the newest 500 notifications; older notifications were not scanned.', scope: 'finapp:read', input: {}, run: () => client.query(api.mcp.notificationState, {}), summarize: (data) => { const state = data as { unreadCount?: number; unreadCapped?: boolean } | null; if (typeof state?.unreadCount !== 'number') return undefined; - return `${state.unreadCount}${state.unreadCapped ? '+' : ''} unread notification(s).`; + return state.unreadCapped + ? `${state.unreadCount} unread notification(s) among the newest 500; older notifications were not scanned.` + : `${state.unreadCount} unread notification(s).`; }, }), defineTool({ diff --git a/tests/convex/mcp-oauth-clients.test.ts b/tests/convex/mcp-oauth-clients.test.ts index bd8ff0d9..213fe320 100644 --- a/tests/convex/mcp-oauth-clients.test.ts +++ b/tests/convex/mcp-oauth-clients.test.ts @@ -56,17 +56,41 @@ describe('confidential clients', () => { clientId: registration.client_id, redirectUri, codeVerifier: verifier, + authTransport: 'post' as const, }; - await expect(t.mutation(api.mcpOAuth.exchangeAuthorizationCode, exchange)).rejects.toThrow( + await expect(t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, exchange)).rejects.toThrow( 'INVALID_CLIENT', ); await expect( - t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { ...exchange, clientSecret: 'wrong' }), + t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { ...exchange, clientSecret: 'wrong' }), ).rejects.toThrow('INVALID_CLIENT'); - const grant = await t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + await expect( + t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { + code, + clientId: registration.client_id, + redirectUri, + codeVerifier: verifier, + clientSecret: registration.client_secret!, + }), + ).rejects.toThrow('INVALID_CLIENT'); + const grant = await t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { ...exchange, clientSecret: registration.client_secret!, }); + await expect( + t.mutation(internal.mcpOAuth.refreshAccessGrant, { + refreshToken: grant.refreshToken, + clientId: registration.client_id, + clientSecret: registration.client_secret!, + }), + ).rejects.toThrow('INVALID_CLIENT'); + const refreshed = await t.mutation(internal.mcpOAuth.refreshAccessGrant, { + refreshToken: grant.refreshToken, + clientId: registration.client_id, + clientSecret: registration.client_secret!, + authTransport: 'post', + }); + expect(refreshed.refreshToken).toEqual(expect.any(String)); expect(grant.refreshToken).toEqual(expect.any(String)); }); @@ -81,12 +105,13 @@ describe('confidential clients', () => { }); expect(await owner.query(api.mcpOAuth.listMyClients, {})).toHaveLength(1); const code = await authorize(created.clientId); - const grant = await t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + const grant = await t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { code, clientId: created.clientId, redirectUri, codeVerifier: verifier, clientSecret: created.clientSecret, + authTransport: 'basic', }); await owner.mutation(api.mcpOAuth.deleteMyClient, { clientId: created.clientId }); const stored = await t.run((ctx) => ctx.db.get(grant.grantId)); @@ -102,12 +127,13 @@ describe('confidential clients', () => { }); const code = await authorize(registration.client_id); await expect( - t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { code, clientId: registration.client_id, redirectUri, codeVerifier: verifier, clientSecret: 'x', + authTransport: 'none', }), ).rejects.toThrow('INVALID_CLIENT'); }); @@ -121,29 +147,33 @@ describe('refresh tokens', () => { redirectUris: [redirectUri], }); const code = await authorize(registration.client_id); - const first = await t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + const first = await t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { code, clientId: registration.client_id, redirectUri, codeVerifier: verifier, + authTransport: 'none', }); - const second = await t.mutation(api.mcpOAuth.refreshAccessGrant, { + const second = await t.mutation(internal.mcpOAuth.refreshAccessGrant, { refreshToken: first.refreshToken, clientId: registration.client_id, + authTransport: 'none', }); expect(second.grantId).toBe(first.grantId); expect(second.refreshToken).not.toBe(first.refreshToken); await expect( - t.mutation(api.mcpOAuth.refreshAccessGrant, { + t.mutation(internal.mcpOAuth.refreshAccessGrant, { refreshToken: first.refreshToken, clientId: registration.client_id, + authTransport: 'none', }), ).rejects.toThrow('INVALID_GRANT'); await owner.mutation(api.mcpOAuth.revokeGrant, { grantId: second.grantId }); await expect( - t.mutation(api.mcpOAuth.refreshAccessGrant, { + t.mutation(internal.mcpOAuth.refreshAccessGrant, { refreshToken: second.refreshToken, clientId: registration.client_id, + authTransport: 'none', }), ).rejects.toThrow('INVALID_GRANT'); }); @@ -218,7 +248,7 @@ describe('client ID metadata documents', () => { }); const code = await authorize(clientId); await expect( - t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { code, clientId, redirectUri, diff --git a/tests/convex/mcp-oauth.test.ts b/tests/convex/mcp-oauth.test.ts index 50c12e15..c5a6e47c 100644 --- a/tests/convex/mcp-oauth.test.ts +++ b/tests/convex/mcp-oauth.test.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto'; import { describe, expect, it } from 'vitest'; import { convexTest } from 'convex-test'; -import { api } from '../../convex/_generated/api'; +import { api, internal } from '../../convex/_generated/api'; import schema from '../../convex/schema'; const modules = import.meta.glob('../../convex/**/*.ts'); @@ -16,7 +16,11 @@ function differentHex(value: string) { return `${value[0] === 'a' ? 'b' : 'a'}${value.slice(1)}`; } -async function authorization(verifier = defaultVerifier) { +async function authorization( + verifier = defaultVerifier, + tokenEndpointAuthMethod: 'none' | 'client_secret_basic' | 'client_secret_post' = 'none', + scopes: string[] = ['finapp:read'], +) { const t = convexTest(schema, modules); const subject = 'mcp-oauth-owner'; const userId = await t.run((ctx) => @@ -31,12 +35,13 @@ async function authorization(verifier = defaultVerifier) { const registration = await t.mutation(api.mcpOAuth.registerClient, { clientName: 'OAuth regression client', redirectUris: [redirectUri], + tokenEndpointAuthMethod, }); const codeArgs = { clientId: registration.client_id, redirectUri, codeChallenge: challenge(verifier), - scopes: ['finapp:read'], + scopes, }; const code = await owner.mutation(api.mcpOAuth.createAuthorizationCode, codeArgs); const exchange = { @@ -44,17 +49,23 @@ async function authorization(verifier = defaultVerifier) { clientId: registration.client_id, redirectUri, codeVerifier: verifier, + authTransport: + tokenEndpointAuthMethod === 'client_secret_basic' + ? ('basic' as const) + : tokenEndpointAuthMethod === 'client_secret_post' + ? ('post' as const) + : ('none' as const), }; const storedCode = () => t.run((ctx) => ctx.db.query('mcpOAuthCodes').unique()); const grants = () => t.run((ctx) => ctx.db.query('mcpOAuthGrants').collect()); - return { t, owner, userId, exchange, codeArgs, storedCode, grants }; + return { t, owner, userId, registration, exchange, codeArgs, storedCode, grants }; } describe('MCP OAuth authorization code exchange', () => { it('consumes a successful code and rejects replay without minting another grant', async () => { const fixture = await authorization(); const grant = await fixture.t.mutation( - api.mcpOAuth.exchangeAuthorizationCode, + internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange, ); @@ -64,7 +75,7 @@ describe('MCP OAuth authorization code exchange', () => { expect.objectContaining({ _id: grant.grantId, userId: fixture.userId }), ]); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).rejects.toThrow('INVALID_GRANT'); expect(await fixture.grants()).toHaveLength(1); }); @@ -72,13 +83,13 @@ describe('MCP OAuth authorization code exchange', () => { it('cannot replay a consumed code to replace a revoked connection', async () => { const fixture = await authorization(); const grant = await fixture.t.mutation( - api.mcpOAuth.exchangeAuthorizationCode, + internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange, ); await fixture.owner.mutation(api.mcpOAuth.revokeGrant, { grantId: grant.grantId }); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).rejects.toThrow('INVALID_GRANT'); expect(await fixture.grants()).toEqual([ expect.objectContaining({ _id: grant.grantId, revokedAt: expect.any(Number) }), @@ -91,7 +102,7 @@ describe('MCP OAuth authorization code exchange', () => { it('does not consume the code when a well-formed verifier fails PKCE', async () => { const fixture = await authorization(); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { ...fixture.exchange, codeVerifier: 'b'.repeat(43), }), @@ -100,7 +111,7 @@ describe('MCP OAuth authorization code exchange', () => { expect(await fixture.grants()).toHaveLength(0); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).resolves.toMatchObject({ userId: fixture.userId }); expect(await fixture.grants()).toHaveLength(1); }); @@ -109,7 +120,7 @@ describe('MCP OAuth authorization code exchange', () => { const verifier = `Az09-_.~${'a'.repeat(length - 8)}`; const fixture = await authorization(verifier); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).resolves.toMatchObject({ userId: fixture.userId }); expect(await fixture.storedCode()).toMatchObject({ consumedAt: expect.any(Number) }); }); @@ -124,7 +135,7 @@ describe('MCP OAuth authorization code exchange', () => { ])('rejects a %s verifier without consuming the code', async (_label, codeVerifier) => { const fixture = await authorization(); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, { + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { ...fixture.exchange, codeVerifier, }), @@ -132,7 +143,7 @@ describe('MCP OAuth authorization code exchange', () => { expect((await fixture.storedCode())?.consumedAt).toBeUndefined(); expect(await fixture.grants()).toHaveLength(0); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).resolves.toMatchObject({ userId: fixture.userId }); }); @@ -146,12 +157,12 @@ describe('MCP OAuth authorization code exchange', () => { if (field === 'code') exchange.code = differentHex(exchange.code); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, exchange), ).rejects.toThrow(field === 'client' ? 'INVALID_CLIENT' : 'INVALID_GRANT'); expect((await fixture.storedCode())?.consumedAt).toBeUndefined(); expect(await fixture.grants()).toHaveLength(0); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).resolves.toMatchObject({ userId: fixture.userId }); }, ); @@ -165,7 +176,7 @@ describe('MCP OAuth authorization code exchange', () => { }); await expect( - fixture.t.mutation(api.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, fixture.exchange), ).rejects.toThrow('INVALID_GRANT'); expect((await fixture.storedCode())?.consumedAt).toBeUndefined(); expect(await fixture.grants()).toHaveLength(0); @@ -186,4 +197,117 @@ describe('MCP OAuth authorization code exchange', () => { ).rejects.toThrow('INVALID_CLIENT'); expect(await fixture.t.run((ctx) => ctx.db.query('mcpOAuthCodes').collect())).toHaveLength(1); }); + it.each([ + { + method: 'client_secret_basic' as const, + wrongTransport: 'post' as const, + correctTransport: 'basic' as const, + }, + { + method: 'client_secret_post' as const, + wrongTransport: 'basic' as const, + correctTransport: 'post' as const, + }, + ])('requires the registered $method credential transport', async ({ + method, + wrongTransport, + correctTransport, + }) => { + const fixture = await authorization(defaultVerifier, method); + const clientSecret = fixture.registration.client_secret; + if (!clientSecret) throw new Error('Expected a registered client secret'); + + await expect( + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { + ...fixture.exchange, + clientSecret, + authTransport: wrongTransport, + }), + ).rejects.toThrow('INVALID_CLIENT'); + await expect( + fixture.t.mutation(internal.mcpOAuth.exchangeAuthorizationCode, { + ...fixture.exchange, + clientSecret, + authTransport: correctTransport, + }), + ).resolves.toMatchObject({ userId: fixture.userId }); + }); + + it('narrows the live grant to a requested refresh scope subset', async () => { + const fixture = await authorization(defaultVerifier, 'none', [ + 'finapp:read', + 'finapp:write:finance', + ]); + const initial = await fixture.t.mutation( + internal.mcpOAuth.exchangeAuthorizationCode, + fixture.exchange, + ); + + await expect( + fixture.t.mutation(internal.mcpOAuth.refreshAccessGrant, { + refreshToken: initial.refreshToken, + clientId: fixture.registration.client_id, + requestedScopes: ['finapp:read', 'finapp:write:social'], + authTransport: 'none', + }), + ).rejects.toThrow('INVALID_SCOPE'); + const narrowed = await fixture.t.mutation(internal.mcpOAuth.refreshAccessGrant, { + refreshToken: initial.refreshToken, + clientId: fixture.registration.client_id, + authTransport: 'none', + requestedScopes: ['finapp:read'], + }); + expect(narrowed.scopes).toEqual(['finapp:read']); + expect(await fixture.grants()).toMatchObject([{ scopes: ['finapp:read'] }]); + await expect( + fixture.t.mutation(internal.mcpOAuth.refreshAccessGrant, { + refreshToken: narrowed.refreshToken, + clientId: fixture.registration.client_id, + authTransport: 'none', + }), + ).resolves.toMatchObject({ scopes: ['finapp:read'] }); + }); + + it('applies newly granted scopes to the live grant policy', async () => { + const fixture = await authorization(); + const grant = await fixture.t.mutation( + internal.mcpOAuth.exchangeAuthorizationCode, + fixture.exchange, + ); + + await fixture.owner.mutation(api.mcpOAuth.updateGrantScopes, { + grantId: grant.grantId, + scopes: ['finapp:write:finance'], + }); + await expect( + fixture.owner.query(api.mcpOAuth.accessPolicy, { grantId: grant.grantId }), + ).resolves.toMatchObject({ scopes: ['finapp:read', 'finapp:write:finance'] }); + }); + + it('revokes every grant when its dashboard client is deleted', async () => { + const fixture = await authorization(); + const client = await fixture.owner.mutation(api.mcpOAuth.createStaticClient, { + clientName: 'Delete all grants regression client', + }); + await fixture.t.run(async (ctx) => { + for (let index = 0; index < 501; index += 1) { + await ctx.db.insert('mcpOAuthGrants', { + clientId: client.clientId, + userId: fixture.userId, + scopes: ['finapp:read'], + createdAt: Date.now(), + }); + } + }); + + await fixture.owner.mutation(api.mcpOAuth.deleteMyClient, { clientId: client.clientId }); + const grants = await fixture.t.run((ctx) => + ctx.db + .query('mcpOAuthGrants') + .withIndex('by_client', (index) => index.eq('clientId', client.clientId)) + .collect(), + ); + expect(grants).toHaveLength(501); + expect(grants.every((grant) => grant.revokedAt !== undefined)).toBe(true); + }); }); diff --git a/tests/web/mcp-plugin.test.ts b/tests/web/mcp-plugin.test.ts index 5f8b5f87..85ed10cb 100644 --- a/tests/web/mcp-plugin.test.ts +++ b/tests/web/mcp-plugin.test.ts @@ -184,6 +184,32 @@ describe('MCP plugin tools', () => { await client.close(); } }); + it('marks transaction deletion destructive and blocks it when destructive actions are disabled', async () => { + backend.scopes = ['finapp:read', 'finapp:write:finance']; + backend.access.allowDestructive = true; + const client = await connect(); + try { + const tools = (await client.listTools()).tools; + const deletion = tools.find((tool) => tool.name === 'finapp.finance.transactions.delete'); + expect(deletion?.annotations).toMatchObject({ + destructiveHint: true, + readOnlyHint: false, + }); + backend.access.allowDestructive = false; + const result = await client.callTool({ + name: 'finapp.finance.transactions.delete', + arguments: { + transactionId: 'transaction-1', + confirm: true, + }, + }); + expect(result.isError).toBe(true); + expect(backend.calls).toEqual([]); + } finally { + await client.close(); + } + }); + it('hides tools the user turned off in access-control settings', async () => { backend.scopes = ['finapp:read', 'finapp:write:groups']; @@ -789,6 +815,29 @@ describe('MCP coverage tools', () => { await client.close(); } }); + it('limits a truncated notification count to the newest 500 without implying more unread items', async () => { + backend.queries = { + 'mcp:notificationState': () => ({ + unreadCount: 12, + unreadCapped: true, + preferences: {}, + }), + }; + const client = await connect(); + try { + const status = await client.callTool({ + name: 'finapp.personal.notifications.summary', + arguments: {}, + }); + expect(text(status)).toBe( + '12 unread notification(s) among the newest 500; older notifications were not scanned.', + ); + expect(data(status)).toMatchObject({ unreadCount: 12, unreadCapped: true }); + } finally { + await client.close(); + } + }); + it('reads and partially updates privacy settings through convex/security', async () => { backend.scopes = ['finapp:read', 'finapp:write:personal']; diff --git a/tests/web/mcp-token-body.test.ts b/tests/web/mcp-token-body.test.ts index cd874a86..e1eb93a8 100644 --- a/tests/web/mcp-token-body.test.ts +++ b/tests/web/mcp-token-body.test.ts @@ -8,7 +8,7 @@ const oauth = vi.hoisted(() => ({ vi.mock('@finapp/mcp/oauth', () => ({ mcpResourceUrl: () => 'https://finapp.test/mcp', - convexClient: () => ({ mutation: oauth.mutation }), + convexAdminClient: () => ({ mutation: oauth.mutation }), prepareMcpAccessTokenSigner: oauth.prepareSigner, }));