Skip to content

feat(rules): add security/csp-blocks-own-resources - #583

Merged
nc9 merged 7 commits into
mainfrom
claude/csp-blocks-own-resources-t6z04b
Oct 8, 2026
Merged

nc9 merged 7 commits into
mainfrom
claude/csp-blocks-own-resources-t6z04b

Conversation

@nc9

@nc9 nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Refs #426

Adds the per-page rule security/csp-blocks-own-resources, which flags a Content-Security-Policy that blocks what the page itself loads. It matches each page's own policy (header plus <meta http-equiv>) against the page's scripts, preloaded modules, stylesheets, frames and images, third-party script URLs inside same-site chunks, and the runtime hosts of detected vendors.

Acceptance criteria

  • Ads-linked gtag plus connect-src 'self' https://www.google-analytics.com produces an error listing analytics.google.com, www.google.com and stats.g.doubleclick.net for connect-src. Test: acceptance fixtures > gtag for an Ads-linked property... in packages/rules/tests/csp-blocks-own-resources.test.ts.
  • A third-party script URL referenced only from a preloaded same-origin chunk, host missing from script-src, produces a finding. Test: ...named only inside a preloaded same-origin chunk is a finding. The audit fetches modulepreload and preload as=script chunks (extractPreloadedScriptUrls in the parser, used by adapter.ts), covered by packages/parser/tests/extract-preloaded-script-urls.test.ts.
  • https://*.example.com passes for cdn.example.com and produces a finding for example.com. Test: a *.example.com source allows cdn.example.com and blocks example.com, plus the source matching block.
  • A page with no CSP header passes (and a report-only policy is ignored). Test: no CSP header passes, and a report-only policy blocks nothing.
  • Each page's own CSP is evaluated, the vendor table records a last-verified date, and the rule has a docs page. Tests: each page is judged by its own policy, every vendor entry records an ISO last-verified date. Docs: docs/rules/security/csp-blocks-own-resources.mdx, listed in docs/docs.json and the Security index.

Engine change

Preloaded chunks are fetched only when a crawled page enforces a CSP, into a separate preloadedScripts list capped at 20 per audit. They are not added to site.scripts, so no other rule's input changes (the canonical golden is unchanged apart from this rule's passes). The rule cache format is bumped to prc-4 and its run context hashes the new field, so the first audit of each site after the upgrade runs every rule fresh, once.

False-positive fixtures

no false positives in the test file covers 'self', directive fallback (script-src-elem, child-src, default-src), unset directives, scheme, port and path sources, nonces, hash sources with integrity, 'strict-dynamic', noscript and data: images, chunk URLs with no script-loading context, chunk-injected scripts under a nonce policy, own-host chunk URLs, a proxied PostHog, commented-out vendor snippets and a covered GA4-only setup.

Registration and counts

  • Registered in packages/rules/src/security/index.ts; declared verdictScope: "page" (it reads the response header) and added to varyingRules in template-invariance-measured.json. That list is normally produced by measuring two third-party crawls, which I cannot do here, so the entry is by construction.
  • Rule count 297 to 298 and Security 16 to 17 in README.md, docs/index.mdx, docs/rules/index.mdx, docs/rules/security/index.mdx and docs/agent-setup/index.mdx. CHANGELOG has an Unreleased entry.
  • streaming-rules-canonical-golden.test.ts: 297 to 298 rules and 100734 to 101234 findings (500 passes on the synthetic site, which serves no CSP).

Verification

  • Tests: the rule's 33 tests, rule-verdict-scope, the canonical golden, rule-cache-replay-golden, page-rule-site-context and the parser extractor test pass. CI is green on the current head.
  • Typecheck clean for rules, parser and audit-engine; make validate in docs, root format:check and the detect-secrets hook pass.

Smoke on public sites

The sandbox egress allows very few hosts (most returned 403 from the proxy, others served a bot wall), so the sample is small.

