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
+7 -1
View File
@@ -16,7 +16,13 @@ RUN CGO_ENABLED=0 GOOS=linux go build \
FROM alpine:3.20 AS runtime
RUN apk add --no-cache ca-certificates tzdata && \
addgroup -g 1000 app && \
adduser -D -u 1000 -G app app
adduser -D -u 1000 -G app app && \
# Pre-create the branding-uploads dir with the right ownership.
# Docker copies this directory's contents + ownership into a
# named volume on first mount, which is the only way to get the
# volume owned by UID 1000 without a chmod entrypoint hack.
mkdir -p /var/lib/guestguard/uploads && \
chown -R 1000:1000 /var/lib/guestguard
WORKDIR /app
COPY --from=build /out/api /app/api
+18
View File
@@ -100,6 +100,24 @@ class HeuristicScorer:
weighted = sum(sub[k] * self.weights[k] for k in self.weights)
final = int(round(min(max(weighted, 0), 100)))
# Tier 2 Block G — tighten the consecutive-fingerprint false
# positive. Pre-Block-G, a guest opening their invitation a second
# time with even a slightly-shifted device fingerprint (browser
# update, different network) would score ~60 (HIGH band): the
# fingerprint_mismatch sub-score of 100 × 0.40 weight = 40, plus a
# tiny baseline of repeated_access, easily tipped them over.
#
# The rule: a single signal can't push the score into HIGH (>=
# configured high threshold). It takes at least *two* sub-scores
# of >= 70 to escalate. The API re-bands using per-event
# thresholds, but we still cap at 55 here so a single signal
# caps at MEDIUM regardless of how strict the host has set their
# band boundaries.
strong_signals = sum(1 for v in sub.values() if v >= 70)
if strong_signals < 2 and final > 55:
final = 55
reasons.append("single-signal cap applied (need ≥2 signals for HIGH)")
# Update baseline AFTER scoring so the first access sets it without
# being penalised against itself.
if baseline.fingerprint_digest is None:
+11 -1
View File
@@ -6,6 +6,16 @@ const route = useRoute()
// page. Inside the app it just clutters the chrome.
const showGithub = computed(() => route.path === '/')
// Guest-facing pages (RSVP submit, calendar invite accept, unsubscribe)
// are seen by people who don't have GuestGuard accounts and aren't trying
// to create one. The "Sign in / Get started" CTAs are noise for them and
// frame the page as a marketing surface, not the personal invitation it
// actually is. Hide both branches on these routes.
const isGuestPublicPage = computed(() => {
const p = route.path
return p.startsWith('/rsvp/') || p.startsWith('/invites/') || p.startsWith('/unsubscribe/')
})
// Profile dropdown state. Closed by default; opens on click, closes on
// outside click / Escape / route change. Industry-standard pattern: the
// account-scoped actions (Account, Billing, Sign out) tuck under an avatar
@@ -160,7 +170,7 @@ async function signOut() {
</Transition>
</div>
</template>
<template v-else>
<template v-else-if="!isGuestPublicPage">
<NuxtLink to="/login" class="px-3 py-1.5 transition hover:text-zinc-100">Sign in</NuxtLink>
<NuxtLink to="/signup" class="btn-primary !px-3 !py-1.5 text-xs">Get started</NuxtLink>
</template>
+120 -63
View File
@@ -2,10 +2,14 @@
// Tier 2 Block E — host analytics dashboard card. Shown on the event
// detail page; viewer+ role.
//
// Charts are inline SVG rather than chart.js — we avoid the ~70kB bundle
// hit for charts this small, and keep the page server-renderable. If the
// host's expectations grow (zoom, tooltips, animations) chart.js becomes
// the right call.
// Layout philosophy (post-UX-pass): hosts mostly want to answer three
// questions on a glance — "Are people coming?", "Who haven't I heard
// back from?", and "Was my last send-out worth it?". The hierarchy
// reflects that: hero metrics first, supporting charts grouped beneath,
// the long stale-guest list collapsed by default.
//
// Charts are inline SVG rather than chart.js — keeps the bundle lean and
// the page server-renderable.
interface Overview {
invited: number
@@ -54,6 +58,14 @@ async function refresh() {
}
onMounted(refresh)
// --- derived stats ---
const responseRatePct = computed(() => {
const o = data.value?.overview
if (!o || o.invited === 0) return 0
return Math.round(((o.attending + o.declined + o.maybe) / o.invited) * 100)
})
const responseRateMax = computed(() => {
const series = data.value?.response_rate ?? []
return Math.max(1, ...series.map((p) => p.count))
@@ -78,6 +90,17 @@ const funnelPct = computed(() => {
}
})
// Total headcount including plus-ones — the number caterers and venues
// actually need. More useful than "attending" alone, which understates the
// crowd.
const totalHeadcount = computed(() => {
const o = data.value?.overview
if (!o) return 0
return o.attending + o.plus_ones_total
})
// SVG path for the 30-day response sparkline. Empty string when there's
// no data so the path renders as nothing instead of "M NaN,NaN".
const responseRateLineD = computed(() => {
const series = data.value?.response_rate ?? []
if (series.length === 0) return ''
@@ -94,10 +117,15 @@ const responseRateLineD = computed(() => {
.join(' ')
})
// Same series as a filled area underneath the line — gives the
// sparkline visual weight without dominating the surrounding text.
const responseRateAreaD = computed(() => {
const d = responseRateLineD.value
if (!d) return ''
return `${d} L600,80 L0,80 Z`
})
function exportCSV() {
// Issue a fresh ws-ticket-style download. Browsers preserve the
// Authorization header on <a download> if we set it via fetch, so we
// use fetch + blob + anchor.
const url = `${config.public.apiBase}/events/${props.eventId}/analytics/export.csv`
fetch(url, {
headers: auth.liveAccessToken() ? { Authorization: `Bearer ${auth.liveAccessToken()}` } : {},
@@ -127,8 +155,11 @@ function fmtDate(iso?: string | null) {
<template>
<section class="card">
<header class="mb-3 flex items-center justify-between">
<header class="mb-5 flex flex-wrap items-center justify-between gap-3">
<div>
<h2 class="text-lg font-semibold">Analytics</h2>
<p class="text-xs text-zinc-500">Last 30 days · {{ responseRatePct }}% response rate</p>
</div>
<button class="btn-ghost text-sm" :disabled="!data" @click="exportCSV">Export CSV</button>
</header>
@@ -136,72 +167,90 @@ function fmtDate(iso?: string | null) {
<p v-else-if="error" class="text-sm text-red-400">{{ error }}</p>
<div v-else-if="data" class="space-y-6">
<!-- Overview tiles -->
<div class="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-3">
<p class="text-xs uppercase tracking-wider text-zinc-500">Invited</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">{{ data.overview.invited }}</p>
<!-- Hero row the three numbers a host opens this tab for. -->
<div class="grid grid-cols-1 gap-3 md:grid-cols-3">
<!-- Headcount: attending guests + their plus-ones. The big
number is what the venue / caterer needs. -->
<div class="relative overflow-hidden rounded-lg border border-brand-700/60 bg-brand-500/[0.06] p-4">
<p class="text-xs font-medium uppercase tracking-wider text-brand-400">Headcount</p>
<p class="mt-1 text-4xl font-semibold tabular-nums text-brand-200">{{ totalHeadcount }}</p>
<p class="mt-1 text-xs text-zinc-400">
{{ data.overview.attending }} attending
<template v-if="data.overview.plus_ones_total > 0">
· +{{ data.overview.plus_ones_total }} plus-ones
</template>
</p>
</div>
<div class="rounded-md border border-brand-900/60 bg-brand-950/20 p-3">
<p class="text-xs uppercase tracking-wider text-brand-400">Attending</p>
<p class="mt-1 text-2xl font-semibold tabular-nums text-brand-200">{{ data.overview.attending }}</p>
<!-- Waiting on: hosts can act on this number; the chase list is
below. -->
<div class="relative overflow-hidden rounded-lg border border-amber-800/40 bg-amber-950/10 p-4">
<p class="text-xs font-medium uppercase tracking-wider text-amber-400">Awaiting reply</p>
<p class="mt-1 text-4xl font-semibold tabular-nums text-amber-200">{{ data.overview.pending }}</p>
<p class="mt-1 text-xs text-zinc-400">
of {{ data.overview.invited }} invited
</p>
</div>
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-3">
<p class="text-xs uppercase tracking-wider text-zinc-500">Declined</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">{{ data.overview.declined }}</p>
</div>
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-3">
<p class="text-xs uppercase tracking-wider text-zinc-500">Maybe</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">{{ data.overview.maybe }}</p>
</div>
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-3">
<p class="text-xs uppercase tracking-wider text-zinc-500">Pending</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">{{ data.overview.pending }}</p>
</div>
<div class="rounded-md border border-zinc-800 bg-zinc-950 p-3">
<p class="text-xs uppercase tracking-wider text-zinc-500">Plus-ones</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">+{{ data.overview.plus_ones_total }}</p>
<!-- Declined + Maybe stacked here; less prominent than the two
above because a host can't act on them. -->
<div class="relative overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<p class="text-xs font-medium uppercase tracking-wider text-zinc-500">Won't make it</p>
<p class="mt-1 text-4xl font-semibold tabular-nums text-zinc-200">{{ data.overview.declined }}</p>
<p class="mt-1 text-xs text-zinc-400">
<span v-if="data.overview.maybe > 0">+{{ data.overview.maybe }} maybe</span>
<span v-else>declined</span>
</p>
</div>
</div>
<!-- Response rate over time -->
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Responses, last 30 days</p>
<!-- Context row: how fast they're replying + the funnel. Side by
side on desktop so they tell one coherent story. -->
<div class="grid grid-cols-1 gap-5 md:grid-cols-2">
<div class="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<div class="mb-3 flex items-center justify-between">
<p class="text-xs font-medium uppercase tracking-wider text-zinc-500">Replies, last 30 days</p>
</div>
<svg viewBox="0 0 600 80" preserveAspectRatio="none" class="h-20 w-full">
<path :d="responseRateAreaD" fill="rgb(34 197 94 / 0.12)" />
<path :d="responseRateLineD" fill="none" stroke="#22c55e" stroke-width="1.5" />
</svg>
</div>
<!-- Funnel -->
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Funnel</p>
<div class="space-y-1.5">
<div class="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<p class="mb-3 text-xs font-medium uppercase tracking-wider text-zinc-500">Funnel</p>
<div class="space-y-2">
<div class="flex items-center gap-3">
<span class="w-24 shrink-0 text-xs text-zinc-400">Invited</span>
<div class="h-6 flex-1 overflow-hidden rounded bg-zinc-900">
<span class="w-20 shrink-0 text-xs text-zinc-400">Invited</span>
<div class="h-5 flex-1 overflow-hidden rounded bg-zinc-900">
<div class="h-full rounded bg-brand-500" :style="{ width: '100%' }"></div>
</div>
<span class="w-12 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.invited }}</span>
<span class="w-10 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.invited }}</span>
</div>
<div class="flex items-center gap-3">
<span class="w-24 shrink-0 text-xs text-zinc-400">Opened</span>
<div class="h-6 flex-1 overflow-hidden rounded bg-zinc-900">
<span class="w-20 shrink-0 text-xs text-zinc-400">Opened</span>
<div class="h-5 flex-1 overflow-hidden rounded bg-zinc-900">
<div class="h-full rounded bg-brand-400" :style="{ width: funnelPct.opened + '%' }"></div>
</div>
<span class="w-12 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.opened }}</span>
<span class="w-10 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.opened }}</span>
</div>
<div class="flex items-center gap-3">
<span class="w-24 shrink-0 text-xs text-zinc-400">Responded</span>
<div class="h-6 flex-1 overflow-hidden rounded bg-zinc-900">
<span class="w-20 shrink-0 text-xs text-zinc-400">Responded</span>
<div class="h-5 flex-1 overflow-hidden rounded bg-zinc-900">
<div class="h-full rounded bg-brand-300" :style="{ width: funnelPct.responded + '%' }"></div>
</div>
<span class="w-12 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.responded }}</span>
<span class="w-10 shrink-0 text-right text-xs tabular-nums text-zinc-300">{{ data.funnel.responded }}</span>
</div>
</div>
</div>
</div>
<!-- Time-to-respond + plus-ones side by side -->
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<!-- Distributions always visible. Two compact charts side by
side share the height of one tall chart so they cost no extra
scroll. -->
<div class="rounded-lg border border-zinc-800 bg-zinc-950">
<div class="border-b border-zinc-900 px-4 py-3">
<p class="text-sm font-medium text-zinc-200">Reply speed &amp; plus-ones</p>
</div>
<div class="grid grid-cols-1 gap-5 p-4 md:grid-cols-2">
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Time to respond</p>
<div class="space-y-1.5">
@@ -214,7 +263,6 @@ function fmtDate(iso?: string | null) {
</div>
</div>
</div>
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Plus-ones (attending)</p>
<div class="space-y-1.5">
@@ -228,33 +276,42 @@ function fmtDate(iso?: string | null) {
</div>
</div>
</div>
</div>
<!-- Stale guests -->
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">
Haven't responded yet ({{ data.stale_guests.length }})
<!-- Stale guests always visible. With 10+ rows we cap the list
and point at the CSV export for the full count, so the panel
doesn't dominate the page even on busy events. -->
<div class="rounded-lg border border-zinc-800 bg-zinc-950">
<div class="flex items-center gap-2 border-b border-zinc-900 px-4 py-3">
<svg class="h-4 w-4 text-amber-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM10 4a1 1 0 011 1v5l3 1a1 1 0 11-.5 1.93l-3.5-1.16A1 1 0 019 10.83V5a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
<p class="text-sm font-medium text-zinc-200">
{{ data.stale_guests.length === 0 ? "Everyone's replied" : `${data.stale_guests.length} haven't replied yet` }}
</p>
<p v-if="data.stale_guests.length === 0" class="text-sm text-zinc-500">
Everyone you've invited has replied. 🎉
</p>
<ul v-else class="space-y-1.5">
</div>
<ul v-if="data.stale_guests.length > 0" class="space-y-1.5 p-4">
<li
v-for="g in data.stale_guests.slice(0, 10)"
:key="g.guest_id"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-900/40 px-3 py-2 text-sm"
>
<div class="min-w-0 flex-1">
<div class="truncate font-medium text-zinc-100">{{ g.name }}</div>
<div class="truncate text-xs text-zinc-500">
{{ g.email || 'no email' }} · invited {{ fmtDate(g.invited_at) }}
<span v-if="g.has_opened" class="ml-1 text-amber-400">opened</span>
</div>
</div>
<span
v-if="g.has_opened"
class="ml-3 shrink-0 rounded-full bg-amber-900/30 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-amber-300"
title="Opened their link but hasn't responded"
>Opened</span>
</li>
<li v-if="data.stale_guests.length > 10" class="px-3 pt-1 text-xs text-zinc-500">
and {{ data.stale_guests.length - 10 }} more export the CSV for the full list.
</li>
</ul>
<p v-if="data.stale_guests.length > 10" class="mt-2 text-xs text-zinc-500">
and {{ data.stale_guests.length - 10 }} more export the CSV for the full list.
</p>
</div>
</div>
</section>
+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>
+386
View File
@@ -0,0 +1,386 @@
<script setup lang="ts">
// Tier 2 Block G — security controls for one event.
//
// Three concerns share this card because they're conceptually one
// surface ("tune the fraud detector for this event"):
// 1. Thresholds — what score counts as medium/high/block.
// 2. Allowlist — CIDRs that bypass scoring entirely.
// 3. Feedback inbox — host verdicts on past flagged accesses (the
// seed corpus for the future ML model).
//
// Reads are viewer+; writes (PUT/POST/DELETE) are editor+. The server
// enforces the role gate; this component just hides write affordances
// from viewers so the buttons don't promise something a click would
// reject.
interface Thresholds {
medium: number
high: number
block: number
defaults: { medium: number; high: number; block: number }
}
interface AllowlistEntry {
event_id: string
cidr: string
label?: string
created_at: string
}
interface FeedbackEntry {
access_log_id: string
verdict: 'legitimate' | 'suspicious'
note?: string
created_at: string
}
const props = defineProps<{
eventId: string
yourRole?: 'owner' | 'editor' | 'viewer' | null
}>()
const canEdit = computed(() => props.yourRole === 'owner' || props.yourRole === 'editor')
// --- state ---
const loading = ref(true)
const error = ref<string | null>(null)
const saving = ref(false)
const thresholds = ref<Thresholds>({ medium: 30, high: 60, block: 85, defaults: { medium: 30, high: 60, block: 85 } })
const allowlist = ref<AllowlistEntry[]>([])
const feedback = ref<FeedbackEntry[]>([])
// Inline-add form for new CIDR rows.
const newCIDR = ref('')
const newLabel = ref('')
const addingCIDR = ref(false)
// Toast — same shape as the BrandingCard toast.
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)
}
async function refresh() {
loading.value = true
error.value = null
try {
const [th, al, fb] = await Promise.all([
useApi<Thresholds>(`/events/${props.eventId}/security/thresholds`),
useApi<{ entries: AllowlistEntry[] }>(`/events/${props.eventId}/security/allowlist`),
useApi<{ feedback: FeedbackEntry[] }>(`/events/${props.eventId}/security/feedback`),
])
thresholds.value = th
allowlist.value = al.entries || []
feedback.value = fb.feedback || []
} catch (e: any) {
error.value = useErrMessage(e, 'Could not load security settings')
} finally {
loading.value = false
}
}
onMounted(refresh)
// --- thresholds ---
// Keep the three sliders mutually ordered: dragging medium past high
// pushes high; same for high past block. Without this the host can
// momentarily produce an invalid ordering and submit it — server
// would 400 but the form feels broken.
function clampOrder(which: 'medium' | 'high' | 'block') {
if (which === 'medium' && thresholds.value.medium > thresholds.value.high) {
thresholds.value.high = thresholds.value.medium
}
if (which === 'high') {
if (thresholds.value.high < thresholds.value.medium) thresholds.value.medium = thresholds.value.high
if (thresholds.value.high > thresholds.value.block) thresholds.value.block = thresholds.value.high
}
if (which === 'block' && thresholds.value.block < thresholds.value.high) {
thresholds.value.high = thresholds.value.block
}
}
async function saveThresholds() {
saving.value = true
try {
await useApi(`/events/${props.eventId}/security/thresholds`, {
method: 'PUT',
body: {
medium: thresholds.value.medium,
high: thresholds.value.high,
block: thresholds.value.block,
},
})
showToast({ kind: 'success', text: 'Thresholds saved.' })
} catch (e: any) {
showToast({ kind: 'error', text: useErrMessage(e, 'Could not save thresholds') })
} finally {
saving.value = false
}
}
function resetThresholds() {
thresholds.value.medium = thresholds.value.defaults.medium
thresholds.value.high = thresholds.value.defaults.high
thresholds.value.block = thresholds.value.defaults.block
}
// --- allowlist ---
async function addCIDR() {
if (!newCIDR.value.trim()) return
addingCIDR.value = true
try {
await useApi(`/events/${props.eventId}/security/allowlist`, {
method: 'POST',
body: { cidr: newCIDR.value.trim(), label: newLabel.value.trim() },
})
newCIDR.value = ''
newLabel.value = ''
showToast({ kind: 'success', text: 'Allowlist entry added.' })
await refresh()
} catch (e: any) {
showToast({ kind: 'error', text: useErrMessage(e, 'Could not add allowlist entry') })
} finally {
addingCIDR.value = false
}
}
async function removeCIDR(entry: AllowlistEntry) {
if (!confirm(`Remove allowlist entry ${entry.cidr}?`)) return
try {
await useApi(
`/events/${props.eventId}/security/allowlist?cidr=${encodeURIComponent(entry.cidr)}`,
{ method: 'DELETE' },
)
showToast({ kind: 'success', text: 'Allowlist entry removed.' })
await refresh()
} catch (e: any) {
showToast({ kind: 'error', text: useErrMessage(e, 'Could not remove allowlist entry') })
}
}
function fmtDate(iso?: string | null) {
if (!iso) return ''
try { return new Date(iso).toLocaleDateString() } catch { return iso }
}
</script>
<template>
<section class="card">
<header class="mb-3 flex items-center justify-between">
<div>
<h2 class="text-lg font-semibold">Security</h2>
<p class="text-xs text-zinc-500">
Tune the fraud detector for this event.
</p>
</div>
</header>
<p v-if="error" class="mb-3 text-sm text-red-400">{{ error }}</p>
<p v-if="loading" class="text-sm text-zinc-500">Loading security settings</p>
<div v-else class="space-y-8">
<!-- Thresholds -->
<div>
<div class="mb-3 flex items-center justify-between">
<div>
<h3 class="text-sm font-semibold text-zinc-100">Risk thresholds</h3>
<p class="text-xs text-zinc-500">
Scores at or above each cut-off land in that band. Defaults work for most events.
</p>
</div>
<div class="flex items-center gap-2">
<button
v-if="canEdit"
type="button"
class="text-xs text-zinc-400 hover:text-zinc-200"
@click="resetThresholds"
>Reset to defaults</button>
<button
v-if="canEdit"
type="button"
class="btn-primary text-sm"
:disabled="saving"
@click="saveThresholds"
>{{ saving ? 'Saving…' : 'Save thresholds' }}</button>
</div>
</div>
<!-- Visual band ribbon: each segment width matches its threshold
range. Gives the host an at-a-glance read of where their
cut-offs sit, instead of three abstract numbers. -->
<div class="mb-4 h-2 w-full overflow-hidden rounded-full bg-zinc-900">
<div class="flex h-full w-full">
<div :style="{ width: thresholds.medium + '%' }" class="bg-brand-700"></div>
<div :style="{ width: (thresholds.high - thresholds.medium) + '%' }" class="bg-amber-700"></div>
<div :style="{ width: (thresholds.block - thresholds.high) + '%' }" class="bg-orange-700"></div>
<div :style="{ width: (100 - thresholds.block) + '%' }" class="bg-red-700"></div>
</div>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
<label class="block text-sm">
<span class="mb-1 flex items-center justify-between text-xs text-zinc-400">
<span><span class="inline-block h-2 w-2 rounded-full bg-brand-500 mr-1.5"></span>Medium</span>
<span class="font-mono tabular-nums text-zinc-300">{{ thresholds.medium }}</span>
</span>
<input
v-model.number="thresholds.medium"
type="range"
min="0"
max="100"
:disabled="!canEdit"
class="w-full accent-brand-500"
@input="clampOrder('medium')"
/>
</label>
<label class="block text-sm">
<span class="mb-1 flex items-center justify-between text-xs text-zinc-400">
<span><span class="inline-block h-2 w-2 rounded-full bg-amber-500 mr-1.5"></span>High</span>
<span class="font-mono tabular-nums text-zinc-300">{{ thresholds.high }}</span>
</span>
<input
v-model.number="thresholds.high"
type="range"
min="0"
max="100"
:disabled="!canEdit"
class="w-full accent-amber-500"
@input="clampOrder('high')"
/>
</label>
<label class="block text-sm">
<span class="mb-1 flex items-center justify-between text-xs text-zinc-400">
<span><span class="inline-block h-2 w-2 rounded-full bg-red-500 mr-1.5"></span>Block</span>
<span class="font-mono tabular-nums text-zinc-300">{{ thresholds.block }}</span>
</span>
<input
v-model.number="thresholds.block"
type="range"
min="0"
max="100"
:disabled="!canEdit"
class="w-full accent-red-500"
@input="clampOrder('block')"
/>
</label>
</div>
</div>
<!-- Allowlist -->
<div>
<h3 class="mb-1 text-sm font-semibold text-zinc-100">IP allowlist</h3>
<p class="mb-3 text-xs text-zinc-500">
Networks that bypass scoring. Use for office Wi-Fi, the venue's
guest network, or a family router. Accepts a single IP or a CIDR
range. Score is forced to 0 for matching requests.
</p>
<div v-if="canEdit" class="mb-3 flex items-end gap-2">
<div class="flex-1">
<label class="label">CIDR</label>
<input
v-model="newCIDR"
type="text"
placeholder="203.0.113.0/24 or 10.0.0.42"
class="input font-mono text-sm"
/>
</div>
<div class="flex-1">
<label class="label">Label (optional)</label>
<input
v-model="newLabel"
type="text"
placeholder="Office Wi-Fi"
class="input text-sm"
/>
</div>
<button
type="button"
class="btn-primary text-sm"
:disabled="addingCIDR || !newCIDR.trim()"
@click="addCIDR"
>{{ addingCIDR ? 'Adding' : 'Add' }}</button>
</div>
<ul v-if="allowlist.length" class="space-y-1.5">
<li
v-for="entry in allowlist"
:key="entry.cidr"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2"
>
<div class="min-w-0 flex-1">
<p class="font-mono text-sm text-zinc-100">{{ entry.cidr }}</p>
<p class="text-xs text-zinc-500">
{{ entry.label || 'no label' }} · added {{ fmtDate(entry.created_at) }}
</p>
</div>
<button
v-if="canEdit"
type="button"
class="text-xs text-zinc-400 hover:text-red-300"
@click="removeCIDR(entry)"
>Remove</button>
</li>
</ul>
<p v-else class="text-sm text-zinc-500">No allowlist entries yet.</p>
</div>
<!-- Feedback inbox — read-only summary; the actual "mark legitimate / suspicious"
lives on the live monitor / activity feed where the host sees the
access in context. This is the audit trail. -->
<div>
<h3 class="mb-1 text-sm font-semibold text-zinc-100">Verdict history</h3>
<p class="mb-3 text-xs text-zinc-500">
Your previous "legitimate" / "suspicious" marks on flagged accesses. Seeds the model and silences known false positives.
</p>
<ul v-if="feedback.length" class="space-y-1.5">
<li
v-for="f in feedback.slice(0, 10)"
:key="f.access_log_id"
class="flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm"
>
<div class="min-w-0 flex-1">
<p class="text-zinc-200">
Marked <strong :class="f.verdict === 'legitimate' ? 'text-brand-300' : 'text-red-300'">{{ f.verdict }}</strong>
<span class="ml-1 text-xs text-zinc-500">· {{ fmtDate(f.created_at) }}</span>
</p>
<p v-if="f.note" class="truncate text-xs text-zinc-500">{{ f.note }}</p>
</div>
</li>
<li v-if="feedback.length > 10" class="text-xs text-zinc-500">
and {{ feedback.length - 10 }} more.
</li>
</ul>
<p v-else class="text-sm text-zinc-500">No verdicts yet.</p>
</div>
</div>
<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'"
role="status"
@click="toast = null"
>{{ toast.text }}</button>
</Transition>
</Teleport>
</section>
</template>
+1 -1
View File
@@ -127,7 +127,7 @@ function fmtDate(iso?: string | null) {
<template>
<section class="card">
<header class="mb-3 flex items-center justify-between">
<h2 class="text-lg font-semibold">Team</h2>
<h2 class="text-lg font-semibold">Collaborators</h2>
<button
v-if="isOwner"
type="button"
+19
View File
@@ -12,6 +12,25 @@ export default defineNuxtConfig({
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'description', content: 'Real-time fraud detection for event RSVPs.' },
],
// Tier 2 Block D — preload the curated branding-font allowlist so
// the host's font picker actually changes how the RSVP page looks.
// Without these, every choice silently falls back to the system
// default font. preconnect cuts ~150ms off the first paint.
link: [
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' },
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' },
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css2' +
'?family=Playfair+Display:wght@400;600;700' +
'&family=Cormorant+Garamond:wght@400;500;600' +
'&family=Lora:wght@400;500;600' +
'&family=DM+Sans:wght@400;500;600' +
'&family=Manrope:wght@400;500;600' +
'&display=swap',
},
],
},
},
runtimeConfig: {
+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.
+6 -3
View File
@@ -277,10 +277,12 @@ const submitLabel = computed(() => {
class="h-10 w-10 rounded object-contain bg-zinc-900"
/>
<div>
<!-- Eyebrow text takes the accent colour when the host set
one; otherwise falls back to the default brand green. -->
<p
class="text-xs uppercase tracking-widest"
:style="branding?.primary_color ? { color: 'var(--brand-primary)' } : undefined"
:class="branding?.primary_color ? '' : 'text-brand-500'"
:style="branding?.accent_color ? { color: 'var(--brand-accent)' } : undefined"
:class="branding?.accent_color ? '' : 'text-brand-500'"
>
{{ existing ? 'Update your response' : 'Invitation' }}
</p>
@@ -293,7 +295,8 @@ const submitLabel = computed(() => {
<p
v-if="greetingMessage"
class="mb-4 rounded-md border border-brand-900/40 bg-brand-500/[0.04] p-3 text-sm text-zinc-300"
class="mb-4 rounded-r border-l-[3px] bg-brand-500/[0.04] py-1.5 pl-3 pr-2 text-sm text-zinc-300"
:style="branding?.accent_color ? { borderColor: 'var(--brand-accent)' } : { borderColor: 'rgb(34 197 94 / 0.6)' }"
>{{ greetingMessage }}</p>
<p class="mb-6 text-sm">
+280
View File
@@ -0,0 +1,280 @@
package api
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/alchemistkay/guestguard/internal/domain"
"github.com/alchemistkay/guestguard/internal/storage"
)
// securityHandler bundles the Tier 2 Block G endpoints: per-event fraud
// thresholds, the CIDR allowlist, and the fraud-feedback inbox.
type securityHandler struct {
logger *slog.Logger
events *storage.EventRepo
collabs *storage.CollaboratorRepo
allowlist *storage.AllowlistRepo
feedback *storage.FeedbackRepo
access *storage.AccessLogRepo
}
// --- thresholds ---
type thresholdsResponse struct {
domain.FraudThresholds
// Defaults are echoed so the slider can show "reset" affordances
// without a hardcoded duplicate in the frontend.
Defaults domain.FraudThresholds `json:"defaults"`
}
// GET /events/{id}/security/thresholds — viewer+.
func (h *securityHandler) getThresholds(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
return
}
th, err := h.events.GetThresholds(r.Context(), eventID)
if err != nil && !errors.Is(err, domain.ErrEventNotFound) {
writeError(w, http.StatusInternalServerError, "failed to load thresholds")
return
}
writeJSON(w, http.StatusOK, thresholdsResponse{
FraudThresholds: th,
Defaults: domain.DefaultThresholds(),
})
}
// PUT /events/{id}/security/thresholds — editor+.
func (h *securityHandler) putThresholds(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
var req domain.FraudThresholds
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if err := req.Valid(); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := h.events.UpdateThresholds(r.Context(), eventID, req); err != nil {
if errors.Is(err, domain.ErrEventNotFound) {
writeError(w, http.StatusNotFound, "event not found")
return
}
h.logger.Error("update thresholds", "err", err)
writeError(w, http.StatusInternalServerError, "failed to update thresholds")
return
}
writeJSON(w, http.StatusOK, thresholdsResponse{
FraudThresholds: req,
Defaults: domain.DefaultThresholds(),
})
}
// --- allowlist ---
type addAllowlistRequest struct {
CIDR string `json:"cidr"`
Label string `json:"label"`
}
// GET /events/{id}/security/allowlist — viewer+.
func (h *securityHandler) listAllowlist(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
return
}
entries, err := h.allowlist.List(r.Context(), eventID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list allowlist")
return
}
writeJSON(w, http.StatusOK, map[string]any{"entries": entries})
}
// POST /events/{id}/security/allowlist — editor+.
func (h *securityHandler) addAllowlist(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
var req addAllowlistRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
canonical, _, err := domain.ParseAllowlistCIDR(req.CIDR)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
entry, err := h.allowlist.Add(r.Context(), storage.AddAllowlistParams{
EventID: eventID,
CIDR: canonical,
Label: req.Label,
CreatedBy: hostID,
})
if err != nil {
if errors.Is(err, storage.ErrAllowlistExists) {
writeError(w, http.StatusConflict, "that CIDR is already allowlisted")
return
}
h.logger.Error("add allowlist", "err", err)
writeError(w, http.StatusInternalServerError, "failed to add allowlist entry")
return
}
writeJSON(w, http.StatusCreated, entry)
}
// DELETE /events/{id}/security/allowlist?cidr=... — editor+. CIDR comes in
// on the query string so the URL stays RESTful without route-encoding the
// slash in the path.
func (h *securityHandler) removeAllowlist(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
cidr := r.URL.Query().Get("cidr")
if cidr == "" {
writeError(w, http.StatusBadRequest, "cidr query parameter required")
return
}
canonical, _, err := domain.ParseAllowlistCIDR(cidr)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := h.allowlist.Remove(r.Context(), eventID, canonical); err != nil {
if errors.Is(err, domain.ErrAllowlistNotFound) {
writeError(w, http.StatusNotFound, "allowlist entry not found")
return
}
writeError(w, http.StatusInternalServerError, "failed to remove allowlist entry")
return
}
w.WriteHeader(http.StatusNoContent)
}
// --- feedback ---
type feedbackRequest struct {
Verdict string `json:"verdict"` // "legitimate" | "suspicious"
Note string `json:"note"`
}
// POST /events/{id}/access-logs/{log_id}/feedback — editor+. Records the
// host's verdict on a specific access log. We re-verify the log belongs
// to the event (a hostile editor on event A shouldn't be able to mark
// event B's logs).
func (h *securityHandler) recordFeedback(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
logID, ok := parseIDParam(w, r, "log_id")
if !ok {
return
}
// Confirm the access log is on this event.
belongs, err := h.access.BelongsToEvent(r.Context(), logID, eventID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to verify access log")
return
}
if !belongs {
writeError(w, http.StatusNotFound, "access log not found")
return
}
var req feedbackRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if err := (domain.FraudFeedback{Verdict: req.Verdict}).Valid(); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
f, err := h.feedback.Record(r.Context(), storage.RecordFeedbackParams{
AccessLogID: logID,
Verdict: req.Verdict,
MarkedBy: hostID,
Note: req.Note,
})
if err != nil {
h.logger.Error("record feedback", "err", err)
writeError(w, http.StatusInternalServerError, "failed to record feedback")
return
}
writeJSON(w, http.StatusOK, f)
}
// GET /events/{id}/security/feedback — viewer+.
func (h *securityHandler) listFeedback(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
return
}
fb, err := h.feedback.ListForEvent(r.Context(), eventID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list feedback")
return
}
writeJSON(w, http.StatusOK, map[string]any{"feedback": fb})
}
+29
View File
@@ -33,6 +33,7 @@ type rsvpHandler struct {
events *storage.EventRepo
rsvps *storage.RSVPRepo
accessLogs *storage.AccessLogRepo
allowlist *storage.AllowlistRepo
scorer fraudScorer
pub rsvpPublisher
}
@@ -322,6 +323,26 @@ func (h *rsvpHandler) scoreAccess(
h.logger.Error("create access log", "err", err)
}
// Block G: allowlist short-circuit. If the request IP matches a CIDR
// the host has explicitly trusted (office Wi-Fi, family network), we
// skip the fraud engine entirely — score 0, low band. Best-effort:
// any error reading the allowlist falls through to normal scoring so a
// dropped DB connection doesn't lock guests out of an event.
if h.allowlist != nil {
if matched, label, err := h.allowlist.Matches(r.Context(), event.ID, ip); err == nil && matched {
reason := "allowlisted"
if label != "" {
reason = "allowlisted: " + label
}
return fraud.Decision{
Score: 0,
Risk: "low",
Reasons: []string{reason},
Used: true,
}, fingerprint, ip, true
}
}
decision := h.scorer.Score(r.Context(), fraud.ScoreInput{
EventID: event.ID,
GuestID: guest.ID,
@@ -332,6 +353,14 @@ func (h *rsvpHandler) scoreAccess(
UserAgent: r.UserAgent(),
Referrer: r.Referer(),
})
// Block G: re-band the score using this event's thresholds. The
// engine's `Risk` field becomes advisory; the API is the source of
// truth for "what counts as block here". This lets a strict-event
// host set Block=70 while a casual-event host sets it to 95 without
// touching the engine.
decision.Risk = event.Thresholds().Band(decision.Score)
if fraud.IsBlock(decision) {
writeJSON(w, http.StatusForbidden, submitRSVPResponse{
Decision: decision,
+31 -1
View File
@@ -41,6 +41,7 @@ type Server struct {
analytics *analyticsHandler
branding *brandingHandler
uploads *uploadHandler
security *securityHandler
}
type ServerDeps struct {
@@ -100,6 +101,8 @@ func NewServer(deps ServerDeps) (*Server, error) {
inviteRepo := storage.NewInviteRepo(deps.DB)
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
brandingRepo := storage.NewBrandingRepo(deps.DB)
allowlistRepo := storage.NewAllowlistRepo(deps.DB)
feedbackRepo := storage.NewFeedbackRepo(deps.DB)
// Branding image store. Empty UploadsDir leaves it nil and the upload
// + serve handlers report 503, so the rest of the service keeps
@@ -204,6 +207,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
events: eventRepo,
rsvps: rsvpRepo,
accessLogs: accessRepo,
allowlist: allowlistRepo,
scorer: deps.FraudScorer,
pub: deps.RSVPPublisher,
},
@@ -259,6 +263,14 @@ func NewServer(deps ServerDeps) (*Server, error) {
logger: deps.Logger,
store: imageStore,
},
security: &securityHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
allowlist: allowlistRepo,
feedback: feedbackRepo,
access: accessRepo,
},
collabs: &collaboratorHandler{
logger: deps.Logger,
events: eventRepo,
@@ -356,6 +368,24 @@ func (s *Server) Handler() http.Handler {
mux.Handle("GET /events/{id}/analytics/export.csv",
authed(http.HandlerFunc(s.analytics.exportCSV)))
// Block G — smarter fraud detection. Per-event thresholds, CIDR
// allowlists, and the verdict feedback inbox. Reads are viewer+;
// writes are editor+ (matches the rest of the event-edit surface).
mux.Handle("GET /events/{id}/security/thresholds",
authed(http.HandlerFunc(s.security.getThresholds)))
mux.Handle("PUT /events/{id}/security/thresholds",
authed(http.HandlerFunc(s.security.putThresholds)))
mux.Handle("GET /events/{id}/security/allowlist",
authed(http.HandlerFunc(s.security.listAllowlist)))
mux.Handle("POST /events/{id}/security/allowlist",
authed(http.HandlerFunc(s.security.addAllowlist)))
mux.Handle("DELETE /events/{id}/security/allowlist",
authed(http.HandlerFunc(s.security.removeAllowlist)))
mux.Handle("GET /events/{id}/security/feedback",
authed(http.HandlerFunc(s.security.listFeedback)))
mux.Handle("POST /events/{id}/access-logs/{log_id}/feedback",
authed(http.HandlerFunc(s.security.recordFeedback)))
// Block D — event branding. Reads are viewer+; PUT is editor+. The
// upload endpoint is gated by auth only (any signed-in user can mint
// an image URL; the URL is no use without an event they can edit
@@ -470,7 +500,7 @@ func corsMiddleware(next http.Handler) http.Handler {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Vary", "Origin")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Device-Fingerprint")
}
if r.Method == http.MethodOptions {
+25
View File
@@ -36,6 +36,31 @@ type Event struct {
Status EventStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-event fraud-band thresholds (Tier 2 Block G). The defaults are
// set by the migration so events created pre-Block-G continue to use
// the previous global 30/60/85 boundaries until a host changes them.
FraudMediumThreshold int `json:"fraud_medium_threshold"`
FraudHighThreshold int `json:"fraud_high_threshold"`
FraudBlockThreshold int `json:"fraud_block_threshold"`
}
// Thresholds returns the event's fraud band trio as a single value the
// scoring path can pass around (or fall back to defaults if the row was
// loaded before this migration).
func (e *Event) Thresholds() FraudThresholds {
t := FraudThresholds{
Medium: e.FraudMediumThreshold,
High: e.FraudHighThreshold,
Block: e.FraudBlockThreshold,
}
// Treat zeros (or invalid orderings) as "host hasn't customised";
// fall back to defaults rather than wedge every score into the lowest
// band.
if t.Valid() != nil || t.Block == 0 {
return DefaultThresholds()
}
return t
}
var (
+125
View File
@@ -0,0 +1,125 @@
package domain
import (
"errors"
"net"
"time"
"github.com/google/uuid"
)
// Tier 2 Block G — per-event thresholds, allowlists, feedback.
// Default band boundaries — matches the previous hardcoded constants in
// the fraud engine so existing events behave identically until a host
// tweaks them. Mirrored on the events table as columns so a host can
// dial them up/down without touching code.
const (
DefaultFraudMediumThreshold = 30
DefaultFraudHighThreshold = 60
DefaultFraudBlockThreshold = 85
)
// FraudThresholds bundles the trio that controls band assignment for one
// event. Sent to the fraud engine on every Score call so the engine can
// apply the host's preference without a separate DB lookup.
type FraudThresholds struct {
Medium int `json:"medium"`
High int `json:"high"`
Block int `json:"block"`
}
// Valid sanity-checks the ordering. The frontend slider keeps these in
// order; this is a belt-and-braces server-side check.
func (t FraudThresholds) Valid() error {
if t.Medium < 0 || t.High > 100 || t.Block > 100 {
return ErrInvalidThresholds
}
if !(t.Medium <= t.High && t.High <= t.Block) {
return ErrInvalidThresholds
}
return nil
}
// DefaultThresholds returns the package defaults — useful when an event
// row hasn't been loaded yet (e.g. fallback in the scoring path).
func DefaultThresholds() FraudThresholds {
return FraudThresholds{
Medium: DefaultFraudMediumThreshold,
High: DefaultFraudHighThreshold,
Block: DefaultFraudBlockThreshold,
}
}
// Band maps a score to one of low/medium/high/block per the configured
// thresholds. Below medium → low; everything else picks the highest band
// the score crosses.
func (t FraudThresholds) Band(score int) string {
switch {
case score >= t.Block:
return "block"
case score >= t.High:
return "high"
case score >= t.Medium:
return "medium"
default:
return "low"
}
}
// Allowlist is one CIDR range that bypasses scoring entirely for the
// event. Hosts use this for known-good networks (office Wi-Fi, the
// venue's guest network, family routers). Score = 0, band = low,
// short-circuited before the fraud engine is even called.
type Allowlist struct {
EventID uuid.UUID `json:"event_id"`
CIDR string `json:"cidr"`
Label string `json:"label,omitempty"`
CreatedBy *uuid.UUID `json:"created_by,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// ParseAllowlistCIDR validates and normalises a CIDR string. Single IPs
// are accepted and widened to /32 (IPv4) or /128 (IPv6). Returns the
// canonical string + the parsed *net.IPNet so the API layer can use both.
func ParseAllowlistCIDR(input string) (string, *net.IPNet, error) {
// Bare IP without /mask? Treat as a host route.
if ip := net.ParseIP(input); ip != nil {
if ip.To4() != nil {
input += "/32"
} else {
input += "/128"
}
}
_, ipnet, err := net.ParseCIDR(input)
if err != nil {
return "", nil, ErrInvalidCIDR
}
return ipnet.String(), ipnet, nil
}
// FraudFeedback is one host-back annotation on an access log: "this was
// fine despite the score" or "this really was suspicious". Seeds the
// future labelled-data ML model and lets hosts hide repeat false
// positives from their live monitor.
type FraudFeedback struct {
AccessLogID uuid.UUID `json:"access_log_id"`
Verdict string `json:"verdict"` // "legitimate" | "suspicious"
MarkedBy *uuid.UUID `json:"marked_by,omitempty"`
Note string `json:"note,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
func (f FraudFeedback) Valid() error {
if f.Verdict != "legitimate" && f.Verdict != "suspicious" {
return ErrInvalidVerdict
}
return nil
}
var (
ErrInvalidThresholds = errors.New("invalid thresholds (must satisfy 0 <= medium <= high <= block <= 100)")
ErrInvalidCIDR = errors.New("invalid CIDR — expected e.g. 203.0.113.0/24 or 2001:db8::/32")
ErrInvalidVerdict = errors.New("verdict must be 'legitimate' or 'suspicious'")
ErrAllowlistNotFound = errors.New("allowlist entry not found")
)
+86
View File
@@ -0,0 +1,86 @@
package domain
import "testing"
func TestThresholdsBand(t *testing.T) {
tt := DefaultThresholds() // 30/60/85
cases := map[int]string{
0: "low", 15: "low", 29: "low",
30: "medium", 45: "medium", 59: "medium",
60: "high", 70: "high", 84: "high",
85: "block", 99: "block", 100: "block",
}
for score, want := range cases {
if got := tt.Band(score); got != want {
t.Errorf("Band(%d) = %q, want %q", score, got, want)
}
}
}
func TestThresholdsValid(t *testing.T) {
ok := []FraudThresholds{
{0, 0, 0},
{30, 60, 85},
{10, 50, 90},
{50, 50, 50}, // equality at every boundary is allowed
{100, 100, 100},
}
for _, th := range ok {
if err := th.Valid(); err != nil {
t.Errorf("expected %+v to be valid, got %v", th, err)
}
}
bad := []FraudThresholds{
{60, 30, 85}, // medium > high
{30, 85, 60}, // high > block
{-1, 30, 60}, // negative
{30, 60, 101},
}
for _, th := range bad {
if err := th.Valid(); err == nil {
t.Errorf("expected %+v to be invalid", th)
}
}
}
func TestParseAllowlistCIDR(t *testing.T) {
cases := []struct {
in, want string
ok bool
}{
{"203.0.113.0/24", "203.0.113.0/24", true},
{"203.0.113.42", "203.0.113.42/32", true}, // bare IPv4 → /32
{"2001:db8::/32", "2001:db8::/32", true},
{"::1", "::1/128", true}, // bare IPv6 → /128
{"not-an-ip", "", false},
{"", "", false},
{"999.0.0.0/24", "", false},
}
for _, tc := range cases {
got, _, err := ParseAllowlistCIDR(tc.in)
if tc.ok {
if err != nil {
t.Errorf("ParseAllowlistCIDR(%q) unexpected err: %v", tc.in, err)
continue
}
if got != tc.want {
t.Errorf("ParseAllowlistCIDR(%q) = %q, want %q", tc.in, got, tc.want)
}
} else if err == nil {
t.Errorf("ParseAllowlistCIDR(%q) should have rejected", tc.in)
}
}
}
func TestFraudFeedbackValid(t *testing.T) {
for _, v := range []string{"legitimate", "suspicious"} {
if err := (FraudFeedback{Verdict: v}).Valid(); err != nil {
t.Errorf("verdict %q should be valid: %v", v, err)
}
}
for _, v := range []string{"", "fraud", "ok", "LEGITIMATE"} {
if err := (FraudFeedback{Verdict: v}).Valid(); err == nil {
t.Errorf("verdict %q should be invalid", v)
}
}
}
+15
View File
@@ -109,6 +109,21 @@ func (r *AccessLogRepo) ListRecentScoredByEvent(ctx context.Context, eventID uui
return out, rows.Err()
}
// BelongsToEvent reports whether the access log identified by `id` is
// attached (via guest) to `eventID`. Used by the feedback endpoint to
// stop a hostile editor on event A from marking event B's logs.
func (r *AccessLogRepo) BelongsToEvent(ctx context.Context, id, eventID uuid.UUID) (bool, error) {
var ok bool
err := r.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM access_logs a
JOIN guests g ON g.id = a.guest_id
WHERE a.id = $1 AND g.event_id = $2
)
`, id, eventID).Scan(&ok)
return ok, err
}
func (r *AccessLogRepo) ApplyScore(ctx context.Context, p ApplyScoreParams) error {
const q = `
UPDATE access_logs
+8 -7
View File
@@ -57,7 +57,7 @@ func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Ev
const q = `
INSERT INTO events (host_id, name, slug, event_date, venue, max_capacity, settings, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
`
row := tx.QueryRow(ctx, q,
p.HostID, p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
@@ -86,7 +86,7 @@ func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Ev
func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error) {
const q = `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1
`
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id))
@@ -104,7 +104,7 @@ func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error
// merging both cases we avoid leaking existence on cross-tenant lookups.
func (r *EventRepo) GetForHost(ctx context.Context, id, hostID uuid.UUID) (*domain.Event, error) {
const q = `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1 AND host_id = $2
`
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id, hostID))
@@ -131,7 +131,7 @@ func (r *EventRepo) ListForUser(ctx context.Context, userID uuid.UUID, collabEve
}
rows, err := r.pool.Query(ctx, `
SELECT DISTINCT
id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
WHERE host_id = $1
OR id = ANY($2::uuid[])
@@ -167,14 +167,14 @@ func (r *EventRepo) List(ctx context.Context, hostID uuid.UUID, limit, offset in
)
if hostID == uuid.Nil {
rows, err = r.pool.Query(ctx, `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
`, limit, offset)
} else {
rows, err = r.pool.Query(ctx, `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
WHERE host_id = $1
ORDER BY created_at DESC
@@ -239,7 +239,7 @@ func (r *EventRepo) update(ctx context.Context, id, hostID uuid.UUID, p UpdateEv
q += ` AND ($2::uuid IS NULL OR $2::uuid = host_id OR TRUE)`
}
q += `
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
`
var settingsJSON []byte
@@ -304,6 +304,7 @@ func scanEvent(s rowScanner) (*domain.Event, error) {
err := s.Scan(
&ev.ID, &ev.HostID, &ev.Name, &ev.Slug, &ev.EventDate, &ev.Venue,
&ev.MaxCapacity, &settingsJSON, &ev.Status, &ev.CreatedAt, &ev.UpdatedAt,
&ev.FraudMediumThreshold, &ev.FraudHighThreshold, &ev.FraudBlockThreshold,
)
if err != nil {
return nil, err
+242
View File
@@ -0,0 +1,242 @@
package storage
import (
"context"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/alchemistkay/guestguard/internal/domain"
)
// AllowlistRepo manages the per-event CIDR bypass list. Lookups happen
// before each fraud-engine call so they need to be cheap — the index on
// event_id keeps that O(log n) even on very busy events.
type AllowlistRepo struct {
pool *pgxpool.Pool
}
func NewAllowlistRepo(db *DB) *AllowlistRepo {
return &AllowlistRepo{pool: db.Pool}
}
// List returns every CIDR allowlisted for the event, newest first.
func (r *AllowlistRepo) List(ctx context.Context, eventID uuid.UUID) ([]domain.Allowlist, error) {
rows, err := r.pool.Query(ctx, `
SELECT event_id, ip_cidr::text, COALESCE(label, ''), created_by, created_at
FROM event_allowlists
WHERE event_id = $1
ORDER BY created_at DESC
`, eventID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []domain.Allowlist{}
for rows.Next() {
var a domain.Allowlist
if err := rows.Scan(&a.EventID, &a.CIDR, &a.Label, &a.CreatedBy, &a.CreatedAt); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
type AddAllowlistParams struct {
EventID uuid.UUID
CIDR string // pre-validated; ParseAllowlistCIDR canonicalised it
Label string
CreatedBy uuid.UUID
}
// Add inserts a row. A pre-existing (event_id, ip_cidr) returns
// ErrAllowlistExists so the API can render a friendly 409 instead of the
// raw Postgres unique-violation.
func (r *AllowlistRepo) Add(ctx context.Context, p AddAllowlistParams) (*domain.Allowlist, error) {
const q = `
INSERT INTO event_allowlists (event_id, ip_cidr, label, created_by)
VALUES ($1, $2::inet, NULLIF($3, ''), $4)
RETURNING event_id, ip_cidr::text, COALESCE(label, ''), created_by, created_at
`
var a domain.Allowlist
err := r.pool.QueryRow(ctx, q, p.EventID, p.CIDR, p.Label, p.CreatedBy).Scan(
&a.EventID, &a.CIDR, &a.Label, &a.CreatedBy, &a.CreatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrAllowlistExists
}
return nil, err
}
return &a, nil
}
// Remove deletes an allowlist entry. Returns ErrAllowlistNotFound if the
// (event, cidr) tuple doesn't exist.
func (r *AllowlistRepo) Remove(ctx context.Context, eventID uuid.UUID, cidr string) error {
tag, err := r.pool.Exec(ctx,
`DELETE FROM event_allowlists WHERE event_id = $1 AND ip_cidr = $2::inet`,
eventID, strings.TrimSpace(cidr))
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrAllowlistNotFound
}
return nil
}
// Matches reports whether the given IP falls inside any allowlisted CIDR
// for the event. Returns the matching label (if any) so the API can log
// "bypassed allowlist=Office Wi-Fi" instead of a bare boolean.
//
// We push the CIDR containment into Postgres via the inet `>>=` operator
// — much faster than streaming every row back to Go and matching there.
// One DB round-trip per access, indexed by event_id.
func (r *AllowlistRepo) Matches(ctx context.Context, eventID uuid.UUID, ip string) (bool, string, error) {
if ip == "" {
return false, "", nil
}
var label string
err := r.pool.QueryRow(ctx, `
SELECT COALESCE(label, '')
FROM event_allowlists
WHERE event_id = $1
AND ip_cidr >>= $2::inet
LIMIT 1
`, eventID, ip).Scan(&label)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return false, "", nil
}
// Invalid IP gets a Postgres error — treat as "doesn't match" so a
// malformed forwarded IP doesn't blow up the access path.
return false, "", nil
}
return true, label, nil
}
// --- thresholds ---
// GetThresholds returns the per-event fraud thresholds. Missing event
// surfaces as the global defaults — the caller normally has the event
// loaded already and doesn't need this method, but the fraud engine /
// access path can use it as a cheap lookup without re-loading the row.
func (r *EventRepo) GetThresholds(ctx context.Context, eventID uuid.UUID) (domain.FraudThresholds, error) {
var th domain.FraudThresholds
err := r.pool.QueryRow(ctx, `
SELECT fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1
`, eventID).Scan(&th.Medium, &th.High, &th.Block)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.DefaultThresholds(), domain.ErrEventNotFound
}
return domain.DefaultThresholds(), err
}
return th, nil
}
// UpdateThresholds patches the trio. Validation lives in the handler
// (host-facing error messages), but we keep the SQL guard rail with the
// ordering check duplicated at the DB level — a misbehaving client should
// never be able to write nonsense.
func (r *EventRepo) UpdateThresholds(ctx context.Context, eventID uuid.UUID, th domain.FraudThresholds) error {
if err := th.Valid(); err != nil {
return err
}
tag, err := r.pool.Exec(ctx, `
UPDATE events SET
fraud_medium_threshold = $2,
fraud_high_threshold = $3,
fraud_block_threshold = $4,
updated_at = now()
WHERE id = $1
`, eventID, th.Medium, th.High, th.Block)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrEventNotFound
}
return nil
}
// --- feedback ---
type FeedbackRepo struct {
pool *pgxpool.Pool
}
func NewFeedbackRepo(db *DB) *FeedbackRepo {
return &FeedbackRepo{pool: db.Pool}
}
type RecordFeedbackParams struct {
AccessLogID uuid.UUID
Verdict string // "legitimate" | "suspicious"
MarkedBy uuid.UUID
Note string
}
// Record upserts the verdict. Hosts sometimes change their mind ("oh,
// that was Aunty after all"); ON CONFLICT lets the second click win
// rather than 409-ing them.
func (r *FeedbackRepo) Record(ctx context.Context, p RecordFeedbackParams) (*domain.FraudFeedback, error) {
const q = `
INSERT INTO fraud_feedback (access_log_id, verdict, marked_by, note)
VALUES ($1, $2, $3, NULLIF($4, ''))
ON CONFLICT (access_log_id) DO UPDATE SET
verdict = EXCLUDED.verdict,
marked_by = EXCLUDED.marked_by,
note = EXCLUDED.note,
created_at = now()
RETURNING access_log_id, verdict, marked_by, COALESCE(note, ''), created_at
`
var f domain.FraudFeedback
err := r.pool.QueryRow(ctx, q, p.AccessLogID, p.Verdict, p.MarkedBy, p.Note).Scan(
&f.AccessLogID, &f.Verdict, &f.MarkedBy, &f.Note, &f.CreatedAt,
)
if err != nil {
return nil, err
}
return &f, nil
}
// ListForEvent returns every feedback row for access logs on the event,
// newest first. Powers the host's "I've reviewed these" filter on the
// Security tab and the future ML training pipeline.
func (r *FeedbackRepo) ListForEvent(ctx context.Context, eventID uuid.UUID) ([]domain.FraudFeedback, error) {
rows, err := r.pool.Query(ctx, `
SELECT f.access_log_id, f.verdict, f.marked_by, COALESCE(f.note, ''), f.created_at
FROM fraud_feedback f
JOIN access_logs a ON a.id = f.access_log_id
JOIN guests g ON g.id = a.guest_id
WHERE g.event_id = $1
ORDER BY f.created_at DESC
`, eventID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []domain.FraudFeedback{}
for rows.Next() {
var f domain.FraudFeedback
if err := rows.Scan(&f.AccessLogID, &f.Verdict, &f.MarkedBy, &f.Note, &f.CreatedAt); err != nil {
return nil, err
}
out = append(out, f)
}
return out, rows.Err()
}
// ErrAllowlistExists is the storage-layer signal for a duplicate insert.
// Exposed here (not in domain) because the API layer is what cares about
// the 409 mapping — domain just sees "already exists".
var ErrAllowlistExists = errors.New("allowlist entry already exists")
@@ -0,0 +1,14 @@
DROP INDEX IF EXISTS idx_allowlists_event;
DROP TABLE IF EXISTS event_allowlists;
DROP TABLE IF EXISTS fraud_feedback;
ALTER TABLE access_logs
DROP COLUMN IF EXISTS geo_lon,
DROP COLUMN IF EXISTS geo_lat,
DROP COLUMN IF EXISTS geo_city,
DROP COLUMN IF EXISTS geo_country;
ALTER TABLE events
DROP COLUMN IF EXISTS fraud_block_threshold,
DROP COLUMN IF EXISTS fraud_high_threshold,
DROP COLUMN IF EXISTS fraud_medium_threshold;
@@ -0,0 +1,44 @@
-- Tier 2 Block G — smarter fraud detection.
--
-- Four schema additions:
-- 1. Per-event tunable thresholds. Defaults match the previous hardcoded
-- 30/60/85 band boundaries so existing events behave identically until
-- a host tweaks them.
-- 2. Geolocation columns on access_logs. The fraud engine fills these
-- asynchronously; nullable so logs from before this migration aren't
-- retroactively required to have geo data.
-- 3. fraud_feedback for the "this was legitimate / actually suspicious"
-- hostback. Seeds the future ML model and lets hosts silence specific
-- false positives.
-- 4. event_allowlists for CIDR-based bypass — the corporate-Wi-Fi and
-- family-router escape valve.
ALTER TABLE events
ADD COLUMN IF NOT EXISTS fraud_medium_threshold SMALLINT NOT NULL DEFAULT 30,
ADD COLUMN IF NOT EXISTS fraud_high_threshold SMALLINT NOT NULL DEFAULT 60,
ADD COLUMN IF NOT EXISTS fraud_block_threshold SMALLINT NOT NULL DEFAULT 85;
ALTER TABLE access_logs
ADD COLUMN IF NOT EXISTS geo_country TEXT,
ADD COLUMN IF NOT EXISTS geo_city TEXT,
ADD COLUMN IF NOT EXISTS geo_lat DOUBLE PRECISION,
ADD COLUMN IF NOT EXISTS geo_lon DOUBLE PRECISION;
CREATE TABLE IF NOT EXISTS fraud_feedback (
access_log_id UUID PRIMARY KEY REFERENCES access_logs(id) ON DELETE CASCADE,
verdict TEXT NOT NULL CHECK (verdict IN ('legitimate', 'suspicious')),
marked_by UUID REFERENCES users(id) ON DELETE SET NULL,
note TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS event_allowlists (
event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
ip_cidr INET NOT NULL,
label TEXT,
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (event_id, ip_cidr)
);
CREATE INDEX IF NOT EXISTS idx_allowlists_event ON event_allowlists(event_id);
+241
View File
@@ -0,0 +1,241 @@
//go:build integration
package integration_test
import (
"context"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
)
// Tier 2 Block G — per-event thresholds, allowlists, feedback.
type thresholdsResp struct {
Medium int `json:"medium"`
High int `json:"high"`
Block int `json:"block"`
Defaults struct {
Medium int `json:"medium"`
High int `json:"high"`
Block int `json:"block"`
} `json:"defaults"`
}
// TestSecurityThresholdsRoundTrip confirms a fresh event has the default
// 30/60/85 thresholds, a PUT persists, and an invalid ordering is rejected
// at the API rather than reaching the DB.
func TestSecurityThresholdsRoundTrip(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, _, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Thresholds", "thresholds-test")
var got thresholdsResp
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID),
token, http.StatusOK, &got)
if got.Medium != 30 || got.High != 60 || got.Block != 85 {
t.Fatalf("defaults: got %+v", got)
}
if got.Defaults.Medium != 30 {
t.Errorf("defaults echo missing: %+v", got)
}
// Tighten the thresholds — a strict event blocks at 70 rather than 85.
putJSON(t, fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID), token,
map[string]any{"medium": 20, "high": 50, "block": 70}, http.StatusOK, nil)
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID),
token, http.StatusOK, &got)
if got.Medium != 20 || got.High != 50 || got.Block != 70 {
t.Errorf("after PUT: got %+v, want 20/50/70", got)
}
// Invalid ordering: medium > high — rejected.
assertStatus(t, http.MethodPut,
fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID), token,
map[string]any{"medium": 80, "high": 50, "block": 90}, http.StatusBadRequest)
}
// TestSecurityAllowlistCRUD covers add → list → remove + duplicate
// rejection + invalid CIDR rejection.
func TestSecurityAllowlistCRUD(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, _, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Allowlist", "allowlist-test")
// Add a CIDR + a single IP (which we auto-widen to /32).
postJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
token, map[string]any{"cidr": "203.0.113.0/24", "label": "Office"},
http.StatusCreated, nil)
postJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
token, map[string]any{"cidr": "10.0.0.42", "label": "Family router"},
http.StatusCreated, nil)
// List.
var list struct {
Entries []struct {
CIDR string `json:"cidr"`
Label string `json:"label"`
} `json:"entries"`
}
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
token, http.StatusOK, &list)
if len(list.Entries) != 2 {
t.Fatalf("expected 2 entries, got %d", len(list.Entries))
}
foundOffice := false
foundFamily := false
for _, e := range list.Entries {
if e.CIDR == "203.0.113.0/24" {
foundOffice = true
}
if e.CIDR == "10.0.0.42/32" { // auto-widened
foundFamily = true
}
}
if !foundOffice || !foundFamily {
t.Errorf("entries: %+v", list.Entries)
}
// Duplicate → 409.
assertStatus(t, http.MethodPost,
fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID), token,
map[string]any{"cidr": "203.0.113.0/24"}, http.StatusConflict)
// Invalid CIDR → 400.
assertStatus(t, http.MethodPost,
fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID), token,
map[string]any{"cidr": "not-an-ip"}, http.StatusBadRequest)
// Remove the office one.
assertStatus(t, http.MethodDelete,
fmt.Sprintf("%s/events/%s/security/allowlist?cidr=%s", srv.URL, eventID, "203.0.113.0%2F24"),
token, nil, http.StatusNoContent)
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
token, http.StatusOK, &list)
if len(list.Entries) != 1 {
t.Errorf("after delete: expected 1 entry, got %d", len(list.Entries))
}
}
// TestSecurityFeedbackRecord exercises POST feedback + list. The access
// log id is forged via the DB so we don't need to drive a full RSVP flow
// — only the feedback path is under test here.
func TestSecurityFeedbackRecord(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, db, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Feedback", "feedback-test")
// Insert a guest + access log directly so we have an ID to feed back on.
var guestID, accessLogID uuid.UUID
must(t, db.Pool.QueryRow(ctx, `
INSERT INTO guests (event_id, name) VALUES ($1, 'Test')
RETURNING id
`, eventID).Scan(&guestID), "insert guest")
must(t, db.Pool.QueryRow(ctx, `
INSERT INTO access_logs (guest_id) VALUES ($1) RETURNING id
`, guestID).Scan(&accessLogID), "insert access_log")
// Record a verdict.
postJSONAuthed(t,
fmt.Sprintf("%s/events/%s/access-logs/%s/feedback", srv.URL, eventID, accessLogID),
token,
map[string]any{"verdict": "legitimate", "note": "Aunty's actually fine"},
http.StatusOK, nil)
// Upsert: change verdict on second call.
postJSONAuthed(t,
fmt.Sprintf("%s/events/%s/access-logs/%s/feedback", srv.URL, eventID, accessLogID),
token,
map[string]any{"verdict": "suspicious"},
http.StatusOK, nil)
// List.
var list struct {
Feedback []struct {
AccessLogID uuid.UUID `json:"access_log_id"`
Verdict string `json:"verdict"`
} `json:"feedback"`
}
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/security/feedback", srv.URL, eventID),
token, http.StatusOK, &list)
if len(list.Feedback) != 1 {
t.Fatalf("expected 1 feedback row after upsert, got %d", len(list.Feedback))
}
if list.Feedback[0].Verdict != "suspicious" {
t.Errorf("verdict not upserted: %+v", list.Feedback)
}
// Cross-tenant: another event's editor can't mark this log.
otherEventID := createEvent(t, srv.URL, token, "Other", "other-feedback")
assertStatus(t, http.MethodPost,
fmt.Sprintf("%s/events/%s/access-logs/%s/feedback", srv.URL, otherEventID, accessLogID),
token,
map[string]any{"verdict": "legitimate"},
http.StatusNotFound)
// Invalid verdict → 400.
assertStatus(t, http.MethodPost,
fmt.Sprintf("%s/events/%s/access-logs/%s/feedback", srv.URL, eventID, accessLogID),
token,
map[string]any{"verdict": "kinda-sus"},
http.StatusBadRequest)
}
// TestSecurityAuthzMatrix confirms viewers can read but not write, and
// non-members can't even see the endpoints exist.
func TestSecurityAuthzMatrix(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, db, ownerID, ownerToken := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, ownerToken, "Authz Sec", "authz-sec")
viewer, viewerToken := makeAuthedUser(t, ctx, db.Pool)
directlyInsertCollaborator(t, ctx, db.Pool, eventID, viewer, "viewer", uuid.UUID(ownerID))
// Viewer can read.
assertStatus(t, http.MethodGet,
fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID),
viewerToken, nil, http.StatusOK)
assertStatus(t, http.MethodGet,
fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
viewerToken, nil, http.StatusOK)
// Viewer can't write.
assertStatus(t, http.MethodPut,
fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID),
viewerToken, map[string]any{"medium": 25, "high": 55, "block": 80},
http.StatusForbidden)
assertStatus(t, http.MethodPost,
fmt.Sprintf("%s/events/%s/security/allowlist", srv.URL, eventID),
viewerToken, map[string]any{"cidr": "10.0.0.0/24"}, http.StatusForbidden)
// Outsider: 404 everywhere.
_, outsiderToken := makeAuthedUser(t, ctx, db.Pool)
assertStatus(t, http.MethodGet,
fmt.Sprintf("%s/events/%s/security/thresholds", srv.URL, eventID),
outsiderToken, nil, http.StatusNotFound)
}