Skip to content

digital-identity-platform-docs


digital-identity-platform-docs / workers/sgtm-router/worker

workers/sgtm-router/worker

Cloudflare Worker that fronts SGTM container origins and related platform endpoints by resolving an incoming host to an upstream base URL, proxying requests, and emitting access logs to Analytics Engine and R2 for analytics/observability.

Role in the platform

  • Acts as the public edge router for customer domains.
  • Resolves {hostname} to an upstream SGTM origin (and optionally a preview UI origin) via KV.
  • Supports an obfuscated proxy path (/k/...) where the true upstream target is encoded in a query param.
  • Emits structured access logs to Cloudflare Analytics Engine + R2 when configured.

Request flow

  • Handle CORS preflight requests early (OPTIONS -> 204).
  • Fetch runtime configuration (from KV EDGE_CONFIG); fails open if unavailable.
  • Enforce allowed_hosts validation to prevent cross-domain abuse.
  • Lookup routing config by request hostname (ROUTING_MAP).
    • Note: ROUTING_MAP is managed by infra-provisioner.
  • Determine whether the request targets SGTM preview UI paths vs the primary origin.
  • Decode /k/... proxy requests (when not preview UI) to rewrite the upstream target.
  • Proxy the request upstream and mirror the response status/body/headers downstream.
  • Emit a fire-and-forget access log (ctx.waitUntil(logAccess(...))).

Security & trust boundaries

  • Routing config is resolved from KV:
    • ROUTING_MAP (Host -> Container ID)
    • EDGE_CONFIG (Container ID -> Runtime features)
    • COOKIE_STORE (FPID -> Cookie State)
  • External Allowlist: /ccm/collect is explicitly allowed to Google endpoints.
  • Open Proxy Protection: /k/ endpoints require a valid container token or signature (future).

CORS & browser behavior

  • Preflight requests (OPTIONS) return 204 with CORS headers from makeCorsHeaders.
  • CORS headers reflect the request Origin and allow credentials.
  • Access-Control-Allow-Headers mirrors Access-Control-Request-Headers when present.

Error handling

  • Returns explicit 4xx/5xx responses for missing KV entry, invalid routing config, and bad KV writes.
  • Logging failures are caught and logged to console.error without failing the proxied request.
  • Billing Paused: Returns 402 JSON if subscription_status === "paused".

Observability

  • Adds x-qaxal-router-target to upstream request headers and downstream response headers.
  • Creates a structured log payload including request/response metadata and correlation IDs.
  • Uses ctx.waitUntil(...) for non-blocking logging to AE + R2.

Runtime Configuration & Module Gating Architecture

This worker participates in the v2 runtime configuration system:

  1. Source of Truth: Fetches config from KV (EDGE_CONFIG) keyed by container ID.
  2. Caching: Config is cached in caches.default with a generic TTL (default 60s).
  3. Fail-Open: If config is unavailable, the worker proceeds without breaking traffic.

Feature Gating

  • Allowed Hosts Enforcement: Request validation against allowed_hosts list.
    • X-Public-Host must match an allowed entry.
    • If not allowed -> 404 Unknown project host.
    • Applies to /gtm.js, /k/*, and measurement endpoints.

To ensure accurate billing despite client-side race conditions (tracking requests vs restoration requests), this worker implements a Virtual Billing Event strategy:

  1. Automatic Restoration: Every request attempts to restore/extend cookies if configured.
  2. Duplicate Logging: If restoration occurs on a non-dedicated endpoint (e.g. a tracking pixel), the worker emits TWO events:
    • The original tracking event (e.g. view_item) with restoration metrics attached for debugging.
    • A dedicated Virtual Billing Event (event_type="cookie_restored" or "cookie_extended").

Billing Schema (Analytics Engine)

  • blob3 ("Event Type"): cookie_restored (if count > 0) or cookie_extended (if only extension).
  • double7: cookies_restored_count
  • double8: cookies_extended_count
  • blob12: restored_types (comma-separated list, e.g. "ga4,facebook")

Classes

Variables

Released under proprietary license.