Site Pages Result
github.com (CSP enforced) 15 15 pass, 0 findings
nodejs.org (no CSP) 15 15 pass
gitlab.com, npmjs.com (CSP, bot-wall page only) 1 each pass

0 findings on about 17 pages under an enforced CSP, so the measured false-positive rate is 0 of 17. That is too small to call it a rate, and it exercises no true positives on live sites.

Agent skill

No change needed to the squirrelscan agent skill.

…cks the page's own resources

Matches each page's own CSP against what its HTML references, third-party script URLs inside same-site chunks, and the runtime hosts of detected vendors. Preloaded script chunks are now fetched like script tags.

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

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Status: pushed and ready for review. Waiting on the bot review; I will fix or rebut any critical, high or medium findings.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of security/csp-blocks-own-resources. I read the diff and the rule, matcher and engine changes. I did not run the tests, and I did not read the vendor table or the test files line by line. The design is sound: per-page policy, report-only ignored, 'strict-dynamic' treated as undecidable, bounded chunk scanning, and good test and docs coverage.

  • (medium) packages/audit-engine/src/adapter.ts (absorbResourceOccurrences): modulepreload and preload as=script chunks now go into the shared scripts map for every audit. Every other rule that reads site.scripts (size, duplicate, third-party, etc.) will now see these chunks, and the crawler fetches more bytes per site. The updated golden and template-invariance fixtures suggest this does change output. Please confirm it's intended for all rules, and that the fetches respect the existing per-site script size and count caps.
  • (low) csp-source-match.ts (sourceListAllows): hash sources ('sha256-…') are ignored. Under CSP3 an external script with matching integrity can be allowed by a hash. A policy that allows scripts only by hash plus SRI would be reported as blocking them, which is a false positive. Consider returning undefined when the list contains a hash source and the reference is a script or style.
  • (low) csp-source-match.ts (parseCspPolicies): splitting on , is right for the header, but <meta http-equiv> content isn't comma-joined, and a comma inside a meta policy is unusual. Treat it as one policy there, or document the assumption.
  • (low) csp-blocks-own-resources.ts (vendorReferences): vendor detection runs regexes over the raw page HTML. A blog post that mentions "gtag" in text, or a commented-out snippet, can trigger an error-level finding (hasError comes from a vendor category). Prefer matching against parsed script or link attributes, or strip comments first.
  • (low) csp-blocks-own-resources.ts (chunkReferences): the SCRIPT_LOAD_HINT window of 300 characters either side is a heuristic. Minified bundles that contain a URL literal in a config object near an unrelated appendChild can produce findings. The (warn) status limits the damage, but the docs should say this is best-effort.
  • (nit) Several slice and regex passes over up to 6 MB per page run on every page. Chunks shared across pages are rescanned each time. Caching per-script results (keyed by script URL) would cut the repeated work on large sites.
  • (nit) wanted.startsWith("*.") with got.endsWith(wanted.slice(1)) is correct. A one-line comment saying that example.com is intentionally excluded would help future readers.

…pets safely in csp-blocks-own-resources

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

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Review round 1, pushed in 252d0a2.

Medium (preloaded chunks in the shared scripts map): intended. The chunks go through the same fetchScriptContents call as every <script src>, so they are bound by the existing caps: maxScripts (the per-site resource limit, scaled to page count), maxSizeBytes per script, the shared tarpit-aware fetchBudget, and the same same-domain filter. They are deduplicated by URL, so a chunk that is also a script tag is fetched once. The canonical golden moved only by the +500 passes from the new rule, which is the synthetic site with no CSP; no other rule's tally changed. I did not add a separate cap, since it would just fork the existing one.

Low, fixed:

  • Hash sources: a hash source on a list that allows an element with integrity is now undecidable instead of a block (test added).
  • Meta policies are no longer split on commas (test added).
  • Vendor detection strips HTML comments first (test added).
  • Docs now say chunk detection is best-effort.
  • Added the comment explaining that *.example.com excludes example.com.

