Skip to content

feat(rules): report uncompressed text assets over size threshold #9 - #179

Merged
nc9 merged 7 commits into
mainfrom
feat/9-uncompressed-assets
Sep 1, 2026
Merged

nc9 merged 7 commits into
mainfrom
feat/9-uncompressed-assets

Conversation

@nc9

@nc9 nc9 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Closes #9

perf/compression only judged the HTML document's own response. A server that compresses text/html but not text/css is a common misconfiguration, and it was invisible: perf/css-file-size and perf/js-file-size measure bytes but never look at content-encoding, so a 300 KB uncompressed stylesheet was reported only as "large".

The rule

New perf/asset-compression (site scope, warning, weight 6). A crawled sub-resource is reported when it is 2xx, its content-type is compressible text, it carries no transfer coding, and it is over 100 KB. Findings list each asset URL biggest-first with its size, source pages, and the estimated saving. Threshold is ASSET_COMPRESSION_LIMITS.MIN_BYTES, tunable per-rule via min_bytes.

Site scope because sub-resources are shared: reporting them per page would repeat one asset N times. perf/compression is untouched — git diff on that file is empty, and a test asserts it still judges only ctx.page.headers.

Classification is by content-type, not by crawl pool, so an SVG discovered as an <img> is judged as the XML it is, while PNG/WebP/font/PDF in that same pool are excluded.

Investigation

Headers were already available. ResourceSizeData.contentEncoding exists from #107 for CSS and images. Scripts had no seam, so this captures it in both forked script fetchers (~1 line each) and passes it through both adapters. In-memory only, no storage column, no migration. Bun's fetch decodes the body but leaves the header intact, so the encoding stays observable even though script sizeBytes is the decoded length.

JSON and XML fetched on their own are not covered: the crawler discovers stylesheets, images, and <script src> only. Adding a neutral text-subresource pool is a crawler change, not this one — putting JSON into the CSS or image pools would corrupt their size rules. The rule classifies by content-type, so such assets are handled the moment a pool exists. Happy to file that as a follow-up.

Two false positives, designed out

content-encoding is tri-state. undefined (never observed) is not null (observed, absent). Cache-reused records carry a prior crawl's headers, and pre-#107 rows have an un-backed null, so both are skipped — as are records carrying an error, whose size is not trustworthy ("script too large" reports the byte it stopped reading at, and this rule's finding names the size out loud).

Any declared coding counts as compressed, rather than matching a known list. An allowlist would report zstd, dcb/dcz, or anything newer than the file as uncompressed. identity is the one value meaning compression is off.

A real false positive found in review, and fixed

