Repository navigation
feat(mcp): one-click OAuth login for the MCP server - #63
Conversation
Add the oauth_application, oauth_access_token, oauth_consent and mcp_grant tables, and resolve a bearer token to a workspace principal through verifyMcpAccessToken instead of an orb_ API key. The MCP server now returns a WWW-Authenticate challenge pointing at the protected-resource metadata, and the create-key tooling and API-key auth path are gone. The api_key table is kept in place, unused, so the non-interactive deploy migration sees only new tables.
Register the better-auth mcp plugin so Orbit issues its own OAuth: dynamic client registration, PKCE authorize, token, and consent. Serve the RFC 8414 and RFC 9728 discovery documents at the root .well-known paths, including the path-scoped oauth-protected-resource/mcp copy, all with permissive CORS so any MCP client can read them.
…ey step-up Force prompt=consent through a start endpoint advertised as the authorization endpoint, then render a consent page where the user picks which workspace the client acts in and, when they have a passkey, re-verifies it before approving. The decision route checks the origin and session, records the workspace grant, and hands the browser back to the client. The login page carries a paused MCP authorize request through sign-in so the whole flow is one click.
…cted clients Replace the API-key instructions with OAuth: a Claude Code command, Cursor and VS Code deeplinks, and a copyable server URL. List the clients you have connected, each with its workspace and last use, and let you disconnect one, which revokes the grant and drops its tokens.
The better-auth mcp plugin only reads a metadata override from the top-level options, so the oidcConfig.metadata override was ignored and clients hit the raw authorize endpoint without prompt=consent, skipping the workspace picker. Patch authorization_endpoint in the discovery route to point at the start endpoint, which injects prompt=consent, so the consent screen always shows.
Point the MCP pod at the public origin so its WWW-Authenticate challenge resolves, and rewrite the README and CLAUDE notes around OAuth instead of API keys.
There was a problem hiding this comment.
pulkitxm has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 41 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughMCP authentication changes from API keys to OAuth 2.1. The PR adds OAuth persistence and consent flows, workspace-bound token verification, protected-resource discovery, passkey re-verification, and UI support for installing and revoking MCP client connections. ChangesMCP OAuth foundation
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant MCPClient
participant MCPServer
participant OAuthDiscovery
participant OrbitWeb
participant OrbitDatabase
MCPClient->>MCPServer: Send MCP request
MCPServer-->>MCPClient: Return 401 with OAuth metadata
MCPClient->>OAuthDiscovery: Discover authorization endpoints
MCPClient->>OrbitWeb: Complete login, PKCE, workspace consent, and passkey verification
OrbitWeb->>OrbitDatabase: Record OAuth consent and MCP grant
MCPClient->>MCPServer: Send bearer access token
MCPServer->>OrbitDatabase: Verify token and workspace grant
MCPServer-->>MCPClient: Process MCP request
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
# Conflicts: # apps/web/src/features/settings/integrations-panel.test.tsx # apps/web/src/features/settings/integrations-panel.tsx # apps/web/src/lib/auth/server.test.ts
There was a problem hiding this comment.
pulkitxm has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
The CI manifest render only substitutes __ORBIT_HOST__, not __ORBIT_ORIGIN__, so build the origin as https://__ORBIT_HOST__ to keep the render placeholder-free.
There was a problem hiding this comment.
pulkitxm has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
apps/mcp/src/env.ts (1)
5-6: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider
z.httpUrl()instead ofz.url()forORBIT_PUBLIC_URL.
ORBIT_PUBLIC_URLis documented as the HTTP(S) origin serving OAuth discovery documents, butz.url()accepts any URL scheme.z.httpUrl()restricts to http/https and better matches intent.♻️ Proposed tightening
- ORBIT_PUBLIC_URL: z.url().default('http://localhost:3000'), + ORBIT_PUBLIC_URL: z.httpUrl().default('http://localhost:3000'),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/mcp/src/env.ts` around lines 5 - 6, Update the ORBIT_PUBLIC_URL schema definition to use z.httpUrl() instead of z.url(), preserving the existing localhost default so the value is restricted to HTTP(S) URLs.apps/mcp/README.md (1)
15-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a language to the new fenced code blocks.
markdownlint (MD040) flags both new fences (the
Run itshell commands and theclaude mcp addexample) for missing a language hint.📝 Proposed fix
-``` +```sh bun run infra:up bun run db:push bun run db:seed bun run dev```diff -``` +```sh claude mcp add --transport http orbit http://localhost:3200/mcp</details> Also applies to: 37-42 <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.In
@apps/mcp/README.mdaround lines 15 - 22, Update the fenced code blocks in
the README’s “Run it” section and theclaude mcp addexample to include the
shlanguage hint, preserving their existing commands unchanged.</details> <!-- cr-comment:v1:2d5af508f8b04dcf277bfe16 --> _Source: Linters/SAST tools_ </blockquote></details> </blockquote></details> <details> <summary>🤖 Prompt for all review comments with AI agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.Inline comments:
In@apps/web/src/app/(auth)/login/continue-url.ts:
- Around line 1-4: Update safeCallback to reject callback values beginning with
a slash followed by either a forward slash or backslash, preventing browser
normalization from turning them into protocol-relative external URLs. Preserve
acceptance of valid single-slash relative paths and the existing undefined
behavior for non-string or invalid values.In
@apps/web/src/app/(auth)/oauth/authorize/decision/route.ts:
- Around line 44-68: Reorder the approval flow so auth.api.oAuthConsent with
accept: true completes successfully before recordMcpGrant persists the
workspace-bound grant. Keep the existing passkey and organization validation
before consent, and only record the grant after the approved consent response is
returned; preserve redirectTo(approved.redirectURI).- Around line 34-40: Replace the raw String casts in the decision route’s form
parsing with a Zod schema from@orbit/sharedthat validates decision,
consentCode, clientId, scope, and organizationId. Parse the FormData through
that schema before any grant-processing logic, and return the existing
consentError response for invalid or missing input while preserving
valid-request behavior.- Around line 25-69: Add a bun:test suite for POST covering missing
consent_code, deny handling, stale or missing passkey verification, invalid
workspace membership, and successful approval. Mock getSession, userHasPasskey,
passkeyVerifiedWithin, listOrganizationsForUser, recordMcpGrant, and
auth.api.oAuthConsent, and assert each branch’s response plus that grants are
persisted only on the valid approval path.In
@apps/web/src/app/api/integrations/mcp/route.ts:
- Around line 13-21: Update the DELETE handler around grantId and revokeMcpGrant
to validate the query parameter through the applicable Zod schema before calling
revokeMcpGrant, replacing the manual length check. Preserve the existing
required-grantId validation behavior and pass the schema-validated value
together with principal.userId.In
@apps/web/src/features/settings/integrations-panel.tsx:
- Around line 575-586: Update the two Button usages in the integrations panel to
use Button with asChild, making each anchor the rendered interactive element
while preserving the existing hrefs, variants, sizes, and labels for
cursorInstallHref and vscodeInstallHref.In
@packages/core/src/auth/mcp-token.ts:
- Around line 33-58: The resolvePrincipal call in the token authentication flow
should normalize membership-loss authorization failures to unauthorized so MCP
clients receive the reconnect signal. Wrap resolvePrincipal(tokenRow.userId,
grant.organizationId) in targeted error handling, convert the specific
removed-membership forbidden failure to unauthorized while preserving unrelated
errors, and continue using the resolved principal for the existing grant update
and return.
Nitpick comments:
In@apps/mcp/README.md:
- Around line 15-22: Update the fenced code blocks in the README’s “Run it”
section and theclaude mcp addexample to include theshlanguage hint,
preserving their existing commands unchanged.In
@apps/mcp/src/env.ts:
- Around line 5-6: Update the ORBIT_PUBLIC_URL schema definition to use
z.httpUrl() instead of z.url(), preserving the existing localhost default so the
value is restricted to HTTP(S) URLs.</details> <details> <summary>🪄 Autofix (Beta)</summary> Fix all unresolved CodeRabbit comments on this PR: - [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended) - [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes </details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Path: .coderabbit.yaml **Review profile**: CHILL **Plan**: Pro **Run ID**: `5816ca6d-a4d7-4701-aaa0-250a578fa996` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between e52df43f9c66643e1f1c5918d10879acd5520a1d and 2d790e539084950bbffdcceb99a50912b83f1f59. </details> <details> <summary>📒 Files selected for processing (39)</summary> * `CLAUDE.md` * `apps/mcp/README.md` * `apps/mcp/package.json` * `apps/mcp/src/auth.test.ts` * `apps/mcp/src/create-key.ts` * `apps/mcp/src/env.ts` * `apps/mcp/src/server.ts` * `apps/mcp/src/test-helpers.ts` * `apps/mcp/src/tools.test.ts` * `apps/web/src/app/(app)/settings/integrations/page.tsx` * `apps/web/src/app/(auth)/login/continue-url.ts` * `apps/web/src/app/(auth)/login/login-continue.test.ts` * `apps/web/src/app/(auth)/login/page.tsx` * `apps/web/src/app/(auth)/oauth/authorize/consent-form.tsx` * `apps/web/src/app/(auth)/oauth/authorize/decision/route.ts` * `apps/web/src/app/(auth)/oauth/authorize/page.tsx` * `apps/web/src/app/.well-known/metadata-headers.test.ts` * `apps/web/src/app/.well-known/metadata-headers.ts` * `apps/web/src/app/.well-known/oauth-authorization-server/route.ts` * `apps/web/src/app/.well-known/oauth-protected-resource/mcp/route.ts` * `apps/web/src/app/.well-known/oauth-protected-resource/route.ts` * `apps/web/src/app/api/integrations/mcp/route.ts` * `apps/web/src/app/api/oauth/start/route.ts` * `apps/web/src/app/api/oauth/start/start.test.ts` * `apps/web/src/features/settings/integrations-panel.test.tsx` * `apps/web/src/features/settings/integrations-panel.tsx` * `apps/web/src/features/settings/mcp-install-links.test.ts` * `apps/web/src/features/settings/mcp-install-links.ts` * `apps/web/src/lib/auth/server.test.ts` * `apps/web/src/lib/auth/server.ts` * `k8s/04-mcp.yaml` * `packages/core/src/auth/api-key.ts` * `packages/core/src/auth/mcp-token.test.ts` * `packages/core/src/auth/mcp-token.ts` * `packages/core/src/index.ts` * `packages/db/src/import/index.ts` * `packages/db/src/schema/index.ts` * `packages/db/src/schema/oauth.ts` * `packages/db/src/seed/index.ts` </details> <details> <summary>💤 Files with no reviewable changes (3)</summary> * apps/mcp/src/create-key.ts * packages/core/src/auth/api-key.ts * apps/mcp/package.json </details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
| export function safeCallback(value: string | string[] | undefined): string | undefined { | ||
| if (typeof value !== 'string') return undefined; | ||
| return /^\/(?!\/)/.test(value) ? value : undefined; | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Open-redirect bypass via backslash in safeCallback.
The guard only blocks a second / (protocol-relative //evil.com), not a second \. A value like /\evil.com passes this regex, but browsers normalize \ to / for special schemes, so it resolves the same way //evil.com does, off-site. This is a well-documented open-redirect bypass class.
🔒 Proposed fix: reject backslashes as well
export function safeCallback(value: string | string[] | undefined): string | undefined {
if (typeof value !== 'string') return undefined;
- return /^\/(?!\/)/.test(value) ? value : undefined;
+ if (value.includes('\\')) return undefined;
+ return /^\/(?!\/)/.test(value) ? value : undefined;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function safeCallback(value: string | string[] | undefined): string | undefined { | |
| if (typeof value !== 'string') return undefined; | |
| return /^\/(?!\/)/.test(value) ? value : undefined; | |
| } | |
| export function safeCallback(value: string | string[] | undefined): string | undefined { | |
| if (typeof value !== 'string') return undefined; | |
| if (value.includes('\\')) return undefined; | |
| return /^\/(?!\/)/.test(value) ? value : undefined; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/app/`(auth)/login/continue-url.ts around lines 1 - 4, Update
safeCallback to reject callback values beginning with a slash followed by either
a forward slash or backslash, preventing browser normalization from turning them
into protocol-relative external URLs. Preserve acceptance of valid single-slash
relative paths and the existing undefined behavior for non-string or invalid
values.
| export async function POST(request: Request): Promise<Response> { | ||
| const origin = request.headers.get('origin'); | ||
| if (origin !== null && origin !== publicAppUrl()) { | ||
| return new Response('Invalid origin.', { status: 403 }); | ||
| } | ||
|
|
||
| const session = await getSession(); | ||
| if (session === null) return new Response('Sign in to continue.', { status: 401 }); | ||
|
|
||
| const form = await request.formData(); | ||
| const decision = String(form.get('decision') ?? ''); | ||
| const consentCode = String(form.get('consent_code') ?? ''); | ||
| const clientId = String(form.get('client_id') ?? ''); | ||
| const scope = String(form.get('scope') ?? ''); | ||
| const organizationId = String(form.get('organization_id') ?? ''); | ||
| if (consentCode.length === 0) return consentError('missing_consent_code'); | ||
|
|
||
| const requestHeaders = await nextHeaders(); | ||
|
|
||
| if (decision !== 'allow') { | ||
| const denied = await auth.api.oAuthConsent({ | ||
| body: { accept: false, consent_code: consentCode }, | ||
| headers: requestHeaders, | ||
| }); | ||
| return redirectTo(denied.redirectURI); | ||
| } | ||
|
|
||
| if (await userHasPasskey(session.user.id)) { | ||
| const fresh = await passkeyVerifiedWithin(session.user.id, PASSKEY_STEP_UP_WINDOW_MS); | ||
| if (!fresh) return consentError('passkey_required'); | ||
| } | ||
|
|
||
| const organizations = await listOrganizationsForUser(session.user.id); | ||
| if (!organizations.some((entry) => entry.organization.id === organizationId)) { | ||
| return consentError('invalid_workspace'); | ||
| } | ||
|
|
||
| await recordMcpGrant({ clientId, userId: session.user.id, organizationId, scopes: scope }); | ||
|
|
||
| const approved = await auth.api.oAuthConsent({ | ||
| body: { accept: true, consent_code: consentCode }, | ||
| headers: requestHeaders, | ||
| }); | ||
| return redirectTo(approved.redirectURI); | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
Missing test coverage for this security-critical route.
This handler covers deny/allow branching, passkey step-up gating, workspace-membership validation, and grant persistence -- yet no decision.test.ts is present in this cohort. Given the guideline requiring tests that would fail if the feature broke, and the sensitivity of this path (it is the sole gate that persists mcp_grant bindings), please add coverage for: deny path, missing consent_code, stale/missing passkey verification, invalid workspace, and the happy path.
Want me to draft a bun:test suite for this route (mocking getSession, userHasPasskey, passkeyVerifiedWithin, listOrganizationsForUser, recordMcpGrant, and auth.api.oAuthConsent)?
As per coding guidelines: "Every feature must include tests that would fail if the feature broke."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/app/`(auth)/oauth/authorize/decision/route.ts around lines 25 -
69, Add a bun:test suite for POST covering missing consent_code, deny handling,
stale or missing passkey verification, invalid workspace membership, and
successful approval. Mock getSession, userHasPasskey, passkeyVerifiedWithin,
listOrganizationsForUser, recordMcpGrant, and auth.api.oAuthConsent, and assert
each branch’s response plus that grants are persisted only on the valid approval
path.
Source: Coding guidelines
| const form = await request.formData(); | ||
| const decision = String(form.get('decision') ?? ''); | ||
| const consentCode = String(form.get('consent_code') ?? ''); | ||
| const clientId = String(form.get('client_id') ?? ''); | ||
| const scope = String(form.get('scope') ?? ''); | ||
| const organizationId = String(form.get('organization_id') ?? ''); | ||
| if (consentCode.length === 0) return consentError('missing_consent_code'); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
No Zod validation of form input.
decision, consentCode, clientId, scope, and organizationId are extracted from request.formData() with raw String(... ?? '') casts and no schema validation, despite this being one of the most sensitive handlers in the flow (it persists workspace grants). This is the same gap present in apps/web/src/app/api/oauth/start/route.ts; see the consolidated comment for both sites.
As per coding guidelines: "Every route handler must parse request input with a Zod schema from @orbit/shared; never trust a request body."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/app/`(auth)/oauth/authorize/decision/route.ts around lines 34 -
40, Replace the raw String casts in the decision route’s form parsing with a Zod
schema from `@orbit/shared` that validates decision, consentCode, clientId, scope,
and organizationId. Parse the FormData through that schema before any
grant-processing logic, and return the existing consentError response for
invalid or missing input while preserving valid-request behavior.
Source: Coding guidelines
| if (decision !== 'allow') { | ||
| const denied = await auth.api.oAuthConsent({ | ||
| body: { accept: false, consent_code: consentCode }, | ||
| headers: requestHeaders, | ||
| }); | ||
| return redirectTo(denied.redirectURI); | ||
| } | ||
|
|
||
| if (await userHasPasskey(session.user.id)) { | ||
| const fresh = await passkeyVerifiedWithin(session.user.id, PASSKEY_STEP_UP_WINDOW_MS); | ||
| if (!fresh) return consentError('passkey_required'); | ||
| } | ||
|
|
||
| const organizations = await listOrganizationsForUser(session.user.id); | ||
| if (!organizations.some((entry) => entry.organization.id === organizationId)) { | ||
| return consentError('invalid_workspace'); | ||
| } | ||
|
|
||
| await recordMcpGrant({ clientId, userId: session.user.id, organizationId, scopes: scope }); | ||
|
|
||
| const approved = await auth.api.oAuthConsent({ | ||
| body: { accept: true, consent_code: consentCode }, | ||
| headers: requestHeaders, | ||
| }); | ||
| return redirectTo(approved.redirectURI); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Grant recorded before consent is confirmed; reorder or guard against partial state.
recordMcpGrant (line 62) persists the workspace-bound grant before auth.api.oAuthConsent({ accept: true, ... }) (lines 64-67) confirms the consent actually succeeded. If oAuthConsent throws (expired/invalid consent_code, race with another decision, etc.), the grant is already committed even though no OAuth authorization was actually completed, leaving orphaned/inconsistent state.
Call oAuthConsent first (or wrap both in a transaction/compensating rollback) so the grant is only persisted once the underlying consent is confirmed to succeed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/app/`(auth)/oauth/authorize/decision/route.ts around lines 44 -
68, Reorder the approval flow so auth.api.oAuthConsent with accept: true
completes successfully before recordMcpGrant persists the workspace-bound grant.
Keep the existing passkey and organization validation before consent, and only
record the grant after the approved consent response is returned; preserve
redirectTo(approved.redirectURI).
| export async function DELETE(request: Request): Promise<Response> { | ||
| return await handleRoute(async () => { | ||
| const { principal } = await apiContext(); | ||
| const grantId = searchParamsOf(request)['grantId'] ?? ''; | ||
| if (grantId.length === 0) throw validationFailed('A grantId is required.'); | ||
| await revokeMcpGrant(grantId, principal.userId); | ||
| return { ok: true }; | ||
| }); | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Validate grantId with a Zod schema instead of a manual length check.
grantId is external request input read from query params but only checked for non-empty length, not parsed through a Zod schema.
🛡️ Proposed fix
+import { z } from 'zod';
+
+const grantIdSchema = z.string().min(1, 'A grantId is required.');
+
export async function DELETE(request: Request): Promise<Response> {
return await handleRoute(async () => {
const { principal } = await apiContext();
- const grantId = searchParamsOf(request)['grantId'] ?? '';
- if (grantId.length === 0) throw validationFailed('A grantId is required.');
+ const parsed = grantIdSchema.safeParse(searchParamsOf(request)['grantId']);
+ if (!parsed.success) throw validationFailed('A grantId is required.');
+ const grantId = parsed.data;
await revokeMcpGrant(grantId, principal.userId);
return { ok: true };
});
}As per coding guidelines, "Validate every external input with Zod."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export async function DELETE(request: Request): Promise<Response> { | |
| return await handleRoute(async () => { | |
| const { principal } = await apiContext(); | |
| const grantId = searchParamsOf(request)['grantId'] ?? ''; | |
| if (grantId.length === 0) throw validationFailed('A grantId is required.'); | |
| await revokeMcpGrant(grantId, principal.userId); | |
| return { ok: true }; | |
| }); | |
| } | |
| import { z } from 'zod'; | |
| const grantIdSchema = z.string().min(1, 'A grantId is required.'); | |
| export async function DELETE(request: Request): Promise<Response> { | |
| return await handleRoute(async () => { | |
| const { principal } = await apiContext(); | |
| const parsed = grantIdSchema.safeParse(searchParamsOf(request)['grantId']); | |
| if (!parsed.success) throw validationFailed('A grantId is required.'); | |
| const grantId = parsed.data; | |
| await revokeMcpGrant(grantId, principal.userId); | |
| return { ok: true }; | |
| }); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/app/api/integrations/mcp/route.ts` around lines 13 - 21, Update
the DELETE handler around grantId and revokeMcpGrant to validate the query
parameter through the applicable Zod schema before calling revokeMcpGrant,
replacing the manual length check. Preserve the existing required-grantId
validation behavior and pass the schema-validated value together with
principal.userId.
Source: Coding guidelines
| <div className="flex flex-wrap gap-2"> | ||
| <a href={cursorInstallHref(mcpUrl)}> | ||
| <Button variant="secondary" size="sm"> | ||
| Add to Cursor | ||
| </Button> | ||
| </div> | ||
| </a> | ||
| <a href={vscodeInstallHref(mcpUrl)}> | ||
| <Button variant="secondary" size="sm"> | ||
| Add to VS Code | ||
| </Button> | ||
| </a> | ||
| </div> |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Don't nest <Button> inside <a>; use asChild.
A button inside an a is invalid interactive-content nesting and can confuse keyboard/focus order and screen readers. Button already supports asChild (via Radix Slot) for exactly this composition.
♻️ Proposed fix
<div className="flex flex-wrap gap-2">
- <a href={cursorInstallHref(mcpUrl)}>
- <Button variant="secondary" size="sm">
- Add to Cursor
- </Button>
- </a>
- <a href={vscodeInstallHref(mcpUrl)}>
- <Button variant="secondary" size="sm">
- Add to VS Code
- </Button>
- </a>
+ <Button asChild variant="secondary" size="sm">
+ <a href={cursorInstallHref(mcpUrl)}>Add to Cursor</a>
+ </Button>
+ <Button asChild variant="secondary" size="sm">
+ <a href={vscodeInstallHref(mcpUrl)}>Add to VS Code</a>
+ </Button>
</div>As per path instructions, apps/web/**/*.{tsx,ts} must "Ensure the UI is keyboard-operable, provides visible focus rings, and uses real semantics from Radix primitives."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <div className="flex flex-wrap gap-2"> | |
| <a href={cursorInstallHref(mcpUrl)}> | |
| <Button variant="secondary" size="sm"> | |
| Add to Cursor | |
| </Button> | |
| </div> | |
| </a> | |
| <a href={vscodeInstallHref(mcpUrl)}> | |
| <Button variant="secondary" size="sm"> | |
| Add to VS Code | |
| </Button> | |
| </a> | |
| </div> | |
| <div className="flex flex-wrap gap-2"> | |
| <Button asChild variant="secondary" size="sm"> | |
| <a href={cursorInstallHref(mcpUrl)}>Add to Cursor</a> | |
| </Button> | |
| <Button asChild variant="secondary" size="sm"> | |
| <a href={vscodeInstallHref(mcpUrl)}>Add to VS Code</a> | |
| </Button> | |
| </div> |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/web/src/features/settings/integrations-panel.tsx` around lines 575 -
586, Update the two Button usages in the integrations panel to use Button with
asChild, making each anchor the rendered interactive element while preserving
the existing hrefs, variants, sizes, and labels for cursorInstallHref and
vscodeInstallHref.
Source: Path instructions
| const [grant] = await db | ||
| .select() | ||
| .from(schema.mcpGrant) | ||
| .where( | ||
| and( | ||
| eq(schema.mcpGrant.clientId, tokenRow.clientId), | ||
| eq(schema.mcpGrant.userId, tokenRow.userId), | ||
| isNull(schema.mcpGrant.revokedAt), | ||
| ), | ||
| ) | ||
| .limit(1); | ||
| if (grant === undefined) { | ||
| throw unauthorized('This connection has been revoked. Reconnect Orbit to continue.'); | ||
| } | ||
|
|
||
| const principal = await resolvePrincipal(tokenRow.userId, grant.organizationId); | ||
| await db.update(schema.mcpGrant).set({ lastUsedAt: now }).where(eq(schema.mcpGrant.id, grant.id)); | ||
|
|
||
| return { | ||
| principal, | ||
| userId: tokenRow.userId, | ||
| clientId: tokenRow.clientId, | ||
| organizationId: grant.organizationId, | ||
| scopes: tokenRow.scopes, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
ast-grep run --pattern 'export async function resolvePrincipal($$$) { $$$ }' --lang typescript packages/core/src/org/member-service.tsRepository: Noveum/orbit
Length of output: 150
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Files of interest:\n'
git ls-files 'packages/core/src/org/member-service.ts' 'packages/core/src/auth/mcp-token.ts' 'apps/mcp/src/server.ts'
printf '\nOutline member-service:\n'
bun x ast-grep outline packages/core/src/org/member-service.ts --view expanded || true
printf '\nRelevant symbols in member-service:\n'
bun x rg -n "resolvePrincipal|unauthorized|forbidden|not_found|DomainError" packages/core/src/org/member-service.ts packages/core/src/auth/mcp-token.ts apps/mcp/src/server.ts
printf '\nRead targeted slices:\n'
sed -n '1,220p' packages/core/src/org/member-service.ts
printf '\n--- mcp-token ---\n'
sed -n '1,220p' packages/core/src/auth/mcp-token.ts
printf '\n--- mcp server ---\n'
sed -n '1,220p' apps/mcp/src/server.tsRepository: Noveum/orbit
Length of output: 409
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- member-service (outline candidates) ---\n'
command -v ast-grep >/dev/null 2>&1 && ast-grep outline packages/core/src/org/member-service.ts --view expanded || true
printf '\n--- search relevant symbols ---\n'
rg -n "resolvePrincipal|unauthorized|forbidden|not_found|DomainError" \
packages/core/src/org/member-service.ts \
packages/core/src/auth/mcp-token.ts \
apps/mcp/src/server.ts
printf '\n--- member-service slice ---\n'
nl -ba packages/core/src/org/member-service.ts | sed -n '1,260p'
printf '\n--- mcp-token slice ---\n'
nl -ba packages/core/src/auth/mcp-token.ts | sed -n '1,220p'
printf '\n--- mcp server slice ---\n'
nl -ba apps/mcp/src/server.ts | sed -n '1,260p'Repository: Noveum/orbit
Length of output: 241
🏁 Script executed:
#!/bin/bash
set -euo pipefail
for f in packages/core/src/org/member-service.ts packages/core/src/auth/mcp-token.ts apps/mcp/src/server.ts; do
echo "### $f"
wc -l "$f"
echo
done
echo "### symbol search"
rg -n "resolvePrincipal|unauthorized|forbidden|not_found|DomainError|WWW-Authenticate|toDomainError|status === 401" \
packages/core/src/org/member-service.ts \
packages/core/src/auth/mcp-token.ts \
apps/mcp/src/server.ts
echo
echo "### member-service relevant slice"
nl -ba packages/core/src/org/member-service.ts | sed -n '1,260p'
echo
echo "### mcp-token relevant slice"
nl -ba packages/core/src/auth/mcp-token.ts | sed -n '1,220p'
echo
echo "### mcp server relevant slice"
nl -ba apps/mcp/src/server.ts | sed -n '1,260p'Repository: Noveum/orbit
Length of output: 2085
Normalize membership-loss failures to 401 here
resolvePrincipal(tokenRow.userId, grant.organizationId) currently throws forbidden('You are not a member of this workspace.') for a removed membership, but apps/mcp/src/server.ts only sends WWW-Authenticate on 401. Wrap this call and convert membership-loss auth failures to unauthorized(...) so MCP clients get the reconnect signal.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/src/auth/mcp-token.ts` around lines 33 - 58, The
resolvePrincipal call in the token authentication flow should normalize
membership-loss authorization failures to unauthorized so MCP clients receive
the reconnect signal. Wrap resolvePrincipal(tokenRow.userId,
grant.organizationId) in targeted error handling, convert the specific
removed-membership forbidden failure to unauthorized while preserving unrelated
errors, and continue using the resolved principal for the existing grant update
and return.
Replace API-key auth for the MCP server with a one-click OAuth 2.1 flow (discovery, dynamic client registration, PKCE, and a consent screen where the user picks a workspace and re-verifies a passkey), so Claude Desktop, Claude Code, and Cursor connect in one click.