Nit, not changed: per-script scan caching. The scan is bounded (2 MB per chunk, 6 MB per page) and only runs on pages that have an enforced CSP; a cache keyed by script URL would be new shared state in a page rule for a bounded cost, so I'm leaving it.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

CodeQL (11 "missing regular expression anchor" alerts on csp-vendors.ts): fixed in 4c22276. The vendor detectors were regexes with hostnames over the page HTML. Detection now parses every URL the page names (comments removed) and compares exact hostname, path prefix and query value, so a lookalike such as www.googletagmanager.com.evil.test no longer matches (test added). No host-literal regexes remain in the vendor table. Rule tests (30), typecheck, format check and secret scan pass locally.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

I read the diff for the new security/csp-blocks-own-resources rule, the CSP matcher, the vendor table, the parser/adapter change and the docs. I didn't run the tests. I found no correctness problems that should block the merge. The matcher follows CSP3 closely (wildcard host, port, path, 'self', nonce, strict-dynamic and hash handling), and it correctly stays quiet on a missing policy and on a Report-Only header.

Findings:

  • (medium) packages/audit-engine/src/adapter.ts (absorbResourceOccurrences): preloaded chunks now join the same-site script set for every script rule, not just this one. Pages with many modulepreload links will fetch more bodies, and file-size, compression and minification rules will see more scripts and may change results on existing sites. Please check the rules that read site.scripts, and consider a per-audit cap on chunk fetches.
  • (low) csp-blocks-own-resources.ts (vendorReferences): vendors are detected by regex over the whole page HTML with only comments stripped. A page that quotes a gtag/js?id=G-... or js.stripe.com/v3 snippet in <pre>/<code> is treated as using that vendor, and can fail on a host it never loads. Restricting detection to script[src], iframe[src] and inline script text would reduce false positives.
  • (low) csp-blocks-own-resources.ts (enforcedPolicies): a meta CSP only applies to elements after it, and the browser ignores frame-ancestors, report-uri and sandbox in a meta policy. A script placed before the meta tag is judged against a policy the browser didn't apply to it. Edge case, worth a comment.
  • (low) csp-source-match.ts (parseCspPolicies): the header is split on every comma, so a directive value containing a comma is read as a second policy. Rare.
  • (low) csp-blocks-own-resources.ts (chunkReferences): the 300-character SCRIPT_LOAD_HINT window is heuristic. A minified bundle with an unrelated .src = nearby can report a docs or CDN URL string as a script load. At most a warning, but IGNORED_CHUNK_HOSTS will keep growing.
  • (low) The rule's severity is warning but the check returns fail for known vendor categories. Confirm the report and score treat that as intended.
  • (nit) csp-source-match.ts: HOST_SOURCE_RE doesn't accept IPv6 literals or punycode hosts, so such sources never match.
  • (nit) csp-vendors.ts: every lastVerified is 2026-10-08, and the test only checks a date exists, not that it is current.
  • (nit) linkKind in the rule and extractPreloadedScriptUrls both parse rel/as. One shared helper would keep them in sync.

Tests: the rule test, the preload extractor test and the updated golden counts (101234 findings, 298 rules, 500 passes) look appropriate. Consider adding a nonce-only policy without strict-dynamic plus a vendor reference, and a multi-policy header where one policy allows and the other blocks.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Review round 2, no new push.

Medium (preloaded chunks reach every script rule): same finding as round 1, and the answer stands. The per-audit cap you suggest already exists and covers these fetches. fetchScriptContents is called once with maxScripts (the per-site resource limit scaled by page count), maxSizeBytes per script and the shared fetch budget, and chunks are deduplicated by URL, so a preload that is also a <script src> is fetched once. The canonical golden changed only by this rule's +500 passes; no other rule's tally moved. A second cap would fork the first.

