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:
@@ -1,155 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
function mockAuth(
|
||||
user: { id: string; email: string | null } | null,
|
||||
rpcResult: { data?: unknown; error?: unknown } = { data: null, error: null }
|
||||
) {
|
||||
const signOut = vi.fn().mockResolvedValue({ error: null })
|
||||
const rpc = vi.fn().mockResolvedValue(rpcResult)
|
||||
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
signOut,
|
||||
},
|
||||
rpc,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { rpc, signOut }
|
||||
}
|
||||
|
||||
function mockServiceClient(blockers: { id: string; name: string }[] = []) {
|
||||
const updateUserById = vi.fn().mockResolvedValue({ data: {}, error: null })
|
||||
const adminSignOut = vi.fn().mockResolvedValue({ data: null, error: null })
|
||||
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
is: vi.fn().mockResolvedValue({
|
||||
data: blockers.map((b) => ({ companies: { id: b.id, name: b.name } })),
|
||||
error: null,
|
||||
}),
|
||||
}
|
||||
|
||||
mockCreateServiceClient.mockReturnValue({
|
||||
from: vi.fn().mockReturnValue(chain),
|
||||
auth: {
|
||||
admin: {
|
||||
updateUserById,
|
||||
signOut: adminSignOut,
|
||||
},
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { updateUserById, adminSignOut }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('POST /api/account/delete', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockAuth(null)
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when confirm_email does not match', async () => {
|
||||
mockAuth({ id: 'user-1', email: '[email protected]' })
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('returns 409 with blockers when RPC raises P0001', async () => {
|
||||
mockAuth(
|
||||
{ id: 'user-1', email: '[email protected]' },
|
||||
{ data: null, error: { code: 'P0001', message: 'blocked' } }
|
||||
)
|
||||
mockServiceClient([{ id: 'c1', name: 'Acme AB' }])
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: string
|
||||
blockers: { id: string; name: string }[]
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.blockers).toEqual([{ id: 'c1', name: 'Acme AB' }])
|
||||
})
|
||||
|
||||
it('anonymizes, bans, signs out, and emits event on happy path', async () => {
|
||||
const { rpc } = mockAuth({ id: 'user-1', email: '[email protected]' })
|
||||
const { updateUserById, adminSignOut } = mockServiceClient()
|
||||
|
||||
const emitted: unknown[] = []
|
||||
eventBus.on('account.deleted', (payload) => {
|
||||
emitted.push(payload)
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean }>(
|
||||
await POST(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
|
||||
expect(rpc).toHaveBeenCalledWith('anonymize_user_account', {
|
||||
target_user_id: 'user-1',
|
||||
})
|
||||
expect(updateUserById).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
expect.objectContaining({ ban_duration: expect.any(String) })
|
||||
)
|
||||
const updatePayload = updateUserById.mock.calls[0][1]
|
||||
// Email must NOT be scrubbed: retaining it is what blocks re-signup
|
||||
// with the same address. Recovery goes through support instead.
|
||||
expect(updatePayload).not.toHaveProperty('email')
|
||||
// Metadata is NOT wiped here: GoTrue merges metadata maps, so passing {}
|
||||
// was a no-op. The anonymize_user_account RPC scrubs auth.users directly
|
||||
// (migration 20260724150000).
|
||||
expect(updatePayload).not.toHaveProperty('user_metadata')
|
||||
expect(updatePayload).not.toHaveProperty('app_metadata')
|
||||
expect(adminSignOut).toHaveBeenCalledWith('user-1', 'global')
|
||||
expect(emitted).toHaveLength(1)
|
||||
expect(emitted[0]).toMatchObject({ userId: 'user-1' })
|
||||
})
|
||||
})
|
||||
@@ -1,138 +0,0 @@
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('api/account/delete')
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const DeleteAccountSchema = z.object({
|
||||
confirm_email: z.string().email(),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/account/delete
|
||||
*
|
||||
* Anonymizes the calling user's account. The auth.users row is retained
|
||||
* (banned for ~100 years) as a tombstone so FKs into BFL-retained
|
||||
* bookkeeping data (companies.created_by, audit_log.user_id, etc.) stay
|
||||
* valid. Memberships are removed, profile PII is stripped, and a global
|
||||
* signout forces all sessions to end.
|
||||
*
|
||||
* Precondition: the user must own zero non-archived companies. The RPC
|
||||
* enforces this at the DB level and raises SQLSTATE P0001 with a message
|
||||
* if the precondition fails: we return 409 in that case.
|
||||
*
|
||||
* Not wrapped in withRouteContext: deletion must work for users with zero
|
||||
* companies, so there is no company context to resolve. requireAuth() is
|
||||
* used directly so MFA (AAL2) is still enforced on hosted: a stolen AAL1
|
||||
* cookie must not be able to destroy the account. BankID-linked users are
|
||||
* exempt from the AAL2 gate (BankID is inherently 2FA, see shouldEnforceMfa).
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const auth = await requireAuth()
|
||||
if (auth.error) return auth.error
|
||||
const { user, supabase } = auth
|
||||
|
||||
const result = await validateBody(request, DeleteAccountSchema)
|
||||
if (!result.success) return result.response
|
||||
const { confirm_email } = result.data
|
||||
|
||||
if (!user.email || confirm_email.trim().toLowerCase() !== user.email.toLowerCase()) {
|
||||
return NextResponse.json(
|
||||
{ error: 'E-postadressen stämmer inte överens med ditt konto.' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Anonymize in the DB. Runs as SECURITY DEFINER and checks auth.uid()
|
||||
// internally, so we don't need service role here.
|
||||
const { error: rpcError } = await supabase.rpc('anonymize_user_account', {
|
||||
target_user_id: user.id,
|
||||
})
|
||||
|
||||
if (rpcError) {
|
||||
// P0001 = precondition violation from our RPC: user still owns active
|
||||
// companies. Re-fetch the blockers and return 409 so the UI can show
|
||||
// the list inline.
|
||||
if (rpcError.code === 'P0001') {
|
||||
const service = createServiceClient()
|
||||
const { data: blockers } = await service
|
||||
.from('company_members')
|
||||
.select('company_id, companies!inner(id, name, archived_at)')
|
||||
.eq('user_id', user.id)
|
||||
.eq('role', 'owner')
|
||||
.is('companies.archived_at', null)
|
||||
|
||||
const list = (blockers ?? []).map((b) => {
|
||||
const company = (b.companies as unknown) as { id: string; name: string }
|
||||
return { id: company.id, name: company.name }
|
||||
})
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Du måste radera eller överlåta dina företag innan du kan radera kontot.',
|
||||
blockers: list,
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
log.error('anonymize_user_account failed', { userId: user.id, error: rpcError.message })
|
||||
return NextResponse.json(
|
||||
{ error: 'Kunde inte radera kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// Ban the tombstone row ~100 years so login is impossible. The DB function
|
||||
// can't set the ban (GoTrue-managed), so we do it here.
|
||||
//
|
||||
// Note: auth.users.email is intentionally NOT scrubbed. The original
|
||||
// address is retained as a legitimate-interest tombstone so that:
|
||||
// (1) re-signup with the same email is blocked by Supabase's unique
|
||||
// constraint: deletion must feel permanent, not trivially
|
||||
// reversible by re-registering
|
||||
// (2) support can verify identity when a former user asks to recover
|
||||
// BFL-retained räkenskapsinformation
|
||||
// This must be documented in the privacy policy under legitimate
|
||||
// interest (GDPR Art. 6(1)(f)). The email is never read by the app
|
||||
// after this point: login is impossible (row is banned) and the
|
||||
// profile is anonymized, so no UI ever surfaces it.
|
||||
//
|
||||
// user_metadata / app_metadata PII is scrubbed by the RPC itself, NOT
|
||||
// here: GoTrue's admin update MERGES metadata maps, so the previous
|
||||
// updateUserById(..., { user_metadata: {}, app_metadata: {} }) call was
|
||||
// a silent no-op that left the full name on the tombstone (found on
|
||||
// prod 2026-07-24, repaired by migration 20260724150000).
|
||||
const service = createServiceClient()
|
||||
try {
|
||||
await service.auth.admin.updateUserById(user.id, {
|
||||
ban_duration: '876000h',
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('Failed to ban anonymized user', { userId: user.id, err })
|
||||
}
|
||||
|
||||
try {
|
||||
await service.auth.admin.signOut(user.id, 'global')
|
||||
} catch (err) {
|
||||
log.error('Failed to global sign out anonymized user', { userId: user.id, err })
|
||||
}
|
||||
|
||||
const deletedAt = new Date().toISOString()
|
||||
await eventBus.emit({
|
||||
type: 'account.deleted',
|
||||
payload: { userId: user.id, deletedAt },
|
||||
})
|
||||
|
||||
// Best-effort: clear the caller's session cookie too.
|
||||
await supabase.auth.signOut().catch(() => {})
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandResultByHost: vi.fn(async () => ({ brand: null, lookupFailed: false })),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
function mockUserClient(opts: {
|
||||
user: { id: string; email?: string } | null
|
||||
updateUserError?: { message: string; status?: number; code?: string } | null
|
||||
// What GoTrue returns for the fresh user (the pending-change fields the
|
||||
// claims fast path lacks). Defaults to "no pending change".
|
||||
freshUser?: {
|
||||
new_email?: string
|
||||
email_change_sent_at?: string
|
||||
} | null
|
||||
// Outcome of claim_email_change_request: true (won, default), false
|
||||
// (another request holds the claim), or an error object (RPC failed).
|
||||
claim?: boolean | { message: string; code?: string }
|
||||
}) {
|
||||
const updateUser = vi.fn().mockResolvedValue({
|
||||
data: {},
|
||||
error: opts.updateUserError ?? null,
|
||||
})
|
||||
const rpc = vi.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'claim_email_change_request') {
|
||||
const claim = opts.claim ?? true
|
||||
return typeof claim === 'boolean'
|
||||
? { data: claim, error: null }
|
||||
: { data: null, error: claim }
|
||||
}
|
||||
return { data: null, error: null }
|
||||
})
|
||||
const getUser = vi.fn().mockResolvedValue({
|
||||
data: {
|
||||
user:
|
||||
opts.freshUser === null
|
||||
? null
|
||||
: { id: opts.user?.id, email: opts.user?.email, ...(opts.freshUser ?? {}) },
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const supabase = { auth: { updateUser, getUser }, rpc } as any
|
||||
|
||||
if (opts.user) {
|
||||
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
|
||||
} else {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
}
|
||||
|
||||
return { updateUser, getUser, rpc }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/account/email', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockUserClient({ user: null })
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid email', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: 'not-an-email' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the new email equals the current one (case-insensitive)', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Det är redan din e-postadress.')
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requests the change via the user session with a callback redirect', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean; pending_email: string }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Normalized to lowercase before it reaches Supabase.
|
||||
expect(body.data?.pending_email).toBe('[email protected]')
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
const [attrs, options] = updateUser.mock.calls[0]
|
||||
expect(attrs).toEqual({ email: '[email protected]' })
|
||||
// flow=email_change routes the stock GoTrue redirect (message/error/code)
|
||||
// to the email-change status page in /auth/callback.
|
||||
expect(String(options.emailRedirectTo)).toMatch(
|
||||
/\/auth\/callback\?flow=email_change$/,
|
||||
)
|
||||
})
|
||||
|
||||
it('short-circuits a repeat request while the pending mails are fresh', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
|
||||
} as { id: string; email?: string },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean; pending_email: string }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.pending_email).toBe('[email protected]')
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-sends when the pending change is stale (expired-link recovery)', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(
|
||||
Date.now() - 2 * 60 * 60 * 1000,
|
||||
).toISOString(),
|
||||
} as { id: string; email?: string },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('re-sends when the pending change has no sent timestamp', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
new_email: '[email protected]',
|
||||
} as { id: string; email?: string },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reads pending state from GoTrue when the session claims lack it (fresh: no-op)', async () => {
|
||||
// The claims fast path carries no new_email; before this the route
|
||||
// re-issued tokens on every re-submit and voided the mails just sent.
|
||||
const { updateUser, getUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
freshUser: {
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(Date.now() - 3 * 60_000).toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean; pending_email: string; resent: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.resent).toBe(false)
|
||||
expect(getUser).toHaveBeenCalledTimes(1)
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads pending state from GoTrue when the session claims lack it (stale: re-send)', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
freshUser: {
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(
|
||||
Date.now() - 2 * 60 * 60 * 1000,
|
||||
).toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { resent: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.resent).toBe(true)
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('requests a different address even while another change is pending and fresh', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
freshUser: {
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
expect(updateUser.mock.calls[0][0]).toEqual({ email: '[email protected]' })
|
||||
})
|
||||
|
||||
it('does not consult GoTrue when the claims already carry the pending change', async () => {
|
||||
const { updateUser, getUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
email: '[email protected]',
|
||||
new_email: '[email protected]',
|
||||
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
|
||||
} as { id: string; email?: string },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(getUser).not.toHaveBeenCalled()
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('claims the address atomically before calling GoTrue', async () => {
|
||||
const { updateUser, rpc } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(rpc).toHaveBeenCalledWith('claim_email_change_request', {
|
||||
p_email: '[email protected]',
|
||||
p_window_seconds: 30 * 60,
|
||||
})
|
||||
// Claim strictly before the GoTrue call.
|
||||
expect(rpc.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
updateUser.mock.invocationCallOrder[0],
|
||||
)
|
||||
expect(rpc).not.toHaveBeenCalledWith('release_email_change_request')
|
||||
})
|
||||
|
||||
it('answers already-pending without calling GoTrue when a concurrent request holds the claim', async () => {
|
||||
// Both requests read "nothing pending" from GoTrue; only the claim
|
||||
// winner may re-issue the tokens.
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
claim: false,
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean; pending_email: string; resent: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
ok: true,
|
||||
pending_email: '[email protected]',
|
||||
resent: false,
|
||||
})
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('proceeds without the claim when the RPC itself fails', async () => {
|
||||
const { updateUser, rpc } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
claim: { message: 'function does not exist', code: '42883' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).toHaveBeenCalledTimes(1)
|
||||
expect(rpc).not.toHaveBeenCalledWith('release_email_change_request')
|
||||
})
|
||||
|
||||
it('releases the claim when GoTrue refuses the change', async () => {
|
||||
const { rpc } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
updateUserError: {
|
||||
message: 'AAL2 session is required',
|
||||
status: 403,
|
||||
code: 'insufficient_aal',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(rpc).toHaveBeenCalledWith('release_email_change_request')
|
||||
})
|
||||
|
||||
it('returns 409 when the address already belongs to another account', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
updateUserError: {
|
||||
message: 'A user with this email address has already been registered',
|
||||
status: 422,
|
||||
code: 'email_exists',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toBe('E-postadressen används redan av ett annat konto.')
|
||||
})
|
||||
|
||||
it('returns 400 and surfaces the AAL2 error when Supabase rejects the update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
updateUserError: {
|
||||
message:
|
||||
'AAL2 session is required to update email or password when MFA is enabled',
|
||||
status: 422,
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/email', {
|
||||
method: 'POST',
|
||||
body: { email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(updateUser).toHaveBeenCalled()
|
||||
expect(body.error).toContain('AAL2')
|
||||
})
|
||||
})
|
||||
@@ -1,190 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import {
|
||||
BrandLookupFailedError,
|
||||
resolveRequestAppOrigin,
|
||||
} from '@/lib/domains/trusted-app-origin'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const log = createLogger('api/account/email')
|
||||
|
||||
const ChangeEmailSchema = z.object({
|
||||
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
|
||||
})
|
||||
|
||||
// How long a pending change is considered fresh enough that re-submitting the
|
||||
// same address is a no-op instead of a re-send. Kept well under the token
|
||||
// expiry so a user with a dead link can always get new mails.
|
||||
const FRESH_PENDING_MS = 30 * 60 * 1000
|
||||
|
||||
/**
|
||||
* POST /api/account/email
|
||||
*
|
||||
* Server-routed login-email change. Always writes via the USER session so
|
||||
* Supabase's AAL2 guard fires: an email change is a credential rotation, and
|
||||
* a stolen AAL1 cookie must not be able to move the account to another
|
||||
* mailbox. (Contrast app/api/account/password/route.ts, whose first-time-set
|
||||
* path may bypass AAL2 because there is no existing credential to protect;
|
||||
* an email change always has one.)
|
||||
*
|
||||
* Nothing changes immediately: with secure email change enabled, Supabase
|
||||
* sends `email_change_current` to the old address and `email_change` to the
|
||||
* new one (templates in lib/email/auth-templates.ts via the send-email hook),
|
||||
* and the address flips only after confirmation. The links verify through
|
||||
* /auth/callback, which already handles type=email_change.
|
||||
*
|
||||
* The account itself is keyed by user id everywhere (company_members,
|
||||
* user_preferences, ...), so a confirmed change moves nothing but the login
|
||||
* identifier and contact address. profiles.email mirrors auth.users.email via
|
||||
* the sync_profile_email trigger (migration 20260828191950), so member lists,
|
||||
* notification recipients, and AGI/KU contact fields follow the change.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error: authError } = await requireAuth()
|
||||
if (authError) return authError
|
||||
|
||||
const result = await validateBody(request, ChangeEmailSchema)
|
||||
if (!result.success) return result.response
|
||||
const { email } = result.data
|
||||
|
||||
if (user.email && email === user.email.toLowerCase()) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Det är redan din e-postadress.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Re-requesting the address that is already awaiting confirmation is a
|
||||
// no-op success ONLY while the pending mails are fresh (protects the send
|
||||
// rate limit against double-clicks). Once they are older than that, the
|
||||
// confirmation links may have expired and the user's only recovery path is
|
||||
// re-running the change, so fall through to GoTrue, which restarts the
|
||||
// change and re-sends both mails.
|
||||
//
|
||||
// new_email/email_change_sent_at live on the GoTrue user, not in the JWT,
|
||||
// so they are absent on the claims-mapped fast path of requireAuth. Reading
|
||||
// them from the claims alone made every re-submit look like a brand-new
|
||||
// request: GoTrue re-issued both tokens and voided the links the user was
|
||||
// about to click, which is exactly the "link invalid" loop users hit after
|
||||
// pressing the button twice. Fetch the fresh user when the claims carry no
|
||||
// pending state; the extra round trip is fine on a route this rare.
|
||||
let pendingEmail = user.new_email
|
||||
let pendingSentAt = user.email_change_sent_at
|
||||
if (!pendingEmail) {
|
||||
const { data } = await supabase.auth.getUser()
|
||||
pendingEmail = data?.user?.new_email
|
||||
pendingSentAt = data?.user?.email_change_sent_at
|
||||
}
|
||||
|
||||
if (pendingEmail && email === pendingEmail.toLowerCase()) {
|
||||
const sentAt = pendingSentAt ? Date.parse(pendingSentAt) : Number.NaN
|
||||
const fresh =
|
||||
Number.isFinite(sentAt) && Date.now() - sentAt < FRESH_PENDING_MS
|
||||
if (fresh) {
|
||||
return NextResponse.json({
|
||||
data: { ok: true, pending_email: email, resent: false },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Trusted-origin resolution against the brands table, not request.url:
|
||||
// behind a proxy request.url can be an internal origin (dead confirmation
|
||||
// links on self-hosted), and auth links may never follow an
|
||||
// attacker-chosen host. Registered brand hosts pass through so the mail
|
||||
// carries the right brand.
|
||||
//
|
||||
// flow=email_change marks the callback so the stock GoTrue links (verified
|
||||
// on the GoTrue host, returned here via redirect_to with ?message=, ?error=
|
||||
// or ?code= instead of a token_hash) land on the email-change status page
|
||||
// rather than the silent login bounce. The Send Email hook preserves this
|
||||
// query on its token_hash links, so both link styles share the marker.
|
||||
let origin: string
|
||||
try {
|
||||
origin = await resolveRequestAppOrigin(request)
|
||||
} catch (err) {
|
||||
if (!(err instanceof BrandLookupFailedError)) throw err
|
||||
// Refuse rather than send a wrong-brand confirmation pair; nothing has
|
||||
// been claimed or sent yet, so a retry is clean.
|
||||
log.warn('email change refused: brand lookup failed', { userId: user.id })
|
||||
return NextResponse.json(
|
||||
{ error: 'Tillfälligt fel. Försök igen om en stund.' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
// Cross-instance gate (migration 20260903083000). The pending-state read
|
||||
// above is not atomic: two concurrent requests (two tabs, a retried fetch)
|
||||
// can both see nothing pending, and each updateUser re-issues the tokens
|
||||
// and voids the other's mails. claim_email_change_request is one
|
||||
// INSERT ... ON CONFLICT row lock per user, so exactly one caller per
|
||||
// address per window proceeds; the rest answer "already pending" and send
|
||||
// nothing. A different address always wins the claim. Best effort: if the
|
||||
// RPC itself fails, fall through to GoTrue rather than block the change.
|
||||
const { data: claimed, error: claimError } = await supabase.rpc(
|
||||
'claim_email_change_request',
|
||||
{ p_email: email, p_window_seconds: FRESH_PENDING_MS / 1000 },
|
||||
)
|
||||
if (claimError) {
|
||||
log.warn('email change claim failed; proceeding without it', {
|
||||
userId: user.id,
|
||||
code: claimError.code,
|
||||
})
|
||||
} else if (claimed === false) {
|
||||
return NextResponse.json({
|
||||
data: { ok: true, pending_email: email, resent: false },
|
||||
})
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase.auth.updateUser(
|
||||
{ email },
|
||||
{ emailRedirectTo: `${origin}/auth/callback?flow=email_change` },
|
||||
)
|
||||
|
||||
if (updateError) {
|
||||
log.warn('email change request failed', {
|
||||
userId: user.id,
|
||||
code: updateError.code,
|
||||
status: updateError.status,
|
||||
})
|
||||
// GoTrue sent nothing, so the claim must not block a retry (after MFA,
|
||||
// with another address, once the network is back).
|
||||
if (!claimError) {
|
||||
const { error: releaseError } = await supabase.rpc('release_email_change_request')
|
||||
if (releaseError) {
|
||||
log.warn('email change claim release failed', {
|
||||
userId: user.id,
|
||||
code: releaseError.code,
|
||||
})
|
||||
}
|
||||
}
|
||||
// Addresses are unique per auth user: a change to an already-registered
|
||||
// address is refused by GoTrue, never merged. Accounts are consolidated
|
||||
// via company invitations, not email changes.
|
||||
if (
|
||||
updateError.code === 'email_exists' ||
|
||||
/already.*registered/i.test(updateError.message ?? '')
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'E-postadressen används redan av ett annat konto.' },
|
||||
{ status: 409 },
|
||||
)
|
||||
}
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
getUserErrorMessage(updateError) ||
|
||||
'Kunde inte begära e-poständring. Försök igen.',
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
log.info('email change requested', { userId: user.id })
|
||||
|
||||
return NextResponse.json({
|
||||
data: { ok: true, pending_email: email, resent: true },
|
||||
})
|
||||
}
|
||||
@@ -1,304 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
type AuthMetadata = Record<string, unknown>
|
||||
|
||||
function mockUserClient(opts: {
|
||||
user: { id: string; app_metadata?: AuthMetadata } | null
|
||||
updateUserError?: { message: string; status?: number; code?: string } | null
|
||||
}) {
|
||||
const updateUser = vi.fn().mockResolvedValue({
|
||||
data: {},
|
||||
error: opts.updateUserError ?? null,
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const supabase = { auth: { updateUser } } as any
|
||||
|
||||
if (opts.user) {
|
||||
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
|
||||
} else {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
}
|
||||
|
||||
return { updateUser }
|
||||
}
|
||||
|
||||
function mockService(opts: {
|
||||
priorAppMetadata?: AuthMetadata
|
||||
// Returned-error from admin.updateUserById when called with { password }
|
||||
passwordSetError?: { message: string; status?: number; code?: string } | null
|
||||
// Thrown error from admin.updateUserById when called with { app_metadata }
|
||||
flagFlipError?: Error | null
|
||||
}) {
|
||||
const updateUserById = vi
|
||||
.fn()
|
||||
.mockImplementation((_id: string, args: Record<string, unknown>) => {
|
||||
if ('password' in args) {
|
||||
return Promise.resolve({
|
||||
data: {},
|
||||
error: opts.passwordSetError ?? null,
|
||||
})
|
||||
}
|
||||
if (opts.flagFlipError) return Promise.reject(opts.flagFlipError)
|
||||
return Promise.resolve({ data: {}, error: null })
|
||||
})
|
||||
|
||||
const getUserById = vi.fn().mockResolvedValue({
|
||||
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
|
||||
})
|
||||
|
||||
mockCreateServiceClient.mockReturnValue({
|
||||
auth: { admin: { getUserById, updateUserById } },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { getUserById, updateUserById }
|
||||
}
|
||||
|
||||
const STRONG_PASSWORD = 'StrongP@ssword1'
|
||||
|
||||
function flagFlipCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'app_metadata' in args,
|
||||
)
|
||||
}
|
||||
|
||||
function passwordSetCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'password' in args,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/account/password', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockUserClient({ user: null })
|
||||
mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when password is too weak', async () => {
|
||||
mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } })
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: 'weak' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
describe('first-time set (has_password !== true)', () => {
|
||||
it('writes the password via admin API and flips the flag', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
app_metadata: { has_password: false, bankid_linked: true },
|
||||
},
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false, bankid_linked: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Did NOT go through the user session: that path would fail with AAL2.
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
// Password set via admin
|
||||
expect(passwordSetCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{ password: STRONG_PASSWORD },
|
||||
])
|
||||
// Flag flipped, siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
bankid_linked: true,
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('treats unset has_password as first-time set', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' /* no app_metadata */ },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(passwordSetCall(updateUserById)).toBeDefined()
|
||||
})
|
||||
|
||||
it('returns 400 and skips flag flip when the admin password set fails', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
passwordSetError: { message: 'Password too weak', status: 400 },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Något gick fel. Försök igen.')
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails after admin password set', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
flagFlipError: new Error('admin down'),
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('change-password (has_password === true)', () => {
|
||||
it('writes via the user session so Supabase enforces AAL2', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true, provider: 'email' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Used user session, NOT admin API for the password itself
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(passwordSetCall(updateUserById)).toBeUndefined()
|
||||
// Flag is still flipped (idempotent) with siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
provider: 'email',
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('returns 400 and skips flag flip when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Något gick fel. Försök igen.')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: {
|
||||
message:
|
||||
'AAL2 session is required to update email or password when MFA is enabled',
|
||||
status: 422,
|
||||
},
|
||||
})
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('AAL2')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,119 +0,0 @@
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
const log = createLogger('api/account/password')
|
||||
|
||||
const SetPasswordSchema = z.object({
|
||||
password: z
|
||||
.string()
|
||||
.min(8, 'Lösenordet måste vara minst 8 tecken')
|
||||
.refine(
|
||||
(v) =>
|
||||
/[a-z]/.test(v) &&
|
||||
/[A-Z]/.test(v) &&
|
||||
/[0-9]/.test(v) &&
|
||||
/[^a-zA-Z0-9]/.test(v),
|
||||
'Lösenordet måste innehålla versaler, gemener, siffror och specialtecken',
|
||||
),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/account/password
|
||||
*
|
||||
* Server-routed password set/change, then flips `app_metadata.has_password =
|
||||
* true` via the service client (clients can't write app_metadata).
|
||||
*
|
||||
* Two paths depending on whether the user already has a real password:
|
||||
*
|
||||
* - First-time set (`app_metadata.has_password !== true`): write via the
|
||||
* admin API. BankID-only users (and legacy users whose `has_password`
|
||||
* flag was set to false by the backfill) sit at AAL1 with a TOTP factor
|
||||
* enrolled, and `updateUser` on the user session would be rejected with
|
||||
* "AAL2 session is required to update email or password when MFA is
|
||||
* enabled". Setting an initial password has no existing credential to
|
||||
* protect, so bypassing AAL2 is safe.
|
||||
*
|
||||
* - Change-password (`app_metadata.has_password === true`): write via the
|
||||
* user session so Supabase's AAL2 guard still fires. A stolen AAL1
|
||||
* cookie must not be able to rotate a known password.
|
||||
*
|
||||
* This route is the single write path for setting a password. SecuritySettings,
|
||||
* the reset-password page, and the /account/set-password page all funnel
|
||||
* through here so the flag stays in sync: see lib/auth/has-password.ts.
|
||||
*
|
||||
* If the password update succeeds but the flag write fails, we log and still
|
||||
* return success: the user has a working password and the banner will show one
|
||||
* more time, but a retry will re-flip the flag.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error: authError } = await requireAuth()
|
||||
if (authError) return authError
|
||||
|
||||
const result = await validateBody(request, SetPasswordSchema)
|
||||
if (!result.success) return result.response
|
||||
const { password } = result.data
|
||||
|
||||
const isFirstTimeSet = user.app_metadata?.has_password !== true
|
||||
const service = createServiceClient()
|
||||
|
||||
let updateError:
|
||||
| { message?: string; status?: number; code?: string }
|
||||
| null
|
||||
| undefined = null
|
||||
|
||||
if (isFirstTimeSet) {
|
||||
const { error } = await service.auth.admin.updateUserById(user.id, {
|
||||
password,
|
||||
})
|
||||
updateError = error
|
||||
} else {
|
||||
const { error } = await supabase.auth.updateUser({ password })
|
||||
updateError = error
|
||||
}
|
||||
|
||||
if (updateError) {
|
||||
log.warn('password update failed', {
|
||||
userId: user.id,
|
||||
isFirstTimeSet,
|
||||
code: updateError.code,
|
||||
status: updateError.status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
getUserErrorMessage(updateError) ||
|
||||
'Kunde inte uppdatera lösenord. Försök igen.',
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Read-merge-write so we don't wipe sibling app_metadata keys.
|
||||
// updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts
|
||||
// and the comment in app/api/account/delete/route.ts).
|
||||
let flagWriteOk = false
|
||||
try {
|
||||
const { data: u } = await service.auth.admin.getUserById(user.id)
|
||||
const prior = u?.user?.app_metadata ?? {}
|
||||
await service.auth.admin.updateUserById(user.id, {
|
||||
app_metadata: { ...prior, has_password: true },
|
||||
})
|
||||
flagWriteOk = true
|
||||
} catch (err) {
|
||||
log.error('failed to flip has_password flag after successful password set', {
|
||||
userId: user.id,
|
||||
err,
|
||||
})
|
||||
// Don't surface the failure: the user has a working password. The
|
||||
// banner will show once more and a retry will succeed.
|
||||
}
|
||||
|
||||
log.info('password set', { userId: user.id, isFirstTimeSet, flagWriteOk })
|
||||
|
||||
return NextResponse.json({ data: { ok: true } })
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/composer.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const checkRateMock = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/keys', () => ({
|
||||
CAPABILITY: { ai: 'ai' },
|
||||
}))
|
||||
|
||||
const composeMock = vi.fn()
|
||||
vi.mock('@/lib/agent/composer', () => ({
|
||||
composeAgentProfile: (...args: unknown[]) => composeMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../composer/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRateMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/composer', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const res = await POST(req, routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 429 when rate limited', async () => {
|
||||
checkRateMock.mockResolvedValue({ ok: false, retryAfterSec: 30 })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const res = await POST(req, routeParams)
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('30')
|
||||
})
|
||||
|
||||
it('refuses a viewer with 403 (composer rewrites the profile)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
expect(composeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the composer for a non-viewer member', async () => {
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
composeMock.mockResolvedValue({ company_id: 'company-1', profile_summary: 'Byggd' })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', {
|
||||
method: 'POST',
|
||||
body: { dry_run: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Byggd')
|
||||
expect(composeMock).toHaveBeenCalledWith(expect.anything(), 'company-1', { dryRun: true })
|
||||
})
|
||||
})
|
||||
@@ -1,176 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/agent/conversations and GET/PATCH /api/agent/conversations/[id].
|
||||
*
|
||||
* Uses a filter-capturing Supabase mock so the user-scoping regression is
|
||||
* locked in: RLS on agent_conversations is company-scoped, so the explicit
|
||||
* .eq('user_id', …) filter in the list route is the only thing preventing
|
||||
* team members from seeing each other's conversation titles/previews.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET as listGET } from '../conversations/route'
|
||||
import { GET as detailGET, PATCH as detailPATCH } from '../conversations/[id]/route'
|
||||
|
||||
interface CapturedCall {
|
||||
method: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
/** Chainable builder that records every call and resolves queued results per from(). */
|
||||
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
|
||||
const calls: CapturedCall[] = []
|
||||
let idx = 0
|
||||
const makeBuilder = () => {
|
||||
const result = results[idx++] ?? { data: null, error: null }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const b: any = {}
|
||||
for (const m of ['select', 'eq', 'is', 'or', 'order', 'limit', 'insert', 'update', 'maybeSingle', 'single']) {
|
||||
b[m] = (...args: unknown[]) => {
|
||||
calls.push({ method: m, args })
|
||||
return b
|
||||
}
|
||||
}
|
||||
b.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null, count: null })
|
||||
return b
|
||||
}
|
||||
const supabase = {
|
||||
from: (table: string) => {
|
||||
calls.push({ method: 'from', args: [table] })
|
||||
return makeBuilder()
|
||||
},
|
||||
}
|
||||
return { supabase, calls }
|
||||
}
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const idParams = { params: Promise.resolve({ id: 'conv-1' }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await listGET(createMockRequest('/api/agent/conversations'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric limit', async () => {
|
||||
const { supabase } = createCapturingSupabase([])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations', { searchParams: { limit: 'abc' } })
|
||||
const { status } = await parseJsonResponse(await listGET(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('filters the list by BOTH company_id and the calling user_id', async () => {
|
||||
const { supabase, calls } = createCapturingSupabase([
|
||||
{ data: [{ id: 'conv-1', title: 'Min konversation' }] },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations')
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
||||
await listGET(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
|
||||
// Privacy regression guard: without this filter, company-scoped RLS lets
|
||||
// every member read colleagues' titles and last_message_preview.
|
||||
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations/[id]', () => {
|
||||
it('returns 404 when the conversation is not owned by the caller', async () => {
|
||||
// Ownership is part of the fetch (.eq user_id) — a non-owned id resolves null.
|
||||
const { supabase, calls } = createCapturingSupabase([{ data: null }])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('CONVERSATION_NOT_FOUND')
|
||||
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
|
||||
it('returns the conversation with its messages for the owner', async () => {
|
||||
const { supabase } = createCapturingSupabase([
|
||||
{ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', title: 'T' } },
|
||||
{ data: { role: 'member' } },
|
||||
{ data: [{ id: 'm1', role: 'user', content: 'Hej' }] },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { conversation: { id: string }; messages: unknown[] }
|
||||
}>(await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.conversation.id).toBe('conv-1')
|
||||
expect(body.data.messages).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/conversations/[id]', () => {
|
||||
it('returns 400 when the body has nothing to update', async () => {
|
||||
const { supabase } = createCapturingSupabase([])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations/conv-1', {
|
||||
method: 'PATCH',
|
||||
body: {},
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await detailPATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
|
||||
})
|
||||
|
||||
it('updates pin state for an owned conversation', async () => {
|
||||
const { supabase } = createCapturingSupabase([
|
||||
{ data: { user_id: 'user-1', company_id: 'company-1' } },
|
||||
{ data: { id: 'conv-1', pinned: true } },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations/conv-1', {
|
||||
method: 'PATCH',
|
||||
body: { pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { pinned: boolean } }>(
|
||||
await detailPATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.pinned).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,184 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/feedback.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const emitMock = vi.fn()
|
||||
vi.mock('@/lib/events/bus', () => ({
|
||||
eventBus: { emit: (...args: unknown[]) => emitMock(...args) },
|
||||
}))
|
||||
|
||||
import { POST } from '../feedback/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const CONVERSATION_ID = '11111111-2222-4333-8444-555555555555'
|
||||
|
||||
const body = (over: Record<string, unknown> = {}) => ({
|
||||
conversation_id: CONVERSATION_ID,
|
||||
sentiment: 'negative',
|
||||
...over,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/feedback', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await POST(req, routeParams)).status).toBe(401)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 for a sentiment outside the two votes the UI can send', async () => {
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ sentiment: 'furious' }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the conversation id is not a uuid', async () => {
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ conversation_id: 'not-a-uuid' }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('404s on a conversation belonging to another user', async () => {
|
||||
// Same hole that /api/agent/invoke had: the id is caller-supplied, so
|
||||
// without the ownership check a member could file feedback against a
|
||||
// colleague's thread and the triage backlog would carry a conversation the
|
||||
// reporter never saw.
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'someone-else',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(404)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s on a conversation in another company', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-2',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s when the conversation does not exist', async () => {
|
||||
enqueue({ data: null })
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
|
||||
})
|
||||
|
||||
it('emits agent.feedback with actorType user on the happy path', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'vat.review',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ sentiment: 'positive', message_index: 4 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(emitMock).toHaveBeenCalledOnce()
|
||||
const event = emitMock.mock.calls[0]![0] as {
|
||||
type: string
|
||||
payload: Record<string, unknown>
|
||||
}
|
||||
// Same event type the MCP tool emits, so chat votes land in the backlog
|
||||
// the product team already reads instead of a second place.
|
||||
expect(event.type).toBe('agent.feedback')
|
||||
expect(event.payload.sentiment).toBe('positive')
|
||||
expect(event.payload.actorType).toBe('user')
|
||||
expect(event.payload.actorId).toBe('user-1')
|
||||
expect(event.payload.companyId).toBe('company-1')
|
||||
expect(event.payload.sessionId).toBe(CONVERSATION_ID)
|
||||
// Traceable to an answer: a thumbs-down that cannot be tied to a turn is a
|
||||
// number, not a report.
|
||||
expect(event.payload.context).toContain('vat.review')
|
||||
expect(event.payload.context).toContain('#4')
|
||||
})
|
||||
|
||||
it('never carries user free text into the telemetry log', async () => {
|
||||
// A comment box here would put whatever the user typed, in an accounting
|
||||
// product, verbatim into event_log under telemetry retention: client
|
||||
// names, personnummer, case details. The field is not accepted, and a
|
||||
// caller that sends one anyway must not have it stored.
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ comment: 'Anna Andersson 19850101-1234 fick fel konto' }),
|
||||
})
|
||||
await POST(req, routeParams)
|
||||
|
||||
const event = emitMock.mock.calls[0]![0] as { payload: { context: string } }
|
||||
expect(event.payload.context).not.toContain('Anna Andersson')
|
||||
expect(event.payload.context).not.toContain('19850101')
|
||||
expect(JSON.stringify(event.payload)).not.toContain('19850101')
|
||||
})
|
||||
})
|
||||
@@ -1,282 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/invoke, focused on conversation ownership.
|
||||
*
|
||||
* RLS on agent_conversations/agent_messages is company-scoped, not user-scoped
|
||||
* (migration 20260517204000), so the route itself has to prove that a resumed
|
||||
* conversation_id belongs to the caller. Without that check, a member could
|
||||
* post a colleague's conversation id and have their history loaded into the
|
||||
* prompt (and their own turns appended to it).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const checkRateMock = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/keys', () => ({
|
||||
CAPABILITY: { ai: 'ai' },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
const getIntentMock = vi.fn()
|
||||
vi.mock('@/lib/agent/intents/registry', () => ({
|
||||
getIntent: (...args: unknown[]) => getIntentMock(...args),
|
||||
}))
|
||||
|
||||
// Deployment-level AI availability (distinct from the per-company paywall).
|
||||
// Default: available, so the ownership tests below exercise the real flow.
|
||||
const aiStatusMock = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({
|
||||
getAiStatus: () => aiStatusMock(),
|
||||
}))
|
||||
|
||||
const runChatTurnMock = vi.fn()
|
||||
vi.mock('@/lib/agent/chat/run-turn', () => ({
|
||||
runChatTurn: (...args: unknown[]) => runChatTurnMock(...args),
|
||||
friendlyModelError: () => 'Något gick fel hos assistenten.',
|
||||
}))
|
||||
|
||||
import { POST } from '../invoke/route'
|
||||
|
||||
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
function body(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
intent_id: 'general.help',
|
||||
user_message: 'Hur gick juli?',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue the reads the route performs before it resolves the conversation.
|
||||
*
|
||||
* Ownership is validated ahead of every side effect and of the company/profile
|
||||
* reads, so a rejected request costs exactly one membership read plus the
|
||||
* conversation lookup.
|
||||
*/
|
||||
function enqueuePreamble() {
|
||||
enqueue({ data: { role: 'owner' } }) // company_members
|
||||
}
|
||||
|
||||
/** The company + profile reads that only happen once a request is accepted. */
|
||||
function enqueueAcceptedTail() {
|
||||
enqueue({ data: { name: 'Nordvik Bygg AB' } }) // companies
|
||||
enqueue({ data: { full_name: 'Johan Nordvik' } }) // profiles
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRateMock.mockResolvedValue({ ok: true })
|
||||
getIntentMock.mockReturnValue({ id: 'general.help', sheetTitle: 'Assistenten' })
|
||||
runChatTurnMock.mockResolvedValue(undefined)
|
||||
aiStatusMock.mockReturnValue({ configured: true, assistantAvailable: true, provider: 'bedrock' })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/invoke', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid body', async () => {
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: { intent_id: '' } }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for an unknown intent', async () => {
|
||||
getIntentMock.mockReturnValue(undefined)
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
// A self-host without an AI key, or on an OpenAI-compatible endpoint the
|
||||
// chat loop does not speak yet: say so up front with a distinct code, never
|
||||
// open a stream that dies on the first model call, never confuse it with
|
||||
// the paywall.
|
||||
it('returns 503 ai_unconfigured when the deployment has no assistant backend', async () => {
|
||||
aiStatusMock.mockReturnValue({ configured: false, assistantAvailable: false, provider: 'bedrock' })
|
||||
enqueuePreamble()
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status, body: json } = await parseJsonResponse<{ error: string; code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(json.code).toBe('ai_unconfigured')
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 when the user is not a member of the company', async () => {
|
||||
enqueue({ data: null }) // company_members: no row
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 when resuming a conversation owned by another user', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-2', // someone else in the same company
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status, body: json } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(404)
|
||||
expect(json.error).toBe('Konversationen hittades inte.')
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when resuming a conversation from another company', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1', // same user...
|
||||
company_id: 'company-2', // ...but a company other than the active one
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(404)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the conversation does not exist', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({ data: null })
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(404)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the conversation belongs to a different intent', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'vat.review', // tool loadout differs from general.help
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the turn when the caller owns the conversation', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
enqueueAcceptedTail()
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
// The route streams NDJSON; draining it is enough to know the turn ran.
|
||||
await res.text()
|
||||
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('hands the first-turn profile summary to the turn instead of re-reading it', async () => {
|
||||
// On a first turn the route reads agent_profiles to build the intent's
|
||||
// prompt template. run-turn needs the same value for the system prompt, so
|
||||
// it is passed through rather than read a second time.
|
||||
getIntentMock.mockReturnValue({
|
||||
id: 'general.help',
|
||||
sheetTitle: 'Assistenten',
|
||||
capture: vi.fn().mockResolvedValue({ some: 'context' }),
|
||||
promptTemplate: vi.fn().mockReturnValue('templated first turn'),
|
||||
})
|
||||
|
||||
enqueuePreamble()
|
||||
enqueue({ data: { id: CONVERSATION_ID } }) // conversation insert
|
||||
enqueueAcceptedTail()
|
||||
enqueue({ data: { profile_summary: 'Byggkonsult, K2' } }) // agent_profiles
|
||||
enqueue({ data: [] }) // agent_memory
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', {
|
||||
method: 'POST',
|
||||
body: { intent_id: 'general.help' }, // no user_message => first turn
|
||||
}),
|
||||
)
|
||||
await res.text()
|
||||
|
||||
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
|
||||
const args = runChatTurnMock.mock.calls[0]![0] as {
|
||||
preloadedProfileSummary?: string | null
|
||||
userMessage: string
|
||||
userMessageHidden?: boolean
|
||||
}
|
||||
expect(args.preloadedProfileSummary).toBe('Byggkonsult, K2')
|
||||
expect(args.userMessage).toBe('templated first turn')
|
||||
expect(args.userMessageHidden).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* Tests for GET/POST /api/agent/memory and PATCH /api/agent/memory/[id].
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../memory/route'
|
||||
import { PATCH } from '../memory/[id]/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const idParams = { params: Promise.resolve({ id: 'mem-1' }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await GET(createMockRequest('/api/agent/memory'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an unknown kind filter', async () => {
|
||||
const req = createMockRequest('/api/agent/memory', { searchParams: { kind: 'gossip' } })
|
||||
const { status } = await parseJsonResponse(await GET(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('lists memory entries', async () => {
|
||||
enqueue({ data: [{ id: 'mem-1', kind: 'fact', content: 'Fakturerar i SEK' }] })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
||||
await GET(createMockRequest('/api/agent/memory'), routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/memory', () => {
|
||||
it('rejects a viewer in the target company with 403', async () => {
|
||||
// requireWrite passed for the ACTIVE company, but the body targets a
|
||||
// company where the caller is only a viewer — the re-check must refuse.
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { company_id: '7f3e0b1a-9c4d-4a2b-8f6e-1d2c3b4a5e6f', content: 'Ett minne' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('rejects an invalid body with 400', async () => {
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'x' }, // below min length 2
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('inserts a memory entry for the active company', async () => {
|
||||
enqueue({ data: { role: 'admin' } }) // membership re-check
|
||||
enqueue({ data: { id: 'mem-2', kind: 'fact', content: 'Ett minne' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'Ett minne' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('mem-2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/memory/[id]', () => {
|
||||
it('returns 400 when the body has nothing to update', async () => {
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} })
|
||||
const { status } = await parseJsonResponse(await PATCH(req, idParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the memory row does not exist', async () => {
|
||||
enqueue({ data: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('MEMORY_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('updates a memory entry', async () => {
|
||||
enqueue({ data: { company_id: 'company-1' } }) // row lookup
|
||||
enqueue({ data: { role: 'member' } }) // membership re-check
|
||||
enqueue({ data: { id: 'mem-1', is_pinned: true } }) // update
|
||||
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_pinned: boolean } }>(
|
||||
await PATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_pinned).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/onboarding/stream — auth surface only.
|
||||
*
|
||||
* The composer pipeline itself is exercised via lib tests; here we lock in
|
||||
* the guard order: 401, membership 403, and the viewer refusal (the pipeline
|
||||
* upserts agent_profiles, so viewers must not be able to trigger it).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: vi.fn().mockResolvedValue({ ok: true }),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
|
||||
// Pipeline internals — never reached in these tests, stubbed so the module loads.
|
||||
vi.mock('@/lib/agent/composer/inputs', () => ({
|
||||
gatherComposerInputs: vi.fn(),
|
||||
inputsToSourceSignals: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/atom-selection', () => ({
|
||||
selectAtoms: vi.fn(),
|
||||
filterRedundantQuestions: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/narrative', () => ({ writeNarrative: vi.fn() }))
|
||||
vi.mock('@/lib/agent/composer/fallback', () => ({
|
||||
fallbackAtomSelection: vi.fn(),
|
||||
fallbackNarrative: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/prewarm', () => ({ preWarmAtomCache: vi.fn() }))
|
||||
vi.mock('@/lib/agent/composer/client', () => ({ OPUS_MODEL: 'opus-test' }))
|
||||
vi.mock('@/lib/agent/composer/tic-fetch', () => ({ ensureTicSnapshot: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../onboarding/stream/route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
function mockAuth(userId: string | null, membership: { role: string } | null) {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: userId ? { id: userId } : null } }),
|
||||
},
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/agent/onboarding/stream', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null, null)
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const res = await POST(req)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a non-member', async () => {
|
||||
mockAuth('user-1', null)
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('refuses a viewer with 403 (pipeline upserts agent_profiles)', async () => {
|
||||
mockAuth('user-1', { role: 'viewer' })
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(await POST(req))
|
||||
expect(status).toBe(403)
|
||||
expect(body.error).toContain('läsbehörighet')
|
||||
})
|
||||
})
|
||||
@@ -1,149 +0,0 @@
|
||||
/**
|
||||
* Tests for GET/PATCH /api/agent/profile and POST /api/agent/profile/verify.
|
||||
*
|
||||
* Covers the role model: reads allow any member, mutations (PATCH, verify)
|
||||
* refuse viewers — the same rule verify always had, now enforced on PATCH too.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET, PATCH } from '../profile/route'
|
||||
import { POST as VERIFY } from '../profile/verify/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/profile', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 when the caller is not a member of the target company', async () => {
|
||||
enqueue({ data: null }) // membership lookup
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('NOT_COMPANY_MEMBER')
|
||||
})
|
||||
|
||||
it('returns the profile for a member (viewers may read)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
enqueue({ data: { company_id: 'company-1', profile_summary: 'Konsultbolag' } })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Konsultbolag')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/profile', () => {
|
||||
it('refuses a viewer with 403 (profile mutation)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Nytt sammandrag' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('returns 404 when the company has no agent_profile row', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: null }) // current profile lookup
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Nytt sammandrag' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('AGENT_PROFILE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 400 when the body contains nothing to update', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: { field_overrides: null } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', { method: 'PATCH', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
|
||||
})
|
||||
|
||||
it('merges field_overrides and updates the profile', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: { field_overrides: { old: { value: 1, overridden_at: 'x' } } } })
|
||||
enqueue({ data: { company_id: 'company-1', profile_summary: 'Uppdaterad' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Uppdaterad', field_overrides: { vat_period: 'quarterly' } },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Uppdaterad')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/profile/verify', () => {
|
||||
it('refuses a viewer with 403', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await VERIFY(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('stamps verified_at for a non-viewer member', async () => {
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
enqueue({ data: { company_id: 'company-1', verified_at: '2026-07-03T00:00:00Z', verified_by_user_id: 'user-1' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ data: { verified_by_user_id: string } }>(
|
||||
await VERIFY(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.verified_by_user_id).toBe('user-1')
|
||||
})
|
||||
})
|
||||
@@ -1,224 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const checkRate = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: () => checkRate(),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
const requireCapability = vi.fn()
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
const aiStatus = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
|
||||
const answer = vi.fn()
|
||||
vi.mock('@/lib/agent/ask/ask-service', () => ({ answerAssistantQuestion: (...a: unknown[]) => answer(...a) }))
|
||||
const resolveConv = vi.fn()
|
||||
const loadHistory = vi.fn()
|
||||
const persistUser = vi.fn()
|
||||
const persistAssistant = vi.fn()
|
||||
vi.mock('@/lib/agent/ask/persist', () => ({
|
||||
resolveChatConversation: (...a: unknown[]) => resolveConv(...a),
|
||||
loadChatHistory: (...a: unknown[]) => loadHistory(...a),
|
||||
persistUserTurn: (...a: unknown[]) => persistUser(...a),
|
||||
persistAssistantTurn: (...a: unknown[]) => persistAssistant(...a),
|
||||
}))
|
||||
|
||||
import { POST, maxDuration } from '../route'
|
||||
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
|
||||
|
||||
const membershipChain = { select: () => membershipChain, eq: () => membershipChain, maybeSingle: async () => ({ data: { user_id: 'user-1' } }) }
|
||||
const supabase = { from: () => membershipChain }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRate.mockResolvedValue({ ok: true })
|
||||
requireCapability.mockResolvedValue(null)
|
||||
aiStatus.mockReturnValue({ configured: true, assistantAvailable: false, provider: 'openai-compatible' })
|
||||
answer.mockResolvedValue({ answer: 'Svar', model: 'qwen3.8' })
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-9', created: true })
|
||||
loadHistory.mockResolvedValue([])
|
||||
persistUser.mockResolvedValue(undefined)
|
||||
persistAssistant.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
const body = (o: Record<string, unknown> = {}) => ({ question: 'Hur gick juli?', ...o })
|
||||
|
||||
describe('POST /api/agent/ask', () => {
|
||||
it('declares a 300s function budget so a tool-loop answer is not killed mid-turn', () => {
|
||||
expect(maxDuration).toBe(300)
|
||||
})
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/api/agent/ask', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(429)
|
||||
})
|
||||
it('400 on an empty question', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { question: '' } }))).status).toBe(400)
|
||||
})
|
||||
it('403 when the company lacks the ai capability (paywall)', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
})
|
||||
|
||||
// The key behaviour: this endpoint runs on ANY configured backend, so it is
|
||||
// available even when the streaming chat (assistantAvailable) is not, e.g.
|
||||
// on a local OpenAI-compatible model.
|
||||
it('answers on an openai-compatible backend where the streaming chat would 503', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ context: 'Resultat juli: +12 000' }) }))
|
||||
const { status, body: b } = await parseJsonResponse<{ data: { answer: string; model: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data).toEqual({ answer: 'Svar', model: 'qwen3.8' })
|
||||
expect(answer).toHaveBeenCalledWith(expect.objectContaining({ companyId: 'company-1', question: 'Hur gick juli?', pageContext: 'Resultat juli: +12 000' }))
|
||||
})
|
||||
|
||||
it('503 ai_unconfigured when no backend is configured at all', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
expect(answer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('502s with a Swedish message when the model answers empty (the silent-stop bug)', async () => {
|
||||
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const { status, body: b } = await parseJsonResponse<{ error: string; code: string }>(res)
|
||||
expect(status).toBe(502)
|
||||
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
|
||||
expect(b.code).toBe('empty_model_answer')
|
||||
})
|
||||
|
||||
it('stateless (no persist): never touches the conversation tables', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
expect(resolveConv).not.toHaveBeenCalled()
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
describe('persist: true (chat console)', () => {
|
||||
it('creates/resumes the thread, writes both turns, returns the conversation id', async () => {
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, context_ref: 'report:vat:2026-07' }),
|
||||
}),
|
||||
)
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { answer: string; model: string; conversation_id: string }
|
||||
}>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.conversation_id).toBe('conv-9')
|
||||
expect(b.data.answer).toBe('Svar')
|
||||
// Order matters: resolve → user turn → answer → assistant turn.
|
||||
expect(resolveConv).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
undefined,
|
||||
'Hur gick juli?',
|
||||
'report:vat:2026-07',
|
||||
)
|
||||
expect(persistUser).toHaveBeenCalledWith(supabase, 'conv-9', 'Hur gick juli?')
|
||||
expect(answer).toHaveBeenCalled()
|
||||
expect(persistAssistant).toHaveBeenCalledWith(supabase, 'conv-9', 'Svar')
|
||||
// A thread created by this very request has no earlier turns to load.
|
||||
expect(loadHistory).not.toHaveBeenCalled()
|
||||
expect(answer.mock.calls[0][0].history).toEqual([])
|
||||
})
|
||||
|
||||
it('a resumed thread answers with its earlier turns, read before the new question is written', async () => {
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
|
||||
const history = [
|
||||
{ role: 'user', text: 'Vad är min största utgift?' },
|
||||
{ role: 'assistant', text: '12 345 kr på 5010.' },
|
||||
]
|
||||
const order: string[] = []
|
||||
loadHistory.mockImplementation(async () => {
|
||||
order.push('load')
|
||||
return history
|
||||
})
|
||||
persistUser.mockImplementation(async () => {
|
||||
order.push('persist')
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111', question: 'Och förra månaden?' }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(loadHistory).toHaveBeenCalledWith(supabase, 'conv-7')
|
||||
expect(order).toEqual(['load', 'persist'])
|
||||
expect(answer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ conversationId: 'conv-7', question: 'Och förra månaden?', history }),
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes with a supplied conversation_id', async () => {
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111' }),
|
||||
}),
|
||||
)
|
||||
const { status, body: b } = await parseJsonResponse<{ data: { conversation_id: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.conversation_id).toBe('conv-7')
|
||||
expect(resolveConv).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'11111111-1111-4111-8111-111111111111',
|
||||
'Hur gick juli?',
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
|
||||
it("404s on a conversation that isn't the user's, without answering or persisting", async () => {
|
||||
resolveConv.mockResolvedValue({ ok: false, reason: 'not_found' })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '22222222-2222-4222-8222-222222222222' }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
expect(answer).not.toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('502s on an empty answer, keeps the question, never persists a blank assistant turn', async () => {
|
||||
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
|
||||
const { status, body: b } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(502)
|
||||
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
|
||||
// The user turn is written before the model call (retry keeps the
|
||||
// question), but no empty assistant turn may ever land in the thread.
|
||||
expect(persistUser).toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still 503s (no write) when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
|
||||
expect(res.status).toBe(503)
|
||||
expect(resolveConv).not.toHaveBeenCalled()
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,191 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getAiStatus } from '@/lib/ai'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { answerAssistantQuestion } from '@/lib/agent/ask/ask-service'
|
||||
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
|
||||
import {
|
||||
resolveChatConversation,
|
||||
loadChatHistory,
|
||||
persistUserTurn,
|
||||
persistAssistantTurn,
|
||||
} from '@/lib/agent/ask/persist'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// The assistant answers over the read-only MCP tools, which are registered
|
||||
// into the agent tool registry by the mcp-server extension at load. Without
|
||||
// this the registry is empty and the assistant falls back to snapshot-only,
|
||||
// so a hosted deploy would silently lose its ledger tools.
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('api.agent.ask')
|
||||
|
||||
// A tool-loop answer can take minutes (several model turns, each preceded by
|
||||
// real report reads). The plan default cap would kill the function mid-answer
|
||||
// and the client would see a silent empty stop; 300 s matches the other
|
||||
// long-running model surfaces (app/api/receipt-hunt/run).
|
||||
export const maxDuration = 300
|
||||
|
||||
// The Swedish body AskConsole's !res.ok branch renders verbatim.
|
||||
const EMPTY_ANSWER_MESSAGE = 'Assistenten gav inget svar. Försök igen.'
|
||||
|
||||
/**
|
||||
* POST /api/agent/ask: a single-call, provider-agnostic assistant answer over a
|
||||
* bounded read-only tool loop.
|
||||
*
|
||||
* Unlike POST /api/agent/invoke (the streaming Anthropic chat runtime, which
|
||||
* is gated on `assistantAvailable` and only runs on the Anthropic family),
|
||||
* this endpoint answers through getAiService().generateText, so it runs on ANY
|
||||
* configured backend, including an OpenAI-compatible local model. It is
|
||||
* therefore gated on `configured`, not `assistantAvailable`. The service
|
||||
* attaches the read-only MCP tools so it can fetch real figures (audit Option
|
||||
* A / rip): a page posts its context and a question, gets one answer back.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
question: z.string().min(1).max(4000),
|
||||
context: z.string().max(24_000).optional(),
|
||||
tier: z.enum(['assistant', 'heavy']).optional(),
|
||||
company_id: z.string().uuid().optional(),
|
||||
// Chat-console persistence (opt-in). When `persist` is true, the turn is
|
||||
// written to agent_conversations/agent_messages so the /chat sidebar keeps
|
||||
// working. Page-scoped one-off actions (a report page asking a question)
|
||||
// omit it and stay stateless. `conversation_id` resumes an existing
|
||||
// general.help thread; omitted means "create one". `context_ref` binds a
|
||||
// fresh thread to a page ("report:vat:2026-07") for the context chip.
|
||||
persist: z.boolean().optional(),
|
||||
conversation_id: z.string().uuid().nullable().optional(),
|
||||
context_ref: z.string().max(200).nullable().optional(),
|
||||
})
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig fråga.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
// Distinct from the paywall: no AI backend configured at all. Unlike the
|
||||
// chat loop, ANY provider works here, so we gate on `configured`.
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
// Stateless page-scoped ask: one answer, nothing written.
|
||||
if (parsed.data.persist !== true) {
|
||||
try {
|
||||
const result = await answerAssistantQuestion({
|
||||
supabase,
|
||||
companyId,
|
||||
userId: user.id,
|
||||
question: parsed.data.question,
|
||||
pageContext: parsed.data.context,
|
||||
tier: parsed.data.tier,
|
||||
})
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof EmptyModelAnswerError) {
|
||||
// Already logged with model + usage by ask-service.
|
||||
return NextResponse.json(
|
||||
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
|
||||
{ status: 502 },
|
||||
)
|
||||
}
|
||||
log.error('assistant ask failed', err, { companyId, persist: false })
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// Persisted chat-console turn: resolve/create the thread, write the question,
|
||||
// answer once, write the answer. Resolve BEFORE the model call so a bad
|
||||
// conversation id 404s without spending a request; the user turn is written
|
||||
// before the answer so a mid-call failure still leaves the question in the
|
||||
// thread (the user can retry), matching the streaming runtime's semantics.
|
||||
try {
|
||||
const resolved = await resolveChatConversation(
|
||||
supabase,
|
||||
user.id,
|
||||
companyId,
|
||||
parsed.data.conversation_id,
|
||||
parsed.data.question,
|
||||
parsed.data.context_ref,
|
||||
)
|
||||
if (!resolved.ok) {
|
||||
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
|
||||
}
|
||||
const { conversationId } = resolved
|
||||
|
||||
// A resumed thread carries its earlier turns into the model call; read
|
||||
// them BEFORE the new question is written so it is not sent twice. A
|
||||
// thread created just now has nothing to load.
|
||||
const history = resolved.created ? [] : await loadChatHistory(supabase, conversationId)
|
||||
|
||||
await persistUserTurn(supabase, conversationId, parsed.data.question)
|
||||
|
||||
const result = await answerAssistantQuestion({
|
||||
supabase,
|
||||
companyId,
|
||||
userId: user.id,
|
||||
conversationId,
|
||||
question: parsed.data.question,
|
||||
pageContext: parsed.data.context,
|
||||
tier: parsed.data.tier,
|
||||
history,
|
||||
})
|
||||
|
||||
// answerAssistantQuestion throws EmptyModelAnswerError on an empty answer,
|
||||
// so an empty assistant turn is never persisted: the thread keeps the
|
||||
// question (retryable) but records no blank reply.
|
||||
await persistAssistantTurn(supabase, conversationId, result.answer)
|
||||
|
||||
return NextResponse.json({ data: { ...result, conversation_id: conversationId } })
|
||||
} catch (err) {
|
||||
if (err instanceof EmptyModelAnswerError) {
|
||||
// Already logged with model + usage by ask-service.
|
||||
return NextResponse.json(
|
||||
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
|
||||
{ status: 502 },
|
||||
)
|
||||
}
|
||||
log.error('assistant ask failed', err, { companyId, persist: true })
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const checkRate = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: () => checkRate(),
|
||||
agentRateLimitResponseBody: () => ({ error: 'rate' }),
|
||||
}))
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
const requireCapability = vi.fn()
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
const aiStatus = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
|
||||
const gatherCandidates = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/candidates', () => ({ gatherCandidates: (...a: unknown[]) => gatherCandidates(...a) }))
|
||||
const gatherUnderlag = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/underlag', () => ({ gatherUnderlag: (...a: unknown[]) => gatherUnderlag(...a) }))
|
||||
const selectAccount = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/select-account', () => ({ selectAccount: (...a: unknown[]) => selectAccount(...a) }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
// supabase router: membership + transactions + companies + company_settings.
|
||||
function makeSupabase(opts: { tx?: unknown; member?: boolean } = {}) {
|
||||
return {
|
||||
auth: { getUser: vi.fn() },
|
||||
from(table: string) {
|
||||
const rows: Record<string, unknown> = {
|
||||
company_members: opts.member === false ? null : { user_id: 'user-1' },
|
||||
transactions: opts.tx === undefined ? { id: 'tx-1' } : opts.tx,
|
||||
companies: { entity_type: 'aktiebolag' },
|
||||
company_settings: { vat_registered: true },
|
||||
}
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () => ({ data: rows[table] ?? null }),
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const VALID_TX = '11111111-1111-4111-8111-111111111111'
|
||||
const body = (o: Record<string, unknown> = {}) => ({ transaction_id: VALID_TX, ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRate.mockResolvedValue({ ok: true })
|
||||
requireCapability.mockResolvedValue(null)
|
||||
aiStatus.mockReturnValue({ configured: true })
|
||||
gatherCandidates.mockResolvedValue([{ account: '5410', label: 'Material', vatTreatment: 'standard_25', source: 'counterparty_template', confidence: 0.9 }])
|
||||
gatherUnderlag.mockResolvedValue('Kvitto: Biltema, totalt 499 SEK.')
|
||||
selectAccount.mockResolvedValue({
|
||||
account: '5410', category: null, vatTreatment: 'standard_25', reverseCharge: false,
|
||||
confidence: 0.86, modelConfidence: 'high', agreement: 1, reasoning: 'r',
|
||||
choice: { kind: 'candidate', account: '5410' }, model: 'qwen3.8', fromCandidate: true,
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(401)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('resolves the session through requireAuth (withRouteContext), never a hand-rolled getUser()', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(requireAuthMock).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.auth.getUser).not.toHaveBeenCalled()
|
||||
})
|
||||
it('403 when the body names a company the caller is not a member of', async () => {
|
||||
const other = '22222222-2222-4222-8222-222222222222'
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ member: false }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ company_id: other }) }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(403)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('uses the active company without a membership round trip when no override is given', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(200)
|
||||
expect(gatherCandidates).toHaveBeenCalledWith(expect.anything(), 'company-1', expect.anything())
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(429)
|
||||
})
|
||||
it('400 on a missing/invalid transaction_id', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }), createMockRouteParams({}))).status).toBe(400)
|
||||
})
|
||||
it('403 without the ai capability', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(403)
|
||||
})
|
||||
it('503 when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('404 when the transaction is not found / not this company', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ tx: null }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(404)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('returns the selection + candidate slate on the happy path', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { account: string; confidence: number; candidates: { account: string }[] }
|
||||
}>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.account).toBe('5410')
|
||||
expect(b.data.confidence).toBe(0.86)
|
||||
expect(b.data.candidates[0].account).toBe('5410')
|
||||
// A caller-supplied underlag is used verbatim (no server gather).
|
||||
expect(gatherUnderlag).not.toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'aktiebolag', vatRegistered: true, underlag: 'Biltema AB 499 kr', samples: 3 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('gathers underlag server-side when the caller did not supply it', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(gatherUnderlag).toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ underlag: 'Kvitto: Biltema, totalt 499 SEK.' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,107 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const guardSandbox = vi.fn()
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: () => guardSandbox() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const inserts: Record<string, unknown>[] = []
|
||||
// company_settings.maybeSingle() feeds the consent gate; company_members
|
||||
// feeds the membership check. Default: a member of an opted-in company.
|
||||
function makeSupabase(membership: unknown = { user_id: 'user-1' }, optedIn = true) {
|
||||
return {
|
||||
from(table: string) {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () =>
|
||||
table === 'company_settings'
|
||||
? { data: { data_analysis_opt_in: optedIn }, error: null }
|
||||
: { data: membership, error: null },
|
||||
insert: async (payload: Record<string, unknown>) => {
|
||||
if (table === 'categorize_calibration_samples') inserts.push(payload)
|
||||
return { error: null }
|
||||
},
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const body = (o: Record<string, unknown> = {}) => ({ confidence: 0.9, booked_account: '5410', ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
inserts.length = 0
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
guardSandbox.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize/outcome', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
})
|
||||
|
||||
it('400 on an invalid body', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { confidence: 2 } }))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { booked_account: '5410' } }))).status).toBe(400)
|
||||
})
|
||||
|
||||
it('403 without company membership', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase(null), error: null })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
})
|
||||
|
||||
it('skips sandbox bookings (204, no sample)', async () => {
|
||||
guardSandbox.mockResolvedValue(NextResponse.json({ error: 'sandbox' }, { status: 403 }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips companies that have not opted in to data analysis (204, no sample)', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ user_id: 'user-1' }, false), error: null })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '5410' }) }),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('logs was_correct=true when the proposed account was booked (opted-in company)', async () => {
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ proposed_account: '5410', booked_account: '5410', confidence: 0.86, source: 'counterparty_template', amount: 499 }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(inserts[0]).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
confidence: 0.86,
|
||||
proposed_account: '5410',
|
||||
booked_account: '5410',
|
||||
was_correct: true,
|
||||
source: 'counterparty_template',
|
||||
amount: 499,
|
||||
})
|
||||
})
|
||||
|
||||
it('logs was_correct=false when the user booked a different account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '6110' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
|
||||
it('logs was_correct=false when there was no proposed account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: null, booked_account: '5410' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { isDataAnalysisOptedIn } from '@/lib/company/data-analysis'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
/**
|
||||
* POST /api/agent/categorize/outcome: log one calibration sample.
|
||||
*
|
||||
* Called (fire-and-forget) after a user books an AI proposal: it records the
|
||||
* confidence the model reported and whether the proposed account was the one
|
||||
* actually booked. That corpus is what lib/agent/categorize/calibration.ts
|
||||
* later fits an isotonic calibrator on, so "säker" can be made to mean ~right.
|
||||
*
|
||||
* Telemetry only: it never posts anything and is gated on auth + membership.
|
||||
* Sandbox bookings run on seed data, so they are silently skipped (a 204) to
|
||||
* keep the corpus clean. The corpus is read across companies, so it only
|
||||
* collects from companies that opted in to data analysis
|
||||
* (company_settings.data_analysis_opt_in, #1346): everyone else gets the same
|
||||
* silent 204 and no row.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
confidence: z.number().min(0).max(1),
|
||||
proposed_account: z.string().max(20).nullable().optional(),
|
||||
booked_account: z.string().min(1).max(20),
|
||||
agreement: z.number().min(0).max(1).nullable().optional(),
|
||||
model_confidence: z.enum(['high', 'medium', 'low']).nullable().optional(),
|
||||
source: z.string().max(40).nullable().optional(),
|
||||
amount: z.number().nullable().optional(),
|
||||
})
|
||||
|
||||
const noContent = () => new Response(null, { status: 204 })
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) return NextResponse.json({ error: 'Invalid body' }, { status: 400 })
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return noContent()
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
// Sandbox bookings are seed data: don't pollute the calibration corpus.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return noContent()
|
||||
|
||||
// Consent gate: the corpus is analysed across companies, so a company that
|
||||
// has not opted in contributes nothing (default false, no grandfathering).
|
||||
if (!(await isDataAnalysisOptedIn(supabase, companyId))) return noContent()
|
||||
|
||||
const proposed = parsed.data.proposed_account ?? null
|
||||
|
||||
// Best-effort: a failed telemetry insert must never surface to the user.
|
||||
try {
|
||||
await supabase.from('categorize_calibration_samples').insert({
|
||||
company_id: companyId,
|
||||
confidence: parsed.data.confidence,
|
||||
agreement: parsed.data.agreement ?? null,
|
||||
model_confidence: parsed.data.model_confidence ?? null,
|
||||
source: parsed.data.source ?? null,
|
||||
proposed_account: proposed,
|
||||
booked_account: parsed.data.booked_account,
|
||||
was_correct: proposed !== null && proposed === parsed.data.booked_account,
|
||||
amount: parsed.data.amount ?? null,
|
||||
})
|
||||
} catch {
|
||||
// swallow
|
||||
}
|
||||
|
||||
return noContent()
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseEntityType } from '@/lib/company/entity-type'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getAiStatus } from '@/lib/ai'
|
||||
import { gatherCandidates } from '@/lib/agent/categorize/candidates'
|
||||
import { gatherUnderlag } from '@/lib/agent/categorize/underlag'
|
||||
import { selectAccount } from '@/lib/agent/categorize/select-account'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { EntityType, Transaction } from '@/types'
|
||||
|
||||
/**
|
||||
* POST /api/agent/categorize: a provider-agnostic booking proposal for one
|
||||
* transaction — the auto-booking cascade end to end (Tier 1 retrieval → Tier 2
|
||||
* selector), minus the write.
|
||||
*
|
||||
* It gathers the deterministic candidate accounts (counterparty templates,
|
||||
* rules, history) with NO model call, then has the model SELECT among them
|
||||
* (self-consistency sampled), and returns the proposed account + VAT +
|
||||
* confidence + reasoning + the candidate slate. It never posts anything: the
|
||||
* caller (the transaction row) renders the proposal as an approval card.
|
||||
*
|
||||
* Runs on any configured backend (Bedrock or a local model), so it is gated on
|
||||
* `configured`, not `assistantAvailable` — same as /api/agent/ask.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
transaction_id: z.string().uuid(),
|
||||
company_id: z.string().uuid().optional(),
|
||||
/** Extracted receipt/invoice text, if the caller already has it. */
|
||||
underlag: z.string().max(24_000).optional(),
|
||||
/** Self-consistency samples (default 3). */
|
||||
samples: z.number().int().min(1).max(5).optional(),
|
||||
})
|
||||
|
||||
// withRouteContext enforces auth (MFA on hosted) and resolves the active
|
||||
// company; the body may still name another company the caller belongs to.
|
||||
export const POST = withRouteContext(
|
||||
'agent.categorize',
|
||||
async (request, { user, supabase, companyId: activeCompanyId }) => {
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig förfrågan.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = parsed.data.company_id ?? activeCompanyId
|
||||
|
||||
// The wrapper already guarantees membership of the active company; an
|
||||
// explicit company_id override must be verified the same way.
|
||||
if (companyId !== activeCompanyId) {
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data: tx } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business, document_id')
|
||||
.eq('id', parsed.data.transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
|
||||
|
||||
const [{ data: company }, { data: settings }] = await Promise.all([
|
||||
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
|
||||
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
|
||||
])
|
||||
|
||||
try {
|
||||
// Gather the matched receipt/invoice text when the caller didn't supply it:
|
||||
// this is what lifts the cold-start case — the model reads the actual
|
||||
// supplier + line items, not just the bank line. Best-effort; '' if none.
|
||||
const underlag =
|
||||
parsed.data.underlag ??
|
||||
(await gatherUnderlag(
|
||||
supabase,
|
||||
companyId,
|
||||
(tx as Transaction).id,
|
||||
(tx as { document_id?: string | null }).document_id,
|
||||
))
|
||||
|
||||
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
|
||||
const selection = await selectAccount({
|
||||
transaction: {
|
||||
merchantName: (tx as Transaction).merchant_name,
|
||||
description: (tx as Transaction).description,
|
||||
amount: (tx as Transaction).amount,
|
||||
date: (tx as Transaction).date,
|
||||
currency: (tx as Transaction).currency,
|
||||
},
|
||||
underlag,
|
||||
candidates,
|
||||
entityType: parseEntityType(company?.entity_type),
|
||||
vatRegistered: settings?.vat_registered ?? false,
|
||||
samples: parsed.data.samples,
|
||||
})
|
||||
return NextResponse.json({ data: { ...selection, candidates } })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,103 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { composeAgentProfile } from '@/lib/agent/composer'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
const BodySchema = z.object({
|
||||
// Optional override; if absent we use the user's active_company_id.
|
||||
company_id: z.string().uuid().optional(),
|
||||
// dry_run=true returns the composed profile without writing to agent_profiles.
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
|
||||
// POST /api/agent/composer
|
||||
//
|
||||
// Runs the specialized accountant composer pipeline for a company:
|
||||
// 1. Gathers TIC snapshot, optional SIE summary, optional banking summary.
|
||||
// 2. Calls Opus 4.7 to select horizontal/vertical/modifier atoms.
|
||||
// 3. Calls Sonnet 4.6 to write the Swedish profile_summary.
|
||||
// 4. Persists to agent_profiles (skipped on dry_run).
|
||||
// 5. Fires fire-and-forget cache pre-warm.
|
||||
//
|
||||
// Auth: must be a non-viewer member of the target company (it rewrites the
|
||||
// company's agent_profile unless dry_run).
|
||||
//
|
||||
// Plan ref: dev_docs/specialized-agent-plan.md §6.
|
||||
export const POST = withRouteContext('agent.composer.run', async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user } = ctx
|
||||
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) {
|
||||
return NextResponse.json(agentRateLimitResponseBody(rate), {
|
||||
status: 429,
|
||||
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// Tolerant parse: ops callers POST with an empty body, which is valid here.
|
||||
const raw = await request.json().catch(() => ({}))
|
||||
const parsed = BodySchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation failed',
|
||||
type: 'validation_error',
|
||||
errors: parsed.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
code: issue.code,
|
||||
})),
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const body = parsed.data
|
||||
|
||||
const companyId = body.company_id ?? activeCompanyId
|
||||
|
||||
// Defense in depth alongside RLS: confirm membership before composing, and
|
||||
// require a non-viewer role: the composer rewrites agent_profiles.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOT_COMPANY_MEMBER',
|
||||
message: 'Du är inte medlem i detta företag.',
|
||||
message_en: 'Not a member of this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
if (membership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'WRITE_PERMISSION_REQUIRED',
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
const composed = await composeAgentProfile(supabase, companyId, { dryRun: body.dry_run })
|
||||
return NextResponse.json({ data: composed })
|
||||
})
|
||||
@@ -1,61 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: (...a: unknown[]) => requireAuthMock(...a) }))
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
vi.mock('@/lib/auth/require-write', () => ({ requireWritePermission: vi.fn().mockResolvedValue({ ok: true }) }))
|
||||
const rejectPending = vi.fn()
|
||||
vi.mock('@/lib/agent/pending/reject-conversation-pending', () => ({
|
||||
rejectPendingForConversation: (...a: unknown[]) => rejectPending(...a),
|
||||
}))
|
||||
|
||||
import { POST } from '../reject-pending/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'conv-1' })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
|
||||
rejectPending.mockResolvedValue(3)
|
||||
})
|
||||
|
||||
describe('POST /api/agent/conversations/[id]/reject-pending', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase: mockSupabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect((await parseJsonResponse(res)).status).toBe(401)
|
||||
})
|
||||
|
||||
it('404 when the conversation is not the caller’s', async () => {
|
||||
enqueue({ data: null }) // conversation ownership lookup misses
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect(res.status).toBe(404)
|
||||
expect(rejectPending).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404 when the caller is no longer a member of the company', async () => {
|
||||
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } }) // owns it
|
||||
enqueue({ data: null }) // membership lookup misses
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect(res.status).toBe(404)
|
||||
expect(rejectPending).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears the conversation’s pending proposals and returns the count', async () => {
|
||||
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } })
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { cleared: number } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.cleared).toBe(3)
|
||||
expect(rejectPending).toHaveBeenCalledWith(mockSupabase, 'company-1', 'conv-1')
|
||||
})
|
||||
})
|
||||
@@ -1,50 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
|
||||
|
||||
// POST /api/agent/conversations/[id]/reject-pending
|
||||
//
|
||||
// Rejects every still-pending proposal the assistant staged in this
|
||||
// conversation — the chat's "clear the proposals I didn't approve" action, so
|
||||
// users don't have to reject leftovers one by one in Granskning.
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.conversations.reject_pending',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user } = ctx
|
||||
|
||||
// Conversations are user-scoped: prove ownership before touching its rows.
|
||||
const { data: conv } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, company_id, user_id')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!conv) return notFound()
|
||||
|
||||
// Defense in depth alongside RLS: still a member of the conversation's company.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const cleared = await rejectPendingForConversation(supabase, conv.company_id as string, id)
|
||||
return NextResponse.json({ data: { cleared } })
|
||||
},
|
||||
)
|
||||
@@ -1,165 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
|
||||
|
||||
// GET /api/agent/conversations/[id]
|
||||
//
|
||||
// Returns one conversation + its messages in chronological order. The chat
|
||||
// page hydrates with this on mount; the agent loop then continues via
|
||||
// /api/agent/invoke with the conversation_id.
|
||||
//
|
||||
// PATCH /api/agent/conversations/[id]
|
||||
//
|
||||
// Updates pin/archive state or title. The chat list relies on these.
|
||||
|
||||
const PatchSchema = z.object({
|
||||
pinned: z.boolean().nullable().optional(),
|
||||
archived: z.boolean().nullable().optional(),
|
||||
title: z.string().min(1).max(200).nullable().optional(),
|
||||
})
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'agent.conversations.get',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user } = ctx
|
||||
|
||||
// Conversations are user-scoped: fetched by ownership rather than the
|
||||
// active company, so a user can open their own conversations in any
|
||||
// company they belong to.
|
||||
const { data: conv, error: convErr } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select(
|
||||
'id, company_id, user_id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at',
|
||||
)
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (convErr) throw convErr
|
||||
if (!conv) return notFound()
|
||||
|
||||
// Defense in depth alongside RLS: the caller must still be a member of
|
||||
// the conversation's company (they may have been removed since).
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const { data: messages, error: msgErr } = await supabase
|
||||
.from('agent_messages')
|
||||
.select('id, role, content, tool_use_id, hidden, created_at')
|
||||
.eq('conversation_id', id)
|
||||
.order('created_at', { ascending: true })
|
||||
if (msgErr) throw msgErr
|
||||
|
||||
// Proposals this conversation staged that nobody has answered yet.
|
||||
//
|
||||
// Approval cards ride on the streamed `staged_operation` events, which are
|
||||
// not persisted, so a resumed thread rendered the tool trace and the answer
|
||||
// but silently dropped the card: the proposal then sat in Granskning for
|
||||
// its full 30 days with nothing in the conversation pointing at it.
|
||||
// run-turn stamps agent_metadata.conversation_id on every staged row, so
|
||||
// the still-open ones can be re-attached here.
|
||||
const { data: staged, error: stagedErr } = await supabase
|
||||
.from('pending_operations')
|
||||
.select('id, operation_type, title, risk_level, preview_data, created_at')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('status', 'pending')
|
||||
.eq('agent_metadata->>conversation_id', id)
|
||||
.order('created_at', { ascending: true })
|
||||
// Do not swallow this: silently returning an empty list would drop the very
|
||||
// proposals this query exists to restore, and the thread would look like it
|
||||
// never staged anything. Same handling as the message query above.
|
||||
if (stagedErr) throw stagedErr
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
conversation: conv,
|
||||
messages: messages ?? [],
|
||||
staged_operations: staged ?? [],
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'agent.conversations.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchSchema, {
|
||||
log,
|
||||
operation: 'agent.conversations.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.pinned != null) update.pinned = body.pinned
|
||||
if (body.archived != null) update.archived = body.archived
|
||||
if (body.title != null) update.title = body.title
|
||||
if (Object.keys(update).length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOTHING_TO_UPDATE',
|
||||
message: 'Inget att uppdatera.',
|
||||
message_en: 'Nothing to update.',
|
||||
},
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Defense in depth: verify ownership before update so a 404 is returned
|
||||
// (instead of relying solely on RLS, which would silently 0-row).
|
||||
const { data: existing } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('user_id, company_id')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!existing) return notFound()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_conversations')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.eq('company_id', existing.company_id)
|
||||
.select('id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at')
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
// Archiving a thread means "I'm done with it": clear any proposals the
|
||||
// assistant staged here that the user never acted on, so they don't linger
|
||||
// in Granskning. Best-effort — a failure here must not fail the archive.
|
||||
if (body.archived === true) {
|
||||
try {
|
||||
await rejectPendingForConversation(supabase, existing.company_id as string, id)
|
||||
} catch {
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
)
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* GET /api/agent/conversations/[id] returns the conversation's still-open
|
||||
* proposals alongside its messages.
|
||||
*
|
||||
* Approval cards live in streamed events that are never persisted, so without
|
||||
* these rows a resumed thread renders the tool trace and the answer but drops
|
||||
* the card, and the proposal waits out its 30-day expiry in Granskning with
|
||||
* nothing in the conversation pointing at it.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, enqueueMany, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { GET } from '../[id]/route'
|
||||
|
||||
const CONV = { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', intent_id: 'general.help' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
expect((await parseJsonResponse(res)).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 for a conversation the caller does not own', async () => {
|
||||
enqueue({ data: null }) // conversation lookup filters on user_id
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
expect((await parseJsonResponse(res)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns unanswered proposals alongside the messages', async () => {
|
||||
enqueueMany([
|
||||
{ data: CONV }, // conversation
|
||||
{ data: { role: 'owner' } }, // company_members
|
||||
{ data: [{ role: 'assistant', content: [] }] }, // agent_messages
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'op-1',
|
||||
operation_type: 'gnubok_categorize_transaction',
|
||||
title: 'Kontering: Circle K',
|
||||
risk_level: 'low',
|
||||
preview_data: {},
|
||||
},
|
||||
],
|
||||
}, // pending_operations
|
||||
])
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { staged_operations: { id: string }[]; messages: unknown[] }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.messages).toHaveLength(1)
|
||||
expect(body.data.staged_operations).toHaveLength(1)
|
||||
expect(body.data.staged_operations[0]!.id).toBe('op-1')
|
||||
})
|
||||
|
||||
it('returns an empty list rather than failing when nothing is staged', async () => {
|
||||
enqueueMany([
|
||||
{ data: CONV },
|
||||
{ data: { role: 'owner' } },
|
||||
{ data: [] },
|
||||
{ data: null }, // no rows at all
|
||||
])
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { staged_operations: unknown[] }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.staged_operations).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,71 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/conversations
|
||||
//
|
||||
// Query params:
|
||||
// archived: 'true' | 'false' (default 'false')
|
||||
// pinned: 'true' filters to pinned only
|
||||
// intent: 'general.help' (or any intent id), filter
|
||||
// q: case-insensitive substring match on title/context_ref
|
||||
// limit: 1..200, default 50
|
||||
//
|
||||
// Returns: { data: [{ id, intent_id, context_ref, title, pinned, archived,
|
||||
// last_message_at, created_at }] }
|
||||
//
|
||||
// Ordered: pinned first (within archived bucket), then last_message_at desc.
|
||||
// Used by the /chat sidebar and "resume conversation" UI in the sheet.
|
||||
|
||||
const ListQuerySchema = z.object({
|
||||
archived: z.enum(['true', 'false']).default('false'),
|
||||
pinned: z.enum(['true', 'false']).optional(),
|
||||
intent: z.string().min(1).optional(),
|
||||
q: z.string().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).default(50),
|
||||
})
|
||||
|
||||
export const GET = withRouteContext('agent.conversations.list', async (request, ctx) => {
|
||||
const { supabase, companyId, user, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, ListQuerySchema, {
|
||||
log,
|
||||
operation: 'agent.conversations.list',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const { archived, pinned, intent, limit } = validated.data
|
||||
const q = validated.data.q?.trim() ?? ''
|
||||
|
||||
let query = supabase
|
||||
.from('agent_conversations')
|
||||
.select(
|
||||
'id, intent_id, context_ref, title, pinned, archived, last_message_at, last_message_preview, created_at',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
// Conversations are user-scoped within a company — one member must not
|
||||
// see another's (see [id]/route.ts). The RLS policy is company-scoped,
|
||||
// so this filter is what actually prevents cross-member leakage of
|
||||
// titles and last_message_preview snippets.
|
||||
.eq('user_id', user.id)
|
||||
.eq('archived', archived === 'true')
|
||||
|
||||
if (pinned === 'true') query = query.eq('pinned', true)
|
||||
if (intent) query = query.eq('intent_id', intent)
|
||||
if (q.length > 0) {
|
||||
// Pattern is sanitized via Postgres' percent-handling; ilike accepts the
|
||||
// % wildcard and we only inject the user's substring between them.
|
||||
const safe = q.replace(/[%_]/g, (m) => `\\${m}`)
|
||||
query = query.or(`title.ilike.%${safe}%,context_ref.ilike.%${safe}%`)
|
||||
}
|
||||
|
||||
// Sort: pinned first, then most recent message.
|
||||
query = query
|
||||
.order('pinned', { ascending: false })
|
||||
.order('last_message_at', { ascending: false, nullsFirst: false })
|
||||
.limit(limit)
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) throw error
|
||||
return NextResponse.json({ data: data ?? [] })
|
||||
})
|
||||
@@ -1,108 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
// The event bus is a module-level singleton and extension handlers are wired
|
||||
// by this call. Without it at module level the emit below goes nowhere and the
|
||||
// vote is silently dropped, which is exactly the failure this route exists to
|
||||
// fix.
|
||||
ensureInitialized()
|
||||
|
||||
// POST /api/agent/feedback
|
||||
//
|
||||
// A thumbs-up or thumbs-down on one assistant answer.
|
||||
//
|
||||
// The buttons have existed since the message-actions pass but were wired to
|
||||
// nothing: they animated, and the vote died in component state. An affordance
|
||||
// that looks like it reports something and does not is worse than no
|
||||
// affordance, because it spends the user's goodwill once and silently.
|
||||
//
|
||||
// This emits the SAME `agent.feedback` event the gnubok_feedback MCP tool
|
||||
// emits, with actorType 'user'. The product team already queries event_log for
|
||||
// that type, so votes from the chat land in the existing triage flow rather
|
||||
// than in a second place someone has to remember to look at. That is also why
|
||||
// there is no migration here: event_log takes the payload as jsonb and already
|
||||
// treats agent.* as telemetry with the longer retention.
|
||||
|
||||
const BodySchema = z.object({
|
||||
conversation_id: z.string().uuid(),
|
||||
sentiment: z.enum(['positive', 'negative']),
|
||||
// Which answer, so a vote can be traced to the turn it was about.
|
||||
message_index: z.number().int().min(0).optional(),
|
||||
})
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.feedback.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, BodySchema, {
|
||||
log,
|
||||
operation: 'agent.feedback.create',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// The conversation id comes from the client, so it is checked the same way
|
||||
// /api/agent/invoke checks it: without this, any member could attach
|
||||
// feedback to another member's thread, and the triage backlog would carry
|
||||
// rows whose conversation the reporter never saw.
|
||||
const { data: conversation } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, user_id, company_id, intent_id')
|
||||
.eq('id', body.conversation_id)
|
||||
.maybeSingle()
|
||||
|
||||
if (
|
||||
!conversation ||
|
||||
conversation.user_id !== user.id ||
|
||||
conversation.company_id !== companyId
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'agent.feedback',
|
||||
payload: {
|
||||
// Deliberately NOT free text. A comment box here would put whatever
|
||||
// the user typed, in an accounting product, verbatim into event_log
|
||||
// under telemetry retention: names, personnummer, client details. The
|
||||
// vote carries only what it needs to be actionable, which is the intent
|
||||
// and which answer it was about. If a comment field is ever wanted, it
|
||||
// needs its own data-classification and redaction decision first, made
|
||||
// with the UI in front of it rather than as an unused parameter.
|
||||
context: [
|
||||
`Chattbetyg på svar i ${conversation.intent_id}.`,
|
||||
body.message_index === undefined ? null : `(svar #${body.message_index})`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
sentiment: body.sentiment,
|
||||
suggestion: null,
|
||||
toolName: null,
|
||||
skillSlug: null,
|
||||
sessionId: conversation.id,
|
||||
actorType: 'user',
|
||||
actorId: user.id,
|
||||
actorLabel: null,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: { recorded: true } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,370 +0,0 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getIntent } from '@/lib/agent/intents/registry'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { runChatTurn, friendlyModelError } from '@/lib/agent/chat/run-turn'
|
||||
import { getAiStatus } from '@/lib/ai'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// Make sure extensions are loaded: the chat loop dispatches against the
|
||||
// agent tool registry which is populated by the mcp-server extension at load.
|
||||
ensureInitialized()
|
||||
|
||||
// Deep turns (thinking at high/xhigh effort, up to 12 tool iterations, a
|
||||
// 15-27k-token prompt prefix) can outlive the plan default duration cap; a
|
||||
// function killed mid-stream closes the NDJSON stream cleanly, which the chat
|
||||
// used to render as silent success. 300 s matches the other long-running model
|
||||
// surfaces (app/api/receipt-hunt/run, app/api/agent/ask).
|
||||
export const maxDuration = 300
|
||||
|
||||
// Hard cap on the per-turn user input. Generous for a chat composer (about
|
||||
// 5k words / 20 pages) but bounds Bedrock token cost if the rate limiter is
|
||||
// ever fail-open and a client floods large payloads.
|
||||
const MAX_USER_MESSAGE_LEN = 20_000
|
||||
|
||||
const BodySchema = z.object({
|
||||
intent_id: z.string().min(1).max(200),
|
||||
// Existing conversation to resume; if omitted, the route creates one. The
|
||||
// chat sheet's React state holds the conversation id as `string | null`
|
||||
// and serializes `null` on the first turn, so accept null alongside
|
||||
// undefined and treat both as "no existing conversation".
|
||||
conversation_id: z.string().uuid().nullable().optional(),
|
||||
// Optional company override; defaults to active_company_id.
|
||||
company_id: z.string().uuid().nullable().optional(),
|
||||
// The user's message (or, on the first turn, this is empty and we send the
|
||||
// intent's prompt template instead). Capped to bound LLM cost.
|
||||
user_message: z.string().max(MAX_USER_MESSAGE_LEN).nullable().optional(),
|
||||
// Intent-specific capture args (e.g. { transaction_id: '...' } for
|
||||
// transaction.categorization). Used only on the first turn to build the
|
||||
// prompt template. Each value is bounded so capture inputs can't be a
|
||||
// megabyte each; the dispatcher rejects oversize values upfront.
|
||||
intent_args: z
|
||||
.record(z.string().max(120), z.unknown())
|
||||
.nullable()
|
||||
.optional()
|
||||
.refine(
|
||||
(v) => {
|
||||
if (!v) return true
|
||||
try {
|
||||
return JSON.stringify(v).length <= MAX_USER_MESSAGE_LEN
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
{ message: 'intent_args too large' },
|
||||
),
|
||||
// Optional context_ref for the conversation row, e.g. 'transaction:<id>'.
|
||||
context_ref: z.string().max(200).nullable().optional(),
|
||||
// When true (and user_message is provided), persist the turn but flag it
|
||||
// hidden so it doesn't render as a user bubble on resume. Used by the chat's
|
||||
// rejection-correction flow (ApprovalCard → AgentChat) to feed the agent a
|
||||
// synthetic correction without showing it as something the user typed.
|
||||
user_message_hidden: z.boolean().nullable().optional(),
|
||||
})
|
||||
|
||||
// POST /api/agent/invoke
|
||||
//
|
||||
// Streams NDJSON events from the chat loop. Each line is a JSON object whose
|
||||
// `kind` identifies the event type: see lib/agent/chat/run-turn.ts StreamEvent.
|
||||
//
|
||||
// Auth: the user must be a member of the resolved company.
|
||||
//
|
||||
// Plan ref: dev_docs/specialized-agent-plan.md §9 (chat loop).
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
// Generous per-user rate limit: bounds runaway Bedrock spend (loop-firing
|
||||
// sessions). Fails open on infra error.
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) {
|
||||
return NextResponse.json(agentRateLimitResponseBody(rate), {
|
||||
status: 429,
|
||||
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
let body: z.infer<typeof BodySchema>
|
||||
try {
|
||||
body = BodySchema.parse(await request.json())
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Invalid body' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const intent = getIntent(body.intent_id)
|
||||
if (!intent) {
|
||||
return NextResponse.json({ error: `Unknown intent: ${body.intent_id}` }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = body.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
// No Anthropic Bedrock calls in the sandbox: the demo runs entirely on
|
||||
// seed data and the assistant is gated to a "look, don't touch" preview.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
// Distinct from the paywall: the deployment has no AI backend the chat
|
||||
// loop can run on (no credentials, or an OpenAI-compatible endpoint, which
|
||||
// the loop does not speak yet). Answer up front instead of opening a
|
||||
// stream that dies on the first model call.
|
||||
if (!getAiStatus().assistantAvailable) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Assistenten är inte konfigurerad på den här installationen.',
|
||||
code: 'ai_unconfigured',
|
||||
},
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve the conversation BEFORE any side effect below (the onboarding
|
||||
// intake stamp): a request that is about to be rejected must not write.
|
||||
let conversationId = body.conversation_id ?? null
|
||||
if (conversationId) {
|
||||
// A resumed conversation id comes straight from the client, so ownership
|
||||
// has to be proven here. RLS on agent_conversations/agent_messages is
|
||||
// COMPANY-scoped (migration 20260517204000), not user-scoped, so RLS alone
|
||||
// would happily load a colleague's thread into the prompt and append this
|
||||
// user's turns to it. The conversations list route filters on user_id for
|
||||
// exactly this reason; the same rule applies to the turn itself.
|
||||
//
|
||||
// The company check matters too: a user who belongs to several companies
|
||||
// must not resume a thread from company B while the turn runs with company
|
||||
// A's ledger, tools and staged operations.
|
||||
const { data: conv } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, user_id, company_id, intent_id')
|
||||
.eq('id', conversationId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!conv || conv.user_id !== user.id || conv.company_id !== companyId) {
|
||||
// Same response for "doesn't exist" and "isn't yours": a 403 here would
|
||||
// confirm that someone else's conversation id is real.
|
||||
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
|
||||
}
|
||||
|
||||
// The intent decides the tool loadout and the system prompt. Letting a
|
||||
// resumed thread switch intent mid-conversation would swap the tool
|
||||
// whitelist under history the model has already been shown.
|
||||
if (conv.intent_id !== body.intent_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Konversationen hör till ett annat sammanhang.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// onboarding.intake completion signal: once the user has actually
|
||||
// engaged (typed a real reply, not the auto-fired greeting prompt that
|
||||
// mounts the chat), stamp intake_completed_at on the profile so re-entry
|
||||
// logic and opportunistic follow-up logic in other intents can tell the
|
||||
// intake happened. Idempotent: the IS NULL guard ensures we never
|
||||
// overwrite the first engagement timestamp. Best-effort: failure here
|
||||
// doesn't break the chat; the next user turn retries.
|
||||
if (
|
||||
body.intent_id === 'onboarding.intake' &&
|
||||
typeof body.user_message === 'string' &&
|
||||
body.user_message.trim().length > 0 &&
|
||||
body.user_message_hidden !== true
|
||||
) {
|
||||
try {
|
||||
await supabase
|
||||
.from('agent_profiles')
|
||||
.update({ intake_completed_at: new Date().toISOString() })
|
||||
.eq('company_id', companyId)
|
||||
.is('intake_completed_at', null)
|
||||
} catch {
|
||||
// ignored: see comment above
|
||||
}
|
||||
}
|
||||
|
||||
// Load lightweight company + user signals for the system prompt.
|
||||
const [{ data: company }, { data: profile }] = await Promise.all([
|
||||
supabase.from('companies').select('name').eq('id', companyId).single(),
|
||||
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
|
||||
])
|
||||
const companyName = company?.name ?? ''
|
||||
const firstName = profile?.full_name?.split(' ')[0] ?? null
|
||||
|
||||
// Create the conversation row when this is a fresh thread.
|
||||
if (!conversationId) {
|
||||
const { data: newConv, error: convErr } = await supabase
|
||||
.from('agent_conversations')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
user_id: user.id,
|
||||
intent_id: body.intent_id,
|
||||
context_ref: body.context_ref ?? null,
|
||||
title: intent.sheetTitle,
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
if (convErr || !newConv) {
|
||||
return NextResponse.json(
|
||||
{ error: getUserErrorMessage(convErr) ?? 'Failed to create conversation' },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
conversationId = newConv.id as string
|
||||
}
|
||||
|
||||
// Compute the user message to send to Anthropic. On the first turn (no
|
||||
// user_message provided), we run the intent's capture + promptTemplate
|
||||
// pipeline so the prompt is anchored on the page context the user
|
||||
// clicked from.
|
||||
let effectiveUserMessage = body.user_message ?? ''
|
||||
// When the caller didn't supply a user_message, we synthesize one from the
|
||||
// intent's promptTemplate. Mark that synthetic turn hidden so the UI
|
||||
// doesn't render the template scaffolding as a user bubble on resume. The
|
||||
// client can also explicitly request a hidden turn (rejection correction)
|
||||
// even when it DID supply a user_message.
|
||||
let userMessageHidden = body.user_message_hidden === true
|
||||
// Set on a first turn, where the prompt template needs it anyway; handed to
|
||||
// runChatTurn so the system prompt reuses it instead of re-reading.
|
||||
let preloadedProfileSummary: string | null | undefined
|
||||
if (!effectiveUserMessage) {
|
||||
try {
|
||||
const captured = await intent.capture(body.intent_args ?? {}, {
|
||||
supabase,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
})
|
||||
const [profileSummary, memory] = await Promise.all([
|
||||
loadProfileSummary(supabase, companyId),
|
||||
loadRankedMemory(supabase, companyId, 30),
|
||||
])
|
||||
effectiveUserMessage = intent.promptTemplate({
|
||||
captured,
|
||||
profileSummary,
|
||||
activeMemory: memory,
|
||||
})
|
||||
// Hand it to the turn so it doesn't re-read it for the system prompt.
|
||||
preloadedProfileSummary = profileSummary
|
||||
userMessageHidden = true
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
err instanceof Error
|
||||
? `Capture failed: ${getUserErrorMessage(err)}`
|
||||
: 'Capture failed',
|
||||
},
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Stream: NDJSON events from the chat loop.
|
||||
const encoder = new TextEncoder()
|
||||
// Conversation id is set above; capture into a non-null local for the
|
||||
// streaming closure's first emission.
|
||||
const convId: string = conversationId
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const emit = (event: unknown): boolean => {
|
||||
try {
|
||||
controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Surface the conversation id so the client can resume with it.
|
||||
emit({ kind: 'conversation', conversation_id: convId })
|
||||
|
||||
try {
|
||||
await runChatTurn({
|
||||
supabase,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
companyName,
|
||||
firstName,
|
||||
intent,
|
||||
conversationId: convId,
|
||||
userMessage: effectiveUserMessage,
|
||||
userMessageHidden,
|
||||
persist: true,
|
||||
preloadedProfileSummary,
|
||||
emit: (event) => emit(event),
|
||||
})
|
||||
} catch (err) {
|
||||
// run-turn already emitted a friendly error before re-throwing; emit a
|
||||
// normalized one here too so this outer catch never overwrites it with a
|
||||
// raw AWS SDK string.
|
||||
emit({
|
||||
kind: 'error',
|
||||
message: friendlyModelError(err),
|
||||
})
|
||||
} finally {
|
||||
try {
|
||||
controller.close()
|
||||
} catch {
|
||||
// Already closed
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function loadProfileSummary(
|
||||
supabase: Awaited<ReturnType<typeof createClient>>,
|
||||
companyId: string,
|
||||
): Promise<string | null> {
|
||||
const { data } = await supabase
|
||||
.from('agent_profiles')
|
||||
.select('profile_summary')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
return (data?.profile_summary as string | null) ?? null
|
||||
}
|
||||
|
||||
async function loadRankedMemory(
|
||||
supabase: Awaited<ReturnType<typeof createClient>>,
|
||||
companyId: string,
|
||||
cap: number,
|
||||
): Promise<{ content: string; kind: string }[]> {
|
||||
const { data } = await supabase
|
||||
.from('agent_memory')
|
||||
.select('content, kind, relevance_score, last_accessed_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.order('relevance_score', { ascending: false })
|
||||
.order('last_accessed_at', { ascending: false, nullsFirst: false })
|
||||
.limit(cap)
|
||||
return (data ?? []).map((r: { content: string; kind: string }) => ({
|
||||
content: r.content,
|
||||
kind: r.kind,
|
||||
}))
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/agent/knowledge (the "Vad din agent vet" data source for
|
||||
* the Kunskap tab in the assistant settings hub). Exercises the route through
|
||||
* the real withRouteContext wrapper, mocking auth/company and the three
|
||||
* ledger-context builders. Covers auth 401, no-company 400, and the happy path
|
||||
* aggregation shape.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
const getCompanyDisplayNameMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
getCompanyDisplayName: (...args: unknown[]) => getCompanyDisplayNameMock(...args),
|
||||
}))
|
||||
|
||||
const buildLedgerContextMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/ledger-context', () => ({
|
||||
buildLedgerContext: (...args: unknown[]) => buildLedgerContextMock(...args),
|
||||
}))
|
||||
|
||||
const buildDeepEntitiesMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/ledger-deep', () => ({
|
||||
buildDeepEntities: (...args: unknown[]) => buildDeepEntitiesMock(...args),
|
||||
}))
|
||||
|
||||
const buildAgentCompetenceMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/agent-competence', () => ({
|
||||
buildAgentCompetence: (...args: unknown[]) => buildAgentCompetenceMock(...args),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
describe('GET /api/agent/knowledge', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
getCompanyDisplayNameMock.mockResolvedValue('Acme AB')
|
||||
buildLedgerContextMock.mockResolvedValue({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
|
||||
buildDeepEntitiesMock.mockResolvedValue({ counterparty_entities: [], supplier_entities: [] })
|
||||
buildAgentCompetenceMock.mockResolvedValue({ atoms: [], facts: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when there is no active company', async () => {
|
||||
getActiveCompanyIdMock.mockResolvedValue(null)
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('aggregates the ledger context, deep entities, competence and company name', async () => {
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { context: unknown; deep: unknown; competence: unknown; companyName: string }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.companyName).toBe('Acme AB')
|
||||
expect(body.data.context).toEqual({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
|
||||
expect(body.data.deep).toEqual({ counterparty_entities: [], supplier_entities: [] })
|
||||
expect(body.data.competence).toEqual({ atoms: [], facts: [] })
|
||||
// each builder was called with the resolved supabase + companyId
|
||||
expect(buildLedgerContextMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
expect(buildDeepEntitiesMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
expect(buildAgentCompetenceMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
})
|
||||
})
|
||||
@@ -1,30 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getCompanyDisplayName } from '@/lib/company/context'
|
||||
import { buildLedgerContext } from '@/lib/agent-context/ledger-context'
|
||||
import { buildDeepEntities } from '@/lib/agent-context/ledger-deep'
|
||||
import { buildAgentCompetence } from '@/lib/agent-context/agent-competence'
|
||||
|
||||
// GET /api/agent/knowledge
|
||||
//
|
||||
// Read-only transparency surface for "Vad din agent vet": the exact ledger
|
||||
// context the AI agent reads before booking, plus the deep entity-resolved
|
||||
// profile and the agent's competence. Powers the Kunskap tab in the assistant
|
||||
// settings hub (client-fetched so it renders identically in the full-page
|
||||
// settings rail and the routed settings modal, which both mount the same
|
||||
// propless content component). Derived per request from live bookings; never
|
||||
// cached, so a fixed profile can't go stale.
|
||||
export const GET = withRouteContext('agent.knowledge.get', async (_request, ctx) => {
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const [context, deep, competence, companyName] = await Promise.all([
|
||||
buildLedgerContext(supabase, companyId),
|
||||
buildDeepEntities(supabase, companyId),
|
||||
buildAgentCompetence(supabase, companyId),
|
||||
getCompanyDisplayName(supabase, companyId),
|
||||
])
|
||||
|
||||
return NextResponse.json({
|
||||
data: { context, deep, competence, companyName: companyName ?? '' },
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
|
||||
// PATCH /api/agent/memory/[id]
|
||||
//
|
||||
// Mutate a single memory entry. Powers the list/edit/pin/dismiss affordances
|
||||
// on /settings/agent-memory (plan §11).
|
||||
//
|
||||
// content: edit the durable text (kind never changes; that would
|
||||
// muddle the audit lineage). Append-only is preserved by
|
||||
// superseded_by chains when an upstream caller wants it; the
|
||||
// transparency UI is allowed to overwrite in place because
|
||||
// the row's `updated_at` already documents the edit.
|
||||
// is_pinned: boost into the top-N prompt block regardless of score.
|
||||
// is_active: false = dismiss (removes from ranking pool); true = restore.
|
||||
//
|
||||
// RLS scopes to user_company_ids(); we ALSO re-verify membership for the
|
||||
// row's company_id as defense in depth before mutating.
|
||||
|
||||
const PatchSchema = z
|
||||
.object({
|
||||
content: z.string().min(2).max(2000).optional(),
|
||||
is_pinned: z.boolean().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(v) => v.content !== undefined || v.is_pinned !== undefined || v.is_active !== undefined,
|
||||
{ message: 'Nothing to update' },
|
||||
)
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'MEMORY_NOT_FOUND',
|
||||
message: 'Minnet hittades inte.',
|
||||
message_en: 'Memory not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'agent.memory.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchSchema, {
|
||||
log,
|
||||
operation: 'agent.memory.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.content !== undefined) update.content = body.content
|
||||
if (body.is_pinned !== undefined) update.is_pinned = body.is_pinned
|
||||
if (body.is_active !== undefined) update.is_active = body.is_active
|
||||
|
||||
// Look up the row's company_id and re-check membership before mutating.
|
||||
const { data: existing } = await supabase
|
||||
.from('agent_memory')
|
||||
.select('company_id')
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
if (!existing) return notFound()
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', existing.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_memory')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('company_id', existing.company_id)
|
||||
.select(
|
||||
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at',
|
||||
)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
if (!data) return notFound()
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user