Runtime security and delivery
Runtime security and delivery protect requests and private data while moving the site through local development, preview, staging, and production. The system combines browser request checks, route security headers, environment-aware service choices, isolated database access, scheduled work, and automated release checks. For the wider platform model, see Platform foundations.
Request security
Request security separates public reading from state-changing work. Public pages can render for visitors, while browser mutations must come from the canonical site and from a same-origin browser context; admin pages and admin APIs also pass through Clerk authentication. proxy.ts and lib/…/request-policy.ts define these outer boundaries.
Browser mutation boundary
The browser mutation boundary rejects a request when its Origin is missing or does not exactly match the canonical site origin. It also requires Sec-Fetch-Site: same-origin, so a cross-site form or script cannot use public booking mutations or admin mutations as a side channel. Denials return 403 with no body and no-store headers. lib/…/http.ts applies this check before public booking work and adds a pseudonymous per-client rate limit.
References: lib/…/request-policy.ts• L14-39 lib/…/http.ts• L69-98
Authentication boundary
The authentication boundary protects /admin pages and /api/admin/* routes with Clerk. A signed-out document request redirects to the sign-in service, while unauthenticated API access stops with 401; the boundary does not expose session data or set a new session cookie. proxy.ts selects the routes that use Clerk, and the hosted browser boundary verifies the signed-out behavior in tests/…/admin-boundary.spec.ts.
References: proxy.ts• L26-43 proxy.ts• L61-82 tests/…/admin-boundary.spec.ts• L21-47
Public capability boundary
The public AMA routes do not require an account. Their safety comes from the same-origin mutation check, input validation, rate limiting, and provider checks. Provider-backed capabilities fail closed when their credentials are not configured rather than starting in a partial state. lib/…/server-env-schema.ts turns provider credential pairs into feature availability.
References: lib/…/http.ts• L128-149 lib/…/server-env-schema.ts• L58-79 scripts/verify-production-security-boundary.mjs• L288-381
Content security policy
The Content-Security-Policy (CSP) is a browser rule set that limits where a page may load scripts, styles, images, connections, and form submissions. A public policy applies to every route, while narrower policies extend only the admin and Google OAuth cases that need extra origins. next.config.ts attaches these policies by route.
Public policy
The public policy keeps scripts and styles tied to the site and self-hosted resources. It blocks framing, objects, script attributes, external fonts, and browser features such as camera, microphone, payment, and geolocation. It permits the configured media CDN only as an image origin and allows the Open Graph image host for image delivery. Development alone adds unsafe-eval; production does not. lib/…/headers.ts builds the policy and its companion transport and content headers.
References: lib/…/headers.ts• L31-67 lib/…/headers.ts• L106-127 lib/…/headers.test.ts• L10-35
Admin policy
The admin policy allows the Clerk instance origin for Clerk scripts and session refresh connections. The instance origin comes from the publishable key at build time, which keeps the policy static and lets the admin shell remain cacheable. The AMA settings page adds only https://accounts.google.com to form-action for its Google OAuth form. Link media receives a document policy of default-src 'none'; sandbox because it must never run as a page in the site origin. lib/…/headers.ts and next.config.ts define these route-specific exceptions.
The site uses a static policy instead of a per-request nonce policy. This preserves prerendering and instant navigation for the admin shell. When an external service or inline behavior changes, the policy must be narrowed to the exact route and origin that needs it.
References: lib/…/headers.ts• L61-104 next.config.ts• L82-141 lib/next-config.test.ts• L32-62
Private document headers
Private resume pages and their API responses are marked as non-cacheable and non-indexable. They also use same-origin or no-referrer policies so private content does not move to another site through a browser referrer. Admin API responses use no-referrer for the same reason, while the global policy remains useful for public navigation. next.config.ts adds these route-specific headers without changing the public CSP.
References: next.config.ts• L82-115
Rate limiting
Rate limiting controls repeated requests within a time window before they reach sensitive work. The same rate-limit contract can use a shared production store, a preview database, or local memory so each environment has a suitable boundary. lib/…/server.ts selects the backend from the parsed server environment.
Protected request groups
The system uses separate scopes so one workload does not consume the allowance for another:
| Request group | Purpose | Default policy |
|---|---|---|
| Public AMA mutations | Limit booking, hold, and alternate-time request traffic | 10 requests per 60 seconds |
| Admin mutations | Limit owner changes | 30 requests per 60 seconds |
| Media upload chunks | Limit repeated upload traffic | 40 requests per 60 seconds |
| Media alt-text generation | Limit calls to the generation provider | Read from the media configuration |
Public client addresses are converted to HMAC-based keys before rate-limit storage. Raw addresses do not leave the request guard. A denied request returns 429 with Retry-After; if the selected limiter cannot work, the request fails closed with 503 rather than bypassing the limit. lib/…/http.ts and lib/…/server.ts connect the policies to AMA requests, while lib/…/server.ts applies the media limits.
References: lib/…/http.ts• L62-98 lib/…/server.ts• L10-27 lib/…/server.ts• L76-120
Rate-limit backends
Production uses Upstash Redis or its supported Vercel KV-compatible credentials. Preview uses its Neon database branch, and local development uses process memory. The database backend stores hashed keys and request times in a short-lived window table, which keeps preview behavior shared across instances. db/…/0010_rate_limit_windows.sql defines that shared state.
References: lib/…/server.ts• L13-32 lib/…/repository.ts• L14-69 db/…/0010_rate_limit_windows.sql• L1-10
Environment boundaries
Environment parsing is the contract between deployment settings and runtime behavior. It validates required runtime settings before services start. It then derives the canonical URL, browser mutation URL, feature flags, and rate-limit backend. lib/…/server-env-schema.ts is the source for these choices; lib/…/server-env.ts caches the parsed result for the process.
Environment roles
The deployment environments have different goals and different trust boundaries:
| Environment | Main role | Database and rate-limit behavior |
|---|---|---|
| Local development | Fast isolated work on a developer machine | Local database settings and in-memory rate limiting |
| Preview | A branch-specific review surface | A Neon branch with database-backed rate limiting |
| Staging | Shared pre-release verification | A staging Neon branch with the same branch deployment model |
| Production | The canonical public site | A production database and shared Redis-compatible rate limiting |
Provider features are enabled only when their credential pairs are complete. Production requires a complete Redis credential pair, while preview requires a trusted *.vercel.app deployment host. Outside preview, the canonical site URL must be present. These checks stop a deployment from silently using the wrong origin or from treating a half-configured provider as available.
References: lib/…/server-env-schema.ts• L58-79 lib/…/server-env-schema.ts• L173-285
Database privilege boundary
Non-production deployments create or reuse a Neon branch before migration and then obtain a separate CRUD-only runtime connection. The migration role can change schema; the runtime role serves the application. Production runs migrations through the protected migration secret before the Vercel deployment. This split limits the effect of a compromised application runtime and keeps schema change separate from request handling. .github/…/action.yml and .github/…/deploy-production.yml define the delivery order.
For the wider schema and migration contract, see Database and migrations.
References: .github/…/action.yml• L77-127 .github/…/deploy-production.yml• L38-67
Next and Vercel delivery
Next provides the application runtime and route rules, while Vercel provides the deployment target and environment-specific hosting. The delivery setup preserves dynamic content and runtime assets, keeps public URLs stable, and runs recurring background work through Vercel Cron. next.config.ts and vercel.json hold the main platform rules.
Next runtime contract
Next is configured for cache components and partial prefetching. Server output tracing explicitly packages repository content and runtime fonts for content routes and Open Graph routes because dynamic content reads cannot be inferred from route code alone when packaging serverless functions. Image delivery is limited to the site's content, image, and Next static paths. The checked-in legacy URL manifest supplies redirects and rewrites for the preserved public URL contract. next.config.ts also pins the project root for nested worktree development and enables subresource integrity for supported scripts.
These delivery rules keep dynamic content available after deployment while limiting image and browser resource access to known paths. The route headers described above are attached through the same Next configuration, so changes to a route can affect both delivery and security behavior.
References: next.config.ts• L28-80 next.config.ts• L82-149 lib/next-config.test.ts• L5-28
Vercel deployment lanes
Each lane ties a Git change to a matching hosted environment and database branch:
- A feature branch deploys a Preview target and receives a branch-specific Neon database branch.
- The
devbranch deploys Staging and uses the shared staging branch. - The
mainbranch runs the production migration checks and migration, then deploys the Production target.
Preview and staging run hosted Chromium checks after deployment. Production uses a non-canceling deployment group and records the Vercel deployment URL. Git-triggered Vercel deployments are disabled in vercel.json, so the workflows remain the controlled delivery path. .github/…/deploy-preview.yml, .github/…/deploy-staging.yml, and .github/…/deploy-production.yml define the lanes.
The following diagram shows how a change moves from a Git branch through its database boundary and hosted verification.
flowchart LR
feature[Feature branch] --> preview[Preview Neon branch]
preview --> previewDeploy[Vercel Preview]
previewDeploy --> previewCheck[Hosted browser check]
dev[dev branch] --> staging[Staging Neon branch]
staging --> stagingDeploy[Vercel Staging]
stagingDeploy --> stagingCheck[Hosted browser check]
main[main branch] --> migration[Production migration gate]
migration --> production[ Vercel Production]
References: .github/…/deploy-preview.yml• L17-62 .github/…/deploy-staging.yml• L16-49 .github/…/deploy-production.yml• L15-74 vercel.json• L1-6
Scheduled work
Vercel Cron invokes internal endpoints for media reconciliation every hour and AMA durable-operation work every 30 minutes. These jobs support recovery and cleanup outside a visitor request, so their route security and runtime database access must remain aligned with the production environment. vercel.json declares the schedules, and the AMA booking service starts newly queued work during the current invocation when possible.
References: vercel.json• L6-15 lib/…/server.ts• L240-244
Analytics
Analytics measures the public AMA booking funnel without carrying booking identity into the analytics system. The event set records high-level progress from time choice through payment and alternate-time requests; it sends event names only. lib/analytics.ts defines the privacy contract, and the booking flow and confirmation UI emit the events.
The Vercel Analytics client loads in the public site and the separate Calibaby document. It does not load in the admin boundary, which keeps owner pages out of public product measurement. Analytics errors are swallowed so a tracking outage cannot stop a booking. app/…/site-document.tsx, app/…/calibaby-document.tsx, and tests/…/admin-boundary.spec.ts cover this split.
References: lib/analytics.ts• L3-20 app/…/site-document.tsx• L46-71 app/…/site-document.tsx• L108-114 app/…/calibaby-document.tsx• L57-63 tests/…/admin-boundary.spec.ts• L5-18
Production verification
Production verification starts a built Next server locally when no external base URL is supplied, or checks an already hosted deployment when one is supplied. It probes public pages, admin redirects, admin APIs, provider authentication, and public AMA mutations. scripts/production-server.mjs manages the server lifecycle, and scripts/verify-production-security-boundary.mjs asserts the observable boundary.
The verifier checks both positive and negative behavior:
- Public pages return successfully with the required security headers.
- Admin document requests stop at Clerk and preserve the requested same-origin return path.
- Cross-site mutations return
403without a body or session cookie. - Unauthenticated admin and provider requests return
401without private details. - Invalid, unavailable, or synthetic public AMA requests stop at validation,
404,503, or signature checks rather than reaching unsafe work. - Responses do not reveal credentials, private markers, stack details, database URLs, or server paths.
The Security workflow runs type checks, unit and integration tests, migration checks, dependency audit, build, browser release tests, URL checks, discovery checks, and the production security boundary check. The final boundary check therefore tests the built delivery surface in addition to isolated code behavior. .github/…/security.yml and package.json define this release gate.
References: scripts/production-server.mjs• L36-90 scripts/verify-production-security-boundary.mjs• L107-392 .github/…/security.yml• L61-111 package.json• L20-50
Change checklist
When these files or sections are changed, remember to consider these:
- A new browser mutation route must use the same-origin guard and a dedicated rate-limit scope before it can change state.
- A new external script, connection, image, font, or form target must be added to the narrowest matching CSP policy and checked against the public policy.
- A new private document or API route must preserve its no-store, indexing, and referrer rules rather than inheriting only the global headers.
- A new provider credential must update pair validation, feature derivation, and the production boundary's safe unavailable outcome.
- A new environment lane must define its canonical URL, database branch or connection role, rate-limit backend, and hosted verification target together.
- A change to migration order or runtime database credentials must preserve the migration-role and CRUD-only runtime-role split.
- A new scheduled endpoint must be added to the Vercel Cron contract and reviewed as an internal production entry point.
- A new analytics event must carry no booking identity and must remain non-blocking when the analytics service fails.
- Changes to Clerk or Next versions must re-check the static admin shell, CSP origins, sign-in redirect behavior, output tracing, and the production boundary assertions.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A mutation omits Origin or uses a non-canonical origin | The request is rejected before state change | Exact origin and fetch-metadata checks return 403 |
| A rate-limit store is unavailable | The protected request does not bypass the limit | The guard returns 503 with Retry-After |
| Production has incomplete Redis-compatible credentials | Runtime environment validation fails | Production requires one complete credential pair |
| A provider has only one credential from its pair | The provider is treated as misconfigured | Pair validation rejects the environment |
| An admin route is added without its Clerk route match | The route can miss the authentication boundary | proxy.ts owns the admin page and API matchers |
| An external origin is used without a CSP exception | The browser blocks the required resource or form | Route-specific CSP policies are tested by header and hosted checks |
| A private resume route loses its route-specific headers | Browsers or crawlers can cache, index, or refer private content | Next attaches no-store, noindex, and referrer rules to the page and API paths |
| Production migration checks or migration fail | Vercel production deployment does not proceed | The production workflow gates deployment on both steps |
| The built app omits dynamic content or OG assets | Hosted routes fail or render incomplete output | Next output tracing includes the runtime content and fonts |
| Analytics tracking throws during booking | Booking must continue without measurement | trackFunnelEvent catches tracking errors |
Key files
| File | Why to read it |
|---|---|
| proxy.ts | Shows the route-level split between public handling and Clerk-protected admin handling. |
| next.config.ts | Defines global headers, private route headers, CSP exceptions, output tracing, image paths, redirects, and rewrites. |
| lib/…/headers.ts | Explains the public, admin, OAuth, and link-media browser policies. |
| lib/…/request-policy.ts | Defines the same-origin mutation contract and safe denial responses. |
| lib/…/http.ts | Connects public mutation checks to pseudonymous rate limiting. |
| lib/…/server.ts | Shows how runtime environment choice selects memory, database, or Redis-backed limiting. |
| lib/…/server-env-schema.ts | Defines environment validation, feature availability, URL boundaries, and backend selection. |
| db/…/0010_rate_limit_windows.sql | Shows the durable state used for shared preview rate limiting. |
| .github/…/action.yml | Shows the non-production branch, migration, runtime-role, and Vercel delivery sequence. |
| .github/…/deploy-production.yml | Shows the production migration gate and controlled Vercel deployment. |
| vercel.json | Defines the disabled Git auto-deploy setting and recurring internal jobs. |
| lib/analytics.ts | Defines the identifier-free AMA funnel measurement contract. |
| scripts/verify-production-security-boundary.mjs | Shows the observable security and privacy checks for the built or hosted site. |
| .github/…/security.yml | Shows the full automated release gate that includes production verification. |