Files
Kwaku Danso 59b8781659 feat: ship Tier 1 — auth, authz, rate limits, real notifications, CSV import, billing, backups/DR, privacy
Closes every block in docs/TIER1_PLAN.md from the Claude-scope side. The
homelab / cloud setup steps (SES verification, restore drill, lawyer-
drafted ToS) remain operator-owned but are unblocked.

Block A — Authentication
- Migration 0003: password_hash, email_verified, email_verification_tokens,
  password_reset_tokens, refresh_tokens (with replaced_by family chain).
- Bcrypt hasher, HS256 JWT signer, single-use refresh tokens with rotation
  + replay-detection (revokes the family on reuse).
- /auth/signup, /login, /refresh, /logout, /verify-email,
  /forgot-password, /reset-password — enumeration-safe.
- requireAuth middleware + GET /me.
- Frontend useAuth/useApi with auto-refresh-on-401, login/signup/verify/
  forgot/reset pages, route-guard middleware.

Block B — Authorisation
- EventRepo.GetForHost; Update/Delete scoped by host_id.
- All host routes behind requireAuth + ownership; cross-tenant returns
  404 (no enumeration). ?host_id removed.
- WS auth via short-lived single-use tickets (POST /auth/ws-ticket).
- Tests: TestCrossTenantIsolation — 9 probes.

Block C — Rate limiting
- Redis sliding-window via Lua (atomic ZADD+ZCARD+PEXPIRE).
- Per-route limits matching the plan (signup IP, login IP+email, RSVP/
  access by token, events/guests/tokens by user_id).
- 429 with Retry-After header and JSON body.
- Auth lockout: 5 failed logins → account locked, only password reset
  clears it.
- Frontend: useErrMessage normalises 429 + locked messaging.

Block D — Real notifications
- Migration 0004: provider_message_id, bounce_type, complained columns
  + unsubscribes (CITEXT) suppression table.
- Branded HTML + plaintext templates for verification, reset, invitation,
  confirmation, reminder. Per-page templates avoid html/template's
  contextual-escape collisions.
- Senders: SESv2, Twilio (SMS), SMTP (Mailpit-friendly), Resend HTTP.
- PickEmailSender priority Resend > SMTP > SES > Log — system boots
  cleanly in dev with Mailpit; production flips one env var.
- Webhook endpoints (Twilio status + SES SNS) — bounces add to suppression;
  signature verification stubbed pending creds.
- Auto-send: POST /tokens publishes invitation.send; notifier renders +
  delivers via the configured backend; suppression list honoured.
- Bulk + per-row invitation flow: POST /events/{id}/guests/invitations/bulk
  returns per-guest tokens so phone-only guests can be SMS'd manually.
- Unsubscribe: signed HMAC token (no TTL) + /unsubscribe/[token] page.
- WhatsApp Option A+: wa.me click-to-chat wizard with per-guest progress
  tracking, isLikelyE164 validation, edit-from-wizard.
- Token rotate (POST /tokens/rotate) invalidates the old URL — used by
  the regenerate-link flow.
- Mailpit added to docker-compose for dev inbox.

Block E — CSV import
- Streaming parser: tolerant header detection, UTF-8 BOM + UTF-16 LE/BE
  decoding, row-level validation, 5,000-row cap.
- Strict E.164 phone validation with helpful error message.
- POST /preview + /import + GET /template; preview UI on event page;
  atomic per-batch with dedup on existing emails.

Phone capture across UI
- PhoneInput component: country picker (~50 ISO codes) + national input +
  live E.164 preview + inline length validation.
- Used in Add Guest and Edit Guest modals. Smart paste-handling extracts
  country code from full E.164 strings.

Block F — Billing (Stripe)
- Migration 0005: subscriptions table (user_id → tier/status/period_end +
  Stripe customer/sub ids). Partial unique index keeps one granting sub
  per user.
- internal/billing: Tier + Limits model (Free 1/50, Pro 10/1000, Business
  ∞/5000), Stripe SDK wrapper with IgnoreAPIVersionMismatch for newer
  account API versions.
- /billing/checkout-session, /billing/portal, /billing/status,
  /webhooks/stripe (signature-verified, lifecycle events).
- Tier enforcement: 402 on POST /events, /guests, /import with
  {error, reason, tier, used, limit, upgrade_url} body.
- Frontend: useBilling composable, /dashboard/billing page (current plan,
  usage bars, tier cards), global UpgradeModal triggered by useApi's
  402 interceptor.
- Customer portal kept for self-service cancel/payment-method changes.

Block G — Backups & DR (application side)
- Every migration has a tested .down.sql.
- TestMigrationRoundtrip applies all ups → all downs → all ups against a
  fresh container; catches asymmetric down migrations.
- cmd/restore-verify: 28-check post-restore invariant tool (schema
  presence, no orphans across 10 FK relationships, email uniqueness,
  single-active subscription, row-count snapshot).
