Skip to content

feat(sw): telemetry executor with claim-every-tick batch cycle - #101

Open
a-d-j-i wants to merge 6 commits into
feat/manifest-telemetry-configfrom
feat/sw-telemetry-executor
Open

a-d-j-i wants to merge 6 commits into
feat/manifest-telemetry-configfrom
feat/sw-telemetry-executor

Conversation

@a-d-j-i

@a-d-j-i a-d-j-i commented Oct 30, 2026

Copy link
Copy Markdown
Collaborator

Security-processor becomes a facade over verdict ingestion + a telemetry executor; both coordinate through a shared task-manager instance. Outside modules (main, lifecycle, message-broker) talk only to the processor.

Executor cycle (telemetry-executor.js):

  • onEvent() is the single entry point; single-flight via cyclePromise.
  • Every TICK_MS (500) the cycle calls claimUnclaimed to absorb any new events into a batch; the batch's .priority field (set when any claimed row is a violation) is the ship signal.
  • Ship fires immediately on priority OR when any waiting batch has aged past CEILING_MS (3000). Age uses batch.createdAt which persists in IDB, so SW killed mid-cycle recovers naturally on next wake.
  • eventFired + continue guards an exit/ship race: an onEvent arriving during the claim/decide window forces another reclaim before the loop can idle-exit.
  • Whole cycle runs inside taskManager.run so keepalive is held through tick waits + the POST.
  • Endpoint + appVersion resolved from manifestService.resolveManifest() per cycle — manifest rotation flips URLs without SW restart.
  • Envelope carries { appVersion, installationTime, origin, userAgent, sentAt, events }.
  • POST failure bumps attemptNumber + registers SYNC_TAG_REPORT_EVENTS so Chromium retries via Background Sync.

@a-d-j-i
a-d-j-i added this pull request to stack #95 October 30, 2026 18:07
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from a5988b5 to 9f2efbc Compare October 31, 2026 12:34
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch 2 times, most recently from 31b87f2 to 21e8950 Compare November 2, 2026 18:51
emiliorizzo
emiliorizzo previously approved these changes Nov 3, 2026
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from 21e8950 to 98d1415 Compare November 3, 2026 14:45
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch 2 times, most recently from c5ef30e to 01ef1f6 Compare November 3, 2026 15:07
@emiliorizzo
emiliorizzo self-requested a review November 3, 2026 20:07

@emiliorizzo emiliorizzo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my AI agent says:

Telemetry Event Payload

What the service worker sends to telemetry.eventsEndpoint, why the current payload sends too much,
and the options for limiting it. Written against feat/sw-telemetry-executor (commit
21e8950e688f9bac372433a7f4c7ac3e7dd795b9, "telemetry executor with claim-every-tick batch cycle").
Fixing this needs a few product decisions first, so they are listed below with a recommended answer
for each.

Summary

Telemetry events are built by copying the whole stored verification row. Nothing chooses which
fields go out, so every field the service worker keeps locally is POSTed to the endpoint: full
request URLs with query strings, per-tab client IDs, and internal row IDs. MATCH verdicts are sent
too, not just violations. Combined with a stable per-install timestamp and the user agent, the
endpoint gets a timeline of what each user loaded and can link it across sessions. The endpoint is
set by the integrator in the manifest.

How the payload is built today

  1. Verdict creation: sw/fetch-handler.js, applyIntegrityPolicy. Every checked request
    becomes a verdict with url: request.url (full URL, query string included) and httpStatus. The
    verifier also sets clientId and destination.
  2. Ingestion: sw/security-processor.js, flushPending. Stores every status except SKIPPED,
    MATCH included.
  3. Row storage: sw/storage/verification-results-store.js, add(). Stores one row with id
    (UUID), appVersion, timestamp, status, fileKey, reason, expectedHashes, actualHash,
    url, destination, httpStatus, clientId, batchId: ''. That's fine for a row that only
    lives in the browser.
  4. Batch claim: sw/storage/telemetry-batches-store.js, claimUnclaimed. Builds each event as
    { ...verdict, key, occurrenceCount: 1 }. This is where the leak happens: the spread copies
    every row field into the event.
  5. Send: sw/telemetry/telemetry-executor.js, sendEvents. Wraps the events in an envelope
    with installationTime, origin and userAgent, and POSTs it.

Sent batches stay in the telemetryBatches store for 7 days (SENT_RETENTION_MS), so the same data
also lives on in the browser after it's sent.

