Skip to content

Active Logical Components

1. Cloudflare Router Worker (sgtm-router)

File: workers/sgtm-router/worker.js

1.1 Responsibility

The Router Worker is the entry point for all tracking traffic. It is responsible for:

  1. Routing: Resolving incoming hostnames to upstream sGTM origins.
  2. Configuration: Fetching runtime config from KV (EDGE_CONFIG).
  3. Module Enforcement: Executing logic for enabled modules (Cookie Keeper, Adblock Detection).
  4. Observability: Logging structured access logs to Cloudflare Analytics Engine (AE) and R2.

1.2 Execution Flow & Inputs

Entry Point: fetch(request, env, ctx)

Input SourceParameterPurpose
HeaderHostUsed to resolve the Infrastructure Host for ROUTING_MAP lookup.
HeaderX-Public-HostIdentifies the client-facing domain for SITE_REGISTRY config resolution (Multi-domain support).
Path/k/?p=...Obfuscated proxy path. Decoded via decodeKParam to determine actual upstream target.
KVROUTING_MAPMaps infraHostcontainerId.
KVEDGE_CONFIGMaps containerId → Runtime Config (Rules, Modules).

1.3 Key Functions

  • resolveInfraHost(request): Normalizes the host used for routing. strictly prefers Host header over X-Forwarded-Host to correctly handle Caddy/infrastructure layering.
  • fetchRoutingConfigWithCache(env, key): Lookups ROUTING_MAP with a short 60s caches.default TTL.
  • logAccess(env, payload): Asynchronous logging.
    • AE: Real-time analytics (indexed).
    • R2: Raw log archival (batched JSON).
    • Uses ctx.waitUntil to ensure logging never blocks the response.

1.4 Outputs

  • Proxied Response: Returns the response from the sGTM origin.
  • Headers:
    • Set-Cookie: Modified/extended by Cookie Keeper logic.
    • Access-Control-Allow-Origin: Reflected from request Origin (if safe).

2. Cloudflare Loader Worker (sst-loader)

File: workers/sst-loader/worker.mjs

2.1 Responsibility

The Loader Worker serves the client-side JavaScript snippet and handles session bootstrapping. It is distinct from the Router in that it generates content rather than just proxying it.

2.2 Endpoints

GET /l/:loaderToken.js

  • Purpose: Returns the dynamic JS loader.
  • Logic:
    1. Resolves loaderTokencontainerId via LOADER_TOKEN_MAP.
    2. Fetches EDGE_CONFIG for the container.
    3. Injects configuration (endpoints, enabled modules) into the JS template.

POST /boot

  • Purpose: Initializes the client session and handles Cookie Restoration.
  • Logic:
    • Receives browser signals (FPID if present).
    • If cookie_restoration module is enabled:
      • Lookups up preserved cookie state in KV.
      • Returns restoreCookies array in JSON response.
  • Outcome: The client-side script writes these cookies immediately.

POST /mark-session-detection

  • Purpose: Receives client-side detection results (Adblock/ITP detected).
  • Logic:
    • Writes to Supabase loader_sessions table (via Edge Function proxy or direct RPC if implemented).
    • Used for "Recovery" statistics.

3. Edge Functions (Supabase)

3.1 sync-edge-config (active)

File: supabase/functions/sync-edge-config/index.ts

Responsibility: The Authoritative Writer.

  • Triggered by any configuration change in the Control Plane (UI/API).
  • Systematically writes to all required KV namespaces to ensure consistency:
    1. EDGE_CONFIG: The master config JSON.
    2. LOADER_TOKEN_MAP: For the Loader Worker.
    3. SITE_REGISTRY: For Multi-domain routing checks.

Invariants:

  • Idempotent: Can be run safely multiple times.
  • Fail-Closed: Returns error if any KV write fails.

3.2 container-config (active)

File: supabase/functions/container-config/index.ts

Responsibility: The Fallback Origin.

  • When sgtm-router gets a KV MISS for EDGE_CONFIG, it fetches from this endpoint.
  • Security: Protected by X-Edge-Auth (Shared Secret). Not public.
  • Output: Returns the exact JSON structure required by EDGE_CONFIG.

3.3 nightly-kv-drift-check (active)

File: supabase/functions/nightly-kv-drift-check/index.ts (implied from logs/logic)

Responsibility: Self-Healing.

  • Runs daily to compare config_version in Database vs. KV.
  • If mismatch found -> Triggers sync-edge-config to repair.

4. Dependencies Diagram

Released under proprietary license.