fix: RLS guard in match_incidents + try/catch around AI/embed calls
- Add new migration 20260711000013_match_incidents_auth_guard.sql that replaces match_incidents with an inline auth guard: callers without hse/admin role receive PGRST301 Forbidden, closing the SECURITY DEFINER RLS bypass. - Wrap anthropic.messages.create() in try/catch returning 503 in all four AI routes: quality-check, triage-suggest, rca-draft, similar. - Wrap JSON.parse(inc.embedding) and embedText() in similar/route.ts in a shared try/catch returning 503 Embedding service unavailable. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
This commit is contained in:
@@ -41,45 +41,47 @@ export async function POST(
|
|||||||
const siteName = (incident.sites as unknown as { name: string } | null)?.name ?? 'Unknown'
|
const siteName = (incident.sites as unknown as { name: string } | null)?.name ?? 'Unknown'
|
||||||
const zoneName = (incident.zones as unknown as { name: string } | null)?.name ?? 'Unknown'
|
const zoneName = (incident.zones as unknown as { name: string } | null)?.name ?? 'Unknown'
|
||||||
|
|
||||||
const message = await anthropic.messages.create({
|
let message: Awaited<ReturnType<typeof anthropic.messages.create>>
|
||||||
model: 'claude-opus-4-8',
|
try {
|
||||||
thinking: { type: 'adaptive' },
|
message = await anthropic.messages.create({
|
||||||
max_tokens: 2048,
|
model: 'claude-opus-4-8',
|
||||||
tools: [{
|
thinking: { type: 'adaptive' },
|
||||||
name: 'draft_rca',
|
max_tokens: 2048,
|
||||||
description: 'Draft a 5-Why root cause analysis and CAPA suggestions for an HSE incident',
|
tools: [{
|
||||||
input_schema: {
|
name: 'draft_rca',
|
||||||
type: 'object' as const,
|
description: 'Draft a 5-Why root cause analysis and CAPA suggestions for an HSE incident',
|
||||||
properties: {
|
input_schema: {
|
||||||
five_why_steps: {
|
type: 'object' as const,
|
||||||
type: 'array',
|
properties: {
|
||||||
items: {
|
five_why_steps: {
|
||||||
type: 'object',
|
type: 'array',
|
||||||
properties: {
|
items: {
|
||||||
why: { type: 'string', description: 'The why question' },
|
type: 'object',
|
||||||
answer: { type: 'string', description: 'The finding or answer' },
|
properties: {
|
||||||
|
why: { type: 'string', description: 'The why question' },
|
||||||
|
answer: { type: 'string', description: 'The finding or answer' },
|
||||||
|
},
|
||||||
|
required: ['why', 'answer'],
|
||||||
},
|
},
|
||||||
required: ['why', 'answer'],
|
description: '3 to 5 why steps',
|
||||||
|
},
|
||||||
|
root_cause_summary: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'One-sentence root cause statement',
|
||||||
|
},
|
||||||
|
capa_suggestions: {
|
||||||
|
type: 'array',
|
||||||
|
items: { type: 'string' },
|
||||||
|
description: 'Up to 3 corrective/preventive action suggestions',
|
||||||
},
|
},
|
||||||
description: '3 to 5 why steps',
|
|
||||||
},
|
|
||||||
root_cause_summary: {
|
|
||||||
type: 'string',
|
|
||||||
description: 'One-sentence root cause statement',
|
|
||||||
},
|
|
||||||
capa_suggestions: {
|
|
||||||
type: 'array',
|
|
||||||
items: { type: 'string' },
|
|
||||||
description: 'Up to 3 corrective/preventive action suggestions',
|
|
||||||
},
|
},
|
||||||
|
required: ['five_why_steps', 'root_cause_summary', 'capa_suggestions'],
|
||||||
},
|
},
|
||||||
required: ['five_why_steps', 'root_cause_summary', 'capa_suggestions'],
|
}],
|
||||||
},
|
tool_choice: { type: 'tool', name: 'draft_rca' },
|
||||||
}],
|
messages: [{
|
||||||
tool_choice: { type: 'tool', name: 'draft_rca' },
|
role: 'user',
|
||||||
messages: [{
|
content: `You are an experienced HSE investigator for a Malaysian 3PL warehouse. Draft a 5-Why root cause analysis for this incident.
|
||||||
role: 'user',
|
|
||||||
content: `You are an experienced HSE investigator for a Malaysian 3PL warehouse. Draft a 5-Why root cause analysis for this incident.
|
|
||||||
|
|
||||||
Site: ${siteName}
|
Site: ${siteName}
|
||||||
Zone: ${zoneName}
|
Zone: ${zoneName}
|
||||||
@@ -92,8 +94,11 @@ Serious bodily injury: ${inc.is_serious_bodily_injury ? 'yes' : 'no'}
|
|||||||
Triage notes: ${inc.triage_notes ?? 'none'}
|
Triage notes: ${inc.triage_notes ?? 'none'}
|
||||||
|
|
||||||
Provide 3–5 Why steps drilling from immediate cause to root cause. Give a one-sentence root cause statement. Suggest 3 corrective/preventive actions appropriate for a Malaysian warehouse context.`,
|
Provide 3–5 Why steps drilling from immediate cause to root cause. Give a one-sentence root cause statement. Suggest 3 corrective/preventive actions appropriate for a Malaysian warehouse context.`,
|
||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 })
|
||||||
|
}
|
||||||
|
|
||||||
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
||||||
if (!toolBlock || toolBlock.type !== 'tool_use')
|
if (!toolBlock || toolBlock.type !== 'tool_use')
|
||||||
|
|||||||
@@ -32,33 +32,35 @@ export async function POST(
|
|||||||
medical_status: string | null
|
medical_status: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = await anthropic.messages.create({
|
let message: Awaited<ReturnType<typeof anthropic.messages.create>>
|
||||||
model: 'claude-opus-4-8',
|
try {
|
||||||
thinking: { type: 'adaptive' },
|
message = await anthropic.messages.create({
|
||||||
max_tokens: 1024,
|
model: 'claude-opus-4-8',
|
||||||
tools: [{
|
thinking: { type: 'adaptive' },
|
||||||
name: 'suggest_triage',
|
max_tokens: 1024,
|
||||||
description: 'Suggest severity rating and NADOPOD 2004 DOSH classification for a warehouse incident',
|
tools: [{
|
||||||
input_schema: {
|
name: 'suggest_triage',
|
||||||
type: 'object' as const,
|
description: 'Suggest severity rating and NADOPOD 2004 DOSH classification for a warehouse incident',
|
||||||
properties: {
|
input_schema: {
|
||||||
severity: { type: 'number', description: '1=minor, 2=low, 3=moderate, 4=serious, 5=critical/fatality' },
|
type: 'object' as const,
|
||||||
is_fatality: { type: 'boolean' },
|
properties: {
|
||||||
is_serious_bodily_injury: { type: 'boolean', description: 'Fracture, amputation, blindness, serious burn, or similar' },
|
severity: { type: 'number', description: '1=minor, 2=low, 3=moderate, 4=serious, 5=critical/fatality' },
|
||||||
is_dangerous_occurrence: { type: 'boolean', description: 'Structural collapse, explosion, fire, scaffold collapse, etc.' },
|
is_fatality: { type: 'boolean' },
|
||||||
is_occupational_disease: { type: 'boolean', description: 'Disease arising from workplace exposure' },
|
is_serious_bodily_injury: { type: 'boolean', description: 'Fracture, amputation, blindness, serious burn, or similar' },
|
||||||
rationale: { type: 'string', description: 'One-sentence rationale citing NADOPOD 2004 where applicable' },
|
is_dangerous_occurrence: { type: 'boolean', description: 'Structural collapse, explosion, fire, scaffold collapse, etc.' },
|
||||||
|
is_occupational_disease: { type: 'boolean', description: 'Disease arising from workplace exposure' },
|
||||||
|
rationale: { type: 'string', description: 'One-sentence rationale citing NADOPOD 2004 where applicable' },
|
||||||
|
},
|
||||||
|
required: [
|
||||||
|
'severity', 'is_fatality', 'is_serious_bodily_injury',
|
||||||
|
'is_dangerous_occurrence', 'is_occupational_disease', 'rationale',
|
||||||
|
],
|
||||||
},
|
},
|
||||||
required: [
|
}],
|
||||||
'severity', 'is_fatality', 'is_serious_bodily_injury',
|
tool_choice: { type: 'tool', name: 'suggest_triage' },
|
||||||
'is_dangerous_occurrence', 'is_occupational_disease', 'rationale',
|
messages: [{
|
||||||
],
|
role: 'user',
|
||||||
},
|
content: `You are an HSE triage specialist for a Malaysian 3PL warehouse. Assess this incident under NADOPOD 2004.
|
||||||
}],
|
|
||||||
tool_choice: { type: 'tool', name: 'suggest_triage' },
|
|
||||||
messages: [{
|
|
||||||
role: 'user',
|
|
||||||
content: `You are an HSE triage specialist for a Malaysian 3PL warehouse. Assess this incident under NADOPOD 2004.
|
|
||||||
|
|
||||||
Incident type: ${inc.incident_type}
|
Incident type: ${inc.incident_type}
|
||||||
Description: ${inc.description}
|
Description: ${inc.description}
|
||||||
@@ -67,8 +69,11 @@ Medical status: ${inc.medical_status ?? 'N/A'}
|
|||||||
Asset/equipment involved: ${inc.asset_involved ? 'yes' : 'no'}
|
Asset/equipment involved: ${inc.asset_involved ? 'yes' : 'no'}
|
||||||
|
|
||||||
Suggest severity (1–5) and tick the appropriate NADOPOD 2004 flags. Give a one-sentence rationale.`,
|
Suggest severity (1–5) and tick the appropriate NADOPOD 2004 flags. Give a one-sentence rationale.`,
|
||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 })
|
||||||
|
}
|
||||||
|
|
||||||
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
||||||
if (!toolBlock || toolBlock.type !== 'tool_use')
|
if (!toolBlock || toolBlock.type !== 'tool_use')
|
||||||
|
|||||||
@@ -27,13 +27,17 @@ export async function GET(
|
|||||||
const inc = incident as { id: string; description: string; embedding: string | null }
|
const inc = incident as { id: string; description: string; embedding: string | null }
|
||||||
|
|
||||||
let embeddingVec: number[]
|
let embeddingVec: number[]
|
||||||
if (inc.embedding) {
|
try {
|
||||||
embeddingVec = JSON.parse(inc.embedding) as number[]
|
if (inc.embedding) {
|
||||||
} else {
|
embeddingVec = JSON.parse(inc.embedding) as number[]
|
||||||
embeddingVec = await embedText(inc.description)
|
} else {
|
||||||
await supabase.from('incidents').update({
|
embeddingVec = await embedText(inc.description)
|
||||||
embedding: `[${embeddingVec.join(',')}]` as unknown as string,
|
await supabase.from('incidents').update({
|
||||||
}).eq('id', id)
|
embedding: `[${embeddingVec.join(',')}]` as unknown as string,
|
||||||
|
}).eq('id', id)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'Embedding service unavailable' }, { status: 503 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data: similar } = await supabase.rpc('match_incidents', {
|
const { data: similar } = await supabase.rpc('match_incidents', {
|
||||||
|
|||||||
@@ -19,39 +19,44 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: 'description and incident_type required' }, { status: 422 })
|
return NextResponse.json({ error: 'description and incident_type required' }, { status: 422 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = await anthropic.messages.create({
|
let message: Awaited<ReturnType<typeof anthropic.messages.create>>
|
||||||
model: 'claude-opus-4-8',
|
try {
|
||||||
thinking: { type: 'adaptive' },
|
message = await anthropic.messages.create({
|
||||||
max_tokens: 1024,
|
model: 'claude-opus-4-8',
|
||||||
tools: [{
|
thinking: { type: 'adaptive' },
|
||||||
name: 'assess_quality',
|
max_tokens: 1024,
|
||||||
description: 'Assess HSE incident report description quality',
|
tools: [{
|
||||||
input_schema: {
|
name: 'assess_quality',
|
||||||
type: 'object' as const,
|
description: 'Assess HSE incident report description quality',
|
||||||
properties: {
|
input_schema: {
|
||||||
score: { type: 'number', description: '1-10 quality score' },
|
type: 'object' as const,
|
||||||
passes: { type: 'boolean', description: 'True when score is 6 or above' },
|
properties: {
|
||||||
feedback: { type: 'string', description: 'One-sentence quality summary' },
|
score: { type: 'number', description: '1-10 quality score' },
|
||||||
suggestions: {
|
passes: { type: 'boolean', description: 'True when score is 6 or above' },
|
||||||
type: 'array',
|
feedback: { type: 'string', description: 'One-sentence quality summary' },
|
||||||
items: { type: 'string' },
|
suggestions: {
|
||||||
description: 'Up to 3 concrete suggestions to improve the description',
|
type: 'array',
|
||||||
|
items: { type: 'string' },
|
||||||
|
description: 'Up to 3 concrete suggestions to improve the description',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
required: ['score', 'passes', 'feedback', 'suggestions'],
|
||||||
},
|
},
|
||||||
required: ['score', 'passes', 'feedback', 'suggestions'],
|
}],
|
||||||
},
|
tool_choice: { type: 'tool', name: 'assess_quality' },
|
||||||
}],
|
messages: [{
|
||||||
tool_choice: { type: 'tool', name: 'assess_quality' },
|
role: 'user',
|
||||||
messages: [{
|
content: `You are an HSE reporting assistant for a Malaysian 3PL warehouse. Assess this incident report description.
|
||||||
role: 'user',
|
|
||||||
content: `You are an HSE reporting assistant for a Malaysian 3PL warehouse. Assess this incident report description.
|
|
||||||
|
|
||||||
Incident type: ${body.incident_type}
|
Incident type: ${body.incident_type}
|
||||||
Description: ${body.description}
|
Description: ${body.description}
|
||||||
|
|
||||||
Score 1–10 based on: specificity (location, time, persons involved), completeness (what happened + immediate actions), and clarity. Score 6 or above passes. If score is below 6, give up to 3 actionable suggestions.`,
|
Score 1–10 based on: specificity (location, time, persons involved), completeness (what happened + immediate actions), and clarity. Score 6 or above passes. If score is below 6, give up to 3 actionable suggestions.`,
|
||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'AI service unavailable' }, { status: 503 })
|
||||||
|
}
|
||||||
|
|
||||||
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
const toolBlock = message.content.find(b => b.type === 'tool_use')
|
||||||
if (!toolBlock || toolBlock.type !== 'tool_use') {
|
if (!toolBlock || toolBlock.type !== 'tool_use') {
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
-- Add authorization guard to match_incidents to enforce DB-level access control.
|
||||||
|
-- Without this, SECURITY DEFINER bypasses RLS for any direct caller.
|
||||||
|
create or replace function match_incidents(
|
||||||
|
query_embedding vector(1024),
|
||||||
|
exclude_id uuid,
|
||||||
|
match_count int default 5
|
||||||
|
)
|
||||||
|
returns table (
|
||||||
|
id uuid,
|
||||||
|
reference_no text,
|
||||||
|
incident_type text,
|
||||||
|
description text,
|
||||||
|
severity int,
|
||||||
|
similarity float
|
||||||
|
)
|
||||||
|
language plpgsql
|
||||||
|
security definer
|
||||||
|
as $$
|
||||||
|
begin
|
||||||
|
-- Enforce that only hse/admin roles can call this function directly
|
||||||
|
if not exists (
|
||||||
|
select 1 from public.users
|
||||||
|
where id = auth.uid()
|
||||||
|
and role in ('hse', 'admin')
|
||||||
|
) then
|
||||||
|
raise exception 'Forbidden' using errcode = 'PGRST301';
|
||||||
|
end if;
|
||||||
|
|
||||||
|
return query
|
||||||
|
select
|
||||||
|
i.id,
|
||||||
|
i.reference_no,
|
||||||
|
i.incident_type,
|
||||||
|
i.description,
|
||||||
|
i.severity,
|
||||||
|
1 - (i.embedding <=> query_embedding) as similarity
|
||||||
|
from incidents i
|
||||||
|
where i.id != exclude_id
|
||||||
|
and i.embedding is not null
|
||||||
|
order by i.embedding <=> query_embedding
|
||||||
|
limit match_count;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
Reference in New Issue
Block a user