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:
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const scannerTestSecret = "scanner-secret-must-be-at-least-32-bytes-yy"
|
||||
|
||||
func TestScannerJWT_RoundTrip(t *testing.T) {
|
||||
s, err := NewScannerJWTSigner(scannerTestSecret, "test-issuer", 4*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatalf("new signer: %v", err)
|
||||
}
|
||||
userID := uuid.New()
|
||||
eventID := uuid.New()
|
||||
now := time.Now().UTC()
|
||||
tok, exp, err := s.Issue(userID, eventID, now)
|
||||
if err != nil {
|
||||
t.Fatalf("issue: %v", err)
|
||||
}
|
||||
if !exp.After(now) {
|
||||
t.Fatalf("expiry should be after now: exp=%v now=%v", exp, now)
|
||||
}
|
||||
got, err := s.Parse(tok)
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if got.UserID != userID || got.EventID != eventID {
|
||||
t.Errorf("claims mismatch: got user=%v event=%v want user=%v event=%v",
|
||||
got.UserID, got.EventID, userID, eventID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerJWT_Expired(t *testing.T) {
|
||||
s, _ := NewScannerJWTSigner(scannerTestSecret, "test-issuer", time.Second)
|
||||
// Issue with `now` 5 minutes in the past; the +1s TTL has long since
|
||||
// elapsed against the actual wall clock.
|
||||
pastNow := time.Now().UTC().Add(-5 * time.Minute)
|
||||
tok, _, err := s.Issue(uuid.New(), uuid.New(), pastNow)
|
||||
if err != nil {
|
||||
t.Fatalf("issue: %v", err)
|
||||
}
|
||||
if _, err := s.Parse(tok); !errors.Is(err, ErrExpiredJWT) {
|
||||
t.Errorf("parse expired: want ErrExpiredJWT, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A scanner JWT must not be acceptable as a session access token even
|
||||
// though both are HS256-signed with the same secret. The audience
|
||||
// constraint on the session signer is responsible for keeping them
|
||||
// apart; this test guards against accidental regressions.
|
||||
func TestScannerJWT_RejectedBySessionParser(t *testing.T) {
|
||||
const issuer = "guestguard-test"
|
||||
scannerSigner, _ := NewScannerJWTSigner(scannerTestSecret, issuer, time.Hour)
|
||||
sessionSigner, err := NewJWTSigner(scannerTestSecret, time.Hour, issuer)
|
||||
if err != nil {
|
||||
t.Fatalf("new session signer: %v", err)
|
||||
}
|
||||
|
||||
tok, _, err := scannerSigner.Issue(uuid.New(), uuid.New(), time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatalf("issue scanner: %v", err)
|
||||
}
|
||||
|
||||
// The session parser doesn't enforce audience itself, so Parse() will
|
||||
// succeed and return claims with the "scanner" audience populated.
|
||||
// Middleware (requireAuth) is what then rejects the audience — so the
|
||||
// guarantee we want here is that the audience claim survives parsing
|
||||
// so that check can fire.
|
||||
claims, err := sessionSigner.Parse(tok)
|
||||
if err != nil {
|
||||
t.Fatalf("session parser unexpectedly errored on a scanner JWT: %v", err)
|
||||
}
|
||||
hasScannerAud := false
|
||||
for _, aud := range claims.Audience {
|
||||
if aud == ScannerJWTAudience {
|
||||
hasScannerAud = true
|
||||
}
|
||||
}
|
||||
if !hasScannerAud {
|
||||
t.Errorf("scanner JWT lost its audience after session-parser parse — middleware can no longer reject it. got audience %v", claims.Audience)
|
||||
}
|
||||
}
|
||||
|
||||
// And the reverse: a normal session token (no audience) must not be
|
||||
// accepted by the scanner parser, because the scanner parser pins
|
||||
// audience=scanner. Otherwise a stolen session token could be turned
|
||||
// into a fake scanner ticket.
|
||||
func TestScannerJWT_RejectsSessionToken(t *testing.T) {
|
||||
const issuer = "guestguard-test"
|
||||
sessionSigner, _ := NewJWTSigner(scannerTestSecret, time.Hour, issuer)
|
||||
scannerSigner, _ := NewScannerJWTSigner(scannerTestSecret, issuer, time.Hour)
|
||||
|
||||
tok, _, err := sessionSigner.Issue(uuid.New(), time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatalf("issue session: %v", err)
|
||||
}
|
||||
if _, err := scannerSigner.Parse(tok); !errors.Is(err, ErrInvalidJWT) {
|
||||
t.Errorf("scanner parser must reject session token: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerJWT_SecretTooShort(t *testing.T) {
|
||||
if _, err := NewScannerJWTSigner("short", "issuer", time.Hour); err == nil {
|
||||
t.Errorf("expected too-short-secret error")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user