Skip to content

fix(v4): validate the address, and return the string that was validated - #6442

Merged
colinhacks merged 2 commits into
mainfrom
fix/ipv6-address-alphabet
Aug 19, 2026
Merged

colinhacks merged 2 commits into
mainfrom
fix/ipv6-address-alphabet

Conversation

@colinhacks

Copy link
Copy Markdown
Owner

new URL("http://[" + value + "]") parses an authority, not an address. The brackets are just characters in that authority, so @ and \ re-delimit it and the parser validates something else entirely and reports success:

z.ipv6().parse("::@1\\"); // passed β€” new URL() resolved the host to 0.0.0.1
z.ipv6().parse("::]/1");  // passed β€” host resolved to [::]
z.ipv6().parse("::1\n");  // passed β€” the parser deletes the newline before parsing
net.isIPv6("::@1\\");     // false

Guard on the address alphabet instead β€” hex digits, colons and dots, and nothing else. That is exhaustive by construction rather than a list of characters that happen to be special to a borrowed parser, and it lets isValidCIDRv6 delegate to isValidIPv6 instead of carrying its own copy of the call. Scored over 56,638 two-character mutations of five IPv6 seeds against net.isIPv6: 4855 false accepts before, 0 after. The 153 false rejects are zone IDs (fe80::1%eth0), pre-existing and unchanged.

Separately, the URL parser deletes every ASCII tab, LF and CR from its input rather than failing, so z.url() validated one string and handed back another β€” "https://exa\nmple.com" came back verbatim after its host had been checked as example.com, and z.url({ hostname }) and z.url({ protocol }) were defeated the same way. The output now carries the same deletion. Every accept/reject verdict on z.url() is unchanged; only the returned value moves, and only for input the parser rewrote. normalize: true already avoided this by returning url.href, but it costs punycoding, percent-encoding and a trailing slash to get there.

Bundle +29 B gzipped on a classic string fixture, unchanged on zod-mini-string where the constructors tree-shake out, +39 B on a mini fixture that uses all four formats. Memory is unchanged β€” both regexes are module-level and no descriptor moves. No runtime number: the machine sat above load average 19 throughout, so anything measured there would be noise.

Closes #6395. Supersedes #6396, which fixed the tab/newline half by rejecting it and left the @ and \ cases open.

Copilot AI lite review requested due to automatic review settings August 19, 2026 20:50

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No blocking issues. Two minor suggestions inline, one coverage gap below.

Reviewed changes β€” full read of the 3-file diff at 7af04c5, plus independent fuzzing of the new IPv6 guard against net.isIPv6 and an experiment reverting the compile.ts hunk to check whether compiler/interpreter drift is actually caught.

  • IPv6/CIDRv6 alphabet guard β€” ipv6Alphabet (/^[0-9a-fA-F:.]+$/) now runs ahead of the new URL("http://[…]") trick, so @, \, ] and tab/LF/CR can no longer re-delimit the authority and get a different string validated. isValidCIDRv6 drops its duplicate new URL call and delegates to isValidIPv6.
  • z.url() returns the string it validated β€” stripTabAndNewline applies the parser's own tab/LF/CR deletion to the returned value, closing the gap where z.url({ hostname }) checked example.com and handed back a URL naming a different host.
  • Matching AOT emission β€” compile.ts hoists the same helper so the compiled path returns the same value.
  • Regression tests β€” new cases in string.test.ts covering both halves.

Verification I ran: full suite is 7392 passed / 12 skipped (the only 3 failing files are packages/treeshake/* demanding pnpm build, unrelated). pnpm check:comments and biome check are clean on all three files. A 2-character mutation fuzz over five seed addresses crossed with full ASCII at three insertion positions found 0 false accepts after the change; the only false rejects are % zone-ID forms, which the pre-diff code rejected too, so that count is unchanged as the description claims. Adversarial construction inside the permitted alphabet β€” embedded-IPv4 leading zeros, trailing dots, over-long hex pieces, :: compression edge cases, piece-count arithmetic, CIDR prefix splitting against embedded-IPv4 dots β€” matched net.isIPv6 in every case.

Compiler parity for the z.url() output change is genuinely covered: reverting the compile.ts:702-703 hunk alone makes compile-mode packages/zod/src/v4/classic/tests/string.test.ts fail at line 389, since the compile-mode project re-runs the suite AOT-compiled. Good fix, and the alphabet guard is the right shape β€” exhaustive by construction rather than a denylist of characters that happen to be special to a borrowed parser.

ℹ️ The URL differential matrix doesn't exercise the case this PR fixes

compile-differential.test.ts's "url options match the runtime across the whole option matrix" is the test whose own comment declares it "what keeps the two copies honest: a fix to either that the other misses fails here rather than drifting silently, which is exactly how z.creditCard() went wrong". Its inputs array contains no \t/\n/\r, so it never reaches stripTabAndNewline β€” with the compile.ts hunk reverted, all 77 tests still pass. This PR is precisely the class of change that matrix exists to guard, and it caught nothing; the drift is caught only incidentally, by compile-mode re-running string.test.ts.

Technical details
# URL differential matrix is blind to the parser's tab/LF/CR deletion

## Affected sites
- `packages/zod/src/v4/core/tests/compile-differential.test.ts:603-617` β€” the `inputs` array for the URL option matrix contains no ASCII tab, LF or CR, so no schema in the matrix ever exercises the `stripTabAndNewline` branch added at `packages/zod/src/v4/core/compile.ts:702-703`.

## Evidence
Reverting ONLY the `compile.ts:702-703` hunk to its pre-diff form (`const ${outputVar} = trimVar;`) and re-running:
- `compile-differential.test.ts` β†’ 77/77 pass (does not catch the drift)
- `compile-mode packages/zod/src/v4/classic/tests/string.test.ts` β†’ fails at line 389, `expected 'https://exa\nmple.com' to be 'https://example.com'`

So parity IS covered today, but by the wrong test β€” incidentally via the compile-mode project rather than by the tripwire that advertises itself as the guard.

## Required outcome
- The URL differential matrix should fail if the interpreted and compiled URL output paths disagree on input the WHATWG parser rewrites.

## Suggested approach
Add one entry to the `inputs` array, e.g. `"https://exa\nmple.com"`. Every schema in the matrix already covers the option axes, so a single input restores the guarantee across `normalize`, `hostname`, `protocol` and `z.httpUrl()` at once. A `\t` and `\r` variant costs nothing extra if you want the full set.

Pullfrog  | Fix all βž” | Fix πŸ‘s βž” | View workflow run | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/core/schemas.ts Resolved
Comment thread packages/zod/src/v4/core/compile.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

βœ… No new issues found.

Reviewed changes β€” the delta since the prior review at 7af04c5, which is commit f2563feb. It addresses all three points from that review; I re-ran the drift experiment to confirm the coverage fix is real rather than nominal.

  • URL differential matrix now exercises the parser's deletions β€” three inputs added to the inputs array ("https://exa\nmple.com", "https://exa\tmple.com", "https://example.com/a\rb?c=d#e"), covering a host-moving LF, a host-moving tab, and a CR in the path.
  • Docstring narrowed to the claim the change delivers β€” stripTabAndNewline's comment no longer asserts the categorical "returned string == validated string" invariant, and names the C0-control strip as the rewrite it does not cover.
  • addConstant folded into the branch that uses it β€” compile.ts:702-703 no longer registers a constant on the normalize: true path that the emitted function never references.

The coverage fix is verified, not assumed. Reverting only the compile.ts:702-703 hunk on this head now fails compile-differential.test.ts at line 632 (value mismatch at $: expected 'https://exa\nmple.com' to deeply equal 'https://example.com'), where the same experiment passed 77/77 before this commit. That matters more than the input count suggests: the differential harness compares with assertIdentical and requires the fast path to have produced the value, so a compiled path that quietly fell back could not have absorbed the difference. The tripwire whose own comment claims it is "what keeps the two copies honest" now earns that description for this class of change.

The docstring reword is accurate β€” the C0 strip is edge-only, so it genuinely cannot move the host the way an interior tab could, and documenting the residual gap rather than closing it was one of the two outcomes offered. On this head: compile-differential.test.ts and string.test.ts pass 378/378 across the zod, compile-mode and typecheck projects, with pnpm check:comments and biome check clean.

Pullfrog  | View workflow run | Using Claude Opus | 𝕏

`new URL("http://[" + value + "]")` parses an authority, not an IPv6
address. `@` and `\` re-delimit that authority, so the parser validates
something else and reports success: `z.ipv6().parse("::@1\\")` passed
against the host `0.0.0.1`. Guard on the address alphabet instead, which
is exhaustive by construction rather than a list of characters that
happen to be special to a borrowed parser, and let `isValidCIDRv6`
delegate to it instead of carrying its own copy of the call.

The URL parser also deletes ASCII tab, LF and CR from its input rather
than failing, so `z.url()` was validating one string and handing back
another β€” `"https://exa\nmple.com"` came back verbatim after the host had
been checked as `example.com`. Apply the same deletion to the output.
That leaves every accept/reject verdict on `z.url()` as it is today; only
the returned value changes, and only for input the parser rewrote.
The matrix advertises itself as what keeps the interpreted and compiled
URL paths honest, but its inputs carried no ASCII tab, LF or CR, so it
never reached the branch this fix added: reverting the compile.ts hunk
alone left all 231 tests passing. Three inputs restore the guarantee
across normalize, hostname, protocol and z.httpUrl() at once.

Also narrow the stripTabAndNewline docstring, which claimed the returned
string always equals the validated one. That holds for the parser's
deletion pass, not for the leading and trailing C0 controls it strips
and String.prototype.trim() leaves behind, and only the deletion half can
move the host. And fold addConstant into the branch that uses it, so a
normalize: true schema stops registering a constant it never references.
@colinhacks
colinhacks force-pushed the fix/ipv6-address-alphabet branch from f2563fe to 477f75a Compare August 19, 2026 21:22
@colinhacks
colinhacks merged commit 830ba31 into main Aug 19, 2026
7 of 8 checks passed
@colinhacks
colinhacks deleted the fix/ipv6-address-alphabet branch August 19, 2026 21:26

This branch was successfully deployed

1 active deployment
Preview – zod-v4 β€” 477f75aa Deployed Aug 19, 2026 by vercel[bot]
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.

z.url(), z.ipv6() and z.cidrv6() accept ASCII tab/newline because the URL parser deletes them

2 participants