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:
- Routing: Resolving incoming hostnames to upstream sGTM origins.
- Configuration: Fetching runtime config from KV (
EDGE_CONFIG). - Module Enforcement: Executing logic for enabled modules (Cookie Keeper, Adblock Detection).
- Observability: Logging structured access logs to Cloudflare Analytics Engine (AE) and R2.
1.2 Execution Flow & Inputs
Entry Point: fetch(request, env, ctx)
| Input Source | Parameter | Purpose |
|---|---|---|
| Header | Host | Used to resolve the Infrastructure Host for ROUTING_MAP lookup. |
| Header | X-Public-Host | Identifies 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. |
| KV | ROUTING_MAP | Maps infraHost → containerId. |
| KV | EDGE_CONFIG | Maps containerId → Runtime Config (Rules, Modules). |
1.3 Key Functions
resolveInfraHost(request): Normalizes the host used for routing. strictly prefersHostheader overX-Forwarded-Hostto correctly handle Caddy/infrastructure layering.fetchRoutingConfigWithCache(env, key): LookupsROUTING_MAPwith a short 60scaches.defaultTTL.logAccess(env, payload): Asynchronous logging.- AE: Real-time analytics (indexed).
- R2: Raw log archival (batched JSON).
- Uses
ctx.waitUntilto 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:
- Resolves
loaderToken→containerIdviaLOADER_TOKEN_MAP. - Fetches
EDGE_CONFIGfor the container. - Injects configuration (endpoints, enabled modules) into the JS template.
- Resolves
POST /boot
- Purpose: Initializes the client session and handles Cookie Restoration.
- Logic:
- Receives browser signals (
FPIDif present). - If
cookie_restorationmodule is enabled:- Lookups up preserved cookie state in KV.
- Returns
restoreCookiesarray in JSON response.
- Receives browser signals (
- 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_sessionstable (via Edge Function proxy or direct RPC if implemented). - Used for "Recovery" statistics.
- Writes to Supabase
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:
EDGE_CONFIG: The master config JSON.LOADER_TOKEN_MAP: For the Loader Worker.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-routergets a KV MISS forEDGE_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_versionin Database vs. KV. - If mismatch found -> Triggers
sync-edge-configto repair.