fix(mcp): explain the Claude-side steps after "Anslut till Claude" and tick the checklist on a real connection (#2133) (#2147)
* fix(mcp): explain the Claude-side steps after "Anslut till Claude" and tick the checklist on a real connection (#2133) Lazy auth is by design: Claude lists the tools before any sign-in and the first company-scoped call answers 401, which opens the Accounted sign-in. Nothing told the user, so a "connected" status with an unanswered first question read as a broken connection (Axel, Discord). - Settings -> API & MCP: one sentence of expectation under the button, and the step-by-step guide link moved from under two disclosures to directly under the button. - Docs (connect-claude / anslut-claude): new "What happens after you click" section for Path A covering the connector dialog, the tools appearing before sign-in, the first-call login + consent screen, "ask again", and the "Required when the server asks" auth setting that only the manual path mentioned. - Hem checklist step "Anslut till Claude": deep link now carries client=claude-connector like the settings button (claudeConnectorLink), the footnote carries the same expectation line plus the guide link, and the done-signal is an unrevoked api_keys row minted by the MCP OAuth token route (OAUTH_MCP_KEY_NAME) instead of the in-app AI-profile flag, which never meant "connected to Claude". - Tests: claudeStepDone with/without a key row, deep-link snapshot. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W7iJQwKiRTDWSMnRm4WM4L * fix(mcp): correct consent-page claims, stop the completion PATCH loop, count OAuth keys past RLS (#2133) Three skeptic refutations on PR #2147, fixed in one pass: - Docs (EN + SV): the consent page shows the company active in the app and pre-selects every scope for Claude's connector (founder decision 2026-08-26); it has no company picker and nothing to tick. Steps 3-4 of the new section, the "Read-only by default" paragraph above it, the sandbox note and the 10-minute test now describe Endast läs under Behörigheter instead. - Checklist completion: users with initial_setup_path NULL (skipped the books question, then imported) hit the route's "Välj först hur du vill komma igång" 400 and, with saving as an effect dependency, retried it forever with a toast. completionPatchBody() records path=migration when none was chosen, and a rejected PATCH is not retried within the session. - hasMcpKey: api_keys' SELECT policy is company-scoped, so the user client could not see companyless (NULL company_id) or archived-company keys and the step stayed open for the user who had just connected. The head count now runs through the service client with an explicit user_id filter. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W7iJQwKiRTDWSMnRm4WM4L * fix(mcp): surface a failed OAuth-key count and reserve the marker name (#2133) CodeRabbit round on PR #2147: - app/(dashboard)/page.tsx: a failed api_keys count answered count null, which claudeStepDone read as "never connected". Throw to the error boundary like the settings fetch does instead of guessing. - app/api/settings/api-keys: reject a hand-minted key named MCP-klient (OAuth) (400 VALIDATION_ERROR): that name is the marker the Hem checklist reads as "connected to Claude", so a manual key with it would tick the step without any connection. Test added. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W7iJQwKiRTDWSMnRm4WM4L --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
8b09b06e14
commit
4f33184a9a
@@ -62,7 +62,7 @@ export async function HemChecklistSection({
|
||||
userId,
|
||||
now,
|
||||
initialSetup,
|
||||
agentBuilt,
|
||||
hasMcpKey,
|
||||
vatRegistered,
|
||||
momsPeriod,
|
||||
}: {
|
||||
@@ -70,7 +70,8 @@ export async function HemChecklistSection({
|
||||
userId: string
|
||||
now: Date
|
||||
initialSetup: InitialSetupState
|
||||
agentBuilt: boolean
|
||||
/** Live OAuth-minted MCP key exists for this user: see claudeStepDone(). */
|
||||
hasMcpKey: boolean
|
||||
vatRegistered: boolean
|
||||
momsPeriod: MomsPeriod | null
|
||||
}) {
|
||||
@@ -160,7 +161,7 @@ export async function HemChecklistSection({
|
||||
hasBankConnected={onboardingProgress.hasBankConnected}
|
||||
hasSkatteverketConnected={onboardingProgress.hasSkatteverketConnected}
|
||||
hasInboxItems={onboardingProgress.hasInboxItems}
|
||||
hasAgentBuilt={agentBuilt}
|
||||
hasMcpKey={hasMcpKey}
|
||||
vatLine={vatLine}
|
||||
sieSweep={
|
||||
sieSweep
|
||||
|
||||
@@ -5,6 +5,9 @@ import DashboardContent from '@/components/dashboard/DashboardContent'
|
||||
import { ChecklistSkeleton, PanesSkeleton } from '@/components/dashboard/HemSkeletons'
|
||||
import { COMPANY_PICKED_COOKIE } from '@/lib/company/context'
|
||||
import { isCockpitLandingRole } from '@/lib/company/home-domain'
|
||||
import { OAUTH_MCP_KEY_NAME } from '@/lib/auth/api-keys'
|
||||
import { claudeStepDone } from '@/lib/onboarding/checklist'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import {
|
||||
getDashboardAuthContext,
|
||||
getDashboardCompanyId,
|
||||
@@ -71,7 +74,22 @@ export default async function DashboardPage() {
|
||||
|
||||
const now = new Date()
|
||||
|
||||
const [settingsRes, { data: profile }, agentProfile, { count: skatteverketTokenCount }] =
|
||||
// Service role for the OAuth-key count below: api_keys' SELECT policy is
|
||||
// company_id IN user_company_ids() (20260330130000), so through the user
|
||||
// client a key minted companyless (company_id NULL, the connect-before-
|
||||
// signup flow) or bound to a company the user has since archived or left is
|
||||
// invisible, and the step would stay open for exactly the user who just
|
||||
// connected. The query filters on user_id explicitly, so no other user's
|
||||
// rows are reachable.
|
||||
const serviceClient = await createServiceClient()
|
||||
|
||||
const [
|
||||
settingsRes,
|
||||
{ data: profile },
|
||||
agentProfile,
|
||||
{ count: skatteverketTokenCount },
|
||||
{ count: oauthKeyCount, error: oauthKeyError },
|
||||
] =
|
||||
await Promise.all([
|
||||
getDashboardSettings(),
|
||||
// First name for the greeting.
|
||||
@@ -80,6 +98,18 @@ export default async function DashboardPage() {
|
||||
// The Skatteverket promo below the panes needs this flag in the shell;
|
||||
// the checklist section reads it again for its own step (cheap head count).
|
||||
supabase.from('skatteverket_tokens').select('*', { count: 'exact', head: true }).eq('user_id', user.id).eq('company_id', companyId),
|
||||
// The checklist's "Anslut till Claude" step is done when the MCP OAuth
|
||||
// token route has minted a key for this user (claudeStepDone). Keyed on
|
||||
// the user, not the company: the Claude connection follows the person,
|
||||
// and the key's company_id is whatever was active at sign-in (or null
|
||||
// for a companyless signup), so a company filter would miss real
|
||||
// connections. Revoked rows do not count.
|
||||
serviceClient
|
||||
.from('api_keys')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
.eq('name', OAUTH_MCP_KEY_NAME)
|
||||
.is('revoked_at', null),
|
||||
])
|
||||
|
||||
// A FAILED settings read must not masquerade as "onboarding not done":
|
||||
@@ -90,6 +120,12 @@ export default async function DashboardPage() {
|
||||
if (settingsError) {
|
||||
throw new Error(`company_settings fetch failed: ${settingsError.message}`)
|
||||
}
|
||||
// Same rule for the OAuth-key count: a failed query answers count null,
|
||||
// which claudeStepDone would read as "never connected" and re-open the
|
||||
// Claude step for a connected user. Surface it instead of guessing.
|
||||
if (oauthKeyError) {
|
||||
throw new Error(`api_keys count failed: ${oauthKeyError.message}`)
|
||||
}
|
||||
|
||||
// If onboarding is not complete, redirect to onboarding. Exception: a byrå
|
||||
// member who did NOT explicitly pick this company this session goes to the
|
||||
@@ -110,6 +146,7 @@ export default async function DashboardPage() {
|
||||
}
|
||||
|
||||
const agentBuilt = Boolean(agentProfile?.verified_at)
|
||||
const hasMcpKey = claudeStepDone({ oauthKeyCount })
|
||||
const userFirstName = profile?.full_name?.trim().split(/\s+/)[0] ?? null
|
||||
const initialSetup = {
|
||||
path: settings.initial_setup_path ?? null,
|
||||
@@ -137,7 +174,7 @@ export default async function DashboardPage() {
|
||||
userId={user.id}
|
||||
now={now}
|
||||
initialSetup={initialSetup}
|
||||
agentBuilt={agentBuilt}
|
||||
hasMcpKey={hasMcpKey}
|
||||
vatRegistered={settings.vat_registered}
|
||||
momsPeriod={settings.moms_period ?? null}
|
||||
/>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { decryptAuthCode, verifyPkce, hashAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import {
|
||||
generateApiKey,
|
||||
OAUTH_MCP_KEY_NAME,
|
||||
generateRefreshToken,
|
||||
hashRefreshToken,
|
||||
createServiceClientNoCookies,
|
||||
@@ -161,7 +162,7 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
company_id: companyId,
|
||||
key_hash: hash,
|
||||
key_prefix: prefix,
|
||||
name: 'MCP-klient (OAuth)',
|
||||
name: OAUTH_MCP_KEY_NAME,
|
||||
scopes: grantedScopes,
|
||||
refresh_token_hash: refresh.hash,
|
||||
})
|
||||
|
||||
@@ -108,6 +108,24 @@ describe('POST /api/settings/api-keys', () => {
|
||||
expect(body.error.code).toBe('API_KEY_SCOPE_INVALID')
|
||||
})
|
||||
|
||||
it('returns 400 for the reserved OAuth marker name (would fake a Claude connection)', async () => {
|
||||
const { insertSpy } = setupFrom({ count: 0 })
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: ' MCP-klient (OAuth) ', scopes: ['reports:read'] },
|
||||
}),
|
||||
{ params: Promise.resolve({}) },
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string; details: { field: string; reason: string } }
|
||||
}>(res)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
expect(body.error.details).toMatchObject({ field: 'name', reason: 'reserved' })
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 409 API_KEY_SOD_CONFLICT for stage+approve without acknowledgement', async () => {
|
||||
setupFrom({ count: 0 })
|
||||
const res = await POST(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import {
|
||||
generateApiKey,
|
||||
DEFAULT_SCOPES,
|
||||
OAUTH_MCP_KEY_NAME,
|
||||
validateScopes,
|
||||
findStageApproveConflict,
|
||||
} from '@/lib/auth/api-keys'
|
||||
@@ -68,6 +69,17 @@ export const POST = withRouteContext(
|
||||
// Empty body: use defaults.
|
||||
}
|
||||
|
||||
// The OAuth token route's key name is the marker the Hem checklist reads
|
||||
// as "connected to Claude" (there is no source column). A hand-minted key
|
||||
// with that name would tick the step without any connection, so the name
|
||||
// is reserved for the OAuth path.
|
||||
if (name.trim() === OAUTH_MCP_KEY_NAME) {
|
||||
return errorResponseFromCode('VALIDATION_ERROR', log, {
|
||||
requestId,
|
||||
details: { field: 'name', reason: 'reserved', reserved: OAUTH_MCP_KEY_NAME },
|
||||
})
|
||||
}
|
||||
|
||||
// Both live and test keys bind to the active company. A test key is
|
||||
// simulation-only (the v1 wrapper forces dry-run on every write) so it can
|
||||
// safely point at the real company without ever persisting anything.
|
||||
|
||||
Reference in New Issue
Block a user