Files
guestguard/internal/api/server.go
T
Kwaku Danso 98678ff5a3 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>
2026-05-21 20:30:02 +01:00

624 lines
24 KiB
Go

package api
import (
"log/slog"
"net/http"
"time"
"github.com/redis/go-redis/v9"
"github.com/alchemistkay/guestguard/internal/audit"
"github.com/alchemistkay/guestguard/internal/auth"
"github.com/alchemistkay/guestguard/internal/billing"
"github.com/alchemistkay/guestguard/internal/flags"
"github.com/alchemistkay/guestguard/internal/notification"
"github.com/alchemistkay/guestguard/internal/ratelimit"
"github.com/alchemistkay/guestguard/internal/storage"
"github.com/alchemistkay/guestguard/internal/uploads"
)
type Server struct {
logger *slog.Logger
db *storage.DB
hub *Hub
authH *authHandler
me *meHandler
events *eventHandler
guests *guestHandler
tokens *tokenHandler
rsvps *rsvpHandler
activity *activityHandler
ws *wsHandler
wsTicket *wsTicketHandler
health *healthHandler
signer *auth.JWTSigner
scannerSigner *auth.ScannerJWTSigner
limiter *ratelimit.Limiter
flags *flags.Store
unsub *unsubscribeHandler
webhooks *webhookHandler
csv *csvImportHandler
billing *billingHandler
stripeWH *stripeWebhookHandler
privacy *privacyHandler
collabs *collaboratorHandler
analytics *analyticsHandler
branding *brandingHandler
uploads *uploadHandler
security *securityHandler
messages *messageHandler
checkIns *checkInHandler
}
type ServerDeps struct {
Logger *slog.Logger
DB *storage.DB
Hub *Hub
AccessPublisher accessPublisher
RSVPPublisher rsvpPublisher
InvitationPublisher invitationPublisher
FraudScorer fraudScorer
TokenTTL time.Duration
// Auth
JWTSecret string
JWTIssuer string
AccessTokenTTL time.Duration
RefreshTokenTTL time.Duration
EmailVerificationTTL time.Duration
PasswordResetTTL time.Duration
PublicBaseURL string
RefreshCookieDomain string
RefreshCookieSecure bool
EmailSender auth.EmailSender
WSTicketTTL time.Duration
// Rate limiting / abuse controls
Redis *redis.Client
LoginLockoutMax int // failed attempts before account lockout (default 5)
LoginFailWindow time.Duration // counter TTL (default 15 min)
// Notifications / unsubscribe
NotificationRepo *notification.Repo
SuppressionRepo *notification.SuppressionRepo
UnsubscribeSigner *notification.UnsubscribeSigner
// Billing (Block F). Nil StripeClient leaves billing disabled — the
// system still boots and runs, all users sit on the free tier with
// its limits enforced; /billing/* returns 503.
StripeClient *billing.Client
// Uploads (Tier 2 Block D). UploadsDir is where the LocalFSStore
// writes images; UploadsPublicURL is the base prefix the API will
// serve them under. Both empty means uploads are disabled (POST
// /uploads/image returns 503).
UploadsDir string
UploadsPublicURL string
}
func NewServer(deps ServerDeps) (*Server, error) {
eventRepo := storage.NewEventRepo(deps.DB)
guestRepo := storage.NewGuestRepo(deps.DB)
tokenRepo := storage.NewTokenRepo(deps.DB)
rsvpRepo := storage.NewRSVPRepo(deps.DB)
accessRepo := storage.NewAccessLogRepo(deps.DB)
userRepo := storage.NewUserRepo(deps.DB)
collabRepo := storage.NewCollaboratorRepo(deps.DB)
inviteRepo := storage.NewInviteRepo(deps.DB)
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
brandingRepo := storage.NewBrandingRepo(deps.DB)
allowlistRepo := storage.NewAllowlistRepo(deps.DB)
editNonces := newEditNonceStore(deps.Redis)
messageRepo := storage.NewMessageRepo(deps.DB)
checkInRepo := storage.NewCheckInRepo(deps.DB)
auditRec := audit.New(deps.DB.Pool, deps.Logger)
flagStore := flags.New(deps.DB.Pool, deps.Logger)
// Tier 2 Block H — QR JWT signer reuses the platform's JWT secret
// so production secrets management already covers it. TTL=6h is the
// minimum lifetime; Issue() extends to eventDate+24h on demand so
// codes minted weeks in advance still scan on the day.
checkInQRSigner, err := auth.NewCheckInQRSigner(deps.JWTSecret, deps.JWTIssuer, 6*time.Hour)
if err != nil {
return nil, err
}
// Scanner magic-link signer — same secret, audience-scoped so it
// can't double as a session token. 4h covers a full event without
// the host re-minting; the door volunteer's phone keeps working
// across the night even if their session would have otherwise
// timed out.
scannerJWTSigner, err := auth.NewScannerJWTSigner(deps.JWTSecret, deps.JWTIssuer, 4*time.Hour)
if err != nil {
return nil, err
}
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
// working in stripped-down environments.
var imageStore uploads.ImageStore
if deps.UploadsDir != "" {
imageStore = &uploads.LocalFSStore{
Dir: deps.UploadsDir,
PublicBase: deps.UploadsPublicURL,
}
}
verifRepo := storage.NewEmailVerificationRepo(deps.DB)
resetRepo := storage.NewPasswordResetRepo(deps.DB)
refreshRepo := storage.NewRefreshTokenRepo(deps.DB)
subRepo := storage.NewSubscriptionRepo(deps.DB)
enforcer := newTierEnforcer(subRepo, deps.PublicBaseURL)
signer, err := auth.NewJWTSigner(deps.JWTSecret, deps.AccessTokenTTL, deps.JWTIssuer)
if err != nil {
return nil, err
}
hasher := auth.NewPasswordHasher()
emails := deps.EmailSender
if emails == nil {
emails = auth.LogEmailSender{Logger: deps.Logger}
}
hub := deps.Hub
if hub == nil {
hub = NewHub(deps.Logger)
}
wsTicketTTL := deps.WSTicketTTL
if wsTicketTTL <= 0 {
wsTicketTTL = 60 * time.Second
}
wsTickets := newWSTicketStore(wsTicketTTL)
var limiter *ratelimit.Limiter
var lockout *auth.LockoutTracker
if deps.Redis != nil {
limiter = ratelimit.New(deps.Redis, "gg:rl")
lockoutMax := deps.LoginLockoutMax
if lockoutMax <= 0 {
lockoutMax = 5
}
failWindow := deps.LoginFailWindow
if failWindow <= 0 {
failWindow = 15 * time.Minute
}
lockout = auth.NewLockoutTracker(deps.Redis, lockoutMax, failWindow)
}
authH := newAuthHandler(authHandlerDeps{
Logger: deps.Logger,
Users: userRepo,
Verifications: verifRepo,
Resets: resetRepo,
Refreshes: refreshRepo,
Hasher: hasher,
Signer: signer,
Emails: emails,
Lockout: lockout,
Limiter: limiter,
PublicBaseURL: deps.PublicBaseURL,
EmailVerificationTTL: deps.EmailVerificationTTL,
PasswordResetTTL: deps.PasswordResetTTL,
RefreshTTL: deps.RefreshTokenTTL,
CookieDomain: deps.RefreshCookieDomain,
CookieSecure: deps.RefreshCookieSecure,
})
return &Server{
logger: deps.Logger,
db: deps.DB,
hub: hub,
authH: authH,
me: &meHandler{users: userRepo},
events: &eventHandler{repo: eventRepo, collabs: collabRepo, enforcer: enforcer},
guests: &guestHandler{guests: guestRepo, events: eventRepo, collabs: collabRepo, enforcer: enforcer},
tokens: &tokenHandler{
logger: deps.Logger,
guests: guestRepo,
tokens: tokenRepo,
events: eventRepo,
users: userRepo,
accessLogs: accessRepo,
rsvps: rsvpRepo,
collabs: collabRepo,
branding: brandingRepo,
editNonces: editNonces,
emails: emails,
checkInQR: checkInQRSigner,
gen: auth.NewGenerator(),
ttl: deps.TokenTTL,
pub: deps.AccessPublisher,
invitations: deps.InvitationPublisher,
publicBaseURL: deps.PublicBaseURL,
},
rsvps: &rsvpHandler{
logger: deps.Logger,
guests: guestRepo,
tokens: tokenRepo,
events: eventRepo,
rsvps: rsvpRepo,
accessLogs: accessRepo,
allowlist: allowlistRepo,
editNonces: editNonces,
scorer: deps.FraudScorer,
pub: deps.RSVPPublisher,
publicBaseURL: deps.PublicBaseURL,
},
activity: &activityHandler{
events: eventRepo,
collabs: collabRepo,
rsvps: rsvpRepo,
accessLogs: accessRepo,
},
ws: &wsHandler{logger: deps.Logger, hub: hub, tickets: wsTickets},
wsTicket: &wsTicketHandler{tickets: wsTickets, events: eventRepo, collabs: collabRepo},
health: &healthHandler{pool: deps.DB.Pool},
signer: signer,
scannerSigner: scannerJWTSigner,
limiter: limiter,
flags: flagStore,
unsub: &unsubscribeHandler{
logger: deps.Logger,
signer: deps.UnsubscribeSigner,
suppress: deps.SuppressionRepo,
},
webhooks: &webhookHandler{
logger: deps.Logger,
notifs: deps.NotificationRepo,
suppress: deps.SuppressionRepo,
},
csv: &csvImportHandler{guests: guestRepo, events: eventRepo, collabs: collabRepo, enforcer: enforcer},
billing: &billingHandler{
logger: deps.Logger,
stripe: deps.StripeClient,
users: userRepo,
subscriptions: subRepo,
publicBaseURL: deps.PublicBaseURL,
},
stripeWH: &stripeWebhookHandler{
logger: deps.Logger,
stripe: deps.StripeClient,
subs: subRepo,
},
analytics: &analyticsHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
repo: analyticsRepo,
redis: deps.Redis,
},
branding: &brandingHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
repo: brandingRepo,
store: imageStore,
audit: auditRec,
enforcer: enforcer,
flags: flagStore,
},
uploads: &uploadHandler{
logger: deps.Logger,
store: imageStore,
},
security: &securityHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
allowlist: allowlistRepo,
feedback: feedbackRepo,
access: accessRepo,
audit: auditRec,
},
messages: &messageHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
repo: messageRepo,
audit: auditRec,
enforcer: enforcer,
flags: flagStore,
},
checkIns: &checkInHandler{
logger: deps.Logger,
events: eventRepo,
guests: guestRepo,
collabs: collabRepo,
repo: checkInRepo,
qrSigner: checkInQRSigner,
scannerSigner: scannerJWTSigner,
publicBaseURL: deps.PublicBaseURL,
hub: hub,
enforcer: enforcer,
flags: flagStore,
},
collabs: &collaboratorHandler{
logger: deps.Logger,
events: eventRepo,
users: userRepo,
collabs: collabRepo,
invites: inviteRepo,
emails: emails,
publicBaseURL: deps.PublicBaseURL,
audit: auditRec,
enforcer: enforcer,
},
privacy: &privacyHandler{
logger: deps.Logger,
users: userRepo,
events: eventRepo,
guests: guestRepo,
tokens: tokenRepo,
rsvps: rsvpRepo,
access: accessRepo,
notifs: deps.DB,
refresh: refreshRepo,
},
}, nil
}
func (s *Server) Hub() *Hub { return s.hub }
// FeatureFlags exposes the loaded flag store so main can start its
// background refresher and shut it down on signal.
func (s *Server) FeatureFlags() *flags.Store { return s.flags }
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", s.health.live)
mux.HandleFunc("GET /health/ready", s.health.ready)
// Per-route rate limiters (no-op when Redis isn't wired).
authed := requireAuth(s.signer)
rl := func(name string, limit int, window time.Duration, keyFn KeyFunc, h http.Handler) http.Handler {
if s.limiter == nil {
return h
}
return s.limiter.Middleware(
ratelimit.Rule{Name: name, Limit: limit, Window: window},
keyFn,
s.logger,
)(h)
}
// Anonymous auth endpoints — POST /auth/login + /auth/forgot-password
// rate-limit inside the handler (key includes the email body field).
mux.Handle("POST /auth/signup",
rl("auth_signup", 5, time.Hour, ipKey, http.HandlerFunc(s.authH.signup)))
mux.HandleFunc("POST /auth/login", s.authH.login)
mux.HandleFunc("POST /auth/refresh", s.authH.refresh)
mux.HandleFunc("POST /auth/logout", s.authH.logout)
mux.HandleFunc("POST /auth/verify-email", s.authH.verifyEmail)
mux.HandleFunc("POST /auth/forgot-password", s.authH.forgotPassword)
mux.HandleFunc("POST /auth/reset-password", s.authH.resetPassword)
mux.Handle("GET /me", authed(http.HandlerFunc(s.me.get)))
mux.Handle("GET /me/public-ip", authed(http.HandlerFunc(s.me.publicIP)))
mux.Handle("POST /auth/ws-ticket", authed(http.HandlerFunc(s.wsTicket.issue)))
// Privacy / GDPR-style endpoints — host can export their data,
// delete their account, and record terms acceptance from the
// onboarding gate.
mux.Handle("GET /me/data-export", authed(http.HandlerFunc(s.privacy.dataExport)))
mux.Handle("DELETE /me", authed(http.HandlerFunc(s.privacy.deleteMe)))
mux.Handle("POST /me/accept-terms", authed(http.HandlerFunc(s.privacy.acceptTerms)))
// Host-facing event/guest/token writes are limited by user_id.
mux.Handle("POST /events",
authed(rl("events_create", 20, 24*time.Hour, userIDKey, http.HandlerFunc(s.events.create))))
mux.Handle("GET /events", authed(http.HandlerFunc(s.events.list)))
mux.Handle("GET /events/{id}", authed(http.HandlerFunc(s.events.get)))
mux.Handle("PATCH /events/{id}", authed(http.HandlerFunc(s.events.update)))
mux.Handle("DELETE /events/{id}", authed(http.HandlerFunc(s.events.delete)))
mux.Handle("POST /events/{id}/guests",
authed(rl("guests_create", 1000, 24*time.Hour, userIDKey, http.HandlerFunc(s.guests.create))))
mux.Handle("GET /events/{id}/guests", authed(http.HandlerFunc(s.guests.list)))
mux.Handle("PATCH /events/{id}/guests/{guest_id}",
authed(rl("guests_update", 500, 24*time.Hour, userIDKey, http.HandlerFunc(s.guests.update))))
mux.Handle("DELETE /events/{id}/guests/{guest_id}",
authed(rl("guests_delete", 200, 24*time.Hour, userIDKey, http.HandlerFunc(s.guests.delete))))
// CSV import (Block E). Preview is cheap (no DB writes), so we keep
// its budget separate from commit's daily-row-add limit.
mux.Handle("POST /events/{id}/guests/import/preview",
authed(rl("guests_import_preview", 30, time.Hour, userIDKey, http.HandlerFunc(s.csv.preview))))
mux.Handle("POST /events/{id}/guests/import",
authed(rl("guests_import_commit", 20, 24*time.Hour, userIDKey, http.HandlerFunc(s.csv.commit))))
mux.Handle("GET /events/{id}/guests/import/template", authed(http.HandlerFunc(s.csv.template)))
mux.Handle("GET /events/{id}/activity", authed(http.HandlerFunc(s.activity.list)))
// Block E — host analytics. Viewer+ on both endpoints; the Redis
// cache absorbs the dashboard's repeated visits.
mux.Handle("GET /events/{id}/analytics", authed(http.HandlerFunc(s.analytics.get)))
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("GET /events/{id}/security/thresholds/preview",
authed(http.HandlerFunc(s.security.previewThresholds)))
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 F — scheduled messages (reminders + broadcasts).
// All editor+ except the recipient-count preview which is viewer+.
mux.Handle("GET /events/{id}/messages",
authed(http.HandlerFunc(s.messages.list)))
mux.Handle("GET /events/{id}/messages/recipient-count",
authed(http.HandlerFunc(s.messages.recipientCount)))
mux.Handle("POST /events/{id}/messages",
authed(rl("messages_create", 100, 24*time.Hour, userIDKey, http.HandlerFunc(s.messages.create))))
mux.Handle("PATCH /events/{id}/messages/{message_id}",
authed(http.HandlerFunc(s.messages.update)))
mux.Handle("POST /events/{id}/messages/{message_id}/send-now",
authed(http.HandlerFunc(s.messages.sendNow)))
mux.Handle("DELETE /events/{id}/messages/{message_id}",
authed(http.HandlerFunc(s.messages.cancel)))
// Block H — day-of check-in. The three door-volunteer endpoints
// accept either a session token (host/collaborator opened the
// scanner on their own phone) or a scoped scanner JWT (the host
// minted a magic link, texted it to a volunteer). The ticket-issue
// endpoint requires a session token: only an editor can authorise a
// new volunteer.
scannerAuthed := requireAuthOrScanner(s.signer, s.scannerSigner)
mux.Handle("POST /events/{id}/scanner-ticket",
authed(rl("scanner_ticket_issue", 50, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.issueScannerTicket))))
mux.Handle("POST /events/{id}/check-in/preview",
scannerAuthed(rl("checkin_preview", 2000, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.preview))))
mux.Handle("POST /events/{id}/check-in",
scannerAuthed(rl("checkin_record", 1000, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.record))))
mux.Handle("POST /events/{id}/walk-ins",
scannerAuthed(rl("checkin_walk_in", 500, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.walkIn))))
mux.Handle("GET /events/{id}/check-ins",
scannerAuthed(http.HandlerFunc(s.checkIns.list)))
// 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
// branding on).
mux.Handle("GET /events/{id}/branding", authed(http.HandlerFunc(s.branding.get)))
mux.Handle("PUT /events/{id}/branding", authed(http.HandlerFunc(s.branding.put)))
mux.Handle("POST /uploads/image",
authed(rl("uploads_image", 30, time.Hour, userIDKey, http.HandlerFunc(s.uploads.post))))
// Public read — the guest RSVP page fetches the host's logo + cover
// without auth. Heavy cache; no rate limiter (one-time fetch per
// guest, behind the CDN in prod anyway).
mux.HandleFunc("GET /uploads/{filename}", s.uploads.serve)
// Block C — collaborators (multi-host). All under /events/{id}/collaborators.
// requireRole inside each handler enforces the right minimum role.
mux.Handle("GET /events/{id}/collaborators",
authed(http.HandlerFunc(s.collabs.list)))
mux.Handle("POST /events/{id}/collaborators",
authed(rl("collab_invite", 50, 24*time.Hour, userIDKey, http.HandlerFunc(s.collabs.invite))))
mux.Handle("PATCH /events/{id}/collaborators/{user_id}",
authed(http.HandlerFunc(s.collabs.updateRole)))
mux.Handle("DELETE /events/{id}/collaborators/{user_id}",
authed(http.HandlerFunc(s.collabs.remove)))
mux.Handle("DELETE /events/{id}/collaborators/pending",
authed(http.HandlerFunc(s.collabs.cancelInvite)))
// Invite acceptance — preview is unauthed (the invitee may not be
// logged in yet); accept requires auth (the caller's account must
// exist + match the invited email).
mux.HandleFunc("GET /invites/{token}", s.collabs.previewInvite)
mux.Handle("POST /invites/{token}/accept",
authed(http.HandlerFunc(s.collabs.acceptInvite)))
// Self-service invite inbox: bypasses the email-token round-trip so a
// user who lost the invite tab after email verification can still
// accept from their dashboard.
mux.Handle("GET /me/invites",
authed(http.HandlerFunc(s.collabs.myInvites)))
mux.Handle("POST /me/invites/{event_id}/accept",
authed(http.HandlerFunc(s.collabs.acceptForEvent)))
mux.Handle("POST /events/{id}/guests/{guest_id}/tokens",
authed(rl("tokens_issue", 500, 24*time.Hour, userIDKey, http.HandlerFunc(s.tokens.issue))))
mux.Handle("POST /events/{id}/guests/{guest_id}/tokens/rotate",
authed(rl("tokens_rotate", 200, 24*time.Hour, userIDKey, http.HandlerFunc(s.tokens.rotate))))
mux.Handle("POST /events/{id}/guests/invitations/bulk",
authed(rl("tokens_bulk", 10, 24*time.Hour, userIDKey, http.HandlerFunc(s.tokens.bulkIssue))))
// Guest-facing endpoints — rate-limited by the access token in the URL
// path so an attacker hammering a single invitation is slowed regardless
// of their source IP.
mux.Handle("GET /access/{token}",
rl("access", 60, time.Hour, pathKey("token"), http.HandlerFunc(s.tokens.access)))
// Block B: .ics download. Same rate-limit class as /access since the
// payload is similarly cheap and the abuse profile is identical (one
// token per attacker).
// Forwarded-link defence: when a guest opens their invitation from a
// device the original RSVP wasn't submitted from, /access hides the
// reply. This endpoint mints a short-lived edit nonce and emails it
// so the real guest can recover from a new phone / new laptop.
mux.Handle("POST /access/{token}/request-edit-link",
rl("rsvp_edit_request", 3, time.Hour, pathKey("token"), http.HandlerFunc(s.tokens.requestEditLink)))
mux.Handle("GET /access/{token}/calendar.ics",
rl("calendar_ics", 60, time.Hour, pathKey("token"), http.HandlerFunc(s.tokens.calendar)))
mux.Handle("POST /rsvp/{token}",
rl("rsvp", 10, time.Hour, pathKey("token"), http.HandlerFunc(s.rsvps.submit)))
// Block A: edits are bounded by MaxRSVPEdits server-side. The redis
// limiter is a coarser guard that also throttles attempts that hit the
// edit-cap 429 path, so a hostile actor can't burn through fraud-engine
// calls on the same token.
mux.Handle("PATCH /rsvp/{token}",
rl("rsvp_edit", 10, time.Hour, pathKey("token"), http.HandlerFunc(s.rsvps.edit)))
// Host view of the edit trail for a single guest.
mux.Handle("GET /events/{id}/guests/{guest_id}/rsvp/history",
authed(http.HandlerFunc(s.rsvps.history)))
// WebSocket endpoint authenticates via single-use ticket on the query
// string (see POST /auth/ws-ticket).
mux.HandleFunc("GET /ws/events/{id}", s.ws.handle)
// Unsubscribe (signed token, no auth required — links live in emails).
mux.HandleFunc("GET /unsubscribe/{token}", s.unsub.preview)
mux.HandleFunc("POST /unsubscribe/{token}", s.unsub.confirm)
// Provider webhooks. Signature verification is enforced in the handler
// once GG_TWILIO_AUTH_TOKEN / GG_SES_WEBHOOK_SECRET are set.
mux.HandleFunc("POST /webhooks/twilio/status", s.webhooks.twilio)
mux.HandleFunc("POST /webhooks/ses/notifications", s.webhooks.ses)
// Billing (Block F). /billing/status is safe for everyone — returns
// free tier defaults when Stripe is unconfigured or the user has no
// subscription, so the frontend's plan page always has something to
// render. The action endpoints (checkout, portal) return 503 in dev
// without Stripe credentials.
mux.Handle("GET /billing/status", authed(http.HandlerFunc(s.billing.status)))
mux.Handle("POST /billing/checkout-session", authed(http.HandlerFunc(s.billing.checkoutSession)))
mux.Handle("POST /billing/portal", authed(http.HandlerFunc(s.billing.portalSession)))
mux.HandleFunc("POST /webhooks/stripe", s.stripeWH.handle)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "not found")
})
var h http.Handler = mux
h = corsMiddleware(h)
h = loggingMiddleware(s.logger)(h)
h = recoverMiddleware(s.logger)(h)
return h
}
// Permissive CORS for the dev frontend on a different origin. In production
// the frontend is served from the same domain so this is largely a no-op.
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
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, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Device-Fingerprint")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}