Files
Mattsson 4f33184a9a 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>
2026-09-02 00:04:31 +02:00

167 lines
5.5 KiB
TypeScript

import { NextResponse } from 'next/server'
import {
generateApiKey,
DEFAULT_SCOPES,
OAUTH_MCP_KEY_NAME,
validateScopes,
findStageApproveConflict,
} from '@/lib/auth/api-keys'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { ApiKeyMode, ApiKeyScope } from '@/lib/auth/api-keys'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/** GET /api/settings/api-keys: list the company's API keys (key value never returned). */
export const GET = withRouteContext(
'api_key.list',
async (_request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
// Both live and test keys for the active company. (Test keys are bound to the
// active company too: they're simulation-only, so they never write real data.)
const { data, error } = await supabase
.from('api_keys')
.select('id, key_prefix, name, scopes, mode, rate_limit_rpm, unattended_commit_limit, last_used_at, revoked_at, created_at')
.eq('company_id', companyId)
.order('created_at', { ascending: false })
if (error) {
log.error('api_keys list failed', error)
return errorResponse(error, log, { requestId })
}
return NextResponse.json({ data })
},
)
/**
* POST /api/settings/api-keys: create a new API key.
*
* Returns the full key exactly once; after this the prefix is the only
* stored representation.
*/
export const POST = withRouteContext(
'api_key.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
let name = 'Unnamed key'
let scopes: ApiKeyScope[] = DEFAULT_SCOPES
let acknowledgeSod = false
let mode: ApiKeyMode = 'live'
try {
const body = await request.json()
if (body.name && typeof body.name === 'string') {
name = body.name.slice(0, 100)
}
acknowledgeSod = body.acknowledge_sod === true
if (body.mode === 'test') mode = 'test'
const parsed = validateScopes(body.scopes)
if (parsed) {
scopes = parsed
} else if (body.scopes !== undefined) {
return errorResponseFromCode('API_KEY_SCOPE_INVALID', log, {
requestId,
details: { received: body.scopes },
})
}
} catch {
// 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.
// Segregation of duties: warn + require explicit acknowledgement (not block)
// when a single key both stages bookkeeping AND can approve it. Surfacing a
// 409 lets the UI raise an explicit confirm dialog and the agent inform the
// user before re-POSTing with acknowledge_sod: true.
const conflictingScope = findStageApproveConflict(scopes)
if (conflictingScope && !acknowledgeSod) {
return errorResponseFromCode('API_KEY_SOD_CONFLICT', log, {
requestId,
details: {
conflicting_scope: conflictingScope,
approve_scope: 'pending_operations:approve',
},
})
}
const sodAcknowledgedAt = conflictingScope ? new Date().toISOString() : null
const { count } = await supabase
.from('api_keys')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.is('revoked_at', null)
if (count !== null && count >= 10) {
return errorResponseFromCode('API_KEY_QUOTA_EXCEEDED', log, {
requestId,
details: { activeCount: count, limit: 10 },
})
}
const { key, hash, prefix } = generateApiKey(mode)
const { data, error } = await supabase
.from('api_keys')
.insert({
user_id: user.id,
company_id: companyId,
key_hash: hash,
key_prefix: prefix,
name,
scopes,
mode,
...(sodAcknowledgedAt
? { sod_acknowledged_at: sodAcknowledgedAt, sod_acknowledged_by: user.id }
: {}),
})
.select('id, key_prefix, name, scopes, mode, created_at')
.single()
if (error) {
log.error('api_key insert failed', error)
return errorResponseFromCode('API_KEY_CREATE_FAILED', log, {
requestId,
details: { reason: getUserErrorMessage(error) },
})
}
if (sodAcknowledgedAt) {
// High-risk security event: the creator self-attested the stage+approve
// combination. The durable record is the sod_acknowledged_* pair on the
// key row; this structured entry additionally lands the acceptance in
// the logging pipeline (ASVS V16.1.1 / SOC 2 CC6.1).
log.warn('api_key.sod_acknowledged', {
keyId: data.id,
keyPrefix: data.key_prefix,
conflictingScope,
scopes,
acknowledgedBy: user.id,
companyId,
})
}
return NextResponse.json({
data: {
...data,
key, // only time the full key is returned
},
})
},
{ requireWrite: true },
)