98678ff5a3
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>
133 lines
5.0 KiB
Go
133 lines
5.0 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/alchemistkay/guestguard/internal/auth"
|
|
)
|
|
|
|
// Scanner JWT integration — Tier 2 Block H follow-up.
|
|
//
|
|
// The host's desktop mints a scoped scanner ticket via POST
|
|
// /events/{id}/scanner-ticket and renders the magic URL into a QR. A
|
|
// door volunteer scans that with their phone camera, lands on /scanner
|
|
// with ?token=<jwt>, and the page uses the token as a Bearer for the
|
|
// three check-in endpoints below. No second login required.
|
|
//
|
|
// The scanner JWT is HS256-signed with the same platform secret as the
|
|
// session token but carries Audience="scanner". `requireAuth` rejects
|
|
// audience=scanner; `requireAuthOrScanner` accepts either, and on a
|
|
// scanner token stamps the URL-event-id constraint into the request
|
|
// context so the handler can verify the path event matches before
|
|
// touching the database.
|
|
|
|
type scannerCtxKey int
|
|
|
|
const scannerEventCtxKey scannerCtxKey = iota
|
|
|
|
// scannerEventFromContext returns the event_id the bearer scanner token
|
|
// is scoped to (if any). On a regular session token this returns
|
|
// uuid.Nil, false — the handler should fall back to its normal role
|
|
// check. On a scanner token it returns the event the token was minted
|
|
// against and the handler must 403 if the request's path event differs.
|
|
func scannerEventFromContext(ctx context.Context) (uuid.UUID, bool) {
|
|
v, ok := ctx.Value(scannerEventCtxKey).(uuid.UUID)
|
|
if !ok || v == uuid.Nil {
|
|
return uuid.Nil, false
|
|
}
|
|
return v, true
|
|
}
|
|
|
|
// requireAuthOrScanner is the middleware applied to the three check-in
|
|
// endpoints. A bearer token can be either:
|
|
//
|
|
// - a normal session JWT (no audience) — usual host/collaborator flow,
|
|
// - a scanner JWT (Audience=scanner) — scoped to one event_id.
|
|
//
|
|
// Either way it sets userIDCtxKey so downstream handlers can call
|
|
// hostFromContext. Scanner tokens additionally set scannerEventCtxKey;
|
|
// handlers that read it MUST verify the URL event matches before doing
|
|
// anything that mutates state.
|
|
func requireAuthOrScanner(signer *auth.JWTSigner, scanner *auth.ScannerJWTSigner) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
h := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(h, "Bearer ") {
|
|
writeError(w, http.StatusUnauthorized, "missing bearer token")
|
|
return
|
|
}
|
|
raw := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
|
|
|
|
// Try scanner first — the audience constraint means a session
|
|
// token will fail this cheaply and we fall through to the
|
|
// normal signer.
|
|
if scanner != nil {
|
|
if claims, err := scanner.Parse(raw); err == nil {
|
|
ctx := context.WithValue(r.Context(), userIDCtxKey, claims.UserID)
|
|
ctx = context.WithValue(ctx, scannerEventCtxKey, claims.EventID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
return
|
|
} else if errors.Is(err, auth.ErrExpiredJWT) {
|
|
// If the audience matched but the token expired, surface
|
|
// the friendlier expired message. Detect by re-parsing
|
|
// without validation? Cheaper: if the normal signer can't
|
|
// parse it either, treat as expired-scanner so the door
|
|
// volunteer's phone gets a clear "ask the host for a
|
|
// fresh link" prompt.
|
|
if _, sessionErr := signer.Parse(raw); sessionErr != nil {
|
|
writeError(w, http.StatusUnauthorized, "scanner link expired — ask the host for a new one")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
claims, err := signer.Parse(raw)
|
|
if err != nil {
|
|
if errors.Is(err, auth.ErrExpiredJWT) {
|
|
writeError(w, http.StatusUnauthorized, "token expired")
|
|
return
|
|
}
|
|
writeError(w, http.StatusUnauthorized, "invalid token")
|
|
return
|
|
}
|
|
// Defence in depth: a session token must not carry the scanner
|
|
// audience. requireAuth enforces the same; mirror it here.
|
|
for _, aud := range claims.Audience {
|
|
if aud == auth.ScannerJWTAudience {
|
|
writeError(w, http.StatusUnauthorized, "scanner token cannot be used here")
|
|
return
|
|
}
|
|
}
|
|
ctx := context.WithValue(r.Context(), userIDCtxKey, claims.UserID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
// requireScannerEventMatch is the per-handler guard. After a check-in
|
|
// handler has parsed its path event id, it calls this to confirm:
|
|
// - if the request used a scanner JWT, the JWT's event matches the URL,
|
|
// - if it didn't (regular session), this is a no-op.
|
|
//
|
|
// The role check (requireRole) is still applied for regular sessions
|
|
// inside the handler; for scanner JWTs the role gate is bypassed because
|
|
// the host already proved they were an editor when they minted the
|
|
// ticket — passing that authority onto the door volunteer is the
|
|
// entire point of the magic link.
|
|
func requireScannerEventMatch(w http.ResponseWriter, r *http.Request, pathEventID uuid.UUID) bool {
|
|
scoped, ok := scannerEventFromContext(r.Context())
|
|
if !ok {
|
|
return true
|
|
}
|
|
if scoped != pathEventID {
|
|
writeError(w, http.StatusForbidden, "scanner link is scoped to a different event")
|
|
return false
|
|
}
|
|
return true
|
|
}
|