- docs/RUNBOOK_RESTORE.md: 9-step restore procedure with RTO/RPO
  targets, drill instructions, rollback path.

Block H — Privacy compliance (application side)
- Migration 0006: deleted_at + terms_accepted_at + privacy_policy_accepted_at
  on users. Partial index on email for live-only uniqueness.
- GET /me/data-export — synchronous JSON dump (user, events, guests,
  tokens, rsvps, access_logs, notifications).
- DELETE /me — soft-delete with PII scrub + refresh-token revocation;
  re-signup with same email works.
- POST /me/accept-terms — idempotent consent recording.
- Frontend /privacy + /terms placeholder pages with substantive (pending
  legal review) copy; footer links; signup terms checkbox; TermsGateModal
  for accounts created before the rollout; export + delete buttons on
  /dashboard/billing.

Tests
- All migrations verified up/down/up.
- Integration suite: TestE2EHappyPath, TestAuthFlow, TestCrossTenantIsolation,
  TestRateLimitSignup, TestLoginLockout, TestUnsubscribeFlow,
  TestSESBounceWebhook, TestTwilioStatusWebhook, TestCsvImportFlow,
  TestCsvImportAtomicRollback, TestBulkIssueInvitations, TestBulkIssueExplicitSubset,
  TestTokenIssuePublishesInvitation, TestTokenIssueWithoutGuestEmailSkipsInvitation,
  TestGuestUpdate, TestGuestDelete, TestTokenRotate, TestSMTPSenderAgainstMailpit,
  TestFreeTierEventLimit, TestFreeTierGuestLimit, TestBusinessTierBypassesLimits,
  TestDataExport, TestDeleteMe, TestAcceptTerms, TestMigrationRoundtrip.
  Full suite runs in ~120s against real Postgres + NATS + Redis + Mailpit.
- Unit suite green across internal/auth, internal/csvimport,
  internal/notification, internal/ratelimit, internal/domain.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-16 23:54:22 +01:00

218 lines
7.7 KiB
Vue

