feat(incidents): anonymous report tracking by token + public /track

Gap: fileIncident minted a reporter_token and the filing UI showed it
("the only way to look it up later") but there was no lookup UI.

- lib/incident-logic.ts (pure, tested): publicIncidentView redacts —
  board_only updates, subjects, decision-maker ids dropped; disposition
  only surfaced once decided/closed; status label mapping
- trackIncident: public service-client action (token is a 192-bit
  bearer credential on a UNIQUE column; anon has no RLS path so the
  service client is used AFTER token validation; generic not-found is
  enumeration-safe; board_only filtered at the query AND in logic)
- public /track page + client (also accepts ?token= deep link);
  /track added to middleware PUBLIC_ROUTES
- filing UI now deep-links /track?token=<code>
- trackIncidentSchema; __tests__/incident-tracking.test.ts (6)
- docs: API_REFERENCE + HANDOFF pass-20 (session arc, web-verified
  integration facts, locked forward roadmap, open items incl. the
  still-open production incident-INSERT RLS bug)

343 tests; build verified (Compiled successfully, exit 0).
This commit is contained in:
Moheeb Zara
2026-05-16 18:13:09 -07:00
parent 2559166092
commit ad477252c8
10 changed files with 417 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
import { describe, it, expect } from 'vitest'
import {
publicIncidentView,
visibleUpdate,
INCIDENT_STATUS_LABELS,
type RawIncident,
type RawUpdate,
} from '@/lib/incident-logic'
import { trackIncidentSchema } from '@/lib/validations'
const baseIncident: RawIncident = {
title: 'Unsafe saw guard',
body: 'The table saw guard is missing.',
category: 'safety',
severity: 'high',
status: 'received',
disposition: 'Removed member X for 30 days',
created_at: '2026-05-17T00:00:00Z',
acknowledged_at: null,
decided_at: null,
closed_at: null,
}
const updates: RawUpdate[] = [
{ body: 'We are looking into this.', author_name: 'Board', visibility: 'all_parties', created_at: '2026-05-17T01:00:00Z' },
{ body: 'Internal: contact insurer.', author_name: 'Chair', visibility: 'board_only', created_at: '2026-05-17T02:00:00Z' },
{ body: 'A note just for you.', author_name: null, visibility: 'reporter_only', created_at: '2026-05-17T03:00:00Z' },
]
describe('visibleUpdate', () => {
it('allows reporter_only and all_parties, denies board_only and unknown', () => {
expect(visibleUpdate('reporter_only')).toBe(true)
expect(visibleUpdate('all_parties')).toBe(true)
expect(visibleUpdate('board_only')).toBe(false)
expect(visibleUpdate('something_else')).toBe(false)
})
})
describe('publicIncidentView redaction', () => {
it('drops board_only updates and keeps the rest, defaulting author', () => {
const v = publicIncidentView(baseIncident, updates)
expect(v.updates).toHaveLength(2)
expect(v.updates.some(u => u.body.includes('Internal'))).toBe(false)
const reporterNote = v.updates.find(u => u.body === 'A note just for you.')
expect(reporterNote?.author).toBe('Space team')
})
it('hides disposition until a decision is reached', () => {
expect(publicIncidentView(baseIncident, []).disposition).toBeNull()
expect(publicIncidentView({ ...baseIncident, status: 'under_review' }, []).disposition).toBeNull()
expect(publicIncidentView({ ...baseIncident, status: 'decided' }, []).disposition).toBe(
'Removed member X for 30 days',
)
expect(publicIncidentView({ ...baseIncident, status: 'closed' }, []).disposition).toBe(
'Removed member X for 30 days',
)
})
it('exposes only the safe projection keys (no subjects/decision makers/ids)', () => {
const v = publicIncidentView(baseIncident, [])
expect(Object.keys(v).sort()).toEqual(
[
'acknowledgedAt',
'body',
'category',
'closedAt',
'createdAt',
'decidedAt',
'disposition',
'severity',
'status',
'statusLabel',
'title',
'updates',
].sort(),
)
})
it('maps status to a human label', () => {
expect(publicIncidentView({ ...baseIncident, status: 'under_review' }, []).statusLabel).toBe(
INCIDENT_STATUS_LABELS.under_review,
)
// Unknown status falls back to the raw value.
expect(publicIncidentView({ ...baseIncident, status: 'weird' }, []).statusLabel).toBe('weird')
})
})
describe('trackIncidentSchema', () => {
it('trims and bounds the token', () => {
expect(trackIncidentSchema.safeParse({ token: ' ' + 'a'.repeat(20) + ' ' }).success).toBe(true)
expect(trackIncidentSchema.safeParse({ token: 'short' }).success).toBe(false)
expect(trackIncidentSchema.safeParse({ token: '' }).success).toBe(false)
expect(trackIncidentSchema.safeParse({ token: 'a'.repeat(129) }).success).toBe(false)
expect(trackIncidentSchema.safeParse({}).success).toBe(false)
})
})
@@ -66,6 +66,13 @@ export function IncidentForm({ members }: { members: Member[] }) {
or display it elsewhere.
</p>
<pre className="bg-background border border-border rounded p-3 font-mono text-sm break-all">{token}</pre>
<p className="font-sans text-sm text-muted-foreground">
Check the status any time at{' '}
<Link href={`/track?token=${encodeURIComponent(token)}`} className="text-primary underline">
/track
</Link>{' '}
with this code. Bookmark it now.
</p>
<Link
href="/incidents"
className="inline-block bg-primary text-white font-sans text-sm font-medium px-4 py-2 rounded hover:bg-primary/90 transition"
+26
View File
@@ -0,0 +1,26 @@
import { TrackClient } from './track-client'
export const dynamic = 'force-dynamic'
// Public, unauthenticated. An anonymous incident reporter pastes the tracking
// token they were given at filing time to see their report's status and the
// official updates meant for them. /track is in middleware PUBLIC_ROUTES.
export default async function TrackPage({
searchParams,
}: {
searchParams: Promise<{ token?: string }>
}) {
const { token } = await searchParams
return (
<main className="mx-auto max-w-xl p-4 md:p-10">
<h1 className="text-2xl font-semibold">Track a report</h1>
<p className="mt-2 text-sm text-muted-foreground">
Enter the tracking code you were given when you filed an anonymous report. It is the
only way to look the report up — we cannot recover it for you.
</p>
<div className="mt-6">
<TrackClient initialToken={token ?? ''} autoSubmit={Boolean(token)} />
</div>
</main>
)
}
+128
View File
@@ -0,0 +1,128 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { trackIncident } from '@/lib/actions'
import type { PublicIncidentView } from '@/lib/incident-logic'
export function TrackClient({
initialToken,
autoSubmit,
}: {
initialToken: string
autoSubmit: boolean
}) {
const [token, setToken] = useState(initialToken)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [view, setView] = useState<PublicIncidentView | null>(null)
const didAuto = useRef(false)
async function lookup(t: string) {
setError(null)
setView(null)
setLoading(true)
const res = await trackIncident({ token: t.trim() })
setLoading(false)
if ('error' in res && res.error) {
setError(res.error)
return
}
setView(res.data)
}
useEffect(() => {
if (autoSubmit && initialToken && !didAuto.current) {
didAuto.current = true
lookup(initialToken)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<div className="space-y-6">
<form
onSubmit={e => {
e.preventDefault()
if (token.trim()) lookup(token)
}}
className="flex gap-2"
>
<Input
value={token}
onChange={e => setToken(e.target.value)}
placeholder="Tracking code"
aria-label="Tracking code"
className="font-mono"
/>
<Button type="submit" disabled={loading || !token.trim()}>
{loading ? 'Looking up…' : 'Track'}
</Button>
</form>
{error && <p className="text-sm text-destructive">{error}</p>}
{view && (
<div className="space-y-5 rounded-lg border p-5">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold">{view.title}</h2>
<Badge variant="secondary">{view.statusLabel}</Badge>
<Badge variant="outline">{view.severity}</Badge>
</div>
<p className="whitespace-pre-wrap text-sm text-muted-foreground">{view.body}</p>
<dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">
<dt>Filed</dt>
<dd>{new Date(view.createdAt).toLocaleString()}</dd>
{view.acknowledgedAt && (
<>
<dt>Acknowledged</dt>
<dd>{new Date(view.acknowledgedAt).toLocaleString()}</dd>
</>
)}
{view.decidedAt && (
<>
<dt>Decided</dt>
<dd>{new Date(view.decidedAt).toLocaleString()}</dd>
</>
)}
{view.closedAt && (
<>
<dt>Closed</dt>
<dd>{new Date(view.closedAt).toLocaleString()}</dd>
</>
)}
</dl>
{view.disposition && (
<div className="rounded-md border bg-muted/40 p-3 text-sm">
<p className="mb-1 font-medium">Outcome</p>
<p className="whitespace-pre-wrap">{view.disposition}</p>
</div>
)}
<div>
<p className="mb-2 text-sm font-medium">Updates</p>
{view.updates.length === 0 ? (
<p className="text-sm text-muted-foreground">No updates yet.</p>
) : (
<ul className="space-y-3">
{view.updates.map((u, i) => (
<li key={i} className="rounded-md border p-3 text-sm">
<p className="whitespace-pre-wrap">{u.body}</p>
<p className="mt-1 text-xs text-muted-foreground">
{u.author} · {new Date(u.createdAt).toLocaleString()}
</p>
</li>
))}
</ul>
)}
</div>
</div>
)}
</div>
)
}
+2
View File
@@ -864,6 +864,8 @@ validate input with Zod via `parseInput`, authorize via `requireMember` /
### Governance — `proposals.ts`, `incidents.ts`, `policies.ts`
`createProposal`, `openProposal`, `castVote`, `decideProposal`, `withdrawProposal`, `deleteProposal`; `fileIncident`, `updateIncidentStatus`, `addIncidentUpdate`, `appealIncident`; `createPolicy`, `supersedePolicy`, `updatePolicyStatus`.
`trackIncident({ token })` — public, unauthenticated. An anonymous reporter's `fileIncident` returns a 192-bit `reporter_token` (UNIQUE column); this looks the case up by that token using the service client (anon has no RLS path) and returns a redacted projection via `lib/incident-logic.ts` `publicIncidentView` (board-only updates, subjects, decision-maker ids dropped; disposition only after decided/closed). Public page `/track` (in middleware PUBLIC_ROUTES); the filing UI deep-links `/track?token=`.
### Areas — `areas.ts`
`createArea`, `updateArea`, `deleteArea` (admin/board; delete admin).
+28
View File
@@ -4,6 +4,34 @@ Append-only. Newest entries on top. Keep each entry to one screen.
---
## 2026-05-17 (pass 20) — Forms epic deployed; research; incident tracking; forward roadmap
### Deployed & verified
- Pushed P6/P7/P8 + docs (commits up to `73eef72`); deploy run succeeded; migrations `028` (forms slug unique per space) + `029` (`space_invites.role`) applied. Smoke-verified on prod: `/f/<space>/<slug>` returns the anonymous 200 page (NOT a login redirect — the long-unverified public-forms route is finally confirmed), `/join/<space>` public, `/forms` + `/my-forms` correctly auth-gated. Forms+invites (migrations 026-029) fully shipped.
- Local commits awaiting deploy at pass close: `2559166` (forms public link + Copy button on member & admin lists) and the incident-tracking work in this entry.
### Integration research (web-verified; saved to memory `integration-api-facts`)
- Payments are manual/CSV only today (no live API; known limitation). For real integration: **Stripe** is the one with a maintained official SDK + signature-verified webhooks (raw body, integer minor units). PayPal v2 works but official Node SDK has gaps (Subscriptions/webhook-verify need raw REST). Zeffy = read-only pull API + manual link. **Venmo has no usable API** (manual link / via PayPal-Braintree only). Canonical platform-agnostic payment record shape recorded in memory.
- HeatSync door = Arduino HTTP query-string API (`?m<slot>&p&t&e=<shared_pw>` add card, `?r` revoke, `?o1`/`?u` open), no TLS, LAN/VPN only. Generic adapter pattern (configurable URL + auth + verbs grant/revoke/open + inbound log) recorded.
### Anonymous incident tracking (this entry, LOCAL)
- Gap found: `fileIncident` mints a `reporter_token` and the filing UI shows it ("the only way to look it up later") but there was NO lookup UI. Built it: pure `lib/incident-logic.ts` `publicIncidentView` (redacts board-only updates, subjects, decision makers; disposition only after decided/closed; double-filtered at DB + logic); `trackIncident` service-client action (token = bearer credential, 192-bit UNIQUE, generic not-found = enumeration-safe); public `/track` page (+ middleware allowlist); filing UI deep-links `/track?token=`; `__tests__/incident-tracking.test.ts`.
### Forward roadmap (decisions LOCKED with user — see memory `heatsync-members-site`, `integration-api-facts`, `architecture-standards`)
Build order, each as its own well-separated module (migration + pure `*-logic.ts` tested + `lib/actions/*` + pages + docs; permissions via the additive catalog; the guarded RLS rule applies):
1. **Certifications + Instructor** (NEXT): `certifications` + `member_certifications` tables/RLS; `certifications.manage` + `certifications.grant` permissions (grant = the Instructor capability, assignable to roles/area-leads); admin pages + member-facing "My certifications & permissions" view.
2. **Classes**: `classes`/`class_sessions`/`class_signups`; `classes.manage`/`classes.instruct`; `payment_link` field at minimum; calendar; a class may grant a cert.
3. **Equipment**: registry + availability + reservations; gated perms.
4. **Door epic ("all of it")**: `member_cards` (RFID/NFC) ↔ member; configurable per-space door integration (URL+auth+verbs+inbound log); native HeatSync adapter; universal API-call UI builder with a door template. Largest/riskiest; own design pass; build last; LAN-only transport caveat.
- Instructor/Host/Champion = PERMISSIONS, not new built-in roles. Payments: add a `payment_link` field generally; a real Stripe integration is a separate, later, explicitly-scoped effort using the verified facts in memory.
### Open / not done
- **Production incident-INSERT RLS bug still OPEN** (separate from the tracking UI just built): never retried/diagnosed since `025`. Needs a prod retry; do not touch the permissions/RLS surface without diagnosis + approval.
- Not browser-verified (no live browser this session): the forms-link Copy buttons, the `/track` flow end-to-end, and the broader forms/onboarding/retro-link chain. Smoke-test lists in pass-18/19.
- Systemic test gap remains: `__tests__/actions.test.ts` largely asserts its own mock; no Supabase mock harness, so action *orchestration* is not unit-tested (pure logic is well covered). Recommended discrete follow-up.
---
## 2026-05-17 (pass 19) — Forms URL restructure + role invites + member surface + audit, LOCAL
User redirected after Phases 1-5 shipped. Decisions (memory `forms-feature` updated): per-space form slug + `/f/[space]/[slug]` (reverses the original global-slug lock), space-scoped invites incl. role-granting + usage caps, member-facing forms surface, starter templates, obvious publish flow.
+38
View File
@@ -2,6 +2,7 @@
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import {
requireMember,
requireMemberWithRole,
@@ -14,7 +15,9 @@ import {
updateIncidentStatusSchema,
addIncidentUpdateSchema,
appealIncidentSchema,
trackIncidentSchema,
} from '@/lib/validations'
import { publicIncidentView } from '@/lib/incident-logic'
/**
* Generate a short opaque tracking token for anonymous reports.
@@ -254,3 +257,38 @@ export async function appealIncident(formData: {
revalidatePath(`/proposals/${proposal.id}`)
return { data: proposal }
}
/**
* Public, unauthenticated lookup of an anonymously-filed incident by its
* opaque reporter token. No session: the token IS the bearer credential, so
* this uses the service client (anon has no RLS path to incidents) AFTER
* validating the token, exactly like the forms public read. The returned
* projection is redacted by `publicIncidentView` — board-only updates,
* subjects, decision-maker ids and an undecided disposition never leave the
* server. The token is 192 bits of randomness on a UNIQUE column, so a
* generic not-found response is safe against enumeration.
*/
export async function trackIncident(input: unknown) {
const v = parseInput(trackIncidentSchema, input)
if (!v.ok) return { error: v.error }
const admin = createAdminClient()
const { data: incident } = await admin
.from('incidents')
.select(
'id, title, body, category, severity, status, disposition, created_at, acknowledged_at, decided_at, closed_at',
)
.eq('reporter_token', v.data.token)
.maybeSingle()
if (!incident) return { error: 'No report matches that tracking code.' }
const { data: updates } = await admin
.from('incident_updates')
.select('body, author_name, visibility, created_at')
.eq('incident_id', incident.id)
.neq('visibility', 'board_only')
.order('created_at', { ascending: true })
return { data: publicIncidentView(incident, updates ?? []) }
}
+83
View File
@@ -0,0 +1,83 @@
// Pure projection logic for the anonymous incident tracking page. No deps so
// it is unit-testable. The single rule that matters here is REDACTION: a
// holder of a reporter token is not authenticated and must never see
// board-only notes, internal decision-maker ids, named subjects, or anything
// beyond their own report's status and the official updates meant for them.
export const INCIDENT_STATUS_LABELS: Record<string, string> = {
received: 'Received',
under_review: 'Under review',
decided: 'Decided',
appealed: 'Appealed',
closed: 'Closed',
}
// Updates a token holder may see. board_only is intentionally excluded.
const VISIBLE_UPDATE_VISIBILITIES = ['reporter_only', 'all_parties'] as const
export interface RawIncident {
title: string
body: string
category: string
severity: string
status: string
disposition: string | null
created_at: string
acknowledged_at: string | null
decided_at: string | null
closed_at: string | null
}
export interface RawUpdate {
body: string
author_name: string | null
visibility: string
created_at: string
}
export interface PublicIncidentView {
title: string
body: string
category: string
severity: string
status: string
statusLabel: string
createdAt: string
acknowledgedAt: string | null
decidedAt: string | null
closedAt: string | null
// Only surfaced once a decision exists — never leak an in-progress lean.
disposition: string | null
updates: { body: string; author: string; createdAt: string }[]
}
export function visibleUpdate(visibility: string): boolean {
return (VISIBLE_UPDATE_VISIBILITIES as readonly string[]).includes(visibility)
}
export function publicIncidentView(
incident: RawIncident,
updates: RawUpdate[],
): PublicIncidentView {
const decisionReached = incident.status === 'decided' || incident.status === 'closed'
return {
title: incident.title,
body: incident.body,
category: incident.category,
severity: incident.severity,
status: incident.status,
statusLabel: INCIDENT_STATUS_LABELS[incident.status] ?? incident.status,
createdAt: incident.created_at,
acknowledgedAt: incident.acknowledged_at,
decidedAt: incident.decided_at,
closedAt: incident.closed_at,
disposition: decisionReached ? incident.disposition : null,
updates: updates
.filter(u => visibleUpdate(u.visibility))
.map(u => ({
body: u.body,
author: u.author_name ?? 'Space team',
createdAt: u.created_at,
})),
}
}
+7
View File
@@ -289,6 +289,13 @@ export const appealIncidentSchema = z.object({
body: z.string().max(20000).default(''),
})
// Anonymous reporters look their case up with the opaque token they were
// given at filing time (48 hex chars today; bound loosely so the format can
// evolve without breaking old tokens).
export const trackIncidentSchema = z.object({
token: z.string().trim().min(16).max(128),
})
// ─── Governance: policies ────────────────────────────────────────────────────
export const policyStatuses = ['draft','active','deprecated','superseded'] as const
+2
View File
@@ -12,6 +12,8 @@ const PUBLIC_ROUTES = [
'/login',
'/signup',
'/join',
// Public anonymous-incident status lookup by reporter token.
'/track',
'/auth',
'/api/health',
// Public form / waiver fill page. Only /f/[slug] lives here and must be