Example request body

{
    "appVersion": "1.4.2",
    "installationTime": 1762180128734,
    "origin": "https://app.example",
    "userAgent": "Mozilla/5.0 (Macintosh; …) Chrome/141…",
    "sentAt": "2026-11-03T15:02:11.000Z",
    "events": [
        {
            "id": "6f1c…",
            "appVersion": "1.4.2",
            "timestamp": 1762182131002,
            "status": "MATCH",
            "fileKey": "/",
            "url": "https://app.example/?ref=alice&code=8f3k2…&address=bc1q…",
            "destination": "document",
            "httpStatus": 200,
            "clientId": "c0ffee-…",
            "batchId": "",
            "expectedHashes": ["sha256-…"],
            "actualHash": "sha256-…",
            "key": "a1b2c3d4e5f60718",
            "occurrenceCount": 3
        }
    ]
}

Problems

1. Full URLs leak secrets and personal data

url is the raw request.url. Navigations and API calls often put sensitive values in the query
string: OAuth code/state, magic-link and password-reset tokens, referral IDs, wallet addresses,
search terms. All of them reach the endpoint unchanged. Paths can also carry user data (for example
/u/alice), and that shows up in fileKey for files that aren't in the manifest.

2. Every request is reported, not just violations

MATCH verdicts are stored and claimed like violations. Batches go out at least every 3 seconds
(CEILING_MS), and deduplication only works within one batch. Over time the endpoint gets a
timestamped list of every page and asset each user loaded, far more than security monitoring needs.

3. The endpoint can identify and follow users

  • installationTime is a millisecond timestamp written once per install and never changed
    (settings-store.js), so in practice it's a permanent device ID.
  • With userAgent and origin, it can link one install's events across sessions.
  • clientId adds per-tab detail inside a session.

4. The event shape isn't defined

Because events are built with a spread, any field added to the verification row later, for any
reason, gets sent automatically. Nothing in review or tests would catch it. The store that existed
before this branch listed its fields explicitly.

5. Some fields are wrong or misleading

  • batchId is always "". The event is copied before the row is marked with the batch ID.
  • id and timestamp only describe the first occurrence of a deduplicated event.
  • url is whichever URL arrived first. The dedup key (eventKey) ignores it, so other URLs
    folded into the same event are lost.

Decisions needed

D1. Which fields an event contains

Field Needed for Recommendation
status, reason what happened keep
assetType, fileKey which asset keep (see D2 for paths not in the manifest)
expectedHashes, actualHash diagnosing tampering keep
destination, httpStatus context for the verdict keep (small, no personal data)
occurrenceCount volume keep
timestamp time of occurrence replace with firstSeen / lastSeen for the whole dedup group
url full location drop or reduce (D2)
clientId tab correlation drop
id, batchId, key local bookkeeping drop
appVersion (per event) already in the envelope drop, unless one batch can mix versions

D2. URLs and paths

Option Keeps Risk
A. Drop url nothing beyond fileKey loses the host for cross-origin assets, if fileKey doesn't already include it
B. Send origin + pathname host and path, no query or fragment personal data in paths still leaks
C. B, but only for violations detail where it matters MATCH events need neither
D. Keep as is everything all of problem 1

Recommendation: C. Also check whether fileKey already includes the host for cross-origin
assets. If it does, A is enough. For NOT_IN_MANIFEST, fileKey is a path the manifest doesn't
know, so it can't be assumed to be free of user data. Consider cutting it down for that reason, for
example to the extension or the first path segment.

D3. What happens to MATCH verdicts

Option Endpoint learns Notes
A. Violations only that something went wrong simplest; no baseline to compare against
B. Violations plus a MATCH counter per appVersion error rate in context small and aggregate; recommended
C. Everything, deduplicated by fileKey (current) each user's asset timeline problem 2

Recommendation: B. A non-violation like REWRITE or CSP_PROTECTED could be sent as an event or
just counted. Decide based on whether anyone acts on them individually.

D4. Device identifier

Sampling (installationTime % logsFilter === 0 in manifest-service.js) runs on the client, so
the raw installationTime never has to leave the browser for sampling to work.

Option Notes
A. Send raw installationTime (current) permanent device ID
B. Send it rounded down (for example to the day) rough cohort ("installed this week"); sample on the raw value, because a day in milliseconds is divisible by 1000 and rounding before sampling would select every install when logsFilter is 1000
C. Random ID that rotates (for example daily) links one session's batches without following users long term
D. Nothing most private; lose cross-batch linking

