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
+115
View File
@@ -0,0 +1,115 @@
package auth
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
// ScannerClaims is the bearer token a host's phone uses to drive the
// check-in scanner. Tier 2 Block H follow-up.
//
// The desktop event-detail page mints one of these via POST
// /events/{id}/scanner-ticket, renders the magic URL into a QR, the
// host scans it with their phone camera, and the scanner page reads
// the token out of the URL. No second login required — the desktop
// host's session is the source of authority for the ticket-issuing
// call.
//
// Scoped: a scanner JWT only authorises POST /events/{id}/check-in,
// POST /events/{id}/walk-ins, and GET /events/{id}/check-ins for the
// `EventID` it carries. Everything else returns 401. This means a
// host who texted the magic link to a door volunteer hasn't given out
// blanket account access.
//
// The token carries Audience="scanner" so the normal Bearer-token
// middleware can reject it for non-scanner endpoints even though it
// shares the same HMAC secret as the platform session JWT.
type ScannerClaims struct {
UserID uuid.UUID `json:"user"`
EventID uuid.UUID `json:"event"`
jwt.RegisteredClaims
}
// ScannerJWTAudience is the audience value that disambiguates a scanner
// token from a regular session access token (both are HS256 with the
// platform secret). Exported so middleware can refuse cross-purpose use.
const ScannerJWTAudience = "scanner"
// ScannerJWTSigner mints + verifies the scoped scanner tokens. Same
// HMAC secret as the rest of the platform.
type ScannerJWTSigner struct {
secret []byte
issuer string
ttl time.Duration
parser *jwt.Parser
}
// NewScannerJWTSigner — ttl bounds how long a magic URL stays usable
// before the host has to mint a fresh one. Default in the API is 4h
// so a door volunteer can stay on the scanner across a full event
// without needing the host to babysit them.
func NewScannerJWTSigner(secret, issuer string, ttl time.Duration) (*ScannerJWTSigner, error) {
if len(secret) < 32 {
return nil, fmt.Errorf("jwt secret must be at least 32 bytes")
}
if ttl <= 0 {
return nil, fmt.Errorf("scanner ttl must be positive")
}
return &ScannerJWTSigner{
secret: []byte(secret),
issuer: issuer,
ttl: ttl,
parser: jwt.NewParser(
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithIssuer(issuer),
jwt.WithAudience(ScannerJWTAudience),
jwt.WithExpirationRequired(),
),
}, nil
}
func (s *ScannerJWTSigner) Issue(userID, eventID uuid.UUID, now time.Time) (string, time.Time, error) {
exp := now.Add(s.ttl)
claims := ScannerClaims{
UserID: userID,
EventID: eventID,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: s.issuer,
Subject: userID.String(),
Audience: jwt.ClaimStrings{ScannerJWTAudience},
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now.Add(-1 * time.Second)),
ExpiresAt: jwt.NewNumericDate(exp),
ID: uuid.NewString(),
},
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := tok.SignedString(s.secret)
if err != nil {
return "", time.Time{}, err
}
return signed, exp, nil
}
// Parse returns the bound user + event. Maps token-expiry to
// ErrExpiredJWT so the API can render a friendlier 410.
func (s *ScannerJWTSigner) Parse(raw string) (*ScannerClaims, error) {
claims := &ScannerClaims{}
tok, err := s.parser.ParseWithClaims(raw, claims, func(t *jwt.Token) (any, error) {
return s.secret, nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
return nil, ErrExpiredJWT
}
return nil, ErrInvalidJWT
}
if !tok.Valid || claims.UserID == uuid.Nil || claims.EventID == uuid.Nil {
return nil, ErrInvalidJWT
}
return claims, nil
}