feat(tier2): smarter fraud detection — Block G

Per-event fraud tuning. Hosts can now dial the medium / high / block
boundaries, allowlist trusted networks, and feed verdicts back on
flagged accesses — the seed corpus for a future ML model.

Schema (migration 0011)
- events.fraud_{medium,high,block}_threshold default 30/60/85 so
  existing events behave identically until a host changes them
- access_logs.geo_{country,city,lat,lon} for future enrichment
- fraud_feedback table — verdict ('legitimate' | 'suspicious') + note,
  PK on access_log_id so re-mark is an upsert
- event_allowlists table — (event_id, ip_cidr) primary key, inet column
  so containment checks use the native >>= operator (indexed lookup)

Domain
- FraudThresholds with Valid() + Band() helpers; Default trio echoed
  through GET responses so the frontend doesn't duplicate constants
- ParseAllowlistCIDR accepts bare IPs (auto-widens to /32 or /128) and
  canonicalises the output (203.0.113.42 → 203.0.113.42/32)
- Event.Thresholds() falls back to defaults if columns weren't
  populated yet, so the API never wedges every score into "low"

Storage
- AllowlistRepo: List / Add / Remove + Matches() — the latter pushes
  CIDR containment into Postgres rather than streaming rows back
- FeedbackRepo: Record (upserts) + ListForEvent (joined through guests)
- EventRepo.GetThresholds + UpdateThresholds, plus the threshold
  columns baked into scanEvent so every event load carries them
- AccessLogRepo.BelongsToEvent — stops a hostile editor on event A
  from marking event B's access logs

API
- GET/PUT /events/{id}/security/thresholds (viewer/editor)
- GET/POST/DELETE /events/{id}/security/allowlist
- POST /events/{id}/access-logs/{log_id}/feedback (editor)
- GET /events/{id}/security/feedback
- RSVP scoring path: allowlist short-circuit fires before the fraud
  engine; the engine's score is then re-banded against the event's
  thresholds (engine.Risk becomes advisory — API is the source of
  truth for "what counts as block here")
- CORS Allow-Methods already includes PUT (Block D fix)

Fraud engine
- Single-signal cap: it now takes ≥2 sub-scores of ≥70 to push the
  final into HIGH. Fixes the well-known "second visit with a slightly
  shifted fingerprint scores 60+" false positive
- Engine band remains advisory; API re-bands using per-event
  thresholds before deciding to block

Frontend
- SecurityCard.vue: visual band ribbon (proportional to thresholds),
  three sliders with mutual clamping so dragging medium past high
  pushes high (not an invalid ordering), reset-to-defaults button,
  CIDR allowlist with inline add + per-row remove, verdict-history
  inbox. Toast feedback on save/add/remove
- "Security" tab added to the event-detail tab nav (5th tab,
  right of Analytics)
- Viewer role hides write affordances; server enforces too

Tests
- Domain: ThresholdsBand, ThresholdsValid, ParseAllowlistCIDR (bare
  IP widening + traversal/typo rejection), FraudFeedbackValid
- Integration: thresholds round-trip + invalid ordering rejection,
  allowlist CRUD + duplicate 409 + invalid CIDR 400 + IP auto-widen,
  feedback record + upsert + cross-tenant 404 + invalid verdict 400,
  viewer can read / editor can write / outsider gets 404