Recommendation: B, plus C only if per-session grouping is actually needed. Also consider
trimming userAgent to browser family and major version.

Proposed implementation

  1. One function that builds the event (toTelemetryEvent(row) in telemetry-batches-store.js,
    or its own module) that copies the allowed fields by name. No spreads. Adding a field then means
    changing this function, which is visible in review.
  2. Build events at claim time, not send time. claimUnclaimed stores the reduced event in the
    batch, so the 7-day batch retention keeps only data that was approved to send. Track
    firstSeen/lastSeen while merging duplicates, both in claimUnclaimed and in mergeBatches
    (executor).
  3. Reduce the URL with a helper (new URL(u).origin + new URL(u).pathname), only for violations
    if D2-C is chosen.
  4. MATCH counter (D3-B). Count MATCH rows per appVersion during the claim and send them as one
    summary (for example envelope.matchCount), not as events.
  5. Envelope. Use the rounded installationTime (D4) and keep sampling on the raw value in
    manifest-service.js.
  6. Leave the stored row as is. The UI drawer (/sw-api/status) reads it locally and still needs
    url/clientId. The limit applies to what leaves the browser.
  7. Delete sent data sooner. Once events are reduced, the 7-day SENT_RETENTION_MS matters less.
    Consider deleting the events of a sent batch right away and keeping only its ID and sentAt.

Tests

Add to sw/__tests__/telemetry-executor.test.js (same setup as the existing tests):

  • Allowed fields only: store a violation with a URL that has a query string and a clientId,
    run one cycle, and check that every POSTed event's keys exactly match the allowed list.
  • No query string: check that no string in the request body contains the query-string value.
  • No MATCH events (D3-A/B): store MATCH verdicts only, and check that no events are sent (and,
    for B, that the counter is correct).
  • Envelope identifier (D4): check that installationTime in the body is rounded down, and
    that sampling still selects installs based on the raw value.
  • Unit test for toTelemetryEvent: a row with an extra unknown field produces an event
    without it, so a future row field can't leak.

Related

The same branch has three other telemetry bugs, each covered by a test that currently fails:
claimUnclaimed awaiting crypto.subtle inside a transaction
(b9fcc8c85fb01ed8709612a6fee9509f5ce8d0ea), Background Sync events reporting success without
sending (a56afaa7c7c5231273daa68824531cbad03ba530), and batches over the 64 KiB keepalive limit
(da3f2d28b73895fbdb420c8527d4f9a376524efb).

@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch 3 times, most recently from 9153eac to 0fcc2fb Compare November 5, 2026 18:08
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from 0fcc2fb to a2909a2 Compare November 16, 2026 15:10
@netlify

netlify Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for dappfence-templates ready!

Name Link
🔨 Latest commit a0af86b
🔍 Latest deploy log https://app.netlify.com/projects/dappfence-templates/deploys/6b130213b1923ea4c4abdf1f
😎 Deploy Preview https://deploy-preview-101--dappfence-templates.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch 2 times, most recently from 029f86a to 826b347 Compare November 16, 2026 17:06
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from 826b347 to 995d372 Compare November 17, 2026 13:28
@a-d-j-i
a-d-j-i removed this pull request from stack #95 November 17, 2026 14:27
@a-d-j-i
a-d-j-i added this pull request to stack #112 November 17, 2026 14:27
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from 95be5b1 to 790f265 Compare November 27, 2026 16:35
Security-processor becomes a facade over verdict ingestion + a telemetry
executor; both coordinate through a shared task-manager instance. Outside
modules (main, lifecycle, message-broker) talk only to the processor.

Executor cycle (telemetry-executor.js):
- `onEvent()` is the single entry point; single-flight via cyclePromise.
- Every TICK_MS (500) the cycle calls claimUnclaimed to absorb any new
  events into a batch; the batch's `.priority` field (set when any claimed
  row is a violation) is the ship signal.
- Ship fires immediately on priority OR when any waiting batch has aged
  past CEILING_MS (3000). Age uses `batch.createdAt` which persists in
  IDB, so SW killed mid-cycle recovers naturally on next wake.
- `eventFired` + `continue` guards an exit/ship race: an onEvent arriving
  during the claim/decide window forces another reclaim before the loop
  can idle-exit.
- Whole cycle runs inside `taskManager.run` so keepalive is held through
  tick waits + the POST.