Lows, left as they are:

  • Vendor detection no longer uses regexes over the page text for hosts (4c22276): it parses the URLs the page names and compares exact host and path. A snippet quoted in <pre> or <code> that names a vendor URL still counts as use. Excluding code samples would add a DOM pass for a rare documentation page, and the failure is a finding on a page that shows a vendor snippet, so I'm not building for it.
  • Meta CSP applies only to later elements and ignores frame-ancestors, report-uri and sandbox: this rule checks none of those directives, and a script before the meta tag is rare; the meta policy is checked as a whole.
  • A comma inside a header directive value: no CSP source expression contains one, so a comma only ever separates policies.
  • Chunk hint window and IGNORED_CHUNK_HOSTS: documented as best-effort; chunk findings warn.
  • fail under a warning rule severity: the same shape as content/placeholder-contact, which fails on contact pages under a warning-severity rule.

Nits: IPv6 and punycode sources are out of scope for a static check of http(s) hostnames, and lastVerified is a record of when an entry was checked, not an expiry. The shared rel/as helper would cross the parser and rules packages for a few lines, so I'm leaving it.

Suggested tests: the multi-policy case (one policy allows, another blocks) is already covered by every policy of a multi-policy header has to allow the resource.

…hunks to the rule

Preloaded script chunks are fetched into a separate preloadedScripts list, capped at 20 per audit, so no other rule's site.scripts input changes. The rule cache format is bumped and the run context hashes the new field.

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

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 0981460: merged origin/main (the only conflict was CHANGELOG.md, kept both entries) and scoped the preloaded chunks to this rule.

What changed

  • Preloaded chunks no longer join site.scripts. absorbResourceOccurrences collects them into their own preloads map, they are fetched in a separate fetchScriptContents call, and they reach rules as site.preloadedScripts. Chunks already named by a <script src> are skipped there, so nothing is fetched twice. Only security/csp-blocks-own-resources reads the new field, together with site.scripts.
  • The extra fetch has its own cap: 20 chunks per audit, on top of the existing page-count scaling, size cap and shared fetch budget. The regular script fetch is the same call with the same inputs as on main.
  • The rule cache run context now hashes preloadedScripts and RULE_CACHE_FORMAT is bumped to prc-4, so a chunk change moves a page's cache key and the first audit after upgrade runs fresh once. CHANGELOG notes this.
  • The rule counts needed no re-run: main added no rules since the branch point, so the merge leaves 298 rules and 17 in Security in all five places.

Evidence that no other rule's output changes

  • streaming-rules-canonical-golden still expects 101234 findings and 298 tallies, unchanged by this commit; rule-cache-replay-golden, rule-cache-codec, page-rule-site-context and template-fanout-parity-golden pass.
  • csp-blocks-own-resources (30, the chunk test now feeds preloadedScripts), rule-verdict-scope and the parser preload extractor tests pass.
  • Typecheck is clean for rules and audit-engine; docs validation, root format check and the secret scan pass.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of security/csp-blocks-own-resources. I read the engine, parser, matcher and rule changes by static reading only. I did not run the tests or build.

