diff --git a/__tests__/incident-tracking.test.ts b/__tests__/incident-tracking.test.ts new file mode 100644 index 0000000..3bcf1b4 --- /dev/null +++ b/__tests__/incident-tracking.test.ts @@ -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) + }) +}) diff --git a/app/(app)/incidents/new/incident-form.tsx b/app/(app)/incidents/new/incident-form.tsx index dcecc58..0c52c1a 100644 --- a/app/(app)/incidents/new/incident-form.tsx +++ b/app/(app)/incidents/new/incident-form.tsx @@ -66,6 +66,13 @@ export function IncidentForm({ members }: { members: Member[] }) { or display it elsewhere.

{token}
+

+ Check the status any time at{' '} + + /track + {' '} + with this code. Bookmark it now. +

+}) { + const { token } = await searchParams + return ( +
+

Track a report

+

+ 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. +

+
+ +
+
+ ) +} diff --git a/app/track/track-client.tsx b/app/track/track-client.tsx new file mode 100644 index 0000000..1faaa33 --- /dev/null +++ b/app/track/track-client.tsx @@ -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(null) + const [view, setView] = useState(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 ( +
+
{ + e.preventDefault() + if (token.trim()) lookup(token) + }} + className="flex gap-2" + > + setToken(e.target.value)} + placeholder="Tracking code" + aria-label="Tracking code" + className="font-mono" + /> + +
+ + {error &&

{error}

} + + {view && ( +
+
+

{view.title}

+ {view.statusLabel} + {view.severity} +
+ +

{view.body}

+ +
+
Filed
+
{new Date(view.createdAt).toLocaleString()}
+ {view.acknowledgedAt && ( + <> +
Acknowledged
+
{new Date(view.acknowledgedAt).toLocaleString()}
+ + )} + {view.decidedAt && ( + <> +
Decided
+
{new Date(view.decidedAt).toLocaleString()}
+ + )} + {view.closedAt && ( + <> +
Closed
+
{new Date(view.closedAt).toLocaleString()}
+ + )} +
+ + {view.disposition && ( +
+

Outcome

+

{view.disposition}

+
+ )} + +
+

Updates

+ {view.updates.length === 0 ? ( +

No updates yet.

+ ) : ( +
    + {view.updates.map((u, i) => ( +
  • +

    {u.body}

    +

    + {u.author} · {new Date(u.createdAt).toLocaleString()} +

    +
  • + ))} +
+ )} +
+
+ )} +
+ ) +} diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 0c6a877..285f83b 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -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). diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 8e3e9bf..f9e7185 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -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//` returns the anonymous 200 page (NOT a login redirect — the long-unverified public-forms route is finally confirmed), `/join/` 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&p&t&e=` 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. diff --git a/lib/actions/incidents.ts b/lib/actions/incidents.ts index 1dba980..0e37eb4 100644 --- a/lib/actions/incidents.ts +++ b/lib/actions/incidents.ts @@ -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 ?? []) } +} diff --git a/lib/incident-logic.ts b/lib/incident-logic.ts new file mode 100644 index 0000000..9d55572 --- /dev/null +++ b/lib/incident-logic.ts @@ -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 = { + 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, + })), + } +} diff --git a/lib/validations.ts b/lib/validations.ts index 7bf0083..70ce0a3 100644 --- a/lib/validations.ts +++ b/lib/validations.ts @@ -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 diff --git a/proxy.ts b/proxy.ts index 041f675..f3d39b2 100644 --- a/proxy.ts +++ b/proxy.ts @@ -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