feat(mcp-oauth): let an account with no company connect and sign up from the OAuth popup (#1814 PR 1) (#1855)

* feat(mcp-oauth): let an account with no company connect and sign up from the OAuth popup

Identity unlock for agent-first onboarding (#1814, shape B+). A person
with no Accounted account can now connect from an MCP client, create the
account inside the Connect popup and finish the OAuth dance.

- authorize/token no longer require a company: consent renders a
  companyless variant and the key is minted with company_id NULL.
- validateApiKey returns companyId string|null and binds an unbound key
  to the user's first company on the first validation after it exists.
- MCP server: company-dependent tools and data resources answer with a
  structured NO_COMPANY_YET error; the company-independent tools still
  run; telemetry skips when there is no company scope.
- /api/events fails closed instead of throwing for an unbound key.
- authorize forces TOTP enrollment (not just verification) for password
  accounts with no factor, since the middleware skips enrollment for
  zero-company users; BankID-linked accounts stay exempt.
- /login forwards next to /register; register, GoogleAuthButton and
  /auth/callback carry it back to the consent page (callback honours
  only /api/mcp-oauth/authorize, via safeReturnTo); /mfa/enroll
  hard-navigates to /api/* destinations like /mfa/verify.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* refactor(company): move getActiveCompanyId out of the next/headers module

lib/auth/api-keys.ts needs the resolver for unbound-key binding, but
lib/company/context.ts imports next/headers for the legacy company cookie
and Turbopack refuses that import on some of api-keys' import paths (the
preview build failed). The resolver and CompanyContextError now live in
lib/company/active-company.ts; context.ts re-exports them so every caller
and test mock is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(mcp-oauth): fail closed on a failed assurance lookup; enroll Back aborts instead of looping

Review findings on #1855: requireAal2 let consent through at AAL1 when
getAuthenticatorAssuranceLevel() returned nothing and a verified factor
existed. Only a positive AAL2 answer passes now; a failed lookup and the
inconsistent verified-factor-at-AAL1 case both step up to /mfa/verify.
Back on /mfa/enroll with the consent page as returnTo went straight back
into the redirect loop; it now aborts to the app.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-25 11:25:42 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 2a33291c18
commit a717f03898
21 changed files with 858 additions and 247 deletions
+7 -4
View File
@@ -9,7 +9,7 @@ import {
} from '@/lib/auth/api-keys'
import { validateQuery } from '@/lib/api/validate'
import { EventsQuerySchema } from '@/lib/api/schemas'
import { requireCompanyId } from '@/lib/company/context'
import { getActiveCompanyId } from '@/lib/company/context'
import type { SupabaseClient } from '@supabase/supabase-js'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
@@ -126,10 +126,13 @@ export async function GET(request: Request) {
}
// Session auth resolves the active company; API-key auth uses the key's bound company.
const companyId = keyCompanyId ?? await requireCompanyId(supabase, userId)
// A key minted before the user's first company exists (companyless OAuth,
// issue #1814) has no bound company either; both cases resolve to null and
// fail closed below rather than throwing.
const companyId = keyCompanyId ?? await getActiveCompanyId(supabase, userId)
// Defense in depth: never run the event_log query with an empty/undefined
// scope. requireCompanyId throws when there is no company, but guard the
// key-bound path too so a malformed binding can't widen the query scope.
// scope. A user with no company resolves to null, and the guard also covers
// a malformed key binding so it can't widen the query scope.
if (!companyId) {
return errorResponseFromCode('FORBIDDEN', log)
}
@@ -4,7 +4,7 @@ import crypto from 'crypto'
const mocks = vi.hoisted(() => ({
createClient: vi.fn(),
isAllowedRedirectUri: vi.fn(),
requireCompanyId: vi.fn(),
getActiveCompanyId: vi.fn(),
getBranding: vi.fn(),
}))
@@ -21,7 +21,7 @@ vi.mock('@/lib/auth/oauth-allowlist', () => ({
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: (...args: unknown[]) => mocks.requireCompanyId(...args),
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
}))
vi.mock('@/lib/branding/service', () => ({
@@ -37,15 +37,25 @@ function buildAuthorizeUrl(params: Record<string, string>): string {
}
function buildSupabase(
user: { id: string } | null,
user: { id: string; email?: string } | null,
companyName = 'Test AB',
aal: { currentLevel: string; nextLevel: string } = { currentLevel: 'aal2', nextLevel: 'aal2' },
verifiedFactors: number = aal.nextLevel === 'aal2' ? 1 : 0,
) {
return {
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user }, error: null }),
mfa: {
getAuthenticatorAssuranceLevel: vi.fn().mockResolvedValue({ data: aal, error: null }),
listFactors: vi.fn().mockResolvedValue({
data: {
totp: Array.from({ length: verifiedFactors }, (_, i) => ({
id: `factor-${i}`,
status: 'verified',
})),
},
error: null,
}),
},
},
from: vi.fn().mockReturnValue({
@@ -67,7 +77,7 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
mocks.isAllowedRedirectUri.mockResolvedValue(true)
mocks.requireCompanyId.mockResolvedValue('company-1')
mocks.getActiveCompanyId.mockResolvedValue('company-1')
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
})
@@ -258,7 +268,7 @@ describe('MFA step-up on /api/mcp-oauth/authorize', () => {
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
mocks.isAllowedRedirectUri.mockResolvedValue(true)
mocks.requireCompanyId.mockResolvedValue('company-1')
mocks.getActiveCompanyId.mockResolvedValue('company-1')
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
})
@@ -310,6 +320,63 @@ describe('MFA step-up on /api/mcp-oauth/authorize', () => {
expect(response.status).toBe(200)
})
it('GET fails closed to /mfa/verify when the assurance lookup returns nothing', async () => {
// A transient auth error must never read as "no MFA needed": consent
// here mints a key that bypasses MFA on every later call.
const supabase = buildSupabase({ id: 'user-1' }, 'Test AB', { currentLevel: 'aal1', nextLevel: 'aal1' }, 1)
;(supabase.auth.mfa.getAuthenticatorAssuranceLevel as ReturnType<typeof vi.fn>).mockResolvedValue({
data: null,
error: { message: 'boom' },
})
mocks.createClient.mockResolvedValue(supabase)
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
expect(new URL(response.headers.get('location')!).pathname).toBe('/mfa/verify')
})
it('GET steps up (not enroll) when a verified factor exists despite an AAL1 answer', async () => {
mocks.createClient.mockResolvedValue(
buildSupabase({ id: 'user-1' }, 'Test AB', { currentLevel: 'aal1', nextLevel: 'aal1' }, 1),
)
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
expect(new URL(response.headers.get('location')!).pathname).toBe('/mfa/verify')
})
it('GET sends a password account with no factor to /mfa/enroll with returnTo', async () => {
// A brand-new account created inside the OAuth popup (issue #1814) has no
// company, so the middleware never forced enrollment. Without this leg the
// consent would mint an MFA-exempt key for an account with no second factor.
mocks.createClient.mockResolvedValue(
buildSupabase({ id: 'user-1' }, 'Test AB', { currentLevel: 'aal1', nextLevel: 'aal1' }, 0),
)
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
expect(response.status).toBeGreaterThanOrEqual(300)
expect(response.status).toBeLessThan(400)
const location = new URL(response.headers.get('location')!)
expect(location.pathname).toBe('/mfa/enroll')
const returnTo = new URL(location.searchParams.get('returnTo')!, location.origin)
expect(returnTo.pathname).toBe('/api/mcp-oauth/authorize')
expect(returnTo.searchParams.get('state')).toBe('xyz')
})
it('POST refuses consent from a password account with no factor', async () => {
mocks.createClient.mockResolvedValue(
buildSupabase({ id: 'user-1' }, 'Test AB', { currentLevel: 'aal1', nextLevel: 'aal1' }, 0),
)
const formData = new FormData()
formData.set('consent', 'allow')
const response = await POST(
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
)
expect(new URL(response.headers.get('location')!).pathname).toBe('/mfa/enroll')
expect(response.headers.get('location')).not.toContain('code=')
})
it('GET skips step-up for BankID-linked users (inherently 2FA)', async () => {
const supabase = buildSupabase(
{ id: 'user-1' },
@@ -327,6 +394,66 @@ describe('MFA step-up on /api/mcp-oauth/authorize', () => {
})
})
describe('account with no company yet (issue #1814)', () => {
// Someone who signed up inside the MCP client's OAuth popup has an account
// but no company. Consent must still complete: the key is minted unbound
// and binds itself once the company exists.
const authorizeParams = {
response_type: 'code',
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
code_challenge: 'abc',
code_challenge_method: 'S256',
scope: 'mcp',
state: 'xyz',
}
function signScope(scopeParam: string): string {
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
}
beforeEach(() => {
vi.clearAllMocks()
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
mocks.isAllowedRedirectUri.mockResolvedValue(true)
mocks.getActiveCompanyId.mockResolvedValue(null)
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
})
it('GET renders consent labelled with the account instead of a company', async () => {
const supabase = buildSupabase({ id: 'user-1', email: 'ny@example.se' })
mocks.createClient.mockResolvedValue(supabase)
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
expect(response.status).toBe(200)
const html = await response.text()
expect(html).toContain('ny@example.se')
expect(html).toContain('inget företag')
expect(html).not.toContain('Test AB')
// No company to look up: company_settings is never queried.
expect(supabase.from).not.toHaveBeenCalled()
})
it('POST still issues an authorization code', async () => {
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1', email: 'ny@example.se' }))
const formData = new FormData()
formData.set('consent', 'allow')
formData.set('scope_binding', 'mcp')
formData.set('scope_binding_sig', signScope('mcp'))
const response = await POST(
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
)
expect(response.status).toBe(303)
const location = new URL(response.headers.get('location')!)
expect(location.searchParams.get('code')).toBe('test-auth-code')
expect(location.searchParams.get('state')).toBe('xyz')
})
})
describe('RFC 9207 iss parameter on authorization responses', () => {
const authorizeParams = {
response_type: 'code',
@@ -350,7 +477,7 @@ describe('RFC 9207 iss parameter on authorization responses', () => {
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.test.example')
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
mocks.isAllowedRedirectUri.mockResolvedValue(true)
mocks.requireCompanyId.mockResolvedValue('company-1')
mocks.getActiveCompanyId.mockResolvedValue('company-1')
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
})
+65 -23
View File
@@ -4,7 +4,7 @@ import { NextResponse } from 'next/server'
import type { SupabaseClient, User } from '@supabase/supabase-js'
import { createAuthCode } from '@/lib/auth/oauth-codes'
import { shouldEnforceMfa } from '@/lib/auth/mfa'
import { requireCompanyId } from '@/lib/company/context'
import { getActiveCompanyId } from '@/lib/company/context'
import { getBranding } from '@/lib/branding/service'
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
import { resolveDiscoveryBaseUrl } from '@/lib/api/v1/base-url'
@@ -114,7 +114,14 @@ function buildLoginRedirect(request: Request): Response {
* The middleware MFA gate deliberately exempts /api/mcp-oauth/* (the token
* endpoint is Bearer-only), which makes this route responsible for its own
* step-up. Returns null when the session is AAL2 (or MFA isn't required),
* otherwise a redirect to /mfa/verify that returns to this authorize URL.
* otherwise a redirect to /mfa/verify (factor enrolled, session still AAL1)
* or /mfa/enroll (no factor at all) that returns to this authorize URL.
*
* The enrollment leg matters for accounts created inside the OAuth popup
* (issue #1814): the middleware only forces enrollment once a company exists,
* so a brand-new password account would otherwise consent at AAL1 and mint an
* MFA-exempt key for an account with no second factor. BankID-linked accounts
* are exempt via shouldEnforceMfa, same as everywhere else.
*/
async function requireAal2(
supabase: SupabaseClient,
@@ -122,15 +129,28 @@ async function requireAal2(
request: Request,
): Promise<Response | null> {
if (!shouldEnforceMfa(user)) return null
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (aal?.nextLevel === 'aal2' && aal?.currentLevel !== 'aal2') {
const url = new URL(request.url)
const returnTo = `${url.pathname}${url.search}`
return NextResponse.redirect(
new URL(`/mfa/verify?returnTo=${encodeURIComponent(returnTo)}`, url.origin),
)
}
return null
const url = new URL(request.url)
const returnTo = `${url.pathname}${url.search}`
const stepUp = (page: '/mfa/verify' | '/mfa/enroll') =>
NextResponse.redirect(new URL(`${page}?returnTo=${encodeURIComponent(returnTo)}`, url.origin))
// Only a positive "this session is AAL2" answer lets consent through. A
// failed or empty assurance lookup is treated as AAL1 (verify page), never
// as "no MFA needed": the alternative would mint an MFA-exempt key on a
// transient auth error.
const { data: aal, error: aalError } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (aalError || !aal) return stepUp('/mfa/verify')
if (aal.currentLevel === 'aal2') return null
if (aal.nextLevel === 'aal2') return stepUp('/mfa/verify')
// nextLevel below aal2 should mean no verified factor exists. If one does
// exist anyway (inconsistent answer), step up rather than enroll a second
// factor. Otherwise enroll: mirrors the middleware gate (lib/supabase/
// middleware.ts), which skips zero-company users and so never ran for an
// account created inside the popup.
const { data: factors } = await supabase.auth.mfa.listFactors()
const hasVerifiedFactor = factors?.totp?.some((f) => f.status === 'verified') ?? false
return stepUp(hasVerifiedFactor ? '/mfa/verify' : '/mfa/enroll')
}
function errorRedirect(request: Request, redirectUri: string, state: string | null, error: string, desc: string): Response {
@@ -209,19 +229,33 @@ export async function GET(request: Request) {
)
}
const companyId = await requireCompanyId(supabase, user.id)
// null for an account with no company yet (signed up from the OAuth popup,
// issue #1814): consent still goes through, the key is minted unbound and
// binds itself once the company exists. The page says so instead of
// showing a company name.
const companyId = await getActiveCompanyId(supabase, user.id)
// Get company name for the consent page
const { data: settings } = await supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single()
const companyName = settings?.company_name || user.email
let companyName: string | null = null
if (companyId) {
const { data: settings } = await supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single()
companyName = settings?.company_name || user.email || null
}
const appNameLower = escapeHtml(getBranding().appName.toLowerCase())
const accountRowHtml = companyName
? `<span class="account-label">Företag</span>
<span class="account-name">${escapeHtml(companyName)}</span>`
: `<span class="account-label">Konto</span>
<span class="account-name">${escapeHtml(user.email ?? '')}</span>`
const noCompanyNoteHtml = companyId
? ''
: `<p class="note">Du har inget företag i ${appNameLower} ännu. Du kan ansluta ändå: skapa företaget i appen så använder anslutningen det automatiskt, utan att du behöver ansluta på nytt.</p>`
// CSP nonce for the inline consent UI controls. A nonce-bound script-src
// makes the inline block executable while keeping the rest of the page
// immune to script injection: without this the consent page is
@@ -374,6 +408,12 @@ export async function GET(request: Request) {
text-align: right;
word-break: break-word;
}
.note {
font-size: 0.8125rem;
color: var(--fg-muted);
line-height: 1.55;
margin: -1rem 0 1.75rem;
}
.scopes-header {
display: flex;
justify-content: space-between;
@@ -557,9 +597,9 @@ export async function GET(request: Request) {
<p class="lede">En extern applikation begär åtkomst till ditt ${appNameLower}-konto. Välj vilka behörigheter du vill bevilja.</p>
<div class="account">
<span class="account-label">Företag</span>
<span class="account-name">${escapeHtml(companyName)}</span>
${accountRowHtml}
</div>
${noCompanyNoteHtml}
<form method="POST" action="${escapeHtml(url.pathname + url.search)}" id="consent-form">
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
@@ -681,7 +721,9 @@ export async function POST(request: Request) {
)
}
await requireCompanyId(supabase, user.id)
// No company check here: the auth code carries only the user id, and the
// token endpoint resolves (or leaves unbound) the company when it mints the
// key. An account without a company may consent (issue #1814).
// Parse form body
const formData = await request.formData()
@@ -3,6 +3,7 @@ import { createQueuedMockSupabase } from '@/tests/helpers'
const mocks = vi.hoisted(() => ({
supabaseFactory: vi.fn(),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
@@ -20,7 +21,7 @@ vi.mock('@/lib/auth/oauth-codes', () => ({
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
}))
import { POST } from '../route'
@@ -93,6 +94,45 @@ describe('POST /api/mcp-oauth/token', () => {
expect(body.expires_in).toBe(3600)
})
it('mints an unbound key (company_id null) when the user has no company yet', async () => {
// Signup inside the OAuth popup (issue #1814): the account exists, the
// company does not. The key is stored unbound and validateApiKey binds
// it on the first call after the company is created.
vi.mocked(decryptAuthCode).mockReturnValue({
userId: 'user-1',
codeChallenge: 'challenge',
redirectUri: 'https://claude.ai/api/cb',
exp: Date.now() + 60_000,
})
vi.mocked(verifyPkce).mockReturnValue(true)
mocks.getActiveCompanyId.mockResolvedValueOnce(null)
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{ data: null, error: null }, // insert into oauth_used_codes
{ data: null, error: null }, // delete expired codes (best-effort)
{ data: null, error: null }, // insert into api_keys
])
const res = await POST(
formRequest({
grant_type: 'authorization_code',
code: 'ciphertext',
code_verifier: 'verifier',
redirect_uri: 'https://claude.ai/api/cb',
})
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.access_token).toMatch(/^gnubok_sk_/)
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
expect(inserted).toBeDefined()
expect(inserted.user_id).toBe('user-1')
expect(inserted.company_id).toBeNull()
})
it('rejects an already-used auth code (replay)', async () => {
vi.mocked(decryptAuthCode).mockReturnValue({
userId: 'user-1',
+5 -2
View File
@@ -9,7 +9,7 @@ import {
DEFAULT_OAUTH_SCOPES,
type ApiKeyScope,
} from '@/lib/auth/api-keys'
import { requireCompanyId } from '@/lib/company/context'
import { getActiveCompanyId } from '@/lib/company/context'
const ACCESS_TOKEN_TTL_SECONDS = 3600
@@ -125,7 +125,10 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
.then(() => {})
const companyId = await requireCompanyId(supabase, payload.userId)
// null for an account that has no company yet (signed up from the OAuth
// popup, issue #1814). The key is minted unbound; validateApiKey binds it
// to the user's first company on the first call after one exists.
const companyId = await getActiveCompanyId(supabase, payload.userId)
const { key, hash, prefix } = generateApiKey()
const refresh = generateRefreshToken()