Overall the design is solid. Preloaded chunks are kept out of scripts so existing rules don't change. RULE_CACHE_FORMAT is bumped and preloadedScripts is included in the cache key. Header and meta handling is correct, report-only policies are ignored, and the scan sizes are bounded.

  • (medium) csp-blocks-own-resources.ts chunkReferences: third-party script URLs found inside chunks are matched with no nonce. Sites that use 'nonce-…' without 'strict-dynamic' often copy the nonce onto scripts their chunks inject. Those get reported as blocked, which is a likely false positive. Consider returning undecided for chunk-origin script refs when the governing list contains a 'nonce-' source, or add a fixture that pins the current behaviour.
  • (medium) adapter.ts preload fetch: every audit now fetches up to 20 extra chunks (PRELOAD_CHUNK_FETCH_LIMIT), even when no page has a CSP and the rule cannot fire. That is extra network time and memory for most users. Consider fetching only when some crawled page has an enforced CSP header or meta tag.
  • (low) vendorReferences: vendor refs are built as https://host/. A policy that allows a specific file path, such as https://www.google-analytics.com/analytics.js, will fail pathMatches against /. That could report a host as blocked when it is allowed for the real URL. Fixtures should cover path-scoped sources, or the vendor table should carry paths.
  • (low) csp-source-match.ts sourceMatches: hostname normalisation is inconsistent. A trailing dot is stripped from the resource host but not from the wildcard suffix check. IDN and punycode hosts are not handled. Both are edge cases.
  • (low) htmlReferences: img[srcset], <source>, <object>/<embed>, <form action> and @import are not covered. That causes false negatives only, which is fine for v1. Worth noting in the docs.
  • (nit) chunkReferences: SCRIPT_LOAD_HINT is tested on a 600-byte slice per URL match. In large minified bundles with many URL literals that is repeated work. It is bounded, but you could short-circuit by host first, using pageHost and IGNORED_CHUNK_HOSTS, before the regex.
  • (nit) The hasError naming is a bit odd next to the fail/warn statuses. Consider hasKnownVendor or similar.

Test coverage looks good: the acceptance fixtures, the matcher unit tests, the parser extractor test and the updated golden counts. No security concerns, since preload fetches are limited to same-domain URLs via isSameDomainScript.

…njected chunk scripts as undecidable

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

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Review round 3, pushed in 62655c4.

Medium, nonce policies and chunk-injected scripts: fixed. A script URL found inside a chunk is now undecidable (not reported) when the governing list carries a 'nonce-...' source and no host matches, because the chunk may copy the page's nonce onto the script it injects. A plain <script src> under the same policy is still reported. Test: a chunk-injected script under a nonce policy is undecidable, a plain tag is not.

Medium, extra fetches on sites with no CSP: fixed. Preloaded chunks are now collected only from pages that enforce a CSP (response header or <meta http-equiv>). A crawl with no CSP anywhere fetches no extra chunks. The 20-per-audit cap and the separate preloadedScripts field are unchanged.

Low, vendor path scoping: fixed. Vendor needs are judged on host only, since the real request path is unknown, so a policy allowing https://www.google-analytics.com/g/collect no longer reports the host as blocked (test added).

Low, unsupported references: the docs now list what is not checked (srcset, <source>, <object>, <embed>, <form action>, @import) and describe the nonce and fetch behaviour. The CHANGELOG entry says chunks are fetched only under a CSP.

Nit, hasError: renamed to hasKnownVendor.

Left as is: IDN and punycode hosts and trailing-dot wildcard normalisation (edge cases for a static http(s) check), and short-circuiting the hint regex by host (the scan is already bounded).

Rule tests (32), canonical golden, rule-cache replay golden, page-rule site context, verdict scope, typecheck, format check, docs validation and the secret scan pass locally. That is the third review round, so I'm stopping the review loop here and not merging.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

