Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions apps/mobile/app/settings/ai/mcp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, { scopes: string[]; pending: Promise<unknown> }>(),
);
const [settings, setSettings] = React.useState(stored);
const [open, setOpen] = React.useState<string | null>(null);
React.useEffect(() => {
Expand Down Expand Up @@ -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(() => {});
}}
/>
)),
<SettingsLink
Expand Down
28 changes: 22 additions & 6 deletions apps/web/app/(finance)/settings/ai/mcp/McpConnectionsClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ export function McpConnectionsClient({ tools }: { tools: readonly McpToolSummary
const removeClient = useMutation(api.mcpOAuth.deleteMyClient);
const updateSettings = useMutation(api.mcpOAuth.updateSettings);
const updateScopes = useMutation(api.mcpOAuth.updateGrantScopes);
const scopeUpdates = React.useRef(
new Map<string, { scopes: string[]; pending: Promise<unknown> }>(),
);
const [settings, setSettings] = React.useState(stored);
const [open, setOpen] = React.useState<string | null>(null);
const [query, setQuery] = React.useState('');
Expand Down Expand Up @@ -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);
Comment on lines +220 to +223

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Rebase queued changes on the current grant scopes

The map entry is initialized once and never synchronized when the reactive grant.scopes value changes. If another device, a refresh-token scope reduction, or another settings session changes this grant while the page remains mounted, the UI renders the new scopes but the next toggle is computed from the stale cached array and can silently restore permissions that were just removed. Refresh or discard the cached entry once pending work completes and the server value changes.

Useful? React with 👍 / 👎.

}
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.');
}
Expand Down
16 changes: 14 additions & 2 deletions apps/web/app/mcp/authorize/screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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.');
Expand Down
4 changes: 1 addition & 3 deletions apps/web/app/mcp/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
53 changes: 46 additions & 7 deletions apps/web/app/oauth/token/route.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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 },
Expand All @@ -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<ReturnType<typeof prepareMcpAccessTokenSigner>>;
try {
Expand All @@ -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');
Expand All @@ -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,
});
Comment on lines +144 to +148

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Narrow private-key refresh scopes before rotating

When a private_key_jwt client supplies scope, the preceding action has already rotated and invalidated the old refresh token before this second mutation runs. If this mutation encounters a transient Convex/network failure, the route returns server_error without revealing the newly issued token, so retrying with the old token produces invalid_grant and permanently disconnects the client. Pass the requested scopes through the assertion action and apply them atomically in the same mutation that rotates the token.

Useful? React with 👍 / 👎.

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 });
}
Comment on lines +157 to 160

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Align the invalid-grant regression with the new error contract

The existing bounded-form test mocks the mutation failure as new Error('Invalid authorization code') and expects HTTP 400, but this changed catch now recognizes only messages containing the exact uppercase INVALID_GRANT; that test therefore falls through to HTTP 503 and fails. Update the regression mock to use the backend's new sentinel error, or retain compatible classification for the mocked legacy message.

Useful? React with 👍 / 👎.


try {
Expand Down
Loading
Loading