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:
@@ -0,0 +1,111 @@
|
||||
// Package audit records meaningful host-facing writes to an
|
||||
// append-only table so the timeline (and any future compliance
|
||||
// export) has a single source of truth.
|
||||
//
|
||||
// Design notes:
|
||||
//
|
||||
// - All writes are best-effort + fire-and-forget. Audit logging must
|
||||
// never block or fail the real action — a host saving branding
|
||||
// should not 500 because the audit insert flaked. We log a warning
|
||||
// and move on.
|
||||
//
|
||||
// - Use the package-level `Record(...)` helper from handler code; it
|
||||
// decorates the call with the request-id middleware adds to the
|
||||
// context and dispatches to the wired Recorder. A nil Recorder
|
||||
// (zero-value Server in tests) is a no-op.
|
||||
//
|
||||
// - Action names follow `entity.verb` (e.g. `branding.update`,
|
||||
// `collaborator.invite`). Verbs are past-tense-implied — the row's
|
||||
// existence is the past tense.
|
||||
//
|
||||
// - Metadata is freeform JSON; keep it small and reviewable. Don't
|
||||
// put secrets in here — this table is queried by support.
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Recorder writes audit rows asynchronously. Construct one per process
|
||||
// and pass it into the handlers that need it (server.go bundles it on
|
||||
// the few handlers that audit).
|
||||
type Recorder struct {
|
||||
pool *pgxpool.Pool
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, logger *slog.Logger) *Recorder {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Recorder{pool: pool, logger: logger}
|
||||
}
|
||||
|
||||
// Params carries everything the audit_log INSERT needs. Most fields
|
||||
// are nullable so a record can describe an action that doesn't have a
|
||||
// specific target (e.g. "feature_flag.toggle") or doesn't sit under
|
||||
// an event (account-level writes).
|
||||
type Params struct {
|
||||
UserID *uuid.UUID
|
||||
EventID *uuid.UUID
|
||||
Action string // e.g. "branding.update"
|
||||
EntityType string // e.g. "event", "guest", "message"
|
||||
TargetID *uuid.UUID // the row that was acted on (nullable)
|
||||
Metadata map[string]any // free-form context — keep small
|
||||
RequestID string // correlation id from middleware (if any)
|
||||
}
|
||||
|
||||
// Record inserts one audit_log row. Returns immediately; the insert
|
||||
// runs on a detached goroutine with the package logger. Errors are
|
||||
// warned, never returned.
|
||||
func (r *Recorder) Record(ctx context.Context, p Params) {
|
||||
if r == nil || r.pool == nil {
|
||||
return
|
||||
}
|
||||
// Detach the context so cancelling the inbound HTTP request
|
||||
// doesn't cancel the audit write mid-flight.
|
||||
go r.write(context.WithoutCancel(ctx), p)
|
||||
}
|
||||
|
||||
func (r *Recorder) write(ctx context.Context, p Params) {
|
||||
var meta []byte
|
||||
if p.Metadata != nil {
|
||||
var err error
|
||||
meta, err = json.Marshal(p.Metadata)
|
||||
if err != nil {
|
||||
r.logger.Warn("audit: marshal metadata", "err", err, "action", p.Action)
|
||||
meta = []byte(`{}`)
|
||||
}
|
||||
} else {
|
||||
meta = []byte(`{}`)
|
||||
}
|
||||
|
||||
const q = `
|
||||
INSERT INTO audit_log
|
||||
(user_id, event_id, action, entity_type, target_id, metadata, request_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb, NULLIF($7, ''))
|
||||
`
|
||||
if _, err := r.pool.Exec(ctx, q,
|
||||
p.UserID, p.EventID, p.Action, nilIfEmpty(p.EntityType),
|
||||
p.TargetID, meta, p.RequestID,
|
||||
); err != nil {
|
||||
r.logger.Warn("audit: insert failed",
|
||||
"err", err,
|
||||
"action", p.Action,
|
||||
"event_id", p.EventID,
|
||||
"user_id", p.UserID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func nilIfEmpty(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
Reference in New Issue
Block a user