Skip to content

Lightweight Threat Model: Wedding Website Template ​

1. System Overview & Asset Inventory ​

This application is a reusable, self-hostable wedding website template built on Next.js (App Router), Prisma, PostgreSQL, and optional S3/R2 hybrid storage.

Primary Assets ​

  • Administrative Access: Admin session tokens, settings modification, content editing, database backups/restores, media uploads.
  • Guest Access & Privacy: Guest RSVP data, registry contributions, invitation codes, hidden event details.
  • System Credentials & Secrets: ADMIN_PASSWORD (scrypt hash), GUEST_PASSCODE, GUEST_SESSION_SECRET (distinct >= 32-character cookie signing secret in production), CRON_SECRET (scheduled job Bearer token), DATABASE_URL (PostgreSQL connection string), S3/R2 access keys, and provider API secrets.
  • Server Resources & Network Integrity: Server compute/memory, internal network access (SSRF target), public file storage.

2. Threat Actors & Attack Vectors ​

Threat ActorMotivationPrimary Attack Vectors
Unauthenticated Internet UserAutomated exploitation, vandalism, scrapingBrute-forcing guest passcode / admin password / guest invitation lookup, unauthorized /api/cron/* invocation, SSRF via registry link scraper, Host Header injection, file upload abuse.
Authenticated GuestAccessing unreleased features, unauthorized editsPrivilege escalation to admin endpoints (including /api/media and /api/media/[id]), tampering with registry items.
Malicious AttendeeForging session tokens to view or mutate other guests' private detailsAttempting HMAC signature forgery using public guest passcode. Stopped by dedicated server-side session secret (GUEST_SESSION_SECRET, enforced >= 32 chars and !== GUEST_PASSCODE).
Malicious Reverse Proxy / MITMSession hijacking, data interceptionMan-in-the-Middle attacks, insecure HTTP redirect handling.
Rogue Admin / Compromised KeyComplete data exfiltration or wipeoutBulk export/import abuse, version history wiping.

3. Trust Boundaries & Security Controls ​

+-----------------------------------------------------------------------------------+
| UNTRUSTED INTERNET                                                                |
| (HTTP Requests, Guest Passcodes, Invitation Lookups, Cron Triggers, Scraped URLs) |
+-----------------------------------------------------------------------------------+
                                       |
                                       v
[Perimeter Control: Edge Middleware (`src/middleware.ts` — `isHostAllowed` & Probe `isHostSyntaxValid`)]
                                       |
                                       v
[Scheduled Cron Gate: Edge Middleware (`/api/cron/*` `Authorization: Bearer <CRON_SECRET>`)]
                                       |
                                       v
[Cross-Origin Mutation Gate: Edge Middleware (`validateMutatingRequestOrigin` — `Sec-Fetch-Site` & `Origin`/`Referer`)]
                                       |
                                       v
[Authentication & Navigation Gate: Edge Middleware (`isGuestRequest` / `getSignedGuestInviteSession` / `isAdminRequest`)]
                                       |
                                       v
[SSR Page Revocation Gate: `RootLayout` (`enforceActiveGuestPageSession` -> Prisma `InvitationCode` check)]
                                       |
                                       v
[API Route Wrapper: `withApiMiddleware` (`src/utils/withApiMiddleware.ts`) & `createValidatedRoute`]
  |-- 0. Fetch Metadata & Canonical Origin Check (`validateMutatingRequestOrigin` -> HTTP 403 on cross-origin `POST`/`PUT`/`PATCH`/`DELETE`)
  |-- 1. Rate Limiter (5 failed attempts / 15m on login & `/api/guest/lookup`, 100/m general API)
  |-- 2. Authorization Check (`isAdminRequest` on protected API routes via `src/lib/routes.ts`)
  |-- 3. Invite Revocation Gate (`getGuestInviteSession` on non-excluded API routes; HTTP 401 + `maxAge: 0`)
  |-- 4. JSON Media-Type Gate (`assertJsonContentType` / `parseJsonRequestBody` -> HTTP 415 unless `Content-Type: application/json`)
                                       |
                                       v
[Egress Control: `safeFetch` & SSRF Guardrail (`isPrivateUrl` with DNS lookup all)]
                                       |
                                       v
+-----------------------------------------------------------------------------------+
| TRUSTED CORE SYSTEM                                                               |
| (PostgreSQL Database via Prisma, S3/R2 Storage, Audit Log Snapshots)              |
+-----------------------------------------------------------------------------------+

Active Security Controls ​

  1. Perimeter Host Validation & TRUST_PROXY Hop Gating: Incoming requests to all application routes, webhooks, scheduled cron endpoints, uploads, and non-read-only probe methods are filtered against ALLOWED_HOSTS (isHostAllowed and resolveRequestHost in src/utils/hostValidation.ts) in Edge Middleware (src/middleware.ts) before routing, preventing HTTP Host Header poisoning and cache poisoning (GET /api/og also emits Cache-Control: private and Vary: Cookie, Host, X-Forwarded-Host). Forwarded X-Forwarded-Host and X-Forwarded-Proto headers are ignored completely when TRUST_PROXY=false (the default) and evaluated via right-to-left hop counting matching src/utils/rateLimit.ts only when TRUST_PROXY is enabled. Public static exclusions in src/middleware.ts are restricted to explicit asset prefixes (/images/, /assets/, /fonts/, /_next/static/, /_next/image/, /favicon.ico, and /robots.txt) rather than filename extension suffixes. Stateless read-only (GET and HEAD) health probes (/api/live, /api/health, and /api/ready, which never read Host or construct URLs and return Cache-Control: no-store) enforce syntactic Host validation (isHostSyntaxValid) to block empty, whitespace, comma-separated, CRLF, and invalid-port headers while permitting orchestrator/internal probe hosts (e.g., healthcheck.railway.app, pod IPs, and loopback).

  2. Scheduled Cron Bearer Authentication: Edge Middleware (src/middleware.ts) intercepts /api/cron and /api/cron/* routes prior to cookie authentication and validates Authorization: Bearer <CRON_SECRET> using constant-time byte comparison (timingSafeEqualJS), rejecting unauthorized requests with 401 Unauthorized in production (allowing non-empty Bearer tokens without CRON_SECRET only in non-production environments).

  3. Password, __Host- Session Cookies, Tenant Claims, & Two-Tier Guest Session Revocation Security:

    • ADMIN_PASSWORD hashed using native scrypt with random salt.
    • Over HTTPS in production (resolveSessionCookieName in src/core/auth/tokenCookieHelpers.ts), session cookies are issued with __Host- prefixes (__Host-admin_auth, __Host-guest_auth, __Host-guest_invite_session, and __Host-guest_photo_session), Secure, HttpOnly, SameSite=Lax, Path=/, and no Domain attribute so sibling subdomains cannot shadow or overwrite host-bound cookies. Plain HTTP local development and loopback test servers use unprefixed admin_auth, guest_auth, guest_invite_session, and guest_photo_session names because browsers reject __Host- cookies without Secure.
    • admin_auth, guest_auth, guest_invite_session, and guest_photo_session (plus /photos?qr= tokens) are signed and verified via src/core/auth/tokenCookieHelpers.ts using HMAC SHA-256 and constant-time signature comparison (timingSafeEqualJS), stamping siteId and normalized subdomain claims on issuance. When MULTISITE_ENABLED=true, Edge Middleware rejects tokens with missing or mismatched subdomain claims and Node API / SSR helpers verify both siteId and subdomain against the active AppConfig tenant. Cookie readers (readRequestCookieCandidates and findVerifiedRequestCookie in src/core/auth/tokenCookieHelpers.ts, plus resolveSessionPrincipal in src/utils/rateLimit.ts) prefer __Host- cookies and evaluate every matching Cookie header entry in order until HMAC and tenant verification succeed, preventing cookie-tossing or path-shadowing DoS.
    • guest_auth (src/core/auth/guest.server.ts) and guest_invite_session (src/core/auth/guestInviteToken.ts) sign cookies with GUEST_SESSION_SECRET; both src/env.ts and the auth modules reject default values, secrets shorter than 32 characters in production, and secrets matching GUEST_PASSCODE.
    • GET /api/registry/validate-code is strictly read-only (returning invitation validity metadata without mutating BroadcastRecipient rows or emitting Set-Cookie headers), whereas same-origin POST /api/registry/validate-code (src/app/api/registry/validate-code/route.ts) mints the guest_invite_session (__Host-guest_invite_session) cookie and transitions SENT BroadcastRecipient rows to VIEWED.
    • Tier 1 (Edge Perimeter HMAC Verification & Signed Internal Headers): src/middleware.ts calls getSignedGuestInviteSession (src/core/auth/guestInviteToken.ts) to verify the guest_invite_session / __Host-guest_invite_session HMAC signature, expiration, and Edge tenant claims without Prisma or Node-only dependencies, gating /uploads/photos/* (and photos/ subpaths on /api/uploads/[...path]) directly with HTTP 401 Unauthorized when no valid admin_auth, guest_auth, signed guest_invite_session, or active guest_photo_session cookie is present, stripping incoming client x-guest-* headers, and HMAC-signing x-guest-gated-page and x-guest-callback-url (x-guest-header-signature) with GUEST_SESSION_SECRET, while exempting public crawlers, non-photo /uploads/* / /api/uploads/* routes (delegated to src/app/api/uploads/[...path]/route.ts), and auth lifecycle endpoints (GET /api/og, GET /api/admin/me, POST /api/admin/logout, /api/admin/login, /api/admin/setup, /api/guest/login, /api/guest/session, /api/guest/address/public, /api/registry/claim, /api/registry/validate-code, POST /api/registry/webhook/stripe, and health probes).
    • Upload Serving Session, Moderation, & Sandboxed Stream Isolation: src/app/api/uploads/[...path]/route.ts verifies admin_auth, guest_auth, database-active guest_invite_session, or (for /uploads/photos/*) active guest_photo_session cookies, permitting unauthenticated reads exclusively when the normalized path matches AppConfig.ogImageUrl or AppConfig.faviconUrl and returning HTTP 401 otherwise. Non-admin requests check PostgreSQL moderation and asset records—returning HTTP 404 for PENDING, REJECTED, hidden, or orphaned uploads—and POST /api/guest/photos/upload withholds url from PENDING responses. Every upload response emits an exclusive Content-Security-Policy: default-src 'none'; sandbox, Cross-Origin-Resource-Policy: same-origin, and X-Content-Type-Options: nosniff (with Content-Disposition: attachment forced on application/octet-stream fallback streams while continuing to serve existing .ico assets under sandbox), S3StorageProvider (getLocalUploadMimeType in src/utils/storage.ts) derives response MIME types strictly from file extensions rather than untrusted S3 ContentType metadata, and authorized local and S3 object streams emit Cache-Control: private, no-cache and Vary: Cookie (Cache-Control: private, no-store for PENDING admin moderation previews).
    • Tier 2 (Database InvitationCode Revocation): In the Node.js runtime, getGuestInviteSession and enforceActiveGuestPageSession (src/core/auth/guestInviteSession.ts) confirm the signed code still matches an active, non-sample (isSample: false) InvitationCode row in PostgreSQL. On guest-gated SSR pages (src/app/layout.tsx), enforceActiveGuestPageSession verifies x-guest-header-signature before skipping revocation checks or trusting x-guest-callback-url, querying InvitationCode whenever the HMAC stamp is missing or invalid and redirecting revoked or deleted invitation sessions to /guest/login with 303 See Other when no valid admin_auth or guest_auth cookie is present; on non-excluded API routes (isInviteRevocationExcludedApiPath in src/utils/withApiMiddleware.ts), withApiMiddleware rejects revoked guest_invite_session cookies with HTTP 401 and clears guest_invite_session / __Host-guest_invite_session (maxAge: 0) when neither admin_auth nor guest_auth is valid.
    • Constant-time SHA-256 digest comparison (crypto.timingSafeEqual) for guest passcode verification in /api/guest/login to eliminate timing side-channels.
  4. Cross-Origin Mutation Defense, Media-Type Enforcement, Strict Authorization, & SSR Admin Guards:

    • Fetch Metadata & Canonical Origin Validation: Edge Middleware (src/middleware.ts) and withApiMiddleware (src/utils/withApiMiddleware.ts) enforce validateMutatingRequestOrigin (src/utils/hostValidation.ts) on POST, PUT, PATCH, and DELETE requests, rejecting browser requests with HTTP 403 when Sec-Fetch-Site is present and equals neither same-origin nor none, or when Origin or Referer fails to match the validated canonical host (honoring TRUST_PROXY hop gating). POST /api/registry/webhook/stripe and /api/cron/* are explicitly exempted because they authenticate via Stripe webhook HMAC signatures (STRIPE_WEBHOOK_SECRET) or CRON_SECRET Bearer tokens.
    • JSON Media-Type Guard: createValidatedRoute (src/utils/createValidatedRoute.ts) and direct JSON POST, PUT, and PATCH route handlers enforce Content-Type: application/json (assertJsonContentType / parseJsonRequestBody in src/utils/contentType.ts) before parsing JSON bodies, returning HTTP 415 Unsupported Media Type for non-JSON requests such as text/plain form posts. Same-origin multipart/form-data uploads remain permitted on /api/guest/photos/upload (/api/photos/upload) and /api/admin/upload, and same-origin application/x-www-form-urlencoded form posts remain permitted on /api/media/export for streaming ZIP downloads.
    • Route Authorization, SSR Admin Guards, & Webhook Verification: All administrative API endpoints (including /api/admin/* except public auth lifecycle routes /api/admin/login, POST /api/admin/logout, GET /api/admin/me, and /api/admin/setup; /api/media, /api/media/[id], /api/media/export; and write/scrape /api/registry/* routes configured in src/lib/routes.ts) are gated in withApiMiddleware and Edge Middleware requiring valid signed admin session tokens (isAdminRequest). Personalized guest mutation routes (/api/guest/address and /api/rsvp) additionally require a database-verified guest_invite_session token (getGuestInviteSession), while /api/registry/webhook/stripe bypasses the Edge cookie gate exclusively on POST requests and verifies stripe-signature payloads via stripe.webhooks.constructEvent (STRIPE_WEBHOOK_SECRET). Both Edge Middleware (src/middleware.ts) and SSR entrypoints (AdminDashboardLayout, AdminSetupPage, AddItemPage, and EditItemPage via enforceAdminPageSession) perform 303 See Other redirects to /admin/login for unauthenticated callers while keeping STATIC_EXPORT builds inert.
  5. Rate Limiting & Bot Honeypot Defenses: IP- and session-based rate limiting executed inside withApiMiddleware (src/utils/withApiMiddleware.ts), stamping verified TCP socket addresses at the HTTP server boundary while gating forwarded IP headers behind TRUST_PROXY (false by default), isolating verified admin_auth, canonical household guest_invite_session, and per-login guest_auth session buckets alongside an aggregate client-IP ceiling on general API routes (resolveSessionPrincipal in src/utils/rateLimit.ts), serializing concurrent login attempts per client IP while scoping POST /api/guest/recover to an isolated guest-recover:<ip> mutex (acquireAuthIpLock in src/utils/rateLimit.ts) so sign-in recovery requests never stall interactive logins on shared Wi-Fi, binding failed authentication, lookup, and recovery lockouts strictly by client IP (HTTP 401, 403, and 404 up to 5 failed attempts per 15 minutes on /api/admin/login, POST /api/admin/setup, /api/guest/login, /api/guest/lookup, and /api/registry/validate-code, plus 5 submissions per 15 minutes with honeypot and 10-minute identifier/household cooldowns on POST /api/guest/recover) synchronized across instances via HMAC-SHA256 hashed keys in PostgreSQL (AuthLockout) with bounded local memory fail-open fallback alongside an IP-bound 100-requests-per-minute burst cap, enforcing an IP rate limit of 10 requests per 15 minutes (public_address_collect) plus honeypot field checks (website, honeypot, hp_field, confirm_email) on unauthenticated POST /api/guest/address/public (src/app/api/guest/address/public/route.ts), exempting /api/health and /api/live, and normalizing dynamic API paths under the standard throttle (100 requests per minute).

  6. SSRF Protections & Bounded Outbound Stream Guards:

    • Canonical Binary CIDR Validation: validateAndResolveHost, isPrivateIP, and isPrivateUrl (src/utils/ssrf.ts) canonicalize IPv4 literals (parseIPv4ToBigInt, including shorthand, octal, hex, trailing-dot, and integer host notations) into unsigned 32-bit BigInt values and IPv6 literals (parseIPv6ToBigInt, including expanded 0:0:0:0:0:0:0:1, mixed-case, and IPv4-embedded notations) into unsigned 128-bit BigInt values before evaluating bitwise CIDR masks across direct IP literals and dns.promises.lookup(..., { all: true }) records. Blocked ranges cover unspecified (0.0.0.0/8, ::/128), loopback (127.0.0.0/8, ::1/128), RFC 1918 private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), IPv6 Unique Local (fc00::/7), link-local and cloud metadata (169.254.0.0/16, fe80::/10), CGNAT (100.64.0.0/10), benchmarking (198.18.0.0/15, 2001:2::/48), documentation (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32), multicast/reserved (224.0.0.0/4, 240.0.0.0/4, ff00::/8), NAT64 (64:ff9b::/96, 64:ff9b:1::/48), and IPv4-transitional IPv6 prefixes (::/96 IPv4-compatible, ::ffff:0:0/96 IPv4-mapped, 2002::/16 6to4, 2001::/32 Teredo).
    • HTTP & SMTP Socket Pinning: Outbound HTTP fetches in safeFetch (createPinnedDispatcher in src/utils/safeFetch.ts) re-validate up to 5 manual redirect hops and pin each undici dispatcher lookup to the validated IP address. Outbound node:net and node:tls SMTP connections in MultiChannelMessagingProvider (src/features/broadcast/providers/index.ts and src/features/broadcast/providers/smtpSocket.ts) validate smtpHost via validateAndResolveHost and pin both family and socket lookup across sendEmail and testConnection (alongside mandatory STARTTLS and rejectUnauthorized: true X.509 verification) to prevent DNS rebinding and non-canonical IPv6 bypasses.
    • Module-Gated Scraping & Bounded Stream Readers: Both POST /api/registry/scrape (src/features/registry/api/scrape.ts) and POST /api/registry/scrape/batch (src/features/registry/api/batch-scrape.ts) enforce isFeatureEnabled('registry', config.modules) (returning HTTP 404 when registry is disabled), and scrapeProductUrl reads HTML via readBoundedResponseText (src/utils/boundedStream.ts) to keep timeoutMs and externalSignal active through full body transfer while enforcing a strict 1 MiB ceiling (MAX_SCRAPE_HTML_BYTES) before node-html-parser DOM parsing. Bulk media archive exports (GET and POST /api/media/export in src/app/api/media/export/route.ts) wrap remote HTTP/S3 transfers in per-request timeouts (REMOTE_EXPORT_TIMEOUT_MS = 15,000 ms) and demand-driven bounded streams (createBoundedBodyReadable, openBoundedRemoteResponse, and openBoundedReadableStream capped at MAX_REMOTE_EXPORT_BYTES = 25 MiB in src/utils/boundedStream.ts) piped directly into archiver without buffering full files in memory.
  7. File Upload Sanitization, .ico Transcoding, & Path Containment: Uploaded images pass through sanitizeImage (src/utils/imageProcessor.ts) and worker-isolated processImageWorkerBuffer (src/utils/imageProcessorWorker.ts), stripping EXIF/GPS metadata and re-encoding JPEG, PNG, and WebP rasters via Sharp, transcoding HEIC/HEIF frames into sanitized JPEG files, parsing .ico directory headers (parseIcoDirectoryEntries in src/utils/imageProcessorWorker.ts) to re-encode the largest icon frame into PNG (image/png, .png), and failing closed with ApiError (400) (src/utils/ApiError.ts) on unsupported or malformed formats rather than returning raw payloads. Local asset reads, image writes, and media archive exports validate filesystem paths through src/utils/pathContainment.ts (resolveContainedExistingPath, resolveContainedWritePath, PathContainmentError) to enforce lexical path.relative bounds, canonical fs.promises.realpath containment, and fs.lstat symlink-escape rejection.

  8. Log Redaction, Broadcast Safeguards, & DTO Secret Masking: Logger automatically redacts sensitive key patterns (password, passcode, secret, cookie, authorization, token) prior to console emission, while toPublicAppConfig and toAdminAppConfig (src/lib/config.ts) and sanitizeAppConfigForBackup (src/lib/backupPersistence.ts) strip raw email/SMS provider secrets from PostgreSQL AppConfig payloads. Broadcast dispatchers strip CR, LF, and angle-bracket characters from email subjects, HTML-escape template variables in HTML email bodies, exclude address-collection leads unless explicitly targeted, exclude isSample: true rows in live server execution, and restrict network-free simulation mode strictly to emailProvider = "none" and smsProvider = "none"—whereas default emailProvider = "smtp" (sendSmtpEmail in src/features/broadcast/providers/index.ts) attempts live node:net / node:tls SMTP delivery when smtpHost is configured and fails closed ({ success: false }) when smtpHost is empty (see Guest Broadcasts & Messaging).

  9. Defense in Depth, Per-Request CSP Nonces, & Least-Privilege Container Runtime: Static security headers (X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Strict-Transport-Security, and Permissions-Policy: camera=(), microphone=(), geolocation=()) are emitted by next.config.ts in dynamic server builds (!isStaticExport), while Edge Middleware (src/middleware.ts) generates a cryptographic per-request nonce (CSP_NONCE_HEADER, generateCspNonce, and buildContentSecurityPolicy in src/lib/csp.ts) on non-upload routes (RootLayout in src/app/layout.tsx reads x-nonce via headers() when !isStaticExport and stamps nonce onto the pre-paint theme <script>), replacing production 'unsafe-inline' and 'unsafe-eval' in script-src with 'nonce-<base64>', 'wasm-unsafe-eval', and blob: workers (permitting 'unsafe-eval' only when NODE_ENV === 'development'), enforcing object-src 'none', base-uri 'self', form-action 'self', and frame-ancestors 'self', scoping connect-src to 'self', https://api.stripe.com, https://js.stripe.com, https://hooks.stripe.com, https://*.basemaps.cartocdn.com, and any configured S3_PUBLIC_URL origin (src/env.ts), and skipping /uploads/* and /api/uploads/* so upload streams exclusively emit Content-Security-Policy: default-src 'none'; sandbox. Production /api/ready responses mask internal database error details, and OCI/Compose containers enforce root:root immutable /app code ownership, stripped setuid/setgid bits, read_only: true root filesystems (tmpfs for /tmp and /app/.next/cache), cap_drop: [ALL], and no-new-privileges:true.


4. Residual Risk Assessment & Operational Guidance ​

  • General In-Memory Rate Limiting: While failed authentication lockouts synchronize across instances via PostgreSQL (AuthLockout), high-frequency general API browsing quotas (100 requests per minute) remain stored in bounded per-instance memory. For volumetric DDoS protection across scaled deployments, deployers should pair application limits with edge/ingress rate limiting (e.g., Cloudflare, Nginx, or AWS WAF).
  • Secret Rotation: Deployers must set custom GUEST_PASSCODE, GUEST_SESSION_SECRET, and ADMIN_PASSWORD values in environment variables upon first deployment and rotate them if compromised.

Released under the AGPL-3.0 License.