feat: API key settings page — store ANTHROPIC/VOYAGE keys in DB with admin UI

- Migration: app_settings table with admin-only RLS (ANTHROPIC_API_KEY, VOYAGE_API_KEY)
- lib/settings.ts: getApiKey() reads DB first, falls back to env var
- lib/claude/client.ts: factory createAnthropicClient(apiKey) replaces singleton
- lib/claude/embed.ts: optional apiKey param, falls back to env
- 3 Claude AI routes + similar route: fetch key from settings before calling AI
- incidents/route.ts: fire-and-forget embed reads VOYAGE key from settings
- GET/POST /api/settings: admin-only masked key management endpoint
- /hse/settings page + ApiKeyForm client component

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
This commit is contained in:
2026-07-11 17:46:40 +08:00
co-authored by Claude Sonnet 4.6
parent a07c9f0910
commit b9ab94c9da
14 changed files with 277 additions and 19 deletions
+32
View File
@@ -0,0 +1,32 @@
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { ApiKeyForm } from '@/components/settings/api-key-form'
export default async function SettingsPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || profile.role !== 'admin') redirect('/hse/dashboard')
const { data: settings } = await supabase
.from('app_settings')
.select('key, value, updated_at')
const settingsMap = Object.fromEntries(
(settings ?? []).map(s => [s.key, { set: Boolean(s.value), updated_at: s.updated_at }])
)
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<h1 className="text-2xl font-bold text-gray-900 mb-2">Settings</h1>
<p className="text-sm text-gray-500 mb-6">
API keys are stored securely in the database. Leave blank to use environment variables.
</p>
<ApiKeyForm settings={settingsMap} />
</main>
)
}
+5 -1
View File
@@ -2,7 +2,8 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { anthropic } from '@/lib/claude/client'
import { createAnthropicClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST(
_request: NextRequest,
@@ -17,6 +18,9 @@ export async function POST(
if (!profile || !['hse', 'admin'].includes(profile.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const anthropicKey = await getApiKey(supabase, 'ANTHROPIC_API_KEY')
const anthropic = createAnthropicClient(anthropicKey)
const { data: incident } = await supabase
.from('incidents')
.select(`
@@ -2,7 +2,8 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { anthropic } from '@/lib/claude/client'
import { createAnthropicClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST(
_request: NextRequest,
@@ -17,6 +18,9 @@ export async function POST(
if (!profile || !['hse', 'admin'].includes(profile.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const anthropicKey = await getApiKey(supabase, 'ANTHROPIC_API_KEY')
const anthropic = createAnthropicClient(anthropicKey)
const { data: incident } = await supabase
.from('incidents')
.select('id, incident_type, description, injury_involved, asset_involved, medical_status')
+4 -1
View File
@@ -3,6 +3,7 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { embedText } from '@/lib/claude/embed'
import { getApiKey } from '@/lib/settings'
export async function GET(
_request: NextRequest,
@@ -17,6 +18,8 @@ export async function GET(
if (!profile || !['hse', 'admin'].includes(profile.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const voyageKey = await getApiKey(supabase, 'VOYAGE_API_KEY')
const { data: incident } = await supabase
.from('incidents')
.select('id, description, embedding')
@@ -31,7 +34,7 @@ export async function GET(
if (inc.embedding) {
embeddingVec = JSON.parse(inc.embedding) as number[]
} else {
embeddingVec = await embedText(inc.description)
embeddingVec = await embedText(inc.description, voyageKey)
await supabase.from('incidents').update({
embedding: `[${embeddingVec.join(',')}]` as unknown as string,
}).eq('id', id)
+5 -1
View File
@@ -2,13 +2,17 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { anthropic } from '@/lib/claude/client'
import { createAnthropicClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST(request: NextRequest) {
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const anthropicKey = await getApiKey(supabase, 'ANTHROPIC_API_KEY')
const anthropic = createAnthropicClient(anthropicKey)
let body: { description?: string; incident_type?: string }
try {
body = await request.json()
+10 -5
View File
@@ -110,11 +110,16 @@ export async function POST(request: Request) {
.catch(err => console.error('email notification failed:', err))
// Embed description asynchronously for future similarity search
import('@/lib/claude/embed').then(({ embedText }) =>
embedText(input.description.trim()).then(embedding =>
supabase.from('incidents').update({
embedding: `[${embedding.join(',')}]` as unknown as string,
}).eq('id', incident.id)
const supabaseForEmbed = supabase
import('@/lib/settings').then(({ getApiKey }) =>
getApiKey(supabaseForEmbed, 'VOYAGE_API_KEY').then(voyageKey =>
import('@/lib/claude/embed').then(({ embedText }) =>
embedText(input.description.trim(), voyageKey).then(embedding =>
supabase.from('incidents').update({
embedding: `[${embedding.join(',')}]` as unknown as string,
}).eq('id', incident.id)
)
)
)
).catch(err => console.error('embed error:', err))
+65
View File
@@ -0,0 +1,65 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
const ALLOWED_KEYS = ['ANTHROPIC_API_KEY', 'VOYAGE_API_KEY'] as const
type SettingKey = typeof ALLOWED_KEYS[number]
async function requireAdmin(supabase: Awaited<ReturnType<typeof createClient>>) {
const { data: { user }, error } = await supabase.auth.getUser()
if (error || !user) return null
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || profile.role !== 'admin') return null
return user
}
export async function GET() {
const supabase = await createClient()
const user = await requireAdmin(supabase)
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const { data } = await supabase.from('app_settings').select('key, value, updated_at')
const masked = (data ?? []).map(row => ({
key: row.key,
set: Boolean(row.value),
masked_value: row.value ? `${row.value.slice(0, 8)}${'•'.repeat(12)}` : '',
updated_at: row.updated_at,
}))
return NextResponse.json(masked)
}
export async function POST(request: NextRequest) {
const supabase = await createClient()
const user = await requireAdmin(supabase)
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
let body: { key?: string; value?: string }
try { body = await request.json() } catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
}
if (!body.key || !ALLOWED_KEYS.includes(body.key as SettingKey)) {
return NextResponse.json({ error: 'Invalid key' }, { status: 422 })
}
if (typeof body.value !== 'string') {
return NextResponse.json({ error: 'value required' }, { status: 422 })
}
const { error } = await supabase.from('app_settings').upsert({
key: body.key,
value: body.value,
updated_at: new Date().toISOString(),
updated_by: user.id,
})
if (error) return NextResponse.json({ error: 'Save failed' }, { status: 500 })
await supabase.rpc('write_audit_log', {
p_table_name: 'app_settings',
p_record_id: user.id,
p_action: 'UPDATE',
p_new_value: { key: body.key, set: Boolean(body.value) } as never,
})
return NextResponse.json({ ok: true })
}