<script setup lang="ts">
interface ParsedRow {
Name: string
Email: string
Phone: string
PlusOnes: number
}
interface RowError {
row: number
reason: string
}
interface PreviewResponse {
rows: ParsedRow[]
errors?: RowError[]
total_count: number
}
interface ImportResponse {
added: number
skipped: number
skipped_emails?: string[]
errors?: RowError[]
total_count: number
}
const props = defineProps<{ eventId: string }>()
const emit = defineEmits<{ (e: 'imported'): void }>()
const config = useRuntimeConfig()
const apiBase = config.public.apiBase as string
type Stage = 'idle' | 'preview' | 'committing' | 'done'
const stage = ref<Stage>('idle')
const fileName = ref('')
const dragging = ref(false)
const error = ref<string | null>(null)
const preview = ref<PreviewResponse | null>(null)
const result = ref<ImportResponse | null>(null)
let pendingFile: File | null = null
function reset() {
stage.value = 'idle'
fileName.value = ''
preview.value = null
result.value = null
error.value = null
pendingFile = null
}
async function onFiles(files: FileList | File[] | null) {
if (!files || !files.length) return
const f = files[0]
if (f.size > 1024 * 1024) {
error.value = 'File is larger than 1MB.'
return
}
fileName.value = f.name
error.value = null
pendingFile = f
await runPreview()
}
async function runPreview() {
if (!pendingFile) return
try {
const fd = new FormData()
fd.append('file', pendingFile)
preview.value = await useApi<PreviewResponse>(
`/events/${props.eventId}/guests/import/preview`,
{ method: 'POST', body: fd },
)
stage.value = 'preview'
} catch (e: any) {
error.value = useErrMessage(e, 'Could not parse that CSV')
stage.value = 'idle'
pendingFile = null
}
}
async function commit() {
if (!pendingFile) return
stage.value = 'committing'
error.value = null
try {
const fd = new FormData()
fd.append('file', pendingFile)
result.value = await useApi<ImportResponse>(
`/events/${props.eventId}/guests/import`,
{ method: 'POST', body: fd },
)
stage.value = 'done'
emit('imported')
} catch (e: any) {
error.value = useErrMessage(e, 'Import failed')
stage.value = 'preview'
}
}
function onDrop(e: DragEvent) {
dragging.value = false
onFiles(e.dataTransfer?.files ?? null)
}
const templateUrl = computed(() => `${apiBase}/events/${props.eventId}/guests/import/template`)
async function downloadTemplate() {
// The endpoint requires a Bearer header, which a plain <a download> can't
// attach — fetch through useApi (which adds auth + handles refresh) then
// synthesise an anchor click on the resulting blob.
try {
const res: any = await useApi(`/events/${props.eventId}/guests/import/template`, {
method: 'GET',
})
// useApi auto-parses JSON; for CSV the response body is plain text.
const text = typeof res === 'string' ? res : JSON.stringify(res)
const blob = new Blob([text], { type: 'text/csv;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'guestguard-import-template.csv'
a.click()
URL.revokeObjectURL(url)
} catch (e: any) {
error.value = useErrMessage(e, 'Could not download template')
}
}
</script>
<template>
<!-- No outer .card chrome: this component is now embedded inside a
modal that supplies the surface. -->
<div>
<div class="mb-3 flex items-center justify-end">
<button class="text-xs text-zinc-400 hover:text-zinc-200" @click="downloadTemplate">
Download template
</button>
</div>
<!-- Stage 1: drag-drop zone -->
<div v-if="stage === 'idle'">
<label
class="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed bg-zinc-900/50 p-6 text-center transition"
:class="dragging ? 'border-brand-500 bg-brand-500/5' : 'border-zinc-700 hover:border-zinc-600'"
@dragover.prevent="dragging = true"
@dragleave.prevent="dragging = false"
@drop.prevent="onDrop"
>
<span class="mb-1 text-sm text-zinc-200">Drop a CSV here or click to choose</span>
<span class="text-xs text-zinc-500">Up to 5,000 rows · 1MB max</span>
<input type="file" accept=".csv,text/csv" class="hidden" @change="onFiles(($event.target as HTMLInputElement).files)" />
</label>
<p class="mt-2 text-xs text-zinc-500">
Required column: <code>name</code>. Optional: <code>email</code>, <code>phone</code>, <code>plus_ones</code>.
</p>
<p v-if="error" class="mt-3 text-sm text-red-400">{{ error }}</p>
</div>
<!-- Stage 2: preview -->
<div v-else-if="stage === 'preview' && preview">
<p class="mb-2 text-sm">
<span class="text-zinc-200">{{ fileName }}</span>
<span class="text-zinc-500"> {{ preview.rows.length }} valid row{{ preview.rows.length === 1 ? '' : 's' }}, {{ preview.errors?.length || 0 }} error{{ preview.errors?.length === 1 ? '' : 's' }}.</span>
</p>
<div v-if="preview.errors && preview.errors.length" class="mb-3 max-h-32 overflow-auto rounded border border-amber-900/40 bg-amber-950/20 p-2 text-xs text-amber-200">
<p class="mb-1 font-medium">Rows with problems (these will be skipped):</p>
<ul class="space-y-0.5">
<li v-for="(err, i) in preview.errors" :key="i">
row {{ err.row }} {{ err.reason }}
</li>
</ul>
</div>
<div v-if="preview.rows.length" class="mb-3 max-h-64 overflow-auto rounded border border-zinc-800">
<table class="w-full text-xs">
<thead class="bg-zinc-900 text-zinc-400">
<tr>
<th class="px-2 py-1.5 text-left">Name</th>
<th class="px-2 py-1.5 text-left">Email</th>
<th class="px-2 py-1.5 text-left">Phone</th>
<th class="px-2 py-1.5 text-right">+1s</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-800">
<tr v-for="(r, i) in preview.rows.slice(0, 100)" :key="i" class="text-zinc-200">
<td class="px-2 py-1">{{ r.Name }}</td>
<td class="px-2 py-1 text-zinc-400">{{ r.Email || '—' }}</td>
<td class="px-2 py-1 text-zinc-400">{{ r.Phone || '—' }}</td>
<td class="px-2 py-1 text-right tabular-nums">{{ r.PlusOnes }}</td>
</tr>
</tbody>
</table>
<p v-if="preview.rows.length > 100" class="px-2 py-1 text-xs text-zinc-500">
+ {{ preview.rows.length - 100 }} more not shown.
</p>
</div>
<div class="flex items-center gap-2">
<button class="btn-primary" :disabled="!preview.rows.length || stage === 'committing'" @click="commit">
Looks good import {{ preview.rows.length }} guest{{ preview.rows.length === 1 ? '' : 's' }}
</button>
<button class="btn-ghost" @click="reset">Cancel</button>
</div>
<p v-if="error" class="mt-3 text-sm text-red-400">{{ error }}</p>
</div>
<!-- Stage 3: committing -->
<div v-else-if="stage === 'committing'" class="text-sm text-zinc-400">Importing</div>
<!-- Stage 4: done -->
<div v-else-if="stage === 'done' && result" class="text-sm">
<p class="mb-1 font-medium text-brand-300">Imported {{ result.added }} guest{{ result.added === 1 ? '' : 's' }}.</p>
<p v-if="result.skipped" class="text-zinc-400">Skipped {{ result.skipped }} duplicate{{ result.skipped === 1 ? '' : 's' }} (already on this event).</p>
<p v-if="result.errors?.length" class="text-zinc-400">{{ result.errors.length }} row{{ result.errors.length === 1 ? '' : 's' }} had errors and were not imported.</p>
<button class="btn-ghost mt-3" @click="reset">Import another file</button>
</div>
</div>
</template>