v160 · javascript · regexp

Multiline validation bypass

A settings page takes a hostname allowlist, one per line. Reaching for /^[a-z0-9.-]+$/m feels right — but under m, test() succeeds if any line matches, so one good line smuggles in anything else. Buffer boundaries let one pattern say both “every line looks like this” (^/$) and “nothing else is in the buffer” (\A/\z).

Probing this browser…

Validate an allowlist

Preset inputs
Each validator is a real RegExp.prototype.test() call on the text above
ValidatorPatterntest()Meaning
 

the fix, verbatim

// BYPASSABLE: true if ANY line is a hostname
/^[a-z0-9.-]+$/m.test("example.com\n<img onerror=…>");   // true (!)

// buffer-bounded: every line is a hostname AND nothing else exists
const allowlist = /\A(?:^[a-z0-9.-]+$(?:\r\n|\n)?)+\z/mu;
allowlist.test("example.com\n<img onerror=…>");            // false
allowlist.test("example.com\ncdn.example.com\n");               // true

// single value read from a file: tolerate ONE trailing line break
/\A[a-z0-9.-]+\Z/u.test("example.com\r\n");                     // true
/\A[a-z0-9.-]+\Z/u.test("example.com\nevil");                   // false

Before this feature you could write the same thing with RegExp modifiers, (?-m:^) and (?-m:$). Where the escapes are unavailable the table runs that desugared form and labels the row fallback — it never reports the fallback as the feature.

see also