docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,216 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
// Mock dependencies: factory must not reference outer variables
const mockExchangeCodeForAccount = vi.fn()
const mockFetchAccountDisplayName = vi.fn()
vi.mock('@/extensions/general/stripe/lib/connect', () => ({
exchangeCodeForAccount: (...args: unknown[]) => mockExchangeCodeForAccount(...args),
fetchAccountDisplayName: (...args: unknown[]) => mockFetchAccountDisplayName(...args),
}))
const { mockFrom, mockGetUser } = vi.hoisted(() => ({
mockFrom: vi.fn(),
// The cookie session the callback binds the completion to. Every pending
// row in this suite belongs to 'user-1', so that is the default session.
mockGetUser: vi.fn(),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn().mockResolvedValue({ from: mockFrom }),
createClient: vi.fn().mockResolvedValue({ auth: { getUser: mockGetUser } }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
import { GET } from '../route'
const CONNECTION_ID = 'connection-1'
const OAUTH_STATE = 'state-token-1'
function makeRequest(params: Record<string, string>) {
const url = new URL('http://localhost:3000/api/extensions/stripe/callback')
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v)
}
return new Request(url.toString())
}
function mockChain(result: { data?: unknown; error?: unknown }) {
const chain: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'update', 'insert']) {
chain[m] = vi.fn().mockReturnValue(chain)
}
chain.single = vi
.fn()
.mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
// For chains ending without .single() (the insert and the error-path updates)
chain.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
return chain
}
describe('GET /api/extensions/stripe/callback', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null })
mockExchangeCodeForAccount.mockResolvedValue({
stripeAccountId: 'acct_123',
livemode: false,
})
mockFetchAccountDisplayName.mockResolvedValue('Test Shop')
})
it('activates the connection and turns the transaction feed on by default', async () => {
const findChain = mockChain({
data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' },
})
const replayChain = mockChain({ error: null })
const activateChain = mockChain({
data: {
id: CONNECTION_ID,
company_id: 'company-1',
user_id: 'user-1',
stripe_account_id: 'acct_123',
livemode: false,
},
})
mockFrom
.mockReturnValueOnce(findChain)
.mockReturnValueOnce(replayChain)
.mockReturnValueOnce(activateChain)
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.status).toBe(307)
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_connected=true',
)
// Feed-only product: a completed OAuth must leave the nightly sync armed,
// otherwise a connected account silently ingests nothing.
const activatePayload = (activateChain.update as ReturnType<typeof vi.fn>).mock.calls[0][0]
expect(activatePayload).toMatchObject({
stripe_account_id: 'acct_123',
livemode: false,
display_name: 'Test Shop',
status: 'active',
oauth_state: null,
transaction_sync_enabled: true,
})
})
it('redirects with an error and never activates when the state is unknown', async () => {
mockFrom.mockReturnValueOnce(mockChain({ data: null, error: { code: 'PGRST116' } }))
const response = await GET(makeRequest({ code: 'ac_123', state: 'unknown-state' }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
)
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('redirects with an error when the authorization code was already used', async () => {
mockFrom
.mockReturnValueOnce(
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
)
.mockReturnValueOnce(mockChain({ error: { code: '23505' } }))
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
)
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('reports the conflict when the Stripe account is already connected', async () => {
mockFrom
.mockReturnValueOnce(
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
)
.mockReturnValueOnce(mockChain({ error: null }))
.mockReturnValueOnce(mockChain({ data: null, error: { code: '23505', message: 'dup' } }))
.mockReturnValueOnce(mockChain({ error: null }))
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=account_already_connected',
)
})
it('redirects without touching Stripe when parameters are missing', async () => {
const response = await GET(makeRequest({ state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=missing_parameters',
)
expect(mockFrom).not.toHaveBeenCalled()
})
// The state token proves the callback belongs to a flow WE started, not that
// the browser completing it is the initiator's. A victim lured into
// approving a Connect someone else started must not have their Stripe
// account attached to that someone's company.
describe('initiator binding', () => {
const PENDING_ROW = { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' }
it('refuses a consent completed by a different user without burning the code or marking the row', async () => {
const findChain = mockChain({ data: PENDING_ROW })
mockFrom.mockReturnValue(findChain)
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-2' } }, error: null })
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.status).toBe(307)
const location = decodeURIComponent(response.headers.get('location') || '')
expect(location.startsWith('http://localhost:3000/import?mode=stripe&stripe_error=')).toBe(true)
// The panel shows an unknown stripe_error value verbatim, so the param
// carries the Swedish explanation itself.
expect(location).toContain('annat användarkonto')
expect(location).not.toContain('stripe_connected')
// Only the lookup touched the database: no oauth_used_codes insert (the
// code stays valid for the initiator), no update on the row.
expect(mockFrom).toHaveBeenCalledTimes(1)
expect(findChain.insert).not.toHaveBeenCalled()
expect(findChain.update).not.toHaveBeenCalled()
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('sends an anonymous browser to /login with the callback URL preserved', async () => {
const findChain = mockChain({ data: PENDING_ROW })
mockFrom.mockReturnValue(findChain)
mockGetUser.mockResolvedValue({ data: { user: null }, error: null })
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.status).toBe(307)
const location = new URL(response.headers.get('location') || '')
expect(location.origin).toBe('http://localhost:3000')
expect(location.pathname).toBe('/login')
expect(location.searchParams.get('next')).toBe(
`/api/extensions/stripe/callback?code=ac_123&state=${OAUTH_STATE}`,
)
expect(mockFrom).toHaveBeenCalledTimes(1)
expect(findChain.insert).not.toHaveBeenCalled()
expect(findChain.update).not.toHaveBeenCalled()
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('does not consult the session for an unknown state (nothing to bind to)', async () => {
mockFrom.mockReturnValueOnce(mockChain({ data: null, error: { code: 'PGRST116' } }))
await GET(makeRequest({ code: 'ac_123', state: 'unknown-state' }))
expect(mockGetUser).not.toHaveBeenCalled()
})
})
})
-230
View File
@@ -1,230 +0,0 @@
import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { eventBus } from '@/lib/events/bus'
import { hashAuthCode } from '@/lib/auth/oauth-codes'
import {
requireFlowInitiator,
FLOW_INITIATOR_MISMATCH_MESSAGE,
} from '@/lib/auth/oauth-flow-binding'
import {
exchangeCodeForAccount,
fetchAccountDisplayName,
} from '@/extensions/general/stripe/lib/connect'
// This route emits stripe.connected (audit trail). ensureInitialized() must
// run at module load so the event_log handler has subscribed before the first
// emit on a cold instance.
ensureInitialized()
/**
* GET /api/extensions/stripe/callback
*
* OAuth callback for Stripe Connect authorization. Must be a real Next.js
* route (not an extension dispatcher handler) because Stripe redirects the
* user's browser to this URL directly.
*/
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const code = searchParams.get('code')
const state = searchParams.get('state')
const error = searchParams.get('error')
const errorDescription = searchParams.get('error_description')
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
// The Stripe surface lives on the import page (?mode=stripe opens the panel
// directly); appended params below must use '&' since the base has a query.
const returnUrl = `${baseUrl}/import?mode=stripe`
if (error) {
const errorMessage = errorDescription || error
// access_denied is the user cancelling at Stripe: an expected outcome.
const logDenied = error === 'access_denied' ? console.warn : console.error
logDenied('[stripe] Connect authorization denied', {
error,
error_description: errorDescription,
has_state: !!state,
})
if (state) {
try {
const supabase = await createServiceClient()
await supabase
.from('stripe_connections')
.update({ status: 'error', error_message: errorMessage, oauth_state: null })
.eq('oauth_state', state)
.eq('status', 'pending')
} catch (cleanupError) {
console.error('[stripe] Failed to clean up pending connection:', cleanupError)
}
}
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent(errorMessage)}`,
)
}
if (!code || !state) {
return NextResponse.redirect(`${returnUrl}&stripe_error=missing_parameters`)
}
const supabase = await createServiceClient()
try {
// Locate the connection awaiting this callback by oauth_state (CSRF-safe:
// the token is a single-use random UUID written before the redirect and
// cleared below).
const { data: pendingConnection, error: findError } = await supabase
.from('stripe_connections')
.select('id, user_id, company_id')
.eq('oauth_state', state)
.eq('status', 'pending')
.single()
if (findError || !pendingConnection) {
console.error('[stripe] No pending connection for oauth_state', {
findError: findError
? { message: findError.message, code: findError.code }
: null,
hasCode: !!code,
})
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent('invalid_state')}`,
)
}
// The state token proves this callback belongs to a flow we started; it
// says nothing about WHO is completing it. Bind the completion to the
// initiator's own cookie session BEFORE the code is burned below:
// otherwise a victim lured into approving a Stripe Connect someone else
// started would have their Stripe account attached to that someone's
// company. Stripe's redirect is a top-level navigation, so the
// initiator's cookies are present on the legitimate path.
const initiator = await requireFlowInitiator(request, pendingConnection.user_id, {
flow: 'stripe.callback',
})
if (!initiator.ok) {
if (initiator.reason === 'no_session') {
// Session expired mid-flow: sign in and the callback re-runs with
// the same (still unused) code + state. The row is untouched.
return initiator.response
}
// A different user completed it. Refuse without exchanging the code
// and without marking the row: it stays pending for its initiator.
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent(FLOW_INITIATOR_MISMATCH_MESSAGE)}`,
)
}
// Replay protection (OAuth 2.1 §4.1.2): a code may be exchanged once.
// The PRIMARY KEY on oauth_used_codes rejects a second insert.
const { error: replayError } = await supabase
.from('oauth_used_codes')
.insert({ code_hash: hashAuthCode(code) })
if (replayError) {
console.error('[stripe] Authorization code already used', {
connectionId: pendingConnection.id,
code: replayError.code,
})
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent('invalid_state')}`,
)
}
const { stripeAccountId, livemode } = await exchangeCodeForAccount(code)
const displayName = await fetchAccountDisplayName(stripeAccountId)
const { data: updatedConnection, error: updateError } = await supabase
.from('stripe_connections')
.update({
stripe_account_id: stripeAccountId,
livemode,
display_name: displayName,
status: 'active',
connected_at: new Date().toISOString(),
error_message: null,
oauth_state: null, // Clear to prevent replay
// Feed-only product: connecting Stripe means fetching its
// transactions, so the nightly feed starts on by default. The panel
// toggle remains as the opt-out.
transaction_sync_enabled: true,
})
.eq('id', pendingConnection.id)
.select('id, company_id, user_id, stripe_account_id, livemode')
.single()
if (updateError || !updatedConnection) {
// 23505 = one of the partial unique indexes: this Stripe account is
// already actively connected (to this or another company), or the
// company connected in a parallel tab. Both are user-facing conflicts.
const isConflict = updateError?.code === '23505'
console.error('[stripe] Failed to activate connection', {
connectionId: pendingConnection.id,
error: updateError
? { message: updateError.message, code: updateError.code }
: null,
})
await supabase
.from('stripe_connections')
.update({
status: 'error',
error_message: isConflict
? 'Stripe-kontot är redan anslutet till ett företag.'
: 'Anslutningen kunde inte slutföras.',
oauth_state: null,
})
.eq('id', pendingConnection.id)
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent(
isConflict ? 'account_already_connected' : 'activation_failed',
)}`,
)
}
try {
await eventBus.emit({
type: 'stripe.connected',
payload: {
connectionId: updatedConnection.id,
stripeAccountId: updatedConnection.stripe_account_id!,
livemode: updatedConnection.livemode,
userId: updatedConnection.user_id,
companyId: updatedConnection.company_id,
},
})
} catch (emitError) {
// Non-fatal: the DB state (source of truth) is already committed.
console.error('[stripe] Failed to emit stripe.connected event', {
connectionId: updatedConnection.id,
error: emitError instanceof Error ? emitError.message : String(emitError),
})
}
return NextResponse.redirect(`${returnUrl}&stripe_connected=true`)
} catch (error) {
console.error('[stripe] Callback error', {
message: error instanceof Error ? error.message : String(error),
name: error instanceof Error ? error.name : undefined,
hasCode: !!code,
})
try {
await supabase
.from('stripe_connections')
.update({
status: 'error',
error_message: 'Anslutningen kunde inte slutföras.',
oauth_state: null,
})
.eq('oauth_state', state)
.eq('status', 'pending')
} catch (cleanupError) {
console.error('[stripe] Callback cleanup failed:', cleanupError)
}
return NextResponse.redirect(
`${returnUrl}&stripe_error=${encodeURIComponent('connection_failed')}`,
)
}
}