feat(tier2): finish the finish line — Block H follow-ups, Block G geolocation, cross-cutting
Three threads of work land here together to close out Tier 2.
### Block H follow-ups — day-of check-in
- Scanner is now an "open on your phone" magic-link flow. Hosts on
desktop mint a scoped JWT via POST /events/{id}/scanner-ticket and
render its URL into a QR; phone scans it and lands on /scanner with
the ticket as bearer. The ticket carries Audience=scanner so it can
never substitute for a session token.
- Plus-one confirmation at the door: scan → POST /check-in/preview to
fetch guest + expected party size → confirm buttons ("Just them",
"Party of N", custom) → POST /check-in. No more silent arrival_count=1.
- Offline scan queue: failed POSTs go into an IndexedDB store and drain
on the 'online' event with poison-message protection.
- Day-of arrivals headline widget on the event overview, gated to the
host's local calendar date so it doesn't dominate the page weeks out.
- Tab nav restyled with inline heroicons + scrollable segmented control;
Check-in moves to the rightmost slot.
- PWA: manifest + service worker scoped to /scanner, generated 192/512
icons (Go scripted renderer in scripts/gen-scanner-icons.go).
- Confirmation email QR was rendering broken because html/template
rewrites data: URLs to #ZgotmplZ; mark the value as template.URL.
- Email "open your invitation" link 404'd because we had no token to
put after /rsvp/. Threaded AccessLink through the RSVPConfirmed NATS
event from the API at submit time.
### Block G remainder — geolocation + threshold preview
- Pluggable GeoResolver in the fraud engine (NullResolver, IPApiResolver
for the free ip-api.com fallback, MaxMindResolver behind GG_GEOIP_DB_PATH).
Wrapped in a Redis cache (30d TTL). Geo flows through both gRPC and
NATS scoring paths.
- geo_jump scoring feature: >500km in <1h flags ("accessed from Lagos
and Paris within 12 minutes"); >500km in <6h is a softer signal. The
existing single-signal cap keeps a lone geo_jump in MEDIUM.
- FraudScored event carries geo_country/city/lat/lon; ApplyScore uses
COALESCE so a later re-score without geo doesn't wipe earlier data.
- Threshold-slider live preview: GET /events/{id}/security/thresholds/preview
returns band counts the host's existing access events would have
fallen into under the proposed thresholds. Debounced (250ms) widget
under the Advanced sliders so the host gets concrete feedback instead
of guessing.
### Cross-cutting — audit, tier-gating, feature flags
- audit_log table + internal/audit.Recorder (async fire-and-forget on
detached context so an audit blip never fails the real action). Wired
into branding update, thresholds update, allowlist add/remove,
collaborator invite/role-change/remove, message create/send-now/cancel.
- Tier-gating: extended billing.Limits with MaxCollaborators,
CustomBranding, Scanner, Broadcasts. Free = none; Pro = 5 + all;
Business = unlimited. Gates the scanner-ticket, message create,
branding put, and collaborator invite endpoints with 402 +
structured upgrade payload. Auto-reminders, fraud detection, and
analytics deliberately stay on every tier — those are safety + visibility
features, not upsell levers.
- Feature flags: feature_flags table + internal/flags.Store with 30s
in-memory refresh, stable sha256(key + user_id) percent bucketing,
unknown-key-defaults-on. Six Tier 2 flags pre-seeded. Three handlers
(branding, broadcasts, scanner) check the kill switch ahead of the
tier gate so ops can pull a feature back without a redeploy.
### Verified
- go test ./... + fraud-engine pytest (12/12 incl. 3 new geo_jump tests + 5
new flags tests).
- docker compose build + up across api, fraud-engine, notifier, frontend.
- /health endpoints 200; migrations 0014 + 0015 applied; 6 flags
seeded; audit_log table + partial indexes confirmed.
- Fraud-engine logs confirm geo resolver kind=CachedGeoResolver provider=auto.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -550,6 +550,17 @@ func requireAuth(signer *auth.JWTSigner) func(http.Handler) http.Handler {
|
||||
writeError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
// Scanner-scoped tokens are signed with the same HMAC secret but
|
||||
// carry Audience="scanner" and are deliberately narrower than a
|
||||
// session token — they only authorise the door-volunteer surface.
|
||||
// Reject them here so requireAuth never grants account-wide access
|
||||
// to a magic-link ticket.
|
||||
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))
|
||||
})
|
||||
|
||||
@@ -135,6 +135,73 @@ func (e *tierEnforcer) allowGuestImport(w http.ResponseWriter, r *http.Request,
|
||||
return true
|
||||
}
|
||||
|
||||
// allowFeature gates a boolean Tier 2 feature (branding, scanner,
|
||||
// broadcasts) against the host's current plan. On denial it writes a
|
||||
// 402 with an upgrade payload and returns false. The `reason` value
|
||||
// goes back to the frontend so it can render a targeted upgrade modal
|
||||
// instead of a generic "upgrade your plan" prompt.
|
||||
func (e *tierEnforcer) allowFeature(w http.ResponseWriter, r *http.Request, hostID uuid.UUID, reason, friendly string) bool {
|
||||
if e == nil || e.subs == nil {
|
||||
return true
|
||||
}
|
||||
tier, err := e.currentTier(r.Context(), hostID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to check plan")
|
||||
return false
|
||||
}
|
||||
limits := billing.LimitsFor(tier)
|
||||
allowed := false
|
||||
switch reason {
|
||||
case "custom_branding":
|
||||
allowed = limits.CustomBranding
|
||||
case "scanner":
|
||||
allowed = limits.Scanner
|
||||
case "broadcasts":
|
||||
allowed = limits.Broadcasts
|
||||
default:
|
||||
// Unknown feature — be conservative, treat as allowed so a
|
||||
// future caller can ship before the gate is hooked up.
|
||||
return true
|
||||
}
|
||||
if allowed {
|
||||
return true
|
||||
}
|
||||
e.writePaymentRequired(w, reason, tier, 0, 0, friendly)
|
||||
return false
|
||||
}
|
||||
|
||||
// allowCollaboratorInvite gates the per-event collaborator count. Used
|
||||
// by POST /events/{id}/collaborators before we mint the invite — saves
|
||||
// us creating an invitation token only to surface a 402 on accept.
|
||||
func (e *tierEnforcer) allowCollaboratorInvite(w http.ResponseWriter, r *http.Request, hostID, eventID uuid.UUID) bool {
|
||||
if e == nil || e.subs == nil {
|
||||
return true
|
||||
}
|
||||
tier, err := e.currentTier(r.Context(), hostID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to check plan")
|
||||
return false
|
||||
}
|
||||
limit := billing.LimitsFor(tier).MaxCollaborators
|
||||
if limit < 0 {
|
||||
return true
|
||||
}
|
||||
used, err := e.subs.CountCollaboratorsByEvent(r.Context(), eventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to count collaborators")
|
||||
return false
|
||||
}
|
||||
if used >= limit {
|
||||
msg := "You've reached the collaborator limit on the " + strings.ToUpper(string(tier)) + " plan."
|
||||
if tier == billing.TierFree {
|
||||
msg = "Collaborators aren't included on the free plan. Upgrade to share this event with editors or viewers."
|
||||
}
|
||||
e.writePaymentRequired(w, "max_collaborators", tier, used, limit, msg)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type paymentRequiredBody struct {
|
||||
Error string `json:"error"`
|
||||
Reason string `json:"reason"`
|
||||
|
||||
@@ -10,7 +10,9 @@ import (
|
||||
"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"
|
||||
)
|
||||
@@ -19,11 +21,14 @@ import (
|
||||
// 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
|
||||
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 {
|
||||
@@ -88,6 +93,20 @@ func (h *brandingHandler) put(w http.ResponseWriter, r *http.Request) {
|
||||
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")
|
||||
@@ -127,6 +146,20 @@ func (h *brandingHandler) put(w http.ResponseWriter, r *http.Request) {
|
||||
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})
|
||||
}
|
||||
|
||||
|
||||
+206
-33
@@ -1,18 +1,22 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/auth"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/flags"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
@@ -20,13 +24,116 @@ import (
|
||||
// codes at the door, record arrivals, register walk-ins, drive the
|
||||
// live arrivals counter on the dashboard.
|
||||
type checkInHandler struct {
|
||||
logger *slog.Logger
|
||||
events *storage.EventRepo
|
||||
guests *storage.GuestRepo
|
||||
collabs *storage.CollaboratorRepo
|
||||
repo *storage.CheckInRepo
|
||||
qrSigner *auth.CheckInQRSigner
|
||||
hub *Hub
|
||||
logger *slog.Logger
|
||||
events *storage.EventRepo
|
||||
guests *storage.GuestRepo
|
||||
collabs *storage.CollaboratorRepo
|
||||
repo *storage.CheckInRepo
|
||||
qrSigner *auth.CheckInQRSigner
|
||||
scannerSigner *auth.ScannerJWTSigner
|
||||
publicBaseURL string
|
||||
hub *Hub
|
||||
enforcer *tierEnforcer
|
||||
flags *flags.Store
|
||||
}
|
||||
|
||||
// --- preview a check-in (POST /events/{id}/check-in/preview) ---
|
||||
//
|
||||
// The scanner submits the decoded QR string; we validate the JWT and
|
||||
// return the guest plus what we already know about them — name,
|
||||
// expected party size, and whether they've already been recorded.
|
||||
// No DB writes. The frontend uses this to render the
|
||||
// "Just them / +1 / +2 / Other" confirmation step before committing
|
||||
// the check-in, matching how Eventbrite / Lu.ma scanners handle
|
||||
// plus-ones at the door.
|
||||
|
||||
type previewCheckInRequest struct {
|
||||
QRPayload string `json:"qr_payload"`
|
||||
}
|
||||
|
||||
type previewCheckInResponse struct {
|
||||
Guest *domain.Guest `json:"guest"`
|
||||
ExpectedPartySize int `json:"expected_party_size"`
|
||||
AlreadyCheckedIn bool `json:"already_checked_in"`
|
||||
ExistingCheckIn *domain.CheckIn `json:"existing_check_in,omitempty"`
|
||||
}
|
||||
|
||||
func (h *checkInHandler) preview(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !requireScannerEventMatch(w, r, eventID) {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req previewCheckInRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
req.QRPayload = strings.TrimSpace(req.QRPayload)
|
||||
if req.QRPayload == "" {
|
||||
writeError(w, http.StatusBadRequest, "qr_payload is required")
|
||||
return
|
||||
}
|
||||
|
||||
claims, status, msg := h.parseCheckInQR(r.Context(), req.QRPayload, eventID)
|
||||
if status != 0 {
|
||||
writeError(w, status, msg)
|
||||
return
|
||||
}
|
||||
|
||||
guest, gerr := h.guests.Get(r.Context(), claims.GuestID)
|
||||
if gerr != nil || guest == nil {
|
||||
writeError(w, http.StatusNotFound, "guest not found")
|
||||
return
|
||||
}
|
||||
// arrival_count counts the guest plus their plus-ones; the door
|
||||
// volunteer most often presses the matching number, so this is what
|
||||
// drives the default-highlight in the UI.
|
||||
expected := guest.PlusOnes + 1
|
||||
|
||||
existing, _ := h.repo.GetByGuest(r.Context(), guest.ID)
|
||||
resp := previewCheckInResponse{
|
||||
Guest: guest,
|
||||
ExpectedPartySize: expected,
|
||||
AlreadyCheckedIn: existing != nil,
|
||||
ExistingCheckIn: existing,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// parseCheckInQR centralises the JWT validation + event-binding +
|
||||
// guest-belongs-to-event checks that both preview and record need.
|
||||
// Returns (claims, 0, "") on success or (nil, statusCode, message) on
|
||||
// the recoverable error paths so the caller writes a single response.
|
||||
func (h *checkInHandler) parseCheckInQR(ctx context.Context, payload string, eventID uuid.UUID) (*auth.CheckInQR, int, string) {
|
||||
claims, err := h.qrSigner.Parse(payload)
|
||||
if err != nil {
|
||||
if errors.Is(err, auth.ErrExpiredJWT) {
|
||||
return nil, http.StatusGone, "this QR has expired"
|
||||
}
|
||||
return nil, http.StatusBadRequest, "invalid QR"
|
||||
}
|
||||
if claims.EventID != eventID {
|
||||
return nil, http.StatusBadRequest, "this QR belongs to a different event"
|
||||
}
|
||||
belongs, err := h.repo.GuestBelongsToEvent(ctx, claims.GuestID, eventID)
|
||||
if err != nil {
|
||||
return nil, http.StatusInternalServerError, "failed to verify guest"
|
||||
}
|
||||
if !belongs {
|
||||
return nil, http.StatusNotFound, "guest is no longer on this event"
|
||||
}
|
||||
return claims, 0, ""
|
||||
}
|
||||
|
||||
// --- record a check-in (QR-scanner POST) ---
|
||||
@@ -57,6 +164,9 @@ func (h *checkInHandler) record(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !requireScannerEventMatch(w, r, eventID) {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
@@ -72,32 +182,9 @@ func (h *checkInHandler) record(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := h.qrSigner.Parse(req.QRPayload)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrExpiredJWT):
|
||||
writeError(w, http.StatusGone, "this QR has expired")
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "invalid QR")
|
||||
}
|
||||
return
|
||||
}
|
||||
if claims.EventID != eventID {
|
||||
// JWT was issued for a different event. The scanner may have
|
||||
// roamed; the host should switch event pages.
|
||||
writeError(w, http.StatusBadRequest, "this QR belongs to a different event")
|
||||
return
|
||||
}
|
||||
|
||||
// Sanity: the guest still belongs to this event (host may have
|
||||
// removed them after issuing the QR).
|
||||
belongs, err := h.repo.GuestBelongsToEvent(r.Context(), claims.GuestID, eventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to verify guest")
|
||||
return
|
||||
}
|
||||
if !belongs {
|
||||
writeError(w, http.StatusNotFound, "guest is no longer on this event")
|
||||
claims, status, msg := h.parseCheckInQR(r.Context(), req.QRPayload, eventID)
|
||||
if status != 0 {
|
||||
writeError(w, status, msg)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -161,6 +248,9 @@ func (h *checkInHandler) walkIn(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !requireScannerEventMatch(w, r, eventID) {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
@@ -237,6 +327,9 @@ func (h *checkInHandler) list(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !requireScannerEventMatch(w, r, eventID) {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
@@ -285,6 +378,86 @@ func nameOf(g *domain.Guest) string {
|
||||
return g.Name
|
||||
}
|
||||
|
||||
// --- scanner magic-link (POST /events/{id}/scanner-ticket) ---
|
||||
|
||||
type scannerTicketResponse struct {
|
||||
Token string `json:"token"`
|
||||
URL string `json:"url"`
|
||||
QRImage string `json:"qr_image"` // data: URL PNG
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// issueScannerTicket mints a short-lived, event-scoped JWT that a host
|
||||
// can render into a QR code on their desktop event-detail page. The
|
||||
// door volunteer scans that QR with their phone camera, the scanner
|
||||
// page reads ?token=<jwt> out of the URL, and uses it as a Bearer for
|
||||
// the three check-in endpoints — no separate phone login required.
|
||||
//
|
||||
// Editor+ on the event. Rate-limited at the route level. Tickets last
|
||||
// four hours by default (see NewScannerJWTSigner), long enough for a
|
||||
// full event without the host having to re-mint mid-night.
|
||||
func (h *checkInHandler) issueScannerTicket(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
|
||||
}
|
||||
// Kill switch — ops can disable scanner ticket minting without a
|
||||
// redeploy if the magic-link UX needs to be pulled back.
|
||||
if !h.flags.Enabled("checkin_pwa", hostID) {
|
||||
writeError(w, http.StatusServiceUnavailable, "the scanner is temporarily disabled")
|
||||
return
|
||||
}
|
||||
// The day-of scanner is a Pro+ feature. Free-tier hosts can still
|
||||
// see arrivals (the headline widget on the overview reads
|
||||
// /check-ins which is viewer+) but minting a magic link for a
|
||||
// volunteer's phone is an upsell lever.
|
||||
if !h.enforcer.allowFeature(w, r, hostID, "scanner",
|
||||
"The day-of check-in scanner is a Pro feature.") {
|
||||
return
|
||||
}
|
||||
if h.scannerSigner == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "scanner tickets are not configured")
|
||||
return
|
||||
}
|
||||
|
||||
tok, exp, err := h.scannerSigner.Issue(hostID, eventID, time.Now())
|
||||
if err != nil {
|
||||
h.logger.Error("issue scanner ticket", "err", err, "event_id", eventID)
|
||||
writeError(w, http.StatusInternalServerError, "failed to issue ticket")
|
||||
return
|
||||
}
|
||||
|
||||
// publicBaseURL is the front-of-house origin (e.g. https://guestguard.k4scloud.com).
|
||||
// We embed the event id as well as the token so the scanner page can
|
||||
// load the right event metadata before any check-in roundtrip.
|
||||
base := strings.TrimRight(h.publicBaseURL, "/")
|
||||
if base == "" {
|
||||
base = ""
|
||||
}
|
||||
scannerURL := base + "/scanner?token=" + url.QueryEscape(tok) + "&event=" + url.QueryEscape(eventID.String())
|
||||
|
||||
qrImage, err := renderQRPNG(scannerURL)
|
||||
if err != nil {
|
||||
h.logger.Error("render scanner QR", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to render QR")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, scannerTicketResponse{
|
||||
Token: tok,
|
||||
URL: scannerURL,
|
||||
QRImage: qrImage,
|
||||
ExpiresAt: exp,
|
||||
})
|
||||
}
|
||||
|
||||
// renderQRPNG converts a JWT-shaped string into a base64-encoded PNG
|
||||
// data URL the frontend can drop straight into an <img src>. Used by
|
||||
// the access response so a successful RSVP comes back with the guest's
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/audit"
|
||||
"github.com/alchemistkay/guestguard/internal/auth"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
@@ -27,6 +28,8 @@ type collaboratorHandler struct {
|
||||
emails auth.EmailSender
|
||||
publicBaseURL string
|
||||
inviteTTL time.Duration
|
||||
audit *audit.Recorder
|
||||
enforcer *tierEnforcer
|
||||
}
|
||||
|
||||
// --- responses ---
|
||||
@@ -159,6 +162,14 @@ func (h *collaboratorHandler) invite(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Tier gate. Free plans cap at 0 shared collaborators; Pro at 5;
|
||||
// Business unlimited. We deny BEFORE minting the invite so we
|
||||
// don't email someone an invite that the host won't be able to
|
||||
// honour.
|
||||
if !h.enforcer.allowCollaboratorInvite(w, r, hostID, eventID) {
|
||||
return
|
||||
}
|
||||
|
||||
// If the invitee already has an account AND is already a collaborator,
|
||||
// short-circuit with a friendly 409 — no email, no DB churn.
|
||||
if existing, err := h.users.GetByEmail(r.Context(), email); err == nil && existing != nil {
|
||||
@@ -192,6 +203,14 @@ func (h *collaboratorHandler) invite(w http.ResponseWriter, r *http.Request) {
|
||||
// so the host knows.
|
||||
sent := h.emailInvite(r.Context(), email, hostID, event.Name, req.Role, raw)
|
||||
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "collaborator.invite",
|
||||
EntityType: "collaborator_invite",
|
||||
Metadata: map[string]any{"email": email, "role": req.Role, "email_sent": sent},
|
||||
})
|
||||
|
||||
writeJSON(w, http.StatusCreated, inviteResponse{
|
||||
Email: email,
|
||||
Role: req.Role,
|
||||
@@ -245,6 +264,14 @@ func (h *collaboratorHandler) updateRole(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "collaborator.role_change",
|
||||
EntityType: "collaborator",
|
||||
TargetID: &userID,
|
||||
Metadata: map[string]any{"role": req.Role},
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -279,6 +306,13 @@ func (h *collaboratorHandler) remove(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "collaborator.remove",
|
||||
EntityType: "collaborator",
|
||||
TargetID: &userID,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ package api
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/audit"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
@@ -19,6 +21,7 @@ type securityHandler struct {
|
||||
allowlist *storage.AllowlistRepo
|
||||
feedback *storage.FeedbackRepo
|
||||
access *storage.AccessLogRepo
|
||||
audit *audit.Recorder
|
||||
}
|
||||
|
||||
// --- thresholds ---
|
||||
@@ -54,6 +57,96 @@ func (h *securityHandler) getThresholds(w http.ResponseWriter, r *http.Request)
|
||||
})
|
||||
}
|
||||
|
||||
// GET /events/{id}/security/thresholds/preview?medium=&high=&block= — viewer+.
|
||||
//
|
||||
// Returns the band-counts that *would* result from applying the
|
||||
// proposed thresholds to the event's recorded access scores. Powers the
|
||||
// live "12 of your 47 access events would be flagged" widget under the
|
||||
// sliders on the Gate tab, so a host moving the slider gets immediate
|
||||
// concrete feedback instead of having to wait for new scans to land.
|
||||
type thresholdsPreviewResponse struct {
|
||||
Total int `json:"total"` // number of scored access logs we considered
|
||||
Low int `json:"low"`
|
||||
Medium int `json:"medium"`
|
||||
High int `json:"high"`
|
||||
Block int `json:"block"`
|
||||
}
|
||||
|
||||
func (h *securityHandler) previewThresholds(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
|
||||
}
|
||||
|
||||
// Parse the proposed thresholds out of the query string. Falling
|
||||
// back to the event's stored thresholds when a value is missing
|
||||
// means the frontend can ask "what would high=70 look like, with
|
||||
// everything else as it is" without having to re-send the whole
|
||||
// triple every time.
|
||||
stored, _ := h.events.GetThresholds(r.Context(), eventID)
|
||||
proposed := stored
|
||||
if v, err := intQuery(r, "medium"); err == nil {
|
||||
proposed.Medium = v
|
||||
}
|
||||
if v, err := intQuery(r, "high"); err == nil {
|
||||
proposed.High = v
|
||||
}
|
||||
if v, err := intQuery(r, "block"); err == nil {
|
||||
proposed.Block = v
|
||||
}
|
||||
if err := proposed.Valid(); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
scores, err := h.access.ScoresForEvent(r.Context(), eventID, 1000)
|
||||
if err != nil {
|
||||
h.logger.Error("preview thresholds: load scores", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to load access history")
|
||||
return
|
||||
}
|
||||
|
||||
out := thresholdsPreviewResponse{Total: len(scores)}
|
||||
for _, s := range scores {
|
||||
switch proposed.Band(s) {
|
||||
case "block":
|
||||
out.Block++
|
||||
case "high":
|
||||
out.High++
|
||||
case "medium":
|
||||
out.Medium++
|
||||
default:
|
||||
out.Low++
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// intQuery extracts a non-negative integer from ?<name>= on the
|
||||
// request. Returns an error when missing or unparseable so the caller
|
||||
// can decide whether to substitute a default.
|
||||
func intQuery(r *http.Request, name string) (int, error) {
|
||||
raw := r.URL.Query().Get(name)
|
||||
if raw == "" {
|
||||
return 0, errors.New("missing")
|
||||
}
|
||||
var v int
|
||||
if _, err := fmt.Sscanf(raw, "%d", &v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if v < 0 || v > 100 {
|
||||
return 0, errors.New("out of range")
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// PUT /events/{id}/security/thresholds — editor+.
|
||||
func (h *securityHandler) putThresholds(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
@@ -85,6 +178,18 @@ func (h *securityHandler) putThresholds(w http.ResponseWriter, r *http.Request)
|
||||
writeError(w, http.StatusInternalServerError, "failed to update thresholds")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "thresholds.update",
|
||||
EntityType: "event",
|
||||
TargetID: &eventID,
|
||||
Metadata: map[string]any{
|
||||
"medium": req.Medium,
|
||||
"high": req.High,
|
||||
"block": req.Block,
|
||||
},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, thresholdsResponse{
|
||||
FraudThresholds: req,
|
||||
Defaults: domain.DefaultThresholds(),
|
||||
@@ -157,6 +262,13 @@ func (h *securityHandler) addAllowlist(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "failed to add allowlist entry")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "allowlist.add",
|
||||
EntityType: "allowlist",
|
||||
Metadata: map[string]any{"cidr": canonical, "label": req.Label},
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
@@ -193,6 +305,13 @@ func (h *securityHandler) removeAllowlist(w http.ResponseWriter, r *http.Request
|
||||
writeError(w, http.StatusInternalServerError, "failed to remove allowlist entry")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "allowlist.remove",
|
||||
EntityType: "allowlist",
|
||||
Metadata: map[string]any{"cidr": canonical},
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/audit"
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/flags"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
@@ -19,6 +21,9 @@ type messageHandler struct {
|
||||
events *storage.EventRepo
|
||||
collabs *storage.CollaboratorRepo
|
||||
repo *storage.MessageRepo
|
||||
audit *audit.Recorder
|
||||
enforcer *tierEnforcer
|
||||
flags *flags.Store
|
||||
}
|
||||
|
||||
// --- response shapes ---
|
||||
@@ -130,6 +135,20 @@ func (h *messageHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
// Kill switch — ops can disable broadcasts entirely without a
|
||||
// redeploy if delivery upstream goes wobbly.
|
||||
if !h.flags.Enabled("broadcasts", hostID) {
|
||||
writeError(w, http.StatusServiceUnavailable, "broadcasts are temporarily disabled")
|
||||
return
|
||||
}
|
||||
// Custom broadcasts are a Pro+ feature. Auto-reminders (which the
|
||||
// system creates on event creation) are NOT gated — those run for
|
||||
// every event regardless of tier so free users still get reminder
|
||||
// emails before their event.
|
||||
if !h.enforcer.allowFeature(w, r, hostID, "broadcasts",
|
||||
"Custom broadcasts are a Pro feature. Auto-reminders still run on every plan.") {
|
||||
return
|
||||
}
|
||||
var req composeMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
@@ -186,6 +205,18 @@ func (h *messageHandler) create(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create message")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "message.create",
|
||||
EntityType: "message",
|
||||
TargetID: &m.ID,
|
||||
Metadata: map[string]any{
|
||||
"audience": req.Audience,
|
||||
"channel": req.Channel,
|
||||
"status": status,
|
||||
},
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, m)
|
||||
}
|
||||
|
||||
@@ -283,6 +314,13 @@ func (h *messageHandler) sendNow(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "failed to schedule send")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "message.send_now",
|
||||
EntityType: "message",
|
||||
TargetID: &msgID,
|
||||
})
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
@@ -312,5 +350,12 @@ func (h *messageHandler) cancel(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusInternalServerError, "failed to cancel message")
|
||||
return
|
||||
}
|
||||
h.audit.Record(r.Context(), audit.Params{
|
||||
UserID: &hostID,
|
||||
EventID: &eventID,
|
||||
Action: "message.cancel",
|
||||
EntityType: "message",
|
||||
TargetID: &msgID,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
+30
-13
@@ -7,6 +7,8 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -27,16 +29,17 @@ type fraudScorer interface {
|
||||
}
|
||||
|
||||
type rsvpHandler struct {
|
||||
logger *slog.Logger
|
||||
guests *storage.GuestRepo
|
||||
tokens *storage.TokenRepo
|
||||
events *storage.EventRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
allowlist *storage.AllowlistRepo
|
||||
editNonces *editNonceStore
|
||||
scorer fraudScorer
|
||||
pub rsvpPublisher
|
||||
logger *slog.Logger
|
||||
guests *storage.GuestRepo
|
||||
tokens *storage.TokenRepo
|
||||
events *storage.EventRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
allowlist *storage.AllowlistRepo
|
||||
editNonces *editNonceStore
|
||||
scorer fraudScorer
|
||||
pub rsvpPublisher
|
||||
publicBaseURL string
|
||||
}
|
||||
|
||||
type submitRSVPRequest struct {
|
||||
@@ -111,7 +114,7 @@ func (h *rsvpHandler) submit(w http.ResponseWriter, r *http.Request) {
|
||||
// The token must remain valid so the guest can come back to the same
|
||||
// link and edit their response.
|
||||
|
||||
h.publishRSVPConfirmed(event.ID, guest.ID, rsvp, &score)
|
||||
h.publishRSVPConfirmed(event.ID, guest.ID, rsvp, &score, h.accessLinkFor(r))
|
||||
|
||||
writeJSON(w, http.StatusCreated, submitRSVPResponse{
|
||||
RSVP: rsvp,
|
||||
@@ -201,7 +204,7 @@ func (h *rsvpHandler) edit(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.publishRSVPConfirmed(event.ID, guest.ID, rsvp, &score)
|
||||
h.publishRSVPConfirmed(event.ID, guest.ID, rsvp, &score, h.accessLinkFor(r))
|
||||
|
||||
writeJSON(w, http.StatusOK, submitRSVPResponse{
|
||||
RSVP: rsvp,
|
||||
@@ -409,7 +412,7 @@ func (h *rsvpHandler) scoreAccess(
|
||||
return decision, fingerprint, ip, true
|
||||
}
|
||||
|
||||
func (h *rsvpHandler) publishRSVPConfirmed(eventID, guestID uuid.UUID, rsvp *domain.RSVP, score *int) {
|
||||
func (h *rsvpHandler) publishRSVPConfirmed(eventID, guestID uuid.UUID, rsvp *domain.RSVP, score *int, accessLink string) {
|
||||
if h.pub == nil {
|
||||
return
|
||||
}
|
||||
@@ -427,9 +430,23 @@ func (h *rsvpHandler) publishRSVPConfirmed(eventID, guestID uuid.UUID, rsvp *dom
|
||||
PlusOnes: rsvp.PlusOnes,
|
||||
RiskScore: score,
|
||||
SubmittedAt: rsvp.SubmittedAt,
|
||||
AccessLink: accessLink,
|
||||
})
|
||||
}
|
||||
|
||||
// accessLinkFor reconstructs the magic invitation URL the guest used to
|
||||
// arrive at the RSVP page. The raw token is only ever available on the
|
||||
// inbound request (the database holds just the hash), so this is the
|
||||
// only point where we can capture it for downstream channels like the
|
||||
// confirmation email.
|
||||
func (h *rsvpHandler) accessLinkFor(r *http.Request) string {
|
||||
raw := strings.TrimSpace(r.PathValue("token"))
|
||||
if raw == "" || h.publicBaseURL == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimRight(h.publicBaseURL, "/") + "/rsvp/" + url.PathEscape(raw)
|
||||
}
|
||||
|
||||
func mergeFingerprint(client map[string]any, server map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(server)+len(client))
|
||||
for k, v := range server {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
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
|
||||
}
|
||||
+81
-34
@@ -7,8 +7,10 @@ import (
|
||||
|
||||
"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"
|
||||
@@ -29,8 +31,10 @@ type Server struct {
|
||||
ws *wsHandler
|
||||
wsTicket *wsTicketHandler
|
||||
health *healthHandler
|
||||
signer *auth.JWTSigner
|
||||
limiter *ratelimit.Limiter
|
||||
signer *auth.JWTSigner
|
||||
scannerSigner *auth.ScannerJWTSigner
|
||||
limiter *ratelimit.Limiter
|
||||
flags *flags.Store
|
||||
unsub *unsubscribeHandler
|
||||
webhooks *webhookHandler
|
||||
csv *csvImportHandler
|
||||
@@ -107,6 +111,8 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
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
|
||||
@@ -116,6 +122,15 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
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
|
||||
@@ -218,16 +233,17 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
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,
|
||||
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,
|
||||
@@ -237,9 +253,11 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
},
|
||||
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,
|
||||
limiter: limiter,
|
||||
health: &healthHandler{pool: deps.DB.Pool},
|
||||
signer: signer,
|
||||
scannerSigner: scannerJWTSigner,
|
||||
limiter: limiter,
|
||||
flags: flagStore,
|
||||
unsub: &unsubscribeHandler{
|
||||
logger: deps.Logger,
|
||||
signer: deps.UnsubscribeSigner,
|
||||
@@ -271,11 +289,14 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
redis: deps.Redis,
|
||||
},
|
||||
branding: &brandingHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
collabs: collabRepo,
|
||||
repo: brandingRepo,
|
||||
store: imageStore,
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
collabs: collabRepo,
|
||||
repo: brandingRepo,
|
||||
store: imageStore,
|
||||
audit: auditRec,
|
||||
enforcer: enforcer,
|
||||
flags: flagStore,
|
||||
},
|
||||
uploads: &uploadHandler{
|
||||
logger: deps.Logger,
|
||||
@@ -288,21 +309,29 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
allowlist: allowlistRepo,
|
||||
feedback: feedbackRepo,
|
||||
access: accessRepo,
|
||||
audit: auditRec,
|
||||
},
|
||||
messages: &messageHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
collabs: collabRepo,
|
||||
repo: messageRepo,
|
||||
},
|
||||
checkIns: &checkInHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
guests: guestRepo,
|
||||
collabs: collabRepo,
|
||||
repo: checkInRepo,
|
||||
qrSigner: checkInQRSigner,
|
||||
hub: hub,
|
||||
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,
|
||||
@@ -312,6 +341,8 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
invites: inviteRepo,
|
||||
emails: emails,
|
||||
publicBaseURL: deps.PublicBaseURL,
|
||||
audit: auditRec,
|
||||
enforcer: enforcer,
|
||||
},
|
||||
privacy: &privacyHandler{
|
||||
logger: deps.Logger,
|
||||
@@ -329,6 +360,10 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
|
||||
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()
|
||||
|
||||
@@ -407,6 +442,8 @@ func (s *Server) Handler() http.Handler {
|
||||
// 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",
|
||||
@@ -435,13 +472,23 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("DELETE /events/{id}/messages/{message_id}",
|
||||
authed(http.HandlerFunc(s.messages.cancel)))
|
||||
|
||||
// Block H — day-of check-in.
|
||||
// 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",
|
||||
authed(rl("checkin_record", 1000, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.record))))
|
||||
scannerAuthed(rl("checkin_record", 1000, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.record))))
|
||||
mux.Handle("POST /events/{id}/walk-ins",
|
||||
authed(rl("checkin_walk_in", 500, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.walkIn))))
|
||||
scannerAuthed(rl("checkin_walk_in", 500, time.Hour, userIDKey, http.HandlerFunc(s.checkIns.walkIn))))
|
||||
mux.Handle("GET /events/{id}/check-ins",
|
||||
authed(http.HandlerFunc(s.checkIns.list)))
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user