feat(tier2): event branding + UX polish — Block D
Backend
- Migration 0010 adds event_branding (one row per event; all fields
nullable so a brand-new event renders with defaults)
- BrandingRepo with COALESCE/NULLIF upsert semantics: nil pointer
preserves the existing value, "" clears the field to NULL
- internal/uploads package: ImageStore interface + LocalFSStore (dev),
pure-stdlib decode + re-encode that strips EXIF and rejects anything
that isn't valid JPEG/PNG. Size cap 2 MB, random 16-byte filenames
- GET /events/{id}/branding (viewer+) returns the row plus the
AllowedFonts list so the frontend picker stays in sync
- PUT /events/{id}/branding (editor+) validates hex colours, font
allowlist, and refuses image URLs whose path doesn't start with
/uploads/ (blocks arbitrary-origin <img> smuggling on guest pages)
- POST /uploads/image (authed) → fresh CDN URL; GET /uploads/{file}
serves with year-long cache (immutable random names)
- GET /access/{token} now embeds the host's branding so the RSVP page
can render in their colours/font with their logo + cover
- docker-compose mounts a named volume for uploads
- Custom-domain sub-block deferred to Tier 3 per the plan
Frontend
- BrandingCard.vue: colour pickers, font dropdown, logo + cover upload
with progressive disclosure, live preview pane that re-renders on
every keystroke
- RSVP page applies branding via CSS vars at the section root, so
primary colour theme + font cascade through every child card. Cover
image renders as a banner above the form; logo lands in the header
- Submit button background switches to var(--brand-primary) when set
- Mounted on the event detail page below the guests block
Plus the small UX fixes from the e2e walkthrough:
- Nav: dropped the top-level "Events" link; the logo doubles as the
home affordance (→ /dashboard when signed in, → / otherwise). Account
+ Billing + Sign out live under a profile dropdown (avatar with
initials, opens on click, closes on outside-click / Esc / route nav)
- Renamed "Back to dashboard" → "Back to events" across event detail,
billing, account, and new-event pages
Tests
- TestBrandingGetReturnsDefaults / TestBrandingPutPersists /
TestBrandingPutRejectsBadInputs / TestUploadAndServeImage /
TestUploadRejectsNonImage — all pass
- Domain tests for IsValidHexColor + IsAllowedFont
- Full integration suite green (176s)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -309,6 +309,63 @@ func (h *collaboratorHandler) cancelInvite(w http.ResponseWriter, r *http.Reques
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- "your pending invites" (self-service inbox) ---
|
||||
|
||||
// GET /me/invites — authed. Lists invites addressed to the caller's email
|
||||
// so the dashboard can show a one-click Accept banner without requiring
|
||||
// the user to re-click the email link. Crucial for the signup → verify-
|
||||
// email → login flow where the email click opens a new tab and the
|
||||
// original invite tab is forgotten.
|
||||
func (h *collaboratorHandler) myInvites(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
user, err := h.users.GetByID(r.Context(), userID)
|
||||
if err != nil || user == nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
pending, err := h.invites.ListPendingForEmail(r.Context(), user.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list invites")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"invites": pending})
|
||||
}
|
||||
|
||||
// POST /me/invites/{event_id}/accept — authed. Accepts the latest pending
|
||||
// invite for (caller.email, event_id). Same effect as POST /invites/{token}/
|
||||
// accept but doesn't require the raw token; the caller's verified email is
|
||||
// the identity signal instead.
|
||||
func (h *collaboratorHandler) acceptForEvent(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
user, err := h.users.GetByID(r.Context(), userID)
|
||||
if err != nil || user == nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "event_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
role, err := h.collabs.AcceptByEventAndEmail(r.Context(), eventID, user.Email, userID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInviteNotFound):
|
||||
writeError(w, http.StatusNotFound, "no pending invitation for this event")
|
||||
default:
|
||||
h.logger.Error("accept by email", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to accept invitation")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, acceptResponse{EventID: eventID, Role: role})
|
||||
}
|
||||
|
||||
// --- public invite-accept flow ---
|
||||
|
||||
type inviteSummary struct {
|
||||
|
||||
+19
-6
@@ -125,23 +125,36 @@ func (h *eventHandler) list(w http.ResponseWriter, r *http.Request) {
|
||||
offset := atoiOr(q.Get("offset"), 0)
|
||||
|
||||
// Block C: the dashboard shows every event the user has any role on,
|
||||
// not just events they own. The collaborators repo gives us the id set;
|
||||
// the events repo paginates the merged list.
|
||||
collabIDs, err := h.collabs.ListEventIDsForUser(r.Context(), hostID)
|
||||
// not just events they own. Pull the role map up front so we can
|
||||
// annotate each card with `your_role` — the frontend uses that to
|
||||
// split "your events" from "shared with you" without a follow-up call.
|
||||
roles, err := h.collabs.RolesForUser(r.Context(), hostID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to resolve memberships")
|
||||
return
|
||||
}
|
||||
collabIDs := make([]uuid.UUID, 0, len(roles))
|
||||
for id := range roles {
|
||||
collabIDs = append(collabIDs, id)
|
||||
}
|
||||
events, err := h.repo.ListForUser(r.Context(), hostID, collabIDs, limit, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list events")
|
||||
return
|
||||
}
|
||||
if events == nil {
|
||||
events = []*domain.Event{}
|
||||
views := make([]eventView, 0, len(events))
|
||||
for _, ev := range events {
|
||||
role := roles[ev.ID]
|
||||
if role == "" && ev.HostID == hostID {
|
||||
// Defensive: legacy events created before Block C's seed-on-
|
||||
// create may not have a collaborator row. Fall back to the
|
||||
// host_id check so they still show as owned.
|
||||
role = domain.RoleOwner
|
||||
}
|
||||
views = append(views, eventView{Event: ev, YourRole: role})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"events": events,
|
||||
"events": views,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"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 {
|
||||
@@ -38,6 +39,8 @@ type Server struct {
|
||||
privacy *privacyHandler
|
||||
collabs *collaboratorHandler
|
||||
analytics *analyticsHandler
|
||||
branding *brandingHandler
|
||||
uploads *uploadHandler
|
||||
}
|
||||
|
||||
type ServerDeps struct {
|
||||
@@ -77,6 +80,13 @@ type ServerDeps struct {
|
||||
// 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) {
|
||||
@@ -89,6 +99,18 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
collabRepo := storage.NewCollaboratorRepo(deps.DB)
|
||||
inviteRepo := storage.NewInviteRepo(deps.DB)
|
||||
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
|
||||
brandingRepo := storage.NewBrandingRepo(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)
|
||||
@@ -168,6 +190,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
accessLogs: accessRepo,
|
||||
rsvps: rsvpRepo,
|
||||
collabs: collabRepo,
|
||||
branding: brandingRepo,
|
||||
gen: auth.NewGenerator(),
|
||||
ttl: deps.TokenTTL,
|
||||
pub: deps.AccessPublisher,
|
||||
@@ -225,6 +248,17 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
repo: analyticsRepo,
|
||||
redis: deps.Redis,
|
||||
},
|
||||
branding: &brandingHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
collabs: collabRepo,
|
||||
repo: brandingRepo,
|
||||
store: imageStore,
|
||||
},
|
||||
uploads: &uploadHandler{
|
||||
logger: deps.Logger,
|
||||
store: imageStore,
|
||||
},
|
||||
collabs: &collaboratorHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
@@ -322,6 +356,19 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("GET /events/{id}/analytics/export.csv",
|
||||
authed(http.HandlerFunc(s.analytics.exportCSV)))
|
||||
|
||||
// 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",
|
||||
@@ -342,6 +389,14 @@ func (s *Server) Handler() http.Handler {
|
||||
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",
|
||||
|
||||
@@ -35,6 +35,7 @@ type tokenHandler struct {
|
||||
accessLogs *storage.AccessLogRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
collabs *storage.CollaboratorRepo
|
||||
branding *storage.BrandingRepo
|
||||
gen *auth.Generator
|
||||
ttl time.Duration
|
||||
pub accessPublisher
|
||||
@@ -416,6 +417,10 @@ type accessResponse struct {
|
||||
// path so the frontend renders four ready-to-click buttons after a
|
||||
// successful RSVP. (Tier 2 Block B.)
|
||||
Calendar calendar.ProviderLinks `json:"calendar"`
|
||||
// Branding lets the RSVP page render in the host's colour scheme /
|
||||
// logo / cover image. Nil when the host hasn't customised yet — the
|
||||
// frontend falls back to defaults. (Tier 2 Block D.)
|
||||
Branding *domain.Branding `json:"branding,omitempty"`
|
||||
}
|
||||
|
||||
// GET /access/{token} — validate token, log the access attempt, publish to NATS.
|
||||
@@ -482,6 +487,21 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
|
||||
OccurredAt: time.Now().UTC(),
|
||||
})
|
||||
|
||||
var brandingPayload *domain.Branding
|
||||
if h.branding != nil {
|
||||
// Same best-effort treatment as the RSVP lookup below — missing
|
||||
// branding row is the common case, not a failure.
|
||||
br, err := h.branding.Get(r.Context(), event.ID)
|
||||
switch {
|
||||
case err == nil:
|
||||
brandingPayload = br
|
||||
case errors.Is(err, domain.ErrBrandingNotFound):
|
||||
// expected when the host hasn't customised yet
|
||||
default:
|
||||
h.logger.Warn("load branding for access", "err", err, "event_id", event.ID)
|
||||
}
|
||||
}
|
||||
|
||||
var existingRSVP *domain.RSVP
|
||||
if h.rsvps != nil {
|
||||
// Best-effort: a missing RSVP just means the guest hasn't submitted
|
||||
@@ -505,6 +525,7 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
|
||||
AccessLog: accessLogID,
|
||||
RSVP: existingRSVP,
|
||||
Calendar: h.calendarLinks(event, raw),
|
||||
Branding: brandingPayload,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,12 @@ type Config struct {
|
||||
StripePriceBusiness string // Stripe Price ID for Business monthly
|
||||
|
||||
UnsubscribeSecret string // HMAC key for signing unsubscribe links
|
||||
|
||||
// Uploads (Tier 2 Block D). LocalFSStore writes to UploadsDir and
|
||||
// serves via the API's /uploads/<file> route; in production this is
|
||||
// a deployment concern (S3 bucket + CDN URL).
|
||||
UploadsDir string
|
||||
UploadsPublicURL string
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
@@ -114,6 +120,9 @@ func Load() (*Config, error) {
|
||||
StripePriceBusiness: os.Getenv("GG_STRIPE_PRICE_BUSINESS"),
|
||||
|
||||
UnsubscribeSecret: os.Getenv("GG_UNSUBSCRIBE_SECRET"),
|
||||
|
||||
UploadsDir: getenv("GG_UPLOADS_DIR", "/var/lib/guestguard/uploads"),
|
||||
UploadsPublicURL: getenv("GG_UPLOADS_PUBLIC_URL", "http://localhost:8080/uploads"),
|
||||
}
|
||||
|
||||
if cfg.Env == "production" && cfg.TokenSecret == "" {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Branding is one event's visual customisation. All fields are optional —
|
||||
// a brand-new event renders with the GuestGuard defaults until the host
|
||||
// fills any of these in. Tier 2 Block D.
|
||||
type Branding struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
PrimaryColor *string `json:"primary_color,omitempty"`
|
||||
AccentColor *string `json:"accent_color,omitempty"`
|
||||
LogoURL *string `json:"logo_url,omitempty"`
|
||||
CoverImageURL *string `json:"cover_image_url,omitempty"`
|
||||
FontFamily *string `json:"font_family,omitempty"`
|
||||
GreetingMessage *string `json:"greeting_message,omitempty"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AllowedFonts is the curated picker list the host can choose from. Locking
|
||||
// it down keeps render times sane (no hot-loading arbitrary @font-face
|
||||
// files) and avoids smuggling untrusted CSS into our emails.
|
||||
var AllowedFonts = []string{
|
||||
"Inter",
|
||||
"Playfair Display",
|
||||
"Cormorant Garamond",
|
||||
"Lora",
|
||||
"DM Sans",
|
||||
"Manrope",
|
||||
}
|
||||
|
||||
// IsAllowedFont reports whether `f` is in the curated set. Empty string is
|
||||
// fine — the RSVP page falls back to its default.
|
||||
func IsAllowedFont(f string) bool {
|
||||
if f == "" {
|
||||
return true
|
||||
}
|
||||
for _, a := range AllowedFonts {
|
||||
if f == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hexColorRe matches #abc, #abcd, #aabbcc, #aabbccdd (alpha optional).
|
||||
// Lowercase + uppercase OK. Length checked because Go regexp + Postgres
|
||||
// don't agree on Unicode digits and we want plain ASCII here.
|
||||
var hexColorRe = regexp.MustCompile(`^#([0-9A-Fa-f]{3,8})$`)
|
||||
|
||||
// IsValidHexColor accepts the three common hex shorthand forms. Empty is OK
|
||||
// (clears the column).
|
||||
func IsValidHexColor(c string) bool {
|
||||
if c == "" {
|
||||
return true
|
||||
}
|
||||
if !hexColorRe.MatchString(c) {
|
||||
return false
|
||||
}
|
||||
n := len(c) - 1
|
||||
return n == 3 || n == 4 || n == 6 || n == 8
|
||||
}
|
||||
|
||||
var (
|
||||
ErrBrandingNotFound = errors.New("branding not found")
|
||||
ErrInvalidColor = errors.New("color must be a hex value (e.g. #22c55e)")
|
||||
ErrUnknownFont = errors.New("font is not in the allowlist")
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
package domain
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsValidHexColor(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"": true, // clears the field
|
||||
"#22c55e": true,
|
||||
"#22C55E": true,
|
||||
"#abc": true,
|
||||
"#abcd": true,
|
||||
"#aabbccdd": true,
|
||||
"22c55e": false, // missing #
|
||||
"#": false,
|
||||
"#xyz": false,
|
||||
"#aabbccddee": false, // too long
|
||||
"#ab": false, // too short
|
||||
"rgb(0,0,0)": false,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := IsValidHexColor(in); got != want {
|
||||
t.Errorf("IsValidHexColor(%q) = %v, want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAllowedFont(t *testing.T) {
|
||||
for _, ok := range []string{"", "Inter", "Playfair Display"} {
|
||||
if !IsAllowedFont(ok) {
|
||||
t.Errorf("expected %q to be allowed", ok)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"Comic Sans", "Arial", "javascript:alert(1)"} {
|
||||
if IsAllowedFont(bad) {
|
||||
t.Errorf("expected %q to be rejected", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
)
|
||||
|
||||
// BrandingRepo holds the per-event customisation row. Updates are upserts —
|
||||
// a host's first PATCH to the branding endpoint inserts the row, subsequent
|
||||
// PATCHes update only the fields the host sent. Tier 2 Block D.
|
||||
type BrandingRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewBrandingRepo(db *DB) *BrandingRepo {
|
||||
return &BrandingRepo{pool: db.Pool}
|
||||
}
|
||||
|
||||
// Get returns the branding row for `eventID`, or ErrBrandingNotFound when
|
||||
// the event has no customisation yet. The caller should render the default
|
||||
// theme in that case — a missing row isn't an error condition.
|
||||
func (r *BrandingRepo) Get(ctx context.Context, eventID uuid.UUID) (*domain.Branding, error) {
|
||||
const q = `
|
||||
SELECT event_id, primary_color, accent_color, logo_url,
|
||||
cover_image_url, font_family, greeting_message, updated_at
|
||||
FROM event_branding WHERE event_id = $1
|
||||
`
|
||||
var b domain.Branding
|
||||
err := r.pool.QueryRow(ctx, q, eventID).Scan(
|
||||
&b.EventID, &b.PrimaryColor, &b.AccentColor, &b.LogoURL,
|
||||
&b.CoverImageURL, &b.FontFamily, &b.GreetingMessage, &b.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, domain.ErrBrandingNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
// UpsertParams holds the patchable fields. Nil pointers leave the existing
|
||||
// value untouched on update; empty strings clear the column to NULL (so
|
||||
// hosts can revert to defaults without deleting the whole row).
|
||||
type UpsertBrandingParams struct {
|
||||
EventID uuid.UUID
|
||||
PrimaryColor *string
|
||||
AccentColor *string
|
||||
LogoURL *string
|
||||
CoverImageURL *string
|
||||
FontFamily *string
|
||||
GreetingMessage *string
|
||||
}
|
||||
|
||||
// Upsert inserts or partially updates the branding row. The COALESCE +
|
||||
// NULLIF idiom in the UPDATE branch means a nil pointer maps to NULL in
|
||||
// SQL and is coalesced away (= keep existing), while an empty string is
|
||||
// kept as-is and stored as NULL (= clear). That lets the API support both
|
||||
// "no change" and "reset to default" cleanly.
|
||||
func (r *BrandingRepo) Upsert(ctx context.Context, p UpsertBrandingParams) (*domain.Branding, error) {
|
||||
const q = `
|
||||
INSERT INTO event_branding (
|
||||
event_id, primary_color, accent_color, logo_url,
|
||||
cover_image_url, font_family, greeting_message, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, NULLIF($2, ''), NULLIF($3, ''), NULLIF($4, ''),
|
||||
NULLIF($5, ''), NULLIF($6, ''), NULLIF($7, ''), now()
|
||||
)
|
||||
ON CONFLICT (event_id) DO UPDATE SET
|
||||
primary_color = COALESCE($2, event_branding.primary_color),
|
||||
accent_color = COALESCE($3, event_branding.accent_color),
|
||||
logo_url = COALESCE($4, event_branding.logo_url),
|
||||
cover_image_url = COALESCE($5, event_branding.cover_image_url),
|
||||
font_family = COALESCE($6, event_branding.font_family),
|
||||
greeting_message = COALESCE($7, event_branding.greeting_message),
|
||||
updated_at = now()
|
||||
RETURNING event_id, primary_color, accent_color, logo_url,
|
||||
cover_image_url, font_family, greeting_message, updated_at
|
||||
`
|
||||
// Convert "" → NULL handling: we pass the same *string into both
|
||||
// COALESCE (the keep-existing path) and NULLIF (the reset path). The
|
||||
// caller passes nil to mean "leave alone" — we surface that as NULL
|
||||
// pgx side which COALESCE swallows.
|
||||
var b domain.Branding
|
||||
err := r.pool.QueryRow(ctx, q,
|
||||
p.EventID,
|
||||
nilOrPtr(p.PrimaryColor),
|
||||
nilOrPtr(p.AccentColor),
|
||||
nilOrPtr(p.LogoURL),
|
||||
nilOrPtr(p.CoverImageURL),
|
||||
nilOrPtr(p.FontFamily),
|
||||
nilOrPtr(p.GreetingMessage),
|
||||
).Scan(
|
||||
&b.EventID, &b.PrimaryColor, &b.AccentColor, &b.LogoURL,
|
||||
&b.CoverImageURL, &b.FontFamily, &b.GreetingMessage, &b.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
// nilOrPtr passes nil through as nil (pgx → NULL); otherwise unwraps the
|
||||
// string so we get a TEXT param instead of pgx receiving a *string and
|
||||
// double-wrapping it.
|
||||
func nilOrPtr(s *string) any {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return *s
|
||||
}
|
||||
@@ -195,6 +195,33 @@ func assertNotLastOwner(ctx context.Context, tx pgx.Tx, eventID uuid.UUID) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// RolesForUser returns a map of event_id → role for every event the user
|
||||
// has any accepted role on. Used by GET /events so the dashboard can
|
||||
// split "your events" from "shared with you" without making N queries
|
||||
// (one per event card).
|
||||
func (r *CollaboratorRepo) RolesForUser(ctx context.Context, userID uuid.UUID) (map[uuid.UUID]domain.Role, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT event_id, role FROM event_collaborators
|
||||
WHERE user_id = $1 AND accepted_at IS NOT NULL
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[uuid.UUID]domain.Role{}
|
||||
for rows.Next() {
|
||||
var (
|
||||
id uuid.UUID
|
||||
role domain.Role
|
||||
)
|
||||
if err := rows.Scan(&id, &role); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[id] = role
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListEventIDsForUser returns the set of event IDs the user has any accepted
|
||||
// role on. Used by GET /events to widen the dashboard list beyond just
|
||||
// `events.host_id = userID`.
|
||||
@@ -341,6 +368,121 @@ func (r *CollaboratorRepo) AcceptInvite(
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// PendingInviteForUser is one pending invitation in a user's inbox-style
|
||||
// list: their own dashboard's "you've been invited" banner. We surface the
|
||||
// event name + inviter name here so the frontend renders one card per
|
||||
// invite without N follow-up lookups.
|
||||
type PendingInviteForUser struct {
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
EventName string `json:"event_name"`
|
||||
Role domain.Role `json:"role"`
|
||||
InvitedBy uuid.UUID `json:"invited_by"`
|
||||
InviterName string `json:"inviter_name"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ListPendingForEmail returns every unconsumed, non-expired invite addressed
|
||||
// to `email`. The most recent invite per (email, event) wins — older
|
||||
// duplicates are squashed so the user sees one card per event even if the
|
||||
// owner re-sent the invitation. Drives the dashboard banner that lets a
|
||||
// just-signed-in user accept without re-clicking the email link.
|
||||
func (r *InviteRepo) ListPendingForEmail(ctx context.Context, email string) ([]PendingInviteForUser, error) {
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT DISTINCT ON (ci.event_id)
|
||||
ci.event_id, e.name, ci.role, ci.invited_by,
|
||||
COALESCE(u.name, '') AS inviter_name,
|
||||
ci.expires_at, ci.created_at
|
||||
FROM collaborator_invites ci
|
||||
JOIN events e ON e.id = ci.event_id
|
||||
LEFT JOIN users u ON u.id = ci.invited_by
|
||||
WHERE lower(ci.email) = $1
|
||||
AND ci.consumed_at IS NULL
|
||||
AND ci.expires_at > now()
|
||||
ORDER BY ci.event_id, ci.created_at DESC
|
||||
`, email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []PendingInviteForUser{}
|
||||
for rows.Next() {
|
||||
var p PendingInviteForUser
|
||||
if err := rows.Scan(
|
||||
&p.EventID, &p.EventName, &p.Role, &p.InvitedBy,
|
||||
&p.InviterName, &p.ExpiresAt, &p.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AcceptByEventAndEmail finds the latest pending invite for (email, eventID)
|
||||
// and atomically consumes it + inserts the collaborator row. Used by the
|
||||
// dashboard "Accept" button — the user authenticates with their session,
|
||||
// and we match by email so the cross-tab signup flow doesn't need the raw
|
||||
// token. Returns ErrInviteNotFound when no matching invite is pending.
|
||||
func (r *CollaboratorRepo) AcceptByEventAndEmail(
|
||||
ctx context.Context,
|
||||
eventID uuid.UUID,
|
||||
email string,
|
||||
userID uuid.UUID,
|
||||
) (domain.Role, error) {
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
// Lock the latest matching invite so two concurrent accepts can't
|
||||
// both consume the same row.
|
||||
var (
|
||||
tokenHash string
|
||||
role domain.Role
|
||||
invitedBy uuid.UUID
|
||||
)
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT token_hash, role, invited_by
|
||||
FROM collaborator_invites
|
||||
WHERE event_id = $1
|
||||
AND lower(email) = $2
|
||||
AND consumed_at IS NULL
|
||||
AND expires_at > now()
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE
|
||||
`, eventID, email).Scan(&tokenHash, &role, &invitedBy)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", domain.ErrInviteNotFound
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE collaborator_invites
|
||||
SET consumed_at = now()
|
||||
WHERE token_hash = $1
|
||||
`, tokenHash); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO event_collaborators (event_id, user_id, role, invited_by, invited_at, accepted_at)
|
||||
VALUES ($1, $2, $3, $4, now(), now())
|
||||
ON CONFLICT (event_id, user_id) DO NOTHING
|
||||
`, eventID, userID, role, invitedBy); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// ListPendingForEvent returns invitations the host hasn't seen accepted yet,
|
||||
// shown alongside accepted collaborators on the Team tab.
|
||||
func (r *InviteRepo) ListPendingForEvent(ctx context.Context, eventID uuid.UUID) ([]domain.CollaboratorInvite, error) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS event_branding;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Tier 2 Block D — event branding.
|
||||
--
|
||||
-- Per-event customisation of the RSVP page and outbound emails. The
|
||||
-- custom-domain sub-block was deferred to Tier 3 (the application surface
|
||||
-- is small but ingress + automatic TLS provisioning isn't — see
|
||||
-- TIER2_PLAN.md open question #1).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS event_branding (
|
||||
event_id UUID PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE,
|
||||
primary_color TEXT,
|
||||
accent_color TEXT,
|
||||
logo_url TEXT,
|
||||
cover_image_url TEXT,
|
||||
font_family TEXT,
|
||||
greeting_message TEXT,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,143 @@
|
||||
// Package uploads handles image uploads for the branding flow (Tier 2 Block D).
|
||||
//
|
||||
// In dev we write to the local filesystem and serve via a dedicated HTTP
|
||||
// handler; in production the same interface should be backed by S3 + CDN
|
||||
// (left as a deployment task, not application code — same split the project
|
||||
// uses for backups and DB infra).
|
||||
//
|
||||
// Validation philosophy: never trust the Content-Type header from the
|
||||
// client. We decode the bytes through Go's image stdlib and re-encode them
|
||||
// to a known format. That strips EXIF, normalises the byte stream, and
|
||||
// turns a "spoof an exe as a PNG" attempt into a decode error instead of a
|
||||
// stored payload.
|
||||
package uploads
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
// Register the standard decoders so image.Decode recognises jpeg/png.
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MaxUploadBytes caps every accepted upload. 2 MB covers logos + cover
|
||||
// photos comfortably; the host's browser usually scales further when the
|
||||
// page actually renders.
|
||||
const MaxUploadBytes = 2 * 1024 * 1024
|
||||
|
||||
// Format names normalised post-decode. Anything else we reject.
|
||||
const (
|
||||
FormatJPEG = "jpeg"
|
||||
FormatPNG = "png"
|
||||
)
|
||||
|
||||
// ImageStore is the production seam. LocalFSStore is the dev impl; a future
|
||||
// S3Store will satisfy the same interface so handlers don't change.
|
||||
type ImageStore interface {
|
||||
// Save persists the (re-encoded) bytes under a fresh random key and
|
||||
// returns the public URL the frontend should reference.
|
||||
Save(ctx context.Context, body []byte, format string) (publicURL string, err error)
|
||||
// FilePath maps a publicly-served filename back to a local path so the
|
||||
// dev HTTP handler can stream it. S3 impls would return "" + an error
|
||||
// (their URLs hit the CDN directly, not the API).
|
||||
FilePath(filename string) (string, error)
|
||||
}
|
||||
|
||||
// LocalFSStore writes each upload to a flat directory on disk. Filenames
|
||||
// are 16 hex bytes + the canonical extension so two uploads can't collide
|
||||
// and a guessing attacker has 128 bits to brute-force.
|
||||
type LocalFSStore struct {
|
||||
// Dir is the on-disk directory. Created on first call if missing.
|
||||
Dir string
|
||||
// PublicBase is the URL prefix the frontend will use to fetch saved
|
||||
// images, e.g. "http://localhost:8080/uploads". The API exposes a
|
||||
// matching handler at PublicBase's path.
|
||||
PublicBase string
|
||||
}
|
||||
|
||||
// Save re-encodes and writes the image to disk. Returns the full public
|
||||
// URL the host should store in their branding row.
|
||||
func (s *LocalFSStore) Save(ctx context.Context, body []byte, format string) (string, error) {
|
||||
if err := os.MkdirAll(s.Dir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("mkdir uploads: %w", err)
|
||||
}
|
||||
ext := ".jpg"
|
||||
if format == FormatPNG {
|
||||
ext = ".png"
|
||||
}
|
||||
name := randName() + ext
|
||||
dest := filepath.Join(s.Dir, name)
|
||||
if err := os.WriteFile(dest, body, 0o644); err != nil {
|
||||
return "", fmt.Errorf("write upload: %w", err)
|
||||
}
|
||||
base := strings.TrimRight(s.PublicBase, "/")
|
||||
return base + "/" + name, nil
|
||||
}
|
||||
|
||||
// FilePath maps a served filename back to its local path. Refuses any
|
||||
// path with a separator so we can't be tricked into serving /etc/passwd.
|
||||
func (s *LocalFSStore) FilePath(filename string) (string, error) {
|
||||
if filename == "" || strings.ContainsAny(filename, "/\\") || strings.HasPrefix(filename, ".") {
|
||||
return "", errors.New("invalid upload filename")
|
||||
}
|
||||
return filepath.Join(s.Dir, filename), nil
|
||||
}
|
||||
|
||||
// DecodeAndReencode validates `raw` as a recognised image format and
|
||||
// returns the re-encoded bytes plus the canonical format name. Anything
|
||||
// that doesn't parse as JPEG/PNG (or that exceeds MaxUploadBytes) returns
|
||||
// an error.
|
||||
//
|
||||
// We deliberately don't trust the Content-Type header here — `image.Decode`
|
||||
// sniffs the magic bytes. Stripped through the encoder, the output is the
|
||||
// same image without EXIF / hidden chunks.
|
||||
func DecodeAndReencode(raw []byte) (out []byte, format string, err error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, "", errors.New("empty upload")
|
||||
}
|
||||
if len(raw) > MaxUploadBytes {
|
||||
return nil, "", fmt.Errorf("upload exceeds %d byte limit", MaxUploadBytes)
|
||||
}
|
||||
img, gotFormat, err := image.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("not a recognised image: %w", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
switch gotFormat {
|
||||
case "jpeg":
|
||||
format = FormatJPEG
|
||||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 88}); err != nil {
|
||||
return nil, "", fmt.Errorf("re-encode jpeg: %w", err)
|
||||
}
|
||||
case "png":
|
||||
format = FormatPNG
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return nil, "", fmt.Errorf("re-encode png: %w", err)
|
||||
}
|
||||
default:
|
||||
return nil, "", fmt.Errorf("unsupported image format %q (jpeg/png only)", gotFormat)
|
||||
}
|
||||
return buf.Bytes(), format, nil
|
||||
}
|
||||
|
||||
// PeekReader reads up to MaxUploadBytes+1 from r. We add one byte so the
|
||||
// caller can tell "exactly at the limit" from "over the limit" without
|
||||
// pulling the whole body into RAM up front for size-only rejection.
|
||||
func PeekReader(r io.Reader) ([]byte, error) {
|
||||
return io.ReadAll(io.LimitReader(r, MaxUploadBytes+1))
|
||||
}
|
||||
|
||||
func randName() string {
|
||||
var b [16]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package uploads
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// makePNG and makeJPEG produce a tiny valid image for the round-trip tests.
|
||||
func makePNG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
|
||||
img.Set(0, 0, color.RGBA{34, 197, 94, 255})
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatalf("encode png: %v", err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func makeJPEG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
|
||||
img.Set(0, 0, color.RGBA{34, 197, 94, 255})
|
||||
var b bytes.Buffer
|
||||
if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: 80}); err != nil {
|
||||
t.Fatalf("encode jpeg: %v", err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func TestDecodeAndReencode_PNG(t *testing.T) {
|
||||
out, format, err := DecodeAndReencode(makePNG(t))
|
||||
if err != nil {
|
||||
t.Fatalf("decode png: %v", err)
|
||||
}
|
||||
if format != FormatPNG {
|
||||
t.Errorf("format: got %q want png", format)
|
||||
}
|
||||
// Output must be valid PNG (round-trip decode).
|
||||
if _, _, err := image.Decode(bytes.NewReader(out)); err != nil {
|
||||
t.Errorf("re-encoded png is not valid: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeAndReencode_JPEG(t *testing.T) {
|
||||
out, format, err := DecodeAndReencode(makeJPEG(t))
|
||||
if err != nil {
|
||||
t.Fatalf("decode jpeg: %v", err)
|
||||
}
|
||||
if format != FormatJPEG {
|
||||
t.Errorf("format: got %q want jpeg", format)
|
||||
}
|
||||
if _, _, err := image.Decode(bytes.NewReader(out)); err != nil {
|
||||
t.Errorf("re-encoded jpeg is not valid: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeAndReencode_RejectsNonImage(t *testing.T) {
|
||||
_, _, err := DecodeAndReencode([]byte("hello, world"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error decoding a non-image payload")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "not a recognised image") {
|
||||
t.Errorf("error: got %q want 'not a recognised image'", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeAndReencode_RejectsTooLarge(t *testing.T) {
|
||||
big := make([]byte, MaxUploadBytes+1)
|
||||
_, _, err := DecodeAndReencode(big)
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Errorf("expected size-limit error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalFSStore_FilePath_RejectsTraversal(t *testing.T) {
|
||||
s := &LocalFSStore{Dir: "/tmp/x", PublicBase: "http://localhost/up"}
|
||||
cases := []string{"../etc/passwd", "a/b.png", "..", ".env"}
|
||||
for _, in := range cases {
|
||||
if _, err := s.FilePath(in); err == nil {
|
||||
t.Errorf("FilePath(%q) should have refused", in)
|
||||
}
|
||||
}
|
||||
// A bare random filename should be accepted.
|
||||
if _, err := s.FilePath("ok.png"); err != nil {
|
||||
t.Errorf("FilePath(ok.png) should have accepted: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user