Codex review caught that neither cheap probe proves absence of compression, and both reproduce:

  • A HEAD carries no body, so a server whose compression is a body filter (nginx's gzip module) answers with no Content-Encoding and the uncompressed Content-Length — exactly the shape of a large uncompressed asset. Every gzipped stylesheet over the threshold on such a server would have been reported.
  • A ranged 206 is equally inconclusive: many origins and CDNs skip compression for range requests specifically.

Absence of the header on a bodiless or ranged response is not evidence of absence. The checker now falls through to the GET, and confirms with one plain GET (body cancelled once headers are in) when the 206 still looks uncompressed. A HEAD that names a coding is positive evidence and still short-circuits.

Because checkResourceSizes is generic and also backs the PDF and sitemap-orphan checks — and text/html is compressible — verification is opt-in per pool (verifyCompression), set only on the css and images pools this rule reads. Sitemap checks keep the cheap HEAD path and pay nothing.

Testing

  • packages/rules/tests/asset-compression.test.ts — 34 tests: reported vs silent, threshold edge (strict >), casing, mixed codings, identity, unknown codings, non-text types, non-2xx, cache reuse, options.
  • packages/audit-engine/tests/asset-compression-capture.test.ts — 11 tests driving the real fetchers against a local server, including HEAD-hides-gzip, range-hides-gzip, a genuinely uncompressed asset that must still be reported after all three probes, and request-sequence assertions so the cost stays visible.
  • apps/cli/tests/crawler/script-fetcher-encoding.test.ts — the CLI fork is separate code the engine's suite cannot speak for.

Every one of these was mutation-tested: reverting the HEAD fall-through, the 206 confirmation, the pool gating, the encoding capture in either fetcher, the tri-state handling, the content-type filter, or the threshold comparison each turns tests red.

Suites: rules 1576 pass, audit-engine 307 pass, cli audit+crawler 377 pass, utils 102 pass. Typechecks clean across rules, utils, core-contracts, audit-engine, cli. make validate in docs/ passes (385 pages, orphan count unchanged).

packages/crawler's full-crawl-harness.test.ts has 2 timeout failures — pre-existing and load-related; verified identical on a clean origin/main checkout, and this branch changes no file in that package.

Golden delta

findings 98220 -> 98221, perRuleTally 278 -> 279. One skipped whole-crawl check: the harness supplies empty resourceSizes/scripts pools, so the rule has nothing to judge. Pass/warn/fail tallies and healthScore.overall (48) are all unmoved — the same shape as the social/asset-divergence precedent documented in that test.

Noted, not fixed

The CLI script fetcher's content store can never hit: it reads with hashContent(url) but writes with store.put(content), which keys by hashContent(content). Left alone — fixing the key is a caching behaviour change, unrelated to #9. Its cache-hit branch is nonetheless correct for this rule (it leaves contentEncoding unset rather than defaulting to null).

perf/compression and perf/bad-caching keep their own inline compressible-type checks. isCompressibleContentType moved to @squirrelscan/utils/headers and is shared by the checker and the new rule; the shared version lowercases content-types and the inline ones do not, so folding them in would change behaviour that acceptance criterion 3 requires to stay put.

nc9 added 6 commits September 1, 2026 21:40
perf/compression only judges the HTML document's own response. A server
that compresses text/html but not text/css is a common misconfiguration
and was invisible: perf/css-file-size and perf/js-file-size measure bytes
but never look at content-encoding.

Adds perf/asset-compression (site scope, warning): a crawled sub-resource
whose content-type is compressible text, served 2xx without a transfer
coding, above 100KB, is reported with its URL, size and source pages.

Classification is by content-type, not by crawl pool, so an SVG found as
an <img> is judged as the XML it is while PNG/WebP/font/PDF are excluded.

Two false positives are designed out:
- content-encoding is tri-state. undefined (never observed) is NOT null
  (observed, absent). Cache-reused records carry a prior crawl's headers,
  and pre-#107 rows have an un-backed null, so both are skipped.
- any declared coding counts as compressed, rather than matching a list,
  so zstd/dcb/dcz or anything newer can't read as uncompressed. identity
  is the one value meaning compression is off.

Scripts had no encoding seam; capture it in both script fetchers (~1 line
each) and pass it through both adapters. In-memory only, no storage or
migration. The CLI's content-store cache hit deliberately leaves it unset.

Golden: findings 98220 -> 98221, tally 278 -> 279, one skipped whole-crawl
check on a fixture with empty resource pools. Scores/tallies unmoved.

Signed-off-by: Nik Cubrilovic <[email protected]>
…ssed #9

Codex review of the previous commit found a real false positive, and it
reproduces: a server whose compression runs as a body filter (nginx's
gzip module) answers HEAD with no Content-Encoding AND the uncompressed
Content-Length, which is exactly the shape of a large uncompressed asset.
The checker's HEAD fast path recorded that as "observed, not compressed",
so every gzipped stylesheet over the threshold on such a server would
have been reported.

Absence of the header on a bodiless response is not evidence of absence.
For compressible text that looks uncompressed the checker now declines the
HEAD shortcut and falls through to its existing Range GET, which is
authoritative. A HEAD that names a coding is positive evidence and still
short-circuits, as does any type that gains nothing from compression, so
the extra request is confined to the assets a compression rule would
otherwise misreport.

Also from that review:
- skip records carrying an error: the script fetcher's "script too large"
  bail reports the byte it stopped reading at, and a finding that names a
  size must not name a fabricated one.
- the tri-state comment overclaimed. null does not by itself prove a live
  observation (the checker also inits it to null on timeout/budget skip);
  the 2xx status gate is what establishes that. Say so.
- add end-to-end tests driving the REAL fetchers against a local server,
  including the HEAD-hides-gzip case. The rule's unit tests inject
  contentEncoding through fixtures and would have survived deleting the
  capture entirely; these fail when either fix is reverted.

isCompressibleContentType moves to @squirrelscan/utils/headers so the
checker and the rule cannot disagree about what counts as text.

Signed-off-by: Nik Cubrilovic <[email protected]>
…atters #9

Second codex pass found the previous fix incomplete in one direction and
too broad in the other.

Incomplete: a ranged GET is no more conclusive than the HEAD was. Many
origins and CDNs skip compression for range requests specifically, so
`Range: bytes=0-0` can answer identity for an asset whose ordinary GET is
gzipped — the same false positive, one probe later. When an asset still
looks uncompressed after the 206, confirm with one plain GET and cancel
the body once the headers are in; the size stays whatever the cheap
probes already found. A failed confirmation keeps the existing record
rather than discarding a usable size.

Too broad: checkResourceSizes is generic and also backs the PDF and
sitemap-orphan checks, and text/html is compressible — so every sitemap
URL had started paying for the extra requests despite never being a
candidate for this rule. Verification is now opt-in per pool
(verifyCompression), set only on the css and images pools that
perf/asset-compression actually reads.

Tests: the capture suite now varies its responses by Range, covering both
the CDN shape and a genuinely uncompressed asset that must still be
reported after all three probes, and asserts the request sequence so the
cost stays visible. Adds a test for the CLI's FORKED script fetcher,
which the engine's suite could not speak for.

Also drops the last overclaiming tri-state comment on normalizeEncoding.

Noted while testing, not fixed here: the CLI script fetcher's content
store can never hit — it reads with hashContent(url) but writes with
store.put(content), which keys by hashContent(content).

Signed-off-by: Nik Cubrilovic <[email protected]>
…ssed #9

The verification GET exists because a ranged 206's missing
Content-Encoding proves nothing. But when that GET could not answer, the
code fell back to the 206's own null, and the rule's gate accepts any
2xx - so a gzipped asset was reported as uncompressed. That is exactly
the false positive the verification was added to prevent.

Reproduced against a local server whose HEAD and ranged GET hide gzip and
whose plain GET is rate-limited: the record came back
{status: 206, contentEncoding: null, sizeBytes: 300006, error: null},
which the rule reports as a 300KB uncompressed stylesheet. Neither
failure mode is exotic - the confirmation shares its AbortController with
the two probes before it, and a second immediate request for the same
asset is what rate-limiters answer with 429/503.

The encoding now degrades to undefined ('never established'), the third
state ResourceCheckResult already documents and the rule already treats
as unjudgeable, so no rule change is needed. Size, status and every other
field survive, so css-file-size and total-byte-weight are unaffected.

Signed-off-by: Nik Cubrilovic <[email protected]>


Content-Encoding is comma-separated, so 'identity, identity' reached
isKnownUncompressed verbatim and was mistaken for a real coding,
suppressing a genuine finding. The fetchers normalize a lone 'identity'
to null but match one token, so lists arrive intact.

Every token is now checked: all-identity is no coding, and
'identity, gzip' stays compressed.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9

nc9 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Review pass: one false-positive defect found and fixed

Reviewed this PR independently (I had built the same feature separately before we consolidated onto this branch, so I came in holding empirical HEAD/206 findings). The design is right and the tests are strong: I mutation-tested all seven key guards — HEAD fall-through, 206 confirmation, cacheReason, error, undefined-encoding, threshold, identity — and every one is falsifiable.

One real defect, now fixed in the two commits above.

The defect

The confirming GET exists because a ranged 206's missing Content-Encoding proves nothing. But when that GET could not answer, the code fell back to the 206's own null, and the rule's gate is status >= 200 && status < 300, which accepts 206. A gzipped asset was therefore reported as uncompressed: exactly the false positive the verification was added to prevent, reintroduced through the error path.

Reproduced against a local server whose HEAD and ranged GET hide gzip and whose plain GET returns 503:

{ status: 206, contentEncoding: null, sizeBytes: 300006, error: null, cacheReason: null }

That clears every gate and is reported as a 300 KB uncompressed stylesheet.

Neither failure mode is exotic. The confirmation shares its AbortController with the two probes before it, so all three share one 10s budget; and a second immediate request for the same asset is what rate-limiters answer with 429/503.

The fix

resource-checker.ts now degrades the encoding to undefined ("never established") when the confirmation does not conclusively answer. That is the third state ResourceCheckResult already documents and the rule already treats as unjudgeable, so no rule change was needed: it drops out of the existing contentEncoding !== undefined gate. sizeBytes, status and error all survive, so perf/css-file-size and perf/total-byte-weight are unaffected.

ResourceCheckResult.contentEncoding widened to string | null | undefined. Safe end to end: ResourceSizeData already declares it optional, and the storage write is ?? null.

Deliberately not done: making the rule reject 206 outright. A confirmed 206 is trustworthy and still records 206, so that would have thrown away this PR's main improvement.

Covered by a new /confirm-503.css route and two capture tests (encoding is undefined; size and error survive). Reverting the fix fails the first.

Also added

Content-Encoding is a comma-separated list, so identity, identity reached isKnownUncompressed verbatim and was mistaken for a real coding, suppressing a genuine finding. The fetchers normalize a lone identity to null but match a single token, so lists arrive intact. Every token is now checked: all-identity is no coding, and identity, gzip stays compressed. Three rule tests.

Reviewed and accepted as correct, no change

  • cacheReason gate — right, and it closes the legacy pre-rules(crawl): sitemap lastmod drifts from the page's own dateModified #107 hole where a record predating the column reads back as null from SQLite and is indistinguishable from a real absence.
  • Errored-script exclusion — right. The script fetcher's post-read bail sets sizeBytes to the read cap + 1, so including those records would print a fabricated size in a finding that names the size out loud.
  • Request cost — well gated. Only the css and images pools opt in; rasters, fonts and PDF short-circuit on HEAD because isCompressibleContentType is false, so only stylesheets and SVGs can cost extra. Worst case is three requests for an asset that still looks uncompressed, bounded by MAX_RESOURCES_TO_CHECK (500) and concurrency 5.

One minor note not worth changing: the confirming GET is not separately gated by budget.shouldSkip, so a tarpitting host can serve one extra request before the budget notices. Its latency is folded into the recorded elapsed time, so the tarpit detector still sees the cost.

Verification

rules 1579 pass, audit-engine 312 pass (golden green), CLI 1877 pass, utils 102 pass, 0 failures. tsgo clean on rules, audit-engine, utils and cli. Root format:check and lint clean. tangly check --strict passes.

@nc9
nc9 merged commit c1253e3 into main Sep 1, 2026
13 checks passed
@nc9
nc9 deleted the feat/9-uncompressed-assets branch September 1, 2026 13:12
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.

Uncompressed assets

1 participant