CodeQL, "incomplete multi-character sanitization" on the comment strip in csp-blocks-own-resources.ts: fixed. The one-pass replace(/<!--...-->/g, "") could leave a new <!-- behind (<!<!-- x -->-- ...). The strip is now an indexOf loop that repeats until no <!-- remains, and an unterminated comment runs to the end of the document. The result is only used to detect vendor URLs, never rendered or parsed as HTML. Tests added for both cases; the rule's 33 tests, typecheck, format check and secret scan pass. The earlier alert on 0981460 (the 11 host-regex alerts) was fixed in 4c22276.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of the new security/csp-blocks-own-resources rule and the preload chunk fetch. I read the diff only and did not run the tests.

  • (medium) csp-source-match.ts parseCspPolicies: the header is split on every comma. Commas are legal inside a directive's source list or a report-uri URL, so a policy that contains one is cut into bogus policies. The bogus ones can have a missing or empty directive, so the rule could report a block that isn't real. Splitting only when a comma starts a new policy, or ignoring fragments that don't begin with a known directive name, would be safer.
  • (medium) adapter.ts hasCsp is !!page.securityHeaders.csp || meta, while the rule reads ctx.page.headers['content-security-policy']. If securityHeaders.csp also covers report-only, preloads are fetched for pages the rule then ignores. If the two sources can disagree on the header, the rule can run on chunks that were never fetched. Please confirm both read the same header.
  • (low) csp-source-match.ts pathMatches: matching ignores redirects and query strings, and the source path is decoded for comparison. That is a reasonable approximation. A fail is only as accurate as this, so a comment or a test for the path-source cases would help.
  • (low) csp-blocks-own-resources.ts chunkReferences: the ±300-char SCRIPT_LOAD_HINT heuristic on minified bundles can miss loads or match unrelated URLs. The scan is bounded (2MB per chunk, 6MB per page), so performance is fine. Chunk-origin hits only ever warn unless the host is a known vendor, which limits the damage.
  • (low) Test coverage: the new rule's own tests aren't in the part of the diff I read, only the parser test and the golden-count bump. I'd expect unit tests for sourceListAllows (wildcards, ports, strict-dynamic, nonce, upgrade-insecure-requests) and for the rule itself (meta CSP, report-only ignored, multiple policies). If they exist, ignore this.
  • (nit) collectResourceOccurrences doesn't pass hasCsp, so it never collects preloads. Only the collector path sets it today, so this is fine, but a comment would prevent surprise.

Otherwise the design is solid: preloads stay in a separate field so other rules' inputs don't change, fetches are capped, and the cache format bump to prc-4 is handled. I have no security concerns.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Round 4 review, answered with evidence, no push (review rounds are spent, and neither medium reproduces).

Medium, comma split of the header: the CSP3 grammar defines a header value as serialized-policy-list = serialized-policy *( "," serialized-policy ), and a source expression cannot contain a comma, so a comma in a header always starts a new policy. A comma in a report-uri value is not legal either. Even if one slipped in, the fragment parses as an unknown directive name (for example https://x/y), and an unknown directive governs no resource, so it cannot produce a block. Only a fragment naming script-src, default-src and so on can block, and that is a real second policy. The meta path is already one policy with no comma split (tested).

Medium, hasCsp and the rule reading different headers: they read the same one. The crawler sets securityHeaders.csp from headers.get("content-security-policy") only (packages/crawler/src/fetcher.ts, extractSecurityHeaders), and buildHeadersMap copies exactly that value into headers["content-security-policy"], which is what the rule reads. Report-only is a different header and is in neither. The meta check is the same condition in both. So preloads are fetched exactly for the pages the rule will evaluate.

Low, tests: they exist: packages/rules/tests/csp-blocks-own-resources.test.ts (33 tests) covers wildcard, port, path and scheme sources, 'self', nonce, 'strict-dynamic', hash plus integrity, duplicate directives, meta policies, report-only and multi-policy headers, plus the three acceptance fixtures. The path cases are in source matching and no false positives. upgrade-insecure-requests is the one matcher branch without its own test; it only rewrites an http subresource to https before matching.

Low, chunk hint heuristic and path approximation: already documented as best-effort, and chunk findings warn.

Nit, collectResourceOccurrences: it has no callers; the audit path goes through the collector that sets hasCsp.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewed the diff for the new rule, the source-matching module, the parser extractor and the adapter and cache plumbing. I did not read csp-vendors.ts in detail, the docs changes, or the rule test file, and I did not run the test suite.

No blocking issues found. The CSP3 fallback chain, 'self', wildcard (*.example.com does not match example.com), nonce, hash, strict-dynamic and 'none' handling all look right. Returning "undecidable" instead of "blocked" in the ambiguous cases is a good way to avoid false positives. The prc-4 cache bump and the preloadedScripts projection into the run-context hash are consistent. Keeping preloads out of scripts leaves the other script rules unchanged.

  • (low) adapter.ts (hasMetaCsp) vs csp-blocks-own-resources.ts (enforcedPolicies): the adapter decides whether to collect preloads with querySelectorAll, but the rule reads meta tags through querySelectorAllOutsideNoscript. A CSP meta inside <noscript> would make the engine fetch chunks the rule then ignores. This only wastes fetches, but use the same helper in both places. The adapter reads the header from page.securityHeaders.csp and the rule from page.headers. They should agree, but share one accessor if you can.
  • (low) adapter.ts preload fetch: the 20-chunk cap is applied in Map insertion order, which is crawl order. On a large site the first CSP pages use up the budget and later pages get no chunk scan, so findings depend on crawl order. Consider prioritising chunks by how many pages reference them, or documenting the limit.
  • (low) csp-blocks-own-resources.ts (chunkReferences): the SCRIPT_LOAD_HINT check looks within ±300 characters of a URL. That is a heuristic, and minified bundles can put an unrelated appendChild or .src = near a documentation URL. It is capped at "warn" unless the host is a known vendor, so the risk is acceptable. A test with a minified bundle containing an unrelated URL literal next to such a call would pin the false-positive rate.
  • (low) csp-source-match.ts (parseCspPolicies): splitting a header on , is correct for source expressions, but a URL path containing a comma in a host source would be cut. It is rare, and worth a one-line comment.
  • (nit) chunkReferences runs script.sourcePages.some(...) for every script on every CSP page, which is pages × scripts × sources. It is fine at current caps, but a prebuilt per-page index would be cheaper if the caps rise.
  • (nit) sourceMatches ignores a * host with a path or port when the scheme is missing, and ws/wss handling is only partly covered. Add a test or a comment saying that is intentional.

Test coverage looks good: acceptance fixtures, a source-matching block, extractor tests, and the golden tally update (+500 passes, 298 rules).

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Status: the latest bot review has no critical, high or medium findings, only lows and nits (meta CSP inside <noscript> costing a wasted fetch, chunk cap in crawl order, heuristic notes), which I'm leaving as they are: none changes a verdict and the review rounds are spent. Head 58cd77f has all review findings and the CodeQL alerts addressed. Ready for a human review; I am not merging.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of the new security/csp-blocks-own-resources rule and the preloaded-chunk fetch. I read the diff, extractPreloadedScriptUrls and the adapter wiring. I did not run the tests or read the rule matcher, csp-source-match.ts, in full.

  • (low) packages/audit-engine/src/adapter.ts (~L891-898): the cap is Math.min(maxScripts ?? 20, 20). If maxResources is set, it also lowers the preload cap, which is probably intended. Please confirm and add a test. The Changed entry in the changelog says "capped at 20", which stays true either way.
  • (low) adapter.ts hasMetaCsp / hasCsp: this gates the preload fetch on the page's CSP header or meta tag. The rule also handles comma-separated policies and report-only headers. Check that securityHeaders.csp is not set for Content-Security-Policy-Report-Only. If it is, report-only sites will pay for fetches the rule discards.
  • (low) adapter.ts absorbResourceOccurrences: hasCsp is optional, so a caller that omits it silently disables preload collection. The streaming collector sets it, but a required field would be safer.
  • (nit) extractPreloadedScriptUrls calls new URL(href, baseUrl). It does not strip fragments or normalise URLs the way the regular script collection might, so the same chunk could be fetched twice. The !scripts.has(url) filter only catches exact matches.
  • (nit) Cache: bumping RULE_CACHE_FORMAT to prc-4 and projecting preloadedScripts into the run-context hash is consistent, and the changelog documents the one-time cold run.
  • (nit) The golden test adds +500 findings and a tally of 298 with an explanatory comment. That matches the rule count in the README and docs.

I found nothing blocking. The preloaded scripts are kept in a separate map, so existing script rules should be unaffected.

@nc9
nc9 merged commit 1d66a45 into main Oct 8, 2026
15 checks passed
@nc9
nc9 deleted the claude/csp-blocks-own-resources-t6z04b branch October 8, 2026 14:31
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