Repository navigation
Conversation
a5988b5 to
9f2efbc
Compare
31b87f2 to
21e8950
Compare
21e8950 to
98d1415
Compare
c5ef30e to
01ef1f6
Compare
emiliorizzo
left a comment
There was a problem hiding this comment.
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
- Verdict creation:
sw/fetch-handler.js,applyIntegrityPolicy. Every checked request
becomes a verdict withurl: request.url(full URL, query string included) andhttpStatus. The
verifier also setsclientIdanddestination. - Ingestion:
sw/security-processor.js,flushPending. Stores every status except SKIPPED,
MATCH included. - Row storage:
sw/storage/verification-results-store.js,add(). Stores one row withid
(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. - 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. - Send:
sw/telemetry/telemetry-executor.js,sendEvents. Wraps the events in an envelope
withinstallationTime,originanduserAgent, 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
installationTimeis a millisecond timestamp written once per install and never changed
(settings-store.js), so in practice it's a permanent device ID.- With
userAgentandorigin, it can link one install's events across sessions. clientIdadds 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
batchIdis always"". The event is copied before the row is marked with the batch ID.idandtimestamponly describe the first occurrence of a deduplicated event.urlis 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
- One function that builds the event (
toTelemetryEvent(row)intelemetry-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. - Build events at claim time, not send time.
claimUnclaimedstores the reduced event in the
batch, so the 7-day batch retention keeps only data that was approved to send. Track
firstSeen/lastSeenwhile merging duplicates, both inclaimUnclaimedand inmergeBatches
(executor). - Reduce the URL with a helper (
new URL(u).origin + new URL(u).pathname), only for violations
if D2-C is chosen. - MATCH counter (D3-B). Count MATCH rows per
appVersionduring the claim and send them as one
summary (for exampleenvelope.matchCount), not as events. - Envelope. Use the rounded
installationTime(D4) and keep sampling on the raw value in
manifest-service.js. - 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. - Delete sent data sooner. Once events are reduced, the 7-day
SENT_RETENTION_MSmatters less.
Consider deleting the events of a sent batch right away and keeping only its ID andsentAt.
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
installationTimein 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).
9153eac to
0fcc2fb
Compare
0fcc2fb to
a2909a2
Compare
✅ Deploy Preview for dappfence-templates ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
029f86a to
826b347
Compare
826b347 to
995d372
Compare
95be5b1 to
790f265
Compare
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.
790f265 to
a0af86b
Compare
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..priorityfield (set when any claimed row is a violation) is the ship signal.batch.createdAtwhich persists in IDB, so SW killed mid-cycle recovers naturally on next wake.eventFired+continueguards an exit/ship race: an onEvent arriving during the claim/decide window forces another reclaim before the loop can idle-exit.taskManager.runso keepalive is held through tick waits + the POST.