feat(tier2): finish the finish line — Block H follow-ups, Block G geolocation, cross-cutting

Three threads of work land here together to close out Tier 2.

### Block H follow-ups — day-of check-in
- Scanner is now an "open on your phone" magic-link flow. Hosts on
  desktop mint a scoped JWT via POST /events/{id}/scanner-ticket and
  render its URL into a QR; phone scans it and lands on /scanner with
  the ticket as bearer. The ticket carries Audience=scanner so it can
  never substitute for a session token.
- Plus-one confirmation at the door: scan → POST /check-in/preview to
  fetch guest + expected party size → confirm buttons ("Just them",
  "Party of N", custom) → POST /check-in. No more silent arrival_count=1.
- Offline scan queue: failed POSTs go into an IndexedDB store and drain
  on the 'online' event with poison-message protection.
- Day-of arrivals headline widget on the event overview, gated to the
  host's local calendar date so it doesn't dominate the page weeks out.
- Tab nav restyled with inline heroicons + scrollable segmented control;
  Check-in moves to the rightmost slot.
- PWA: manifest + service worker scoped to /scanner, generated 192/512
  icons (Go scripted renderer in scripts/gen-scanner-icons.go).
- Confirmation email QR was rendering broken because html/template
  rewrites data: URLs to #ZgotmplZ; mark the value as template.URL.
- Email "open your invitation" link 404'd because we had no token to
  put after /rsvp/. Threaded AccessLink through the RSVPConfirmed NATS
  event from the API at submit time.

### Block G remainder — geolocation + threshold preview
- Pluggable GeoResolver in the fraud engine (NullResolver, IPApiResolver
  for the free ip-api.com fallback, MaxMindResolver behind GG_GEOIP_DB_PATH).
  Wrapped in a Redis cache (30d TTL). Geo flows through both gRPC and
  NATS scoring paths.
- geo_jump scoring feature: >500km in <1h flags ("accessed from Lagos
  and Paris within 12 minutes"); >500km in <6h is a softer signal. The
  existing single-signal cap keeps a lone geo_jump in MEDIUM.
- FraudScored event carries geo_country/city/lat/lon; ApplyScore uses
  COALESCE so a later re-score without geo doesn't wipe earlier data.
- Threshold-slider live preview: GET /events/{id}/security/thresholds/preview
  returns band counts the host's existing access events would have
  fallen into under the proposed thresholds. Debounced (250ms) widget
  under the Advanced sliders so the host gets concrete feedback instead
  of guessing.

### Cross-cutting — audit, tier-gating, feature flags
- audit_log table + internal/audit.Recorder (async fire-and-forget on
  detached context so an audit blip never fails the real action). Wired
  into branding update, thresholds update, allowlist add/remove,
  collaborator invite/role-change/remove, message create/send-now/cancel.
- Tier-gating: extended billing.Limits with MaxCollaborators,
  CustomBranding, Scanner, Broadcasts. Free = none; Pro = 5 + all;
  Business = unlimited. Gates the scanner-ticket, message create,
  branding put, and collaborator invite endpoints with 402 +
  structured upgrade payload. Auto-reminders, fraud detection, and
  analytics deliberately stay on every tier — those are safety + visibility
  features, not upsell levers.
- Feature flags: feature_flags table + internal/flags.Store with 30s
  in-memory refresh, stable sha256(key + user_id) percent bucketing,
  unknown-key-defaults-on. Six Tier 2 flags pre-seeded. Three handlers
  (branding, broadcasts, scanner) check the kill switch ahead of the
  tier gate so ops can pull a feature back without a redeploy.

### Verified
- go test ./... + fraud-engine pytest (12/12 incl. 3 new geo_jump tests + 5
  new flags tests).
- docker compose build + up across api, fraud-engine, notifier, frontend.
- /health endpoints 200; migrations 0014 + 0015 applied; 6 flags
  seeded; audit_log table + partial indexes confirmed.
- Fraud-engine logs confirm geo resolver kind=CachedGeoResolver provider=auto.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-21 20:30:02 +01:00
parent 003a320690
commit 98678ff5a3
49 changed files with 3798 additions and 238 deletions
+206 -33
View File
@@ -1,18 +1,22 @@
package api
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/uuid"
"github.com/skip2/go-qrcode"
"github.com/alchemistkay/guestguard/internal/auth"
"github.com/alchemistkay/guestguard/internal/domain"
"github.com/alchemistkay/guestguard/internal/flags"
"github.com/alchemistkay/guestguard/internal/storage"
)
@@ -20,13 +24,116 @@ import (
// codes at the door, record arrivals, register walk-ins, drive the
// live arrivals counter on the dashboard.
type checkInHandler struct {
logger *slog.Logger
events *storage.EventRepo
guests *storage.GuestRepo
collabs *storage.CollaboratorRepo
repo *storage.CheckInRepo
qrSigner *auth.CheckInQRSigner
hub *Hub
logger *slog.Logger
events *storage.EventRepo
guests *storage.GuestRepo
collabs *storage.CollaboratorRepo
repo *storage.CheckInRepo
qrSigner *auth.CheckInQRSigner
scannerSigner *auth.ScannerJWTSigner
publicBaseURL string
hub *Hub
enforcer *tierEnforcer
flags *flags.Store
}
// --- preview a check-in (POST /events/{id}/check-in/preview) ---
//
// The scanner submits the decoded QR string; we validate the JWT and
// return the guest plus what we already know about them — name,
// expected party size, and whether they've already been recorded.
// No DB writes. The frontend uses this to render the
// "Just them / +1 / +2 / Other" confirmation step before committing
// the check-in, matching how Eventbrite / Lu.ma scanners handle
// plus-ones at the door.
type previewCheckInRequest struct {
QRPayload string `json:"qr_payload"`
}
type previewCheckInResponse struct {
Guest *domain.Guest `json:"guest"`
ExpectedPartySize int `json:"expected_party_size"`
AlreadyCheckedIn bool `json:"already_checked_in"`
ExistingCheckIn *domain.CheckIn `json:"existing_check_in,omitempty"`
}
func (h *checkInHandler) preview(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if !requireScannerEventMatch(w, r, eventID) {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
var req previewCheckInRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
req.QRPayload = strings.TrimSpace(req.QRPayload)
if req.QRPayload == "" {
writeError(w, http.StatusBadRequest, "qr_payload is required")
return
}
claims, status, msg := h.parseCheckInQR(r.Context(), req.QRPayload, eventID)
if status != 0 {
writeError(w, status, msg)
return
}
guest, gerr := h.guests.Get(r.Context(), claims.GuestID)
if gerr != nil || guest == nil {
writeError(w, http.StatusNotFound, "guest not found")
return
}
// arrival_count counts the guest plus their plus-ones; the door
// volunteer most often presses the matching number, so this is what
// drives the default-highlight in the UI.
expected := guest.PlusOnes + 1
existing, _ := h.repo.GetByGuest(r.Context(), guest.ID)
resp := previewCheckInResponse{
Guest: guest,
ExpectedPartySize: expected,
AlreadyCheckedIn: existing != nil,
ExistingCheckIn: existing,
}
writeJSON(w, http.StatusOK, resp)
}
// parseCheckInQR centralises the JWT validation + event-binding +
// guest-belongs-to-event checks that both preview and record need.
// Returns (claims, 0, "") on success or (nil, statusCode, message) on
// the recoverable error paths so the caller writes a single response.
func (h *checkInHandler) parseCheckInQR(ctx context.Context, payload string, eventID uuid.UUID) (*auth.CheckInQR, int, string) {
claims, err := h.qrSigner.Parse(payload)
if err != nil {
if errors.Is(err, auth.ErrExpiredJWT) {
return nil, http.StatusGone, "this QR has expired"
}
return nil, http.StatusBadRequest, "invalid QR"
}
if claims.EventID != eventID {
return nil, http.StatusBadRequest, "this QR belongs to a different event"
}
belongs, err := h.repo.GuestBelongsToEvent(ctx, claims.GuestID, eventID)
if err != nil {
return nil, http.StatusInternalServerError, "failed to verify guest"
}
if !belongs {
return nil, http.StatusNotFound, "guest is no longer on this event"
}
return claims, 0, ""
}
// --- record a check-in (QR-scanner POST) ---
@@ -57,6 +164,9 @@ func (h *checkInHandler) record(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if !requireScannerEventMatch(w, r, eventID) {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
@@ -72,32 +182,9 @@ func (h *checkInHandler) record(w http.ResponseWriter, r *http.Request) {
return
}
claims, err := h.qrSigner.Parse(req.QRPayload)
if err != nil {
switch {
case errors.Is(err, auth.ErrExpiredJWT):
writeError(w, http.StatusGone, "this QR has expired")
default:
writeError(w, http.StatusBadRequest, "invalid QR")
}
return
}
if claims.EventID != eventID {
// JWT was issued for a different event. The scanner may have
// roamed; the host should switch event pages.
writeError(w, http.StatusBadRequest, "this QR belongs to a different event")
return
}
// Sanity: the guest still belongs to this event (host may have
// removed them after issuing the QR).
belongs, err := h.repo.GuestBelongsToEvent(r.Context(), claims.GuestID, eventID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to verify guest")
return
}
if !belongs {
writeError(w, http.StatusNotFound, "guest is no longer on this event")
claims, status, msg := h.parseCheckInQR(r.Context(), req.QRPayload, eventID)
if status != 0 {
writeError(w, status, msg)
return
}
@@ -161,6 +248,9 @@ func (h *checkInHandler) walkIn(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if !requireScannerEventMatch(w, r, eventID) {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
@@ -237,6 +327,9 @@ func (h *checkInHandler) list(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if !requireScannerEventMatch(w, r, eventID) {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
return
}
@@ -285,6 +378,86 @@ func nameOf(g *domain.Guest) string {
return g.Name
}
// --- scanner magic-link (POST /events/{id}/scanner-ticket) ---
type scannerTicketResponse struct {
Token string `json:"token"`
URL string `json:"url"`
QRImage string `json:"qr_image"` // data: URL PNG
ExpiresAt time.Time `json:"expires_at"`
}
// issueScannerTicket mints a short-lived, event-scoped JWT that a host
// can render into a QR code on their desktop event-detail page. The
// door volunteer scans that QR with their phone camera, the scanner
// page reads ?token=<jwt> out of the URL, and uses it as a Bearer for
// the three check-in endpoints — no separate phone login required.
//
// Editor+ on the event. Rate-limited at the route level. Tickets last
// four hours by default (see NewScannerJWTSigner), long enough for a
// full event without the host having to re-mint mid-night.
func (h *checkInHandler) issueScannerTicket(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
}
// Kill switch — ops can disable scanner ticket minting without a
// redeploy if the magic-link UX needs to be pulled back.
if !h.flags.Enabled("checkin_pwa", hostID) {
writeError(w, http.StatusServiceUnavailable, "the scanner is temporarily disabled")
return
}
// The day-of scanner is a Pro+ feature. Free-tier hosts can still
// see arrivals (the headline widget on the overview reads
// /check-ins which is viewer+) but minting a magic link for a
// volunteer's phone is an upsell lever.
if !h.enforcer.allowFeature(w, r, hostID, "scanner",
"The day-of check-in scanner is a Pro feature.") {
return
}
if h.scannerSigner == nil {
writeError(w, http.StatusServiceUnavailable, "scanner tickets are not configured")
return
}
tok, exp, err := h.scannerSigner.Issue(hostID, eventID, time.Now())
if err != nil {
h.logger.Error("issue scanner ticket", "err", err, "event_id", eventID)
writeError(w, http.StatusInternalServerError, "failed to issue ticket")
return
}
// publicBaseURL is the front-of-house origin (e.g. https://guestguard.k4scloud.com).
// We embed the event id as well as the token so the scanner page can
// load the right event metadata before any check-in roundtrip.
base := strings.TrimRight(h.publicBaseURL, "/")
if base == "" {
base = ""
}
scannerURL := base + "/scanner?token=" + url.QueryEscape(tok) + "&event=" + url.QueryEscape(eventID.String())
qrImage, err := renderQRPNG(scannerURL)
if err != nil {
h.logger.Error("render scanner QR", "err", err)
writeError(w, http.StatusInternalServerError, "failed to render QR")
return
}
writeJSON(w, http.StatusOK, scannerTicketResponse{
Token: tok,
URL: scannerURL,
QRImage: qrImage,
ExpiresAt: exp,
})
}
// renderQRPNG converts a JWT-shaped string into a base64-encoded PNG
// data URL the frontend can drop straight into an <img src>. Used by
// the access response so a successful RSVP comes back with the guest's