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 Actor | Motivation | Primary Attack Vectors |
|---|---|---|
| Unauthenticated Internet User | Automated exploitation, vandalism, scraping | Brute-forcing guest passcode / admin password / guest invitation lookup, unauthorized /api/cron/* invocation, SSRF via registry link scraper, Host Header injection, file upload abuse. |
| Authenticated Guest | Accessing unreleased features, unauthorized edits | Privilege escalation to admin endpoints (including /api/media and /api/media/[id]), tampering with registry items. |
| Malicious Attendee | Forging session tokens to view or mutate other guests' private details | Attempting 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 / MITM | Session hijacking, data interception | Man-in-the-Middle attacks, insecure HTTP redirect handling. |
| Rogue Admin / Compromised Key | Complete data exfiltration or wipeout | Bulk 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
Perimeter Host Validation &
TRUST_PROXYHop Gating: Incoming requests to all application routes, webhooks, scheduled cron endpoints, uploads, and non-read-only probe methods are filtered againstALLOWED_HOSTS(isHostAllowedandresolveRequestHostinsrc/utils/hostValidation.ts) in Edge Middleware (src/middleware.ts) before routing, preventing HTTP Host Header poisoning and cache poisoning (GET /api/ogalso emitsCache-Control: privateandVary: Cookie, Host, X-Forwarded-Host). ForwardedX-Forwarded-HostandX-Forwarded-Protoheaders are ignored completely whenTRUST_PROXY=false(the default) and evaluated via right-to-left hop counting matchingsrc/utils/rateLimit.tsonly whenTRUST_PROXYis enabled. Public static exclusions insrc/middleware.tsare 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 (GETandHEAD) health probes (/api/live,/api/health, and/api/ready, which never readHostor construct URLs and returnCache-Control: no-store) enforce syntacticHostvalidation (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).Scheduled Cron Bearer Authentication: Edge Middleware (
src/middleware.ts) intercepts/api/cronand/api/cron/*routes prior to cookie authentication and validatesAuthorization: Bearer <CRON_SECRET>using constant-time byte comparison (timingSafeEqualJS), rejecting unauthorized requests with401 Unauthorizedin production (allowing non-empty Bearer tokens withoutCRON_SECRETonly in non-production environments).Password,
__Host-Session Cookies, Tenant Claims, & Two-Tier Guest Session Revocation Security:ADMIN_PASSWORDhashed using nativescryptwith random salt.- Over HTTPS in production (
resolveSessionCookieNameinsrc/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 noDomainattribute so sibling subdomains cannot shadow or overwrite host-bound cookies. Plain HTTP local development and loopback test servers use unprefixedadmin_auth,guest_auth,guest_invite_session, andguest_photo_sessionnames because browsers reject__Host-cookies withoutSecure. admin_auth,guest_auth,guest_invite_session, andguest_photo_session(plus/photos?qr=tokens) are signed and verified viasrc/core/auth/tokenCookieHelpers.tsusing HMAC SHA-256 and constant-time signature comparison (timingSafeEqualJS), stampingsiteIdand normalizedsubdomainclaims on issuance. WhenMULTISITE_ENABLED=true, Edge Middleware rejects tokens with missing or mismatchedsubdomainclaims and Node API / SSR helpers verify bothsiteIdandsubdomainagainst the activeAppConfigtenant. Cookie readers (readRequestCookieCandidatesandfindVerifiedRequestCookieinsrc/core/auth/tokenCookieHelpers.ts, plusresolveSessionPrincipalinsrc/utils/rateLimit.ts) prefer__Host-cookies and evaluate every matchingCookieheader entry in order until HMAC and tenant verification succeed, preventing cookie-tossing or path-shadowing DoS.guest_auth(src/core/auth/guest.server.ts) andguest_invite_session(src/core/auth/guestInviteToken.ts) sign cookies withGUEST_SESSION_SECRET; bothsrc/env.tsand the auth modules reject default values, secrets shorter than 32 characters in production, and secrets matchingGUEST_PASSCODE.GET /api/registry/validate-codeis strictly read-only (returning invitation validity metadata without mutatingBroadcastRecipientrows or emittingSet-Cookieheaders), whereas same-originPOST /api/registry/validate-code(src/app/api/registry/validate-code/route.ts) mints theguest_invite_session(__Host-guest_invite_session) cookie and transitionsSENTBroadcastRecipientrows toVIEWED.- Tier 1 (Edge Perimeter HMAC Verification & Signed Internal Headers):
src/middleware.tscallsgetSignedGuestInviteSession(src/core/auth/guestInviteToken.ts) to verify theguest_invite_session/__Host-guest_invite_sessionHMAC signature, expiration, and Edge tenant claims without Prisma or Node-only dependencies, gating/uploads/photos/*(andphotos/subpaths on/api/uploads/[...path]) directly with HTTP401 Unauthorizedwhen no validadmin_auth,guest_auth, signedguest_invite_session, or activeguest_photo_sessioncookie is present, stripping incoming clientx-guest-*headers, and HMAC-signingx-guest-gated-pageandx-guest-callback-url(x-guest-header-signature) withGUEST_SESSION_SECRET, while exempting public crawlers, non-photo/uploads/*//api/uploads/*routes (delegated tosrc/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.tsverifiesadmin_auth,guest_auth, database-activeguest_invite_session, or (for/uploads/photos/*) activeguest_photo_sessioncookies, permitting unauthenticated reads exclusively when the normalized path matchesAppConfig.ogImageUrlorAppConfig.faviconUrland returning HTTP401otherwise. Non-admin requests check PostgreSQL moderation and asset records—returning HTTP404forPENDING,REJECTED, hidden, or orphaned uploads—andPOST /api/guest/photos/uploadwithholdsurlfromPENDINGresponses. Every upload response emits an exclusiveContent-Security-Policy: default-src 'none'; sandbox,Cross-Origin-Resource-Policy: same-origin, andX-Content-Type-Options: nosniff(withContent-Disposition: attachmentforced onapplication/octet-streamfallback streams while continuing to serve existing.icoassets undersandbox),S3StorageProvider(getLocalUploadMimeTypeinsrc/utils/storage.ts) derives response MIME types strictly from file extensions rather than untrusted S3ContentTypemetadata, and authorized local and S3 object streams emitCache-Control: private, no-cacheandVary: Cookie(Cache-Control: private, no-storeforPENDINGadmin moderation previews). - Tier 2 (Database
InvitationCodeRevocation): In the Node.js runtime,getGuestInviteSessionandenforceActiveGuestPageSession(src/core/auth/guestInviteSession.ts) confirm the signed code still matches an active, non-sample (isSample: false)InvitationCoderow in PostgreSQL. On guest-gated SSR pages (src/app/layout.tsx),enforceActiveGuestPageSessionverifiesx-guest-header-signaturebefore skipping revocation checks or trustingx-guest-callback-url, queryingInvitationCodewhenever the HMAC stamp is missing or invalid and redirecting revoked or deleted invitation sessions to/guest/loginwith303 See Otherwhen no validadmin_authorguest_authcookie is present; on non-excluded API routes (isInviteRevocationExcludedApiPathinsrc/utils/withApiMiddleware.ts),withApiMiddlewarerejects revokedguest_invite_sessioncookies with HTTP401and clearsguest_invite_session/__Host-guest_invite_session(maxAge: 0) when neitheradmin_authnorguest_authis valid. - Constant-time SHA-256 digest comparison (
crypto.timingSafeEqual) for guest passcode verification in/api/guest/loginto eliminate timing side-channels.
Cross-Origin Mutation Defense, Media-Type Enforcement, Strict Authorization, & SSR Admin Guards:
- Fetch Metadata & Canonical Origin Validation: Edge Middleware (
src/middleware.ts) andwithApiMiddleware(src/utils/withApiMiddleware.ts) enforcevalidateMutatingRequestOrigin(src/utils/hostValidation.ts) onPOST,PUT,PATCH, andDELETErequests, rejecting browser requests with HTTP403whenSec-Fetch-Siteis present and equals neithersame-originnornone, or whenOriginorRefererfails to match the validated canonical host (honoringTRUST_PROXYhop gating).POST /api/registry/webhook/stripeand/api/cron/*are explicitly exempted because they authenticate via Stripe webhook HMAC signatures (STRIPE_WEBHOOK_SECRET) orCRON_SECRETBearer tokens. - JSON Media-Type Guard:
createValidatedRoute(src/utils/createValidatedRoute.ts) and direct JSONPOST,PUT, andPATCHroute handlers enforceContent-Type: application/json(assertJsonContentType/parseJsonRequestBodyinsrc/utils/contentType.ts) before parsing JSON bodies, returning HTTP415 Unsupported Media Typefor non-JSON requests such astext/plainform posts. Same-originmultipart/form-datauploads remain permitted on/api/guest/photos/upload(/api/photos/upload) and/api/admin/upload, and same-originapplication/x-www-form-urlencodedform posts remain permitted on/api/media/exportfor 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 insrc/lib/routes.ts) are gated inwithApiMiddlewareand Edge Middleware requiring valid signed admin session tokens (isAdminRequest). Personalized guest mutation routes (/api/guest/addressand/api/rsvp) additionally require a database-verifiedguest_invite_sessiontoken (getGuestInviteSession), while/api/registry/webhook/stripebypasses the Edge cookie gate exclusively onPOSTrequests and verifiesstripe-signaturepayloads viastripe.webhooks.constructEvent(STRIPE_WEBHOOK_SECRET). Both Edge Middleware (src/middleware.ts) and SSR entrypoints (AdminDashboardLayout,AdminSetupPage,AddItemPage, andEditItemPageviaenforceAdminPageSession) perform303 See Otherredirects to/admin/loginfor unauthenticated callers while keepingSTATIC_EXPORTbuilds inert.
- Fetch Metadata & Canonical Origin Validation: Edge Middleware (
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 behindTRUST_PROXY(falseby default), isolating verifiedadmin_auth, canonical householdguest_invite_session, and per-loginguest_authsession buckets alongside an aggregate client-IP ceiling on general API routes (resolveSessionPrincipalinsrc/utils/rateLimit.ts), serializing concurrent login attempts per client IP while scopingPOST /api/guest/recoverto an isolatedguest-recover:<ip>mutex (acquireAuthIpLockinsrc/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, and404up 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 onPOST /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 of10requests per15minutes (public_address_collect) plus honeypot field checks (website,honeypot,hp_field,confirm_email) on unauthenticatedPOST /api/guest/address/public(src/app/api/guest/address/public/route.ts), exempting/api/healthand/api/live, and normalizing dynamic API paths under the standard throttle (100 requests per minute).SSRF Protections & Bounded Outbound Stream Guards:
- Canonical Binary CIDR Validation:
validateAndResolveHost,isPrivateIP, andisPrivateUrl(src/utils/ssrf.ts) canonicalize IPv4 literals (parseIPv4ToBigInt, including shorthand, octal, hex, trailing-dot, and integer host notations) into unsigned 32-bitBigIntvalues and IPv6 literals (parseIPv6ToBigInt, including expanded0:0:0:0:0:0:0:1, mixed-case, and IPv4-embedded notations) into unsigned 128-bitBigIntvalues before evaluating bitwise CIDR masks across direct IP literals anddns.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 (::/96IPv4-compatible,::ffff:0:0/96IPv4-mapped,2002::/166to4,2001::/32Teredo). - HTTP & SMTP Socket Pinning: Outbound HTTP fetches in
safeFetch(createPinnedDispatcherin src/utils/safeFetch.ts) re-validate up to 5 manual redirect hops and pin eachundicidispatcherlookupto the validated IP address. Outboundnode:netandnode:tlsSMTP connections inMultiChannelMessagingProvider(src/features/broadcast/providers/index.ts and src/features/broadcast/providers/smtpSocket.ts) validatesmtpHostviavalidateAndResolveHostand pin bothfamilyand socketlookupacrosssendEmailandtestConnection(alongside mandatorySTARTTLSandrejectUnauthorized: trueX.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) andPOST /api/registry/scrape/batch(src/features/registry/api/batch-scrape.ts) enforceisFeatureEnabled('registry', config.modules)(returning HTTP404whenregistryis disabled), andscrapeProductUrlreads HTML viareadBoundedResponseText(src/utils/boundedStream.ts) to keeptimeoutMsandexternalSignalactive through full body transfer while enforcing a strict1 MiBceiling (MAX_SCRAPE_HTML_BYTES) beforenode-html-parserDOM parsing. Bulk media archive exports (GETandPOST /api/media/exportin 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, andopenBoundedReadableStreamcapped atMAX_REMOTE_EXPORT_BYTES=25 MiBin src/utils/boundedStream.ts) piped directly intoarchiverwithout buffering full files in memory.
- Canonical Binary CIDR Validation:
File Upload Sanitization,
.icoTranscoding, & Path Containment: Uploaded images pass throughsanitizeImage(src/utils/imageProcessor.ts) and worker-isolatedprocessImageWorkerBuffer(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.icodirectory headers (parseIcoDirectoryEntriesin src/utils/imageProcessorWorker.ts) to re-encode the largest icon frame into PNG (image/png,.png), and failing closed withApiError(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 lexicalpath.relativebounds, canonicalfs.promises.realpathcontainment, andfs.lstatsymlink-escape rejection.Log Redaction, Broadcast Safeguards, & DTO Secret Masking: Logger automatically redacts sensitive key patterns (
password,passcode,secret,cookie,authorization,token) prior to console emission, whiletoPublicAppConfigandtoAdminAppConfig(src/lib/config.ts) andsanitizeAppConfigForBackup(src/lib/backupPersistence.ts) strip raw email/SMS provider secrets from PostgreSQLAppConfigpayloads. Broadcast dispatchers strip CR, LF, and angle-bracket characters from email subjects, HTML-escape template variables in HTML email bodies, excludeaddress-collectionleads unless explicitly targeted, excludeisSample: truerows in live server execution, and restrict network-free simulation mode strictly toemailProvider = "none"andsmsProvider = "none"—whereas defaultemailProvider = "smtp"(sendSmtpEmailin src/features/broadcast/providers/index.ts) attempts livenode:net/node:tlsSMTP delivery whensmtpHostis configured and fails closed ({ success: false }) whensmtpHostis empty (see Guest Broadcasts & Messaging).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, andPermissions-Policy: camera=(), microphone=(), geolocation=()) are emitted bynext.config.tsin dynamic server builds (!isStaticExport), while Edge Middleware (src/middleware.ts) generates a cryptographic per-request nonce (CSP_NONCE_HEADER,generateCspNonce, andbuildContentSecurityPolicyin src/lib/csp.ts) on non-upload routes (RootLayoutin src/app/layout.tsx readsx-nonceviaheaders()when!isStaticExportand stampsnonceonto the pre-paint theme<script>), replacing production'unsafe-inline'and'unsafe-eval'inscript-srcwith'nonce-<base64>','wasm-unsafe-eval', andblob:workers (permitting'unsafe-eval'only whenNODE_ENV === 'development'), enforcingobject-src 'none',base-uri 'self',form-action 'self', andframe-ancestors 'self', scopingconnect-srcto'self',https://api.stripe.com,https://js.stripe.com,https://hooks.stripe.com,https://*.basemaps.cartocdn.com, and any configuredS3_PUBLIC_URLorigin (src/env.ts), and skipping/uploads/*and/api/uploads/*so upload streams exclusively emitContent-Security-Policy: default-src 'none'; sandbox. Production/api/readyresponses mask internal database error details, and OCI/Compose containers enforceroot:rootimmutable/appcode ownership, stripped setuid/setgid bits,read_only: trueroot filesystems (tmpfsfor/tmpand/app/.next/cache),cap_drop: [ALL], andno-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, andADMIN_PASSWORDvalues in environment variables upon first deployment and rotate them if compromised.