- Full integration suite green (315.8s, all 36 top-level tests pass)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-19 21:33:57 +01:00
parent e5b187c575
commit b873012191
22 changed files with 1953 additions and 142 deletions
+81 -8
View File
@@ -63,6 +63,37 @@ const stats = ref<GuestStats>({ total: 0, attending: 0, declined: 0, maybe: 0, p
const filter = ref<'all' | 'attending' | 'declined' | 'maybe' | 'pending'>('all')
const loading = ref(true)
// Tab state — only one section is mounted at a time so the page stops
// being a giant scroll of cards. Hash-driven so deep links + browser
// back/forward Just Work. Order: Guests (daily workflow) → setup tabs
// (Collaborators + Branding, configured once) → Analytics (results,
// checked periodically). The two action-y tabs anchor the ends; setup
// clusters in the middle.
type EventTab = 'guests' | 'collaborators' | 'branding' | 'analytics' | 'security'
const validTabs: EventTab[] = ['guests', 'collaborators', 'branding', 'analytics', 'security']
function tabFromHash(): EventTab {
if (import.meta.client) {
const h = window.location.hash.replace('#', '') as EventTab
if (validTabs.includes(h)) return h
// Block C / preview alias: older share links used #team.
if (h === ('team' as EventTab)) return 'collaborators'
}
return 'guests'
}
const activeTab = ref<EventTab>(tabFromHash())
function setTab(t: EventTab) {
activeTab.value = t
if (import.meta.client) {
// Update the URL hash without triggering a router scroll-to-top.
history.replaceState(null, '', `#${t}`)
}
}
if (import.meta.client) {
onMounted(() => {
window.addEventListener('hashchange', () => { activeTab.value = tabFromHash() })
})
}
async function refresh() {
const [evt, list] = await Promise.all([
useApi<EventDetail>(`/events/${eventId}`),
@@ -737,7 +768,41 @@ function checkLabel(band?: string): string {
<p class="text-sm text-zinc-400">{{ event.venue }} · {{ fmtDate(event.event_date) }}</p>
</div>
<div class="grid gap-8 lg:grid-cols-[2fr_1fr]">
<!-- Tab nav segmented-control style: a single bordered container
with a brand-tinted "lifted" state for the active tab. Stronger
visual weight than underlined tabs, no overflow tricks (the
previous absolute-positioned underline was leaking a 1px vertical
scrollbar on the sticky container). Mobile wraps onto two rows
when needed rather than introducing horizontal scroll. -->
<nav
role="tablist"
aria-label="Event sections"
class="flex flex-wrap gap-1 rounded-lg border border-zinc-800 bg-zinc-900/40 p-1"
>
<button
v-for="t in [
{ id: 'guests', label: 'Guests' },
{ id: 'collaborators', label: 'Collaborators' },
{ id: 'branding', label: 'Branding' },
{ id: 'analytics', label: 'Analytics' },
{ id: 'security', label: 'Security' },
] as { id: EventTab, label: string }[]"
:key="t.id"
role="tab"
:aria-selected="activeTab === t.id"
:class="[
'flex-1 whitespace-nowrap rounded-md px-3 py-2 text-sm font-medium transition',
activeTab === t.id
? 'border border-brand-700/40 bg-brand-500/10 text-brand-200 shadow-sm'
: 'border border-transparent text-zinc-400 hover:bg-zinc-800/60 hover:text-zinc-100',
]"
@click="setTab(t.id)"
>
{{ t.label }}
</button>
</nav>
<div v-show="activeTab === 'guests'" class="grid gap-8 lg:grid-cols-[2fr_1fr]">
<!-- Primary content: the guest list. Add / Import live as modals
triggered from the toolbar — keeps secondary tools out of the
way until the host needs them. -->
@@ -1121,8 +1186,9 @@ function checkLabel(band?: string): string {
</div>
<!-- Branding (Tier 2 Block D). Editor+ can change colours/logo/cover;
viewers see read-only. -->
<div v-if="event" class="mt-6">
viewers see read-only. Mounted only when its tab is active so the
live preview computes against the current state, not stale data. -->
<div v-if="activeTab === 'branding' && event" class="mt-2">
<BrandingCard
:event-id="eventId"
:your-role="event.your_role"
@@ -1132,17 +1198,24 @@ function checkLabel(band?: string): string {
/>
</div>
<!-- Analytics (Tier 2 Block E). Read-only summary; viewer+ can see it. -->
<div v-if="event" class="mt-6">
<!-- Analytics (Tier 2 Block E). v-if (not v-show) so the GET fires
fresh on each tab visit — hosts revisit this tab specifically to
re-check numbers. -->
<div v-if="activeTab === 'analytics' && event" class="mt-2">
<AnalyticsCard :event-id="eventId" />
</div>
<!-- Team (Tier 2 Block C). Visible to anyone with viewer+ access; action
buttons gated to owners. -->
<div v-if="event" class="mt-6">
<!-- Collaborators (Tier 2 Block C). -->
<div v-if="activeTab === 'collaborators' && event" class="mt-2">
<TeamCard :event-id="eventId" :your-role="event.your_role" />
</div>
<!-- Security (Tier 2 Block G). Per-event thresholds, IP allowlist,
feedback inbox. Editor+ for writes, viewer+ for reads. -->
<div v-if="activeTab === 'security' && event" class="mt-2">
<SecurityCard :event-id="eventId" :your-role="event.your_role" />
</div>
<!-- ===== Modals ===== -->
<!-- All modals share the same pattern: backdrop click + Esc close,
role=dialog + aria-modal, primary action on the right.