Introducing a new way to review your PRs.

Read the announcement

calicastle / cali.so

Personal website for Cali Castle

View on GitHub

21 documents · Updated Sep 21, 2026

docs / runtime-security-and-delivery

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 groupPurposeDefault policy
Public AMA mutationsLimit booking, hold, and alternate-time request traffic10 requests per 60 seconds
Admin mutationsLimit owner changes30 requests per 60 seconds
Media upload chunksLimit repeated upload traffic40 requests per 60 seconds
Media alt-text generationLimit calls to the generation providerRead 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:

EnvironmentMain roleDatabase and rate-limit behavior
Local developmentFast isolated work on a developer machineLocal database settings and in-memory rate limiting
PreviewA branch-specific review surfaceA Neon branch with database-backed rate limiting
StagingShared pre-release verificationA staging Neon branch with the same branch deployment model
ProductionThe canonical public siteA 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:

  1. A feature branch deploys a Preview target and receives a branch-specific Neon database branch.
  2. The dev branch deploys Staging and uses the shared staging branch.
  3. The main branch 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 403 without a body or session cookie.
  • Unauthenticated admin and provider requests return 401 without 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

TriggerConsequenceGuard
A mutation omits Origin or uses a non-canonical originThe request is rejected before state changeExact origin and fetch-metadata checks return 403
A rate-limit store is unavailableThe protected request does not bypass the limitThe guard returns 503 with Retry-After
Production has incomplete Redis-compatible credentialsRuntime environment validation failsProduction requires one complete credential pair
A provider has only one credential from its pairThe provider is treated as misconfiguredPair validation rejects the environment
An admin route is added without its Clerk route matchThe route can miss the authentication boundaryproxy.ts owns the admin page and API matchers
An external origin is used without a CSP exceptionThe browser blocks the required resource or formRoute-specific CSP policies are tested by header and hosted checks
A private resume route loses its route-specific headersBrowsers or crawlers can cache, index, or refer private contentNext attaches no-store, noindex, and referrer rules to the page and API paths
Production migration checks or migration failVercel production deployment does not proceedThe production workflow gates deployment on both steps
The built app omits dynamic content or OG assetsHosted routes fail or render incomplete outputNext output tracing includes the runtime content and fonts
Analytics tracking throws during bookingBooking must continue without measurementtrackFunnelEvent catches tracking errors

Key files

FileWhy to read it
proxy.tsShows the route-level split between public handling and Clerk-protected admin handling.
next.config.tsDefines global headers, private route headers, CSP exceptions, output tracing, image paths, redirects, and rewrites.
lib/…/headers.tsExplains the public, admin, OAuth, and link-media browser policies.
lib/…/request-policy.tsDefines the same-origin mutation contract and safe denial responses.
lib/…/http.tsConnects public mutation checks to pseudonymous rate limiting.
lib/…/server.tsShows how runtime environment choice selects memory, database, or Redis-backed limiting.
lib/…/server-env-schema.tsDefines environment validation, feature availability, URL boundaries, and backend selection.
db/…/0010_rate_limit_windows.sqlShows the durable state used for shared preview rate limiting.
.github/…/action.ymlShows the non-production branch, migration, runtime-role, and Vercel delivery sequence.
.github/…/deploy-production.ymlShows the production migration gate and controlled Vercel deployment.
vercel.jsonDefines the disabled Git auto-deploy setting and recurring internal jobs.
lib/analytics.tsDefines the identifier-free AMA funnel measurement contract.
scripts/verify-production-security-boundary.mjsShows the observable security and privacy checks for the built or hosted site.
.github/…/security.ymlShows the full automated release gate that includes production verification.