Files
guestguard/internal/api/branding.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

280 lines
9.0 KiB
Go

package api
import (
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"github.com/alchemistkay/guestguard/internal/audit"
"github.com/alchemistkay/guestguard/internal/domain"
"github.com/alchemistkay/guestguard/internal/flags"
"github.com/alchemistkay/guestguard/internal/storage"
"github.com/alchemistkay/guestguard/internal/uploads"
)
// brandingHandler owns the per-event customisation row plus image uploads.
// Tier 2 Block D. Reads are viewer+; writes (PUT + image upload) are
// editor+. The role check uses the standard requireRole helper.
type brandingHandler struct {
logger *slog.Logger
events *storage.EventRepo
collabs *storage.CollaboratorRepo
repo *storage.BrandingRepo
store uploads.ImageStore
audit *audit.Recorder
enforcer *tierEnforcer
flags *flags.Store
}
type brandingResponse struct {
*domain.Branding
// AllowedFonts is echoed back on every GET so the frontend's picker
// stays in sync with the server's allowlist without a separate
// /branding/fonts endpoint.
AllowedFonts []string `json:"allowed_fonts"`
}
// GET /events/{id}/branding — viewer+. Missing row is rendered as
// "defaults" (200 with nulls) rather than 404 so the frontend doesn't
// need a special-case loader.
func (h *brandingHandler) get(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.RoleViewer); !ok {
return
}
b, err := h.repo.Get(r.Context(), eventID)
if err != nil && !errors.Is(err, domain.ErrBrandingNotFound) {
writeError(w, http.StatusInternalServerError, "failed to load branding")
return
}
if b == nil {
b = &domain.Branding{EventID: eventID}
}
writeJSON(w, http.StatusOK, brandingResponse{Branding: b, AllowedFonts: domain.AllowedFonts})
}
type updateBrandingRequest struct {
// Pointer-typed so omitted JSON keys map to nil = "leave unchanged",
// while empty-string maps to "clear the field". The repo's Upsert
// honours this distinction.
PrimaryColor *string `json:"primary_color"`
AccentColor *string `json:"accent_color"`
LogoURL *string `json:"logo_url"`
CoverImageURL *string `json:"cover_image_url"`
FontFamily *string `json:"font_family"`
GreetingMessage *string `json:"greeting_message"`
}
// PUT /events/{id}/branding — editor+. Validates each field server-side
// (the allowlist for fonts, hex shape for colours, our-CDN-only for image
// URLs to prevent the host smuggling an `<img>` from an arbitrary origin
// into the guest-facing page).
func (h *brandingHandler) put(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
}
// Feature flag: ops can kill custom_branding without a redeploy
// (e.g. an image-processing bug). 503 makes it obvious this is a
// temporary outage rather than a billing matter.
if !h.flags.Enabled("custom_branding", hostID) {
writeError(w, http.StatusServiceUnavailable, "branding is temporarily disabled")
return
}
// Custom branding is a Pro+ feature. Free-tier hosts get the
// default invitation card; this endpoint refuses with 402 +
// upgrade payload so the frontend can render a targeted modal.
if !h.enforcer.allowFeature(w, r, hostID, "custom_branding",
"Custom branding (logo, cover, colours, font) is a Pro feature.") {
return
}
var req updateBrandingRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if req.PrimaryColor != nil && !domain.IsValidHexColor(*req.PrimaryColor) {
writeError(w, http.StatusBadRequest, "primary_color: "+domain.ErrInvalidColor.Error())
return
}
if req.AccentColor != nil && !domain.IsValidHexColor(*req.AccentColor) {
writeError(w, http.StatusBadRequest, "accent_color: "+domain.ErrInvalidColor.Error())
return
}
if req.FontFamily != nil && !domain.IsAllowedFont(*req.FontFamily) {
writeError(w, http.StatusBadRequest, domain.ErrUnknownFont.Error())
return
}
if !validImageURL(req.LogoURL) {
writeError(w, http.StatusBadRequest, "logo_url must be a previously-uploaded image URL")
return
}
if !validImageURL(req.CoverImageURL) {
writeError(w, http.StatusBadRequest, "cover_image_url must be a previously-uploaded image URL")
return
}
b, err := h.repo.Upsert(r.Context(), storage.UpsertBrandingParams{
EventID: eventID,
PrimaryColor: req.PrimaryColor,
AccentColor: req.AccentColor,
LogoURL: req.LogoURL,
CoverImageURL: req.CoverImageURL,
FontFamily: req.FontFamily,
GreetingMessage: req.GreetingMessage,
})
if err != nil {
h.logger.Error("upsert branding", "err", err)
writeError(w, http.StatusInternalServerError, "failed to save branding")
return
}
h.audit.Record(r.Context(), audit.Params{
UserID: &hostID,
EventID: &eventID,
Action: "branding.update",
EntityType: "event",
TargetID: &eventID,
Metadata: map[string]any{
"primary_color": req.PrimaryColor,
"accent_color": req.AccentColor,
"font_family": req.FontFamily,
"has_logo": req.LogoURL != nil && *req.LogoURL != "",
"has_cover": req.CoverImageURL != nil && *req.CoverImageURL != "",
},
})
writeJSON(w, http.StatusOK, brandingResponse{Branding: b, AllowedFonts: domain.AllowedFonts})
}
// validImageURL accepts nil / "" / any URL whose path begins with
// /uploads/ — i.e. the host must have run the bytes through our own
// /uploads/image endpoint. This prevents `logo_url=https://evil/x.png`
// from rendering attacker-controlled content on every RSVP page.
func validImageURL(p *string) bool {
if p == nil || *p == "" {
return true
}
u, err := url.Parse(*p)
if err != nil {
return false
}
return strings.HasPrefix(u.Path, "/uploads/")
}
// uploadHandler is split out so the route can sit at /uploads/image without
// being tied to an event id (a single host may upload before deciding
// which of their events to attach the image to).
type uploadHandler struct {
logger *slog.Logger
store uploads.ImageStore
}
type uploadResponse struct {
URL string `json:"url"`
}
// POST /uploads/image — authed. multipart "file" or raw body. Validates
// size + format, re-encodes to strip EXIF, stores under a random name.
// The response URL is what the host pastes into the branding PUT body.
func (h *uploadHandler) post(w http.ResponseWriter, r *http.Request) {
if _, ok := hostFromContext(w, r); !ok {
return
}
// Cap the read so a hostile client can't OOM the API even on a slow
// connection. The +1 lets DecodeAndReencode report "exceeds limit"
// distinctly from "exactly the limit".
r.Body = http.MaxBytesReader(w, r.Body, uploads.MaxUploadBytes+1024)
body, err := readImageUpload(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
out, format, err := uploads.DecodeAndReencode(body)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
publicURL, err := h.store.Save(r.Context(), out, format)
if err != nil {
h.logger.Error("save upload", "err", err)
writeError(w, http.StatusInternalServerError, "failed to save upload")
return
}
writeJSON(w, http.StatusCreated, uploadResponse{URL: publicURL})
}
// readImageUpload accepts either a multipart upload (the drag-drop UI's
// shape) or a raw body (curl-friendly).
func readImageUpload(r *http.Request) ([]byte, error) {
if err := r.ParseMultipartForm(uploads.MaxUploadBytes + 1024); err == nil && r.MultipartForm != nil {
files := r.MultipartForm.File["file"]
if len(files) > 0 {
f, err := files[0].Open()
if err != nil {
return nil, err
}
defer f.Close()
return uploads.PeekReader(f)
}
}
defer r.Body.Close()
return uploads.PeekReader(r.Body)
}
// GET /uploads/{filename} — serves the bytes the LocalFSStore wrote. In
// production a CDN would handle this; in dev the API streams them.
func (h *uploadHandler) serve(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("filename")
if name == "" {
writeError(w, http.StatusBadRequest, "missing filename")
return
}
local, ok := h.store.(*uploads.LocalFSStore)
if !ok {
writeError(w, http.StatusNotFound, "upload not found")
return
}
path, err := local.FilePath(name)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid filename")
return
}
f, err := os.Open(path)
if err != nil {
writeError(w, http.StatusNotFound, "upload not found")
return
}
defer f.Close()
if strings.HasSuffix(name, ".png") {
w.Header().Set("Content-Type", "image/png")
} else {
w.Header().Set("Content-Type", "image/jpeg")
}
// Branding images don't change once uploaded (host gets a new URL on
// re-upload), so long cache lifetime is safe.
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
if _, err := io.Copy(w, f); err != nil {
h.logger.Warn("serve upload", "err", err, "name", name)
}
}