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
+127 -20
View File
@@ -46,6 +46,20 @@ const saving = ref(false)
const error = ref<string | null>(null)
const allowedFonts = ref<string[]>([])
// Toast state — auto-dismisses after a few seconds; the user can also
// click it to dismiss. Kind drives the colour: success = brand-green,
// error = red. We keep this local to the component rather than reaching
// for a global toast system (the same inline pattern is used on the
// account + billing pages already).
type Toast = { kind: 'success' | 'error'; text: string }
const toast = ref<Toast | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null
function showToast(t: Toast, ms = 4000) {
toast.value = t
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => { toast.value = null }, ms)
}
// Form state — strings so empty maps cleanly to "clear this field".
const primary = ref('')
const accent = ref('')
@@ -99,26 +113,67 @@ async function upload(file: File): Promise<string> {
return json.url as string
}
// Object URLs for the file the user just picked, shown in the preview
// pane while the upload is in flight. Once the server returns its real
// URL we swap to that and revoke the temporary one. Without this the
// preview stays empty until the round-trip completes, which feels broken
// even when uploads are fast.
const logoObjectURL = ref<string | null>(null)
const coverObjectURL = ref<string | null>(null)
function revokeIf(u: string | null) {
if (u) URL.revokeObjectURL(u)
}
async function onLogoSelect(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
revokeIf(logoObjectURL.value)
logoObjectURL.value = URL.createObjectURL(file)
uploadingLogo.value = true
error.value = null
try { logoURL.value = await upload(file) }
catch (e: any) { error.value = useErrMessage(e, 'Logo upload failed') }
finally { uploadingLogo.value = false }
try {
logoURL.value = await upload(file)
} catch (e: any) {
error.value = useErrMessage(e, 'Logo upload failed')
// Roll back the local preview so the host doesn't think the upload
// succeeded when it didn't.
revokeIf(logoObjectURL.value)
logoObjectURL.value = null
} finally {
uploadingLogo.value = false
}
}
async function onCoverSelect(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
revokeIf(coverObjectURL.value)
coverObjectURL.value = URL.createObjectURL(file)
uploadingCover.value = true
error.value = null
try { coverURL.value = await upload(file) }
catch (e: any) { error.value = useErrMessage(e, 'Cover upload failed') }
finally { uploadingCover.value = false }
try {
coverURL.value = await upload(file)
} catch (e: any) {
error.value = useErrMessage(e, 'Cover upload failed')
revokeIf(coverObjectURL.value)
coverObjectURL.value = null
} finally {
uploadingCover.value = false
}
}
// Resolved URLs the preview pane consumes. Prefer the server URL once it's
// landed; while the upload is in flight we show the local object URL so
// the host sees their image straight away.
const logoPreviewURL = computed(() => logoURL.value || logoObjectURL.value || '')
const coverPreviewURL = computed(() => coverURL.value || coverObjectURL.value || '')
onUnmounted(() => {
revokeIf(logoObjectURL.value)
revokeIf(coverObjectURL.value)
})
async function save() {
saving.value = true
error.value = null
@@ -134,8 +189,11 @@ async function save() {
greeting_message: greeting.value,
},
})
showToast({ kind: 'success', text: 'Branding saved.' })
} catch (e: any) {
error.value = useErrMessage(e, 'Could not save branding')
const msg = useErrMessage(e, 'Could not save branding')
error.value = msg
showToast({ kind: 'error', text: msg })
} finally {
saving.value = false
}
@@ -246,13 +304,14 @@ function fmtDate(iso?: string) {
:disabled="!canEdit || uploadingLogo"
@change="onLogoSelect"
/>
<div v-if="logoURL" class="mt-2 flex items-center gap-2">
<img :src="logoURL" alt="logo preview" class="h-12 w-12 rounded object-contain bg-zinc-900" />
<div v-if="logoPreviewURL" class="mt-2 flex items-center gap-2">
<img :src="logoPreviewURL" alt="logo preview" class="h-12 w-12 rounded object-contain bg-zinc-900" />
<span v-if="uploadingLogo" class="text-xs text-zinc-500">Uploading…</span>
<button
v-if="canEdit"
v-if="canEdit && !uploadingLogo"
type="button"
class="text-xs text-zinc-500 hover:text-red-300"
@click="logoURL = ''"
@click="logoURL = ''; revokeIf(logoObjectURL); logoObjectURL = null"
>Remove</button>
</div>
</div>
@@ -265,13 +324,14 @@ function fmtDate(iso?: string) {
:disabled="!canEdit || uploadingCover"
@change="onCoverSelect"
/>
<div v-if="coverURL" class="mt-2 flex items-center gap-2">
<img :src="coverURL" alt="cover preview" class="h-12 w-24 rounded object-cover" />
<div v-if="coverPreviewURL" class="mt-2 flex items-center gap-2">
<img :src="coverPreviewURL" alt="cover preview" class="h-12 w-24 rounded object-cover" />
<span v-if="uploadingCover" class="text-xs text-zinc-500">Uploading…</span>
<button
v-if="canEdit"
v-if="canEdit && !uploadingCover"
type="button"
class="text-xs text-zinc-500 hover:text-red-300"
@click="coverURL = ''"
@click="coverURL = ''; revokeIf(coverObjectURL); coverObjectURL = null"
>Remove</button>
</div>
</div>
@@ -290,23 +350,33 @@ function fmtDate(iso?: string) {
:style="previewStyle"
>
<div
v-if="coverURL"
v-if="coverPreviewURL"
class="h-28 w-full bg-cover bg-center"
:style="{ backgroundImage: `url(${coverURL})` }"
:style="{ backgroundImage: `url(${coverPreviewURL})` }"
></div>
<div v-else class="h-28 w-full" :style="{ background: 'var(--brand-primary)' }"></div>
<div class="p-4">
<div class="mb-3 flex items-center gap-3">
<img v-if="logoURL" :src="logoURL" alt="" class="h-10 w-10 rounded object-contain bg-zinc-900" />
<img v-if="logoPreviewURL" :src="logoPreviewURL" alt="" class="h-10 w-10 rounded object-contain bg-zinc-900" />
<div>
<p class="text-xs uppercase tracking-widest" :style="{ color: 'var(--brand-primary)' }">Invitation</p>
<!-- Eyebrow text uses the accent colour visible on
every page, gives the host immediate feedback that
their accent choice landed. -->
<p class="text-xs uppercase tracking-widest" :style="{ color: 'var(--brand-accent)' }">Invitation</p>
<h3 class="text-xl font-semibold text-zinc-50">{{ eventName || 'Your event name' }}</h3>
</div>
</div>
<p class="mb-3 text-xs text-zinc-400">
{{ eventVenue || 'Venue' }} · {{ fmtDate(eventDate) || 'When' }}
</p>
<p v-if="greeting" class="mb-4 text-sm text-zinc-300">{{ greeting }}</p>
<!-- Greeting takes a 3px accent-colour left border so the
accent shows up even when the host hasn't customised
the message itself. -->
<p
v-if="greeting"
class="mb-4 rounded-r border-l-[3px] bg-zinc-900/40 py-1.5 pl-3 pr-2 text-sm text-zinc-300"
:style="{ borderColor: 'var(--brand-accent)' }"
>{{ greeting }}</p>
<button
type="button"
class="w-full rounded-md px-3 py-2 text-sm font-medium text-zinc-950"
@@ -315,7 +385,44 @@ function fmtDate(iso?: string) {
>Submit RSVP</button>
</div>
</div>
<p class="mt-2 text-xs text-zinc-500">
Primary fills the main button; accent picks out the eyebrow + greeting border.
</p>
</div>
</div>
<!-- Save feedback toast. Teleported to body so the fixed positioning
isn't trapped by the card's stacking context. Click to dismiss
early; auto-fades after 4s. -->
<Teleport to="body">
<Transition
enter-active-class="transition duration-200 ease-out"
enter-from-class="translate-y-2 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-200 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-2 opacity-0"
>
<button
v-if="toast"
type="button"
class="fixed bottom-6 right-6 z-50 flex max-w-sm items-center gap-2 rounded-lg border px-4 py-3 text-left text-sm shadow-lg backdrop-blur"
:class="toast.kind === 'success'
? 'border-brand-700/60 bg-brand-950/90 text-brand-100'
: 'border-red-800/60 bg-red-950/90 text-red-100'"
:aria-live="toast.kind === 'error' ? 'assertive' : 'polite'"
role="status"
@click="toast = null"
>
<svg v-if="toast.kind === 'success'" class="h-4 w-4 shrink-0 text-brand-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M16.704 5.296a1 1 0 010 1.408l-8 8a1 1 0 01-1.408 0l-4-4a1 1 0 011.408-1.408L8 12.592l7.296-7.296a1 1 0 011.408 0z" clip-rule="evenodd" />
</svg>
<svg v-else class="h-4 w-4 shrink-0 text-red-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM10 5a1 1 0 011 1v4a1 1 0 11-2 0V6a1 1 0 011-1zm0 8.5a1.25 1.25 0 110 2.5 1.25 1.25 0 010-2.5z" clip-rule="evenodd" />
</svg>
<span>{{ toast.text }}</span>
</button>
</Transition>
</Teleport>
</section>
</template>