- Endpoint + appVersion resolved from manifestService.resolveManifest()
  per cycle — manifest rotation flips URLs without SW restart.
- Envelope carries { appVersion, installationTime, origin, userAgent,
  sentAt, events }.
- POST failure bumps attemptNumber + registers SYNC_TAG_REPORT_EVENTS so
  Chromium retries via Background Sync.
… sizing

Keepalive POSTs reject bodies over 64 KiB. The executor had no size cap,
so a realistic violation batch blew the quota and the browser rejected
the fetch — forever stuck in retry.

makeDedupMap owns a Map and its serialized byte footprint together.
addOne and addMany are atomic (snapshot/rollback on overflow); sizing is
exact and dedup-aware. Caps apply at claim time (selectVerdicts) and
merge time (mergeBatches, all-or-nothing per batch).

The byte cap is derived from the real envelope shape (real origin,
userAgent, installationTime; exact-length placeholders for appVersion
and sentAt). renderEnvelope + renderEvent are the single source of truth
for wire shape; renderEvent's explicit allow-list prevents future verdict
fields from shipping silently.

VERIFICATION_STATUS_BY_NAME on core/constants.js replaces two local Sets
that could silently diverge.

Regression test: a full 50-event batch whose JSON exceeds 64 KiB splits
across cycles and delivers all events.
- Split scheduleSend/scheduleSyncSend so reportOnSync forces its own
  bypass attempt and never drops Chromium's retry ticket when
  coalescing with a regular cycle (including a gated no-op).
- taskManager.attach takes an isSync flag so short-budget events
  (~30s) don't downgrade a sync carrier's ~5min waitUntil budget.
- sendLoop re-arms the sync tag at every attempt (idempotent per tag,
  noop on browsers without Background Sync); removed the duplicate
  register from the sendEvents failure path.
…el streams

Replaces the single telemetry-executor with a shared stream-driver and
two per-channel streams (event-stream, log-stream). The scheduler loop
moves into stream-driver so driving multiple channels in one tick is
iterating a streams array; each channel owns its buffer, retry state,
and hasPending check.

services.js builds `streams = [events, logs]` and passes the array to
securityProcessor; downstream code reaches telemetry through the stream
interface instead of a single executor.

Also:
- log-stream consumes the new buffered logger sink; logger.js prefixes
  every line with HH:MM:SS.mmm so per-channel traces are readable
- SYNC_TAG_REPORT_EVENTS -> SYNC_TAG_TELEMETRY (covers both channels)
- tests renamed: telemetry-executor.test.js -> event-stream.test.js
…isy logs + manifest logsMinLevel knob

Logger:
- adds .debug, withDebugLog(fn) scope, setMinLevel(level) floor
- client realm skips the SW-only buffer (nothing drains it there)
- buffer entries become {ts, level, args, count} so the server can see
  per-line timing; dedup collapses consecutive identical entries
- new src/core/__tests__/logger.test.js covers both realms

Silence:
- noisy .log -> .debug across appsw-hooks, lifecycle-handlers (sync
  handler reshuffled to log only non-telemetry tags), manifest-service,
  manifest-loader (cache hit), security-processor (report* paths),
  task-manager, telemetry-batches-store
- message-broker strips generic "Received message:" / REPORT_EVENTS /
  PAGE_LOADED noise
- stream-driver wraps its own sendLoop work in withDebugLog so the
  log-stream's flush doesn't feed the buffer it's draining

Knob:
- services.js reads config.logsMinLevel from the URL params
- manifest-loader normalizes manifest.logsMinLevel and applies the
  floor on each manifest load

Also: event-stream wire envelope drops the url field (redundant with
fileKey + hostname).
Introduces `logger.local.{debug,log,warn,error}` that writes to the
console the same way the normal levels do, but skips the SW's log
buffer. Used in two kinds of sites:

1. Noisy SW plumbing (per-request fetch tracing, lifecycle breadcrumbs,
   manifest resolve logs) where we want devtools visibility but not
   telemetry volume.
2. Critically, the telemetry POST pipeline's own failure logs
   (`telemetry POST failed`, `POST threw`, `send tick threw`,
   stream-driver backoff state, batches-store diagnostics). Before
   `.local` these went through the buffered logger, so a failing
   endpoint would append its own failure message to the next batch
   attempt — a direct amplification path.
@a-d-j-i
a-d-j-i force-pushed the feat/sw-telemetry-executor branch from 790f265 to a0af86b Compare December 4, 2026 18:10

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants