fix(audit): wrap admin + capa mutations with their audit writes in single transactions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-07-24 06:44:05 +08:00
co-authored by Claude Sonnet 4.6
parent 8acca41ca1
commit 9c67014bb9
5 changed files with 145 additions and 114 deletions
+16 -15
View File
@@ -2,7 +2,8 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth/get-session'
import { asAdmin, withUser } from '@/lib/db/with-user'
import { sql } from 'drizzle-orm'
import { asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { appSettings } from '@/lib/db/schema'
@@ -47,21 +48,21 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'value must be a non-empty string' }, { status: 422 })
}
await asAdmin(db =>
db.insert(appSettings).values({
key: body.key!,
value: body.value!,
updatedAt: new Date(),
updatedBy: session.sub,
}).onConflictDoUpdate({
target: appSettings.key,
set: { value: body.value!, updatedAt: new Date(), updatedBy: session.sub },
await asAdmin(async db => {
await db.transaction(async tx => {
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
await tx.insert(appSettings).values({
key: body.key!,
value: body.value!,
updatedAt: new Date(),
updatedBy: session.sub,
}).onConflictDoUpdate({
target: appSettings.key,
set: { value: body.value!, updatedAt: new Date(), updatedBy: session.sub },
})
await writeAuditLog(tx, 'app_settings', session.sub, 'UPDATE', { key: body.key, set: Boolean(body.value) })
})
)
await withUser(session.sub, async tx =>
writeAuditLog(tx, 'app_settings', session.sub, 'UPDATE', { key: body.key, set: Boolean(body.value) })
)
})
return NextResponse.json({ ok: true })
}