Skip to content

feat(cli): batch audit groundwork: urls-file reader and results manifest #1231 - #1547

Closed
nc9 wants to merge 4 commits into
mainfrom
feat/batch-urls-file-slice1
Closed

nc9 wants to merge 4 commits into
mainfrom
feat/batch-urls-file-slice1

Conversation

@nc9

@nc9 nc9 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1231 (slice 1 of 4). Groundwork only: two CLI modules and a stricter host classifier in packages/utils, with tests. No CLI flag, no file or network I/O, no behaviour change for any command, so no docs, CHANGELOG or completion entry yet (they ship with slice 2, which adds the flag).

Split of #1231 (L) into small PRs

  1. This PR: the urls file reader and the results manifest with resume planning (pure code, tested).
  2. The runner at --concurrency 1: squirrel audit --urls-file F --out-dir D, each URL as a child squirrel audit, one report per key, the results file appended as each URL ends (a running line when it starts), the status mapping from the child's exit code, batch exit codes 0, 1, 2 and 6, the rejected-flags message, completion.ts, docs/cli/audit.mdx, CHANGELOG.
  3. Safety of a long batch: the out-dir lock file, SIGTERM forwarded to children with resume, a per-child timeout recorded as timeout, a child that dies without a record recorded as crashed, never two URLs of one project at once.
  4. --concurrency N above 1 (after Concurrent squirrel audit processes fail with 'SQLite database is busy (locked)' #1226), --retry-failed, the retention notice and recipe, and the signed-in rules.

What is in this PR

  • packages/utils/src/non-public-host.ts: new isNonPublicHostnameStrict, exported from @squirrelscan/utils and @squirrelscan/utils/non-public-host. It is the shared classifier plus the special-use ranges the shared one accepts: IPv4 192.0.0.0/24, 192.0.2.0/24, 192.88.99.0/24, 198.18.0.0/15, 198.51.100.0/24, 203.0.113.0/24, multicast, reserved and broadcast (224.0.0.0 and up, which also covers 255.255.255.255 and 4294967295); IPv6 NAT64 64:ff9b::/96 (judged by the IPv4 it carries, so 64:ff9b::808:808 stays public) and local-use 64:ff9b:1::/48, 6to4 (judged by its IPv4), Teredo, IPv4-compatible ::a.b.c.d, site-local fec0::/10, documentation 2001:db8::/32 and 3fff::/20 (a true /20), multicast ff00::/8, discard 100::/64, and mapped, translated and ISATAP (::5efe:a.b.c.d, ::200:5efe: under any prefix) IPv4 re-checked against the strict rules, and 2001:2::/48, 2001:10::/28, 2001:20::/28 and 5f00::/16. Deliberate deviation from the review: I added a separate function instead of changing isNonPublicHostname. The shared one also decides which delivery rules run on a page and whether a cloud handoff is attempted, and its callers (rules runner, cloud preflight, crawler seed redirect, TLS probe, MCP) and fixtures use documentation ranges; its tests are unchanged and still pass. Say so if you want the shared function changed instead.
  • apps/cli/src/batch/urls-file.ts: parseUrlsFile reads the file as untrusted input. Blank lines and # lines are ignored; a BOM, CRLF and surrounding spaces are not part of a URL. A bare example.com or localhost:3000 is read as https. Refused with line number and reason, never dropped silently: not http or https, unparsable, a control character anywhere in the line (a lone CR no longer joins two URLs), userinfo (including a password alone), a non-public host by the strict classifier unless allowPrivateHosts, a line over 2,048 characters, and a URL that is over 2,048 characters once parsed (2,000 multi-byte characters become 18,020). The echo of a refused line cannot carry a credential: when the WHATWG parser finds userinfo (it reads any mix of / and \ after the scheme) the echo is rebuilt from its parts (scheme://***@host, path, masked query and fragment) and nothing of the original authority is kept; when the parse throws, a conservative fallback masks everything up to the last @, fullwidth or small @, or %40 before the first ? or #, and keeps only a real scheme (http, https, ftp, ws, wss, file). A line cut for length echoes only its size. Control characters show as U+FFFD. A randomized 3,000-line differential and the slash, fullwidth, %3a, over-long and unparsable shapes are tests. The rejected list is capped (default 1,000) and rejectedCount counts all of them (an 8 MiB file of a lines made 4.19 million objects, 884 MB). More than maxUrls (default 100,000) distinct URLs is an error before any request, not a silent cut. Byte cap is the spec's 64 MiB, a parameter (maxBytes); a slice 2 caller must stat the file or read at most the cap plus one byte before decoding, because the check here runs on a decoded string (noted in the file header and the constant). A line far over the cap is refused from its head without being copied whole.
  • apps/cli/src/batch/manifest.ts: the record (adds finishedAt) with the issue's status vocabulary plus running. blocked and redirected are failures: --retry-failed runs them again and they count toward exit code 6 (isFailedStatus), as the Batch mode for squirrel audit: --urls-file with concurrency, resume and per-URL failure records #1231 spec says (the first version treated them as final). A running line that is the last record of a URL is read as crashed (effectiveStatus). parseManifest validates what it reads: key must be 16 hex characters, report a relative path with no .., ., backslash, colon or control character, attempt an integer 1 to 1,000 (a tampered 1e308 no longer masks later records), score 0 to 100, pages and exitCode integers in range, non-finite numbers dropped, text fields and notes capped, a URL over the URL cap rejected, and a line over 64 KiB skipped without parsing. planBatch derives the plan from the urls file only: a record counts only when its key is a listed URL's key and its own url equals that URL, so a forged record cannot count a URL done or mask its real record. On a same-attempt tie the later line wins.
  • The key stays the first 16 hex characters of the SHA-256 of the URL (safe for file names). This deviates on purpose from the spec text, which should be amended to say so.
  • .example and .test hosts are refused by default (fixtures use allowPrivateHosts).

What is not masked: the path and the names of query keys of a refused line are echoed, and an accepted URL keeps its path and query (they reach the manifest and child process args), so a secret carried in a path or a query key is not protected here (stated in the urls-file.ts header). Only userinfo, query values and the fragment are masked.

Classifier, fail closed: an embedded IPv4 (NAT64, 6to4, ISATAP, mapped, translated) now only adds a refusal; a public one falls through to the prefix rules, so ff02::5efe:808:808, fec0::5efe:808:808, 3fff::5efe:808:808 and 100::5efe:808:808 stay refused. Text with the shape of an address (a colon, or four dotted numbers) that is not well formed (nine groups, two ::, a zone id, brackets, an octet over 255) is refused by the exported strict function; 100:0:0:1::/64 is refused.

Notes for slice 2: accepted URLs keep their query strings, so they land in the manifest and in child process arguments; read the urls file at most maxBytes + 1 bytes before decoding; terminate a partial last manifest line (add a newline) before appending, or the next record joins it; stat or slice the urls file before decoding it; write the running line when a URL starts.

Acceptance criteria of #1231 touched by this slice (none complete alone): the untrusted-urls-file criterion is implemented here for the reader and wired in slice 2; the resume criteria and the record format are implemented here as pure functions and wired in slice 2.

Tests: apps/cli/tests/batch/urls-file.test.ts 29, manifest.test.ts 27, packages/utils/tests/non-public-host-strict.test.ts plus the unchanged non-public-host.test.ts 144. New cases: every special-use range and public neighbour, embedded-IPv4 forms, bare hosts, masked echo (userinfo, http://:pw@host, query, fragment), the rejected cap at 8 MiB of one-character lines, the 2,048 and 2,049 line cap boundary, control characters, grown-URL cap, maxUrls and maxBytes boundaries, manifest validation for each field, 1e999, the line cap, forged and mismatched records, the same-attempt tie, running as crashed. Mutants run one at a time with the file restored after each: 18 classifier mutants (one per family and sub-range), 9 urls-file mutants, 14 manifest mutants, each fails a test. Two survivors are equivalent: removing Number.isFinite from the range check (the range already excludes Infinity and NaN) and removing the huge-line fast path (the line is refused as too long either way; it only avoids a copy).

Gates (one at a time with heavy.sh): the three test files above, bun run lint, bun run format:check, tsgo --noEmit in apps/cli and packages/utils.

Skill: no change needed (no user-facing change yet).

nik

@claude

claude Bot commented Nov 2, 2026

Copy link
Copy Markdown

Reviewed the diff. The slice is well scoped: pure functions, linear scans, caps in constants.ts, and the host check reuses isNonPublicHostname, which already handles IP literals, brackets and zones. I did not run the tests. I found no blocking issues. Notes for this slice or the next:

  • (medium) manifest.ts asRecord: report, finalUrl and key are read back from a file that may have been edited, and are not validated. Slice 2 will probably join report onto the out-dir. Validate here that key matches /^[0-9a-f]{16}$/ and that report is a relative path with no .. and no absolute prefix. Otherwise a tampered manifest can steer file access. It would also be worth checking that key === urlKey(url), or at least deriving the plan from the urls file only.
  • (low) urls-file.ts rejected is unbounded. An 8 MiB file of 1-character lines gives about 4M RejectedUrl objects, since each a is invalid. Cap the stored list (for example 1,000) and keep a count of the rest.
  • (low) parseManifest caps the number of lines but not the length of a line or the size of the content. A single multi-hundred-MB line goes straight to JSON.parse. Add a per-line length cap, and a byte cap on the content before it is read, matching the urls-file reader.
  • (low) latestRecords uses >=, so a duplicated attempt number in the file lets the later line win. That is fine, but a comment would make it explicit.
  • (nit) asRecord calls str() twice per field. A small helper that sets a key only when defined would be tidier.
  • (nit) The 15 s timing assertion in the manifest test could flake on a loaded CI runner. The repo guidance prefers asserting the effect over the elapsed time.

…d echo, caps, validated manifest, spec alignment #1231

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

claude Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #1547 (slice 1: urls-file reader, manifest, strict host classifier). I read the manifest.ts, urls-file.ts and constants.ts changes. I did not read the non-public-host.ts diff or the test files, and I ran no tests.

  • (medium) manifest.ts parseManifest: when the file has more than maxLines lines, it reads only the first ones and sets truncated. Records past the cap are dropped, so planBatch treats those URLs as having no record and re-runs them. A resumed batch could silently repeat finished work. BATCH_URLS allows 100k URLs and each can have several records (running, then final, then retries), so the 1M cap is reachable. Slice 2 should fail the resume on truncated, or read the file tail-first. Please say so in a comment or the docs.
  • (low) manifest.ts planBatch: latestRecords uses attempt >=, so on equal attempts the later line wins. That is right for running then final. A tampered or duplicated line can still override a final status with an older one. This is acceptable for a local file, but worth stating.
  • (low) urls-file.ts redactForEcho: it masks userinfo, query values and the fragment, but not path segments. Tokens in paths (for example /reset/<token>) are echoed into the results file for rejected lines. The doc comment says a results file must never hold a credential, so please soften that wording or document the limit.
  • (low) urls-file.ts parseUrlsFile: Buffer.byteLength(content) runs after the string is decoded, so a 64MB cap does not bound memory. The header says callers must stat first, and slice 2 must enforce that.
  • (nit) isRetryableStatus is a plain alias of isFailedStatus. Either drop it or add a comment on why it is a separate name.
  • (nit) asRecord calls str(r.reason) twice per field; assign each result once.
  • (nit) The isNonPublicHostnameStrict approach of adding a separate function is reasonable. Please confirm that the rules in non-public-host.ts are not duplicated with the shared classifier and instead reuse it.

Overall, no blocking issues found.

…arser-derived, conservative fallback); 3fff /20, ISATAP and residual special-use IPv6; edge tests #1231

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

claude Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of slice 1 (urls file reader, manifest and resume planning, strict host classifier). The code is careful and the untrusted-input handling is good: bounded lines, validated keys and report paths, and masked echoes. I found nothing blocking.

  • (medium) apps/cli/src/batch/manifest.ts parseManifest: when the file exceeds maxLines it keeps the first lines and drops the newest records. In an append-only log those are the ones that decide resume, so a truncated read can re-run URLs that already finished, or miss a running line. Slice 2 must treat truncated: true as a hard error, not a warning. Alternatively, read the tail.
  • (low) manifest.ts: the writer and the reader limits can disagree. formatRecord does not bound field length, but asRecord drops any string over MAX_TEXT (10k) and parseManifest skips any line over 64k chars. A record with a long error or many notes is written but silently skipped on read, so that URL looks unrecorded and is re-run. Clamp fields in formatRecord, or add a bound-check test for the writer.
  • (low) urls-file.ts redactForEcho: userinfo, query values and the fragment are masked, but the path is echoed as written. Tokens in paths (/reset/<token>) would reach a results file. Probably acceptable, but say so in the header comment.
  • (low) isNonPublicHostnameStrict is new shared logic with many IPv6 branches. The test file exists, so please confirm it covers the boundaries: 3fff:fff:: (inside the /20) against 3fff:1000:: (outside), 64:ff9b::808:808 (public), 2002: wrapping private and public IPv4, and a malformed literal. A malformed literal currently falls through as public (ipv6Groups returns undefined). That is fine only because the URL parser rejects them first, so a comment would help.
  • (nit) manifest.ts: isRetryableStatus is a bare alias of isFailedStatus. str(r.reason) and the other str(...) calls are evaluated twice in asRecord, so bind each once.
  • (nit) The CI checks (format, lint, typecheck and docs) were still pending when I looked, so I did not verify them. Per AGENTS.md, the packages/utils change should be checked with the pinned oxfmt and oxlint on the changed files.

…usal, malformed address-shaped text refused, dummy 100:0:0:1::/64; cut-line echo test; header states what is echoed #1231

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

claude Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #1547 (slice 1 of #1231: urls-file reader, manifest and resume planning, strict host classifier). The code reads carefully and the untrusted-input handling matches AGENTS.md. Findings:

  • (medium) apps/cli/tests/batch/urls-file.test.ts: two tests time out at Bun's 5 s limit when I ran bun test ./apps/cli/tests/batch locally: "8 MB of comment lines, of blank lines and of one-character lines" (about 6.4 s) and "the rejected list is capped and counted: 8 MiB of one-character lines" (about 5.9 s). They will probably flake in CI too. AGENTS.md says to shrink the fixture rather than raise the timeout. The in-test toBeLessThan(20_000) bound is looser than the 5 s per-test limit, so it can never be what fails. Use smaller inputs and check that time grows about 4x when the input grows 4x, or assert on the result.
  • (low) apps/cli/src/batch/manifest.ts planBatch: a trailing running record is read as crashed, which is a failed status. Without --retry-failed it is counted in failedKept and not re-run, so the URL in flight when a batch was killed is skipped on the plain re-run. That matches the doc comment, but please confirm it is intended for slice 2 and spell it out in the user docs, since users will expect resume to finish that URL.
  • (low) apps/cli/src/batch/urls-file.ts: the host check is syntactic only. A public-looking hostname that resolves or redirects to a private address is not caught. That is fine for groundwork, but slice 2 should say so in the docs and not rely on this check alone for any hosted caller.
  • (nit) manifest.ts: isRetryableStatus is just an alias of isFailedStatus. Drop it until a caller needs the distinction.
  • (nit) asRecord calls str(r.reason), str(r.startedAt) and similar twice per field. Compute each once.

I read the IPv4 and IPv6 range logic in non-public-host.ts (NAT64, 6to4, Teredo, 3fff::/20, ISATAP, mapped) and found no errors. scripts/test-suites.ts --check passes. Deferring the CHANGELOG, docs and completion is correct, since this slice has no user-visible change.

@nc9

nc9 commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Landed in bundle #1799, rebase-merged to main.

nik

@nc9 nc9 closed this Nov 13, 2026
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.

1 participant