Repository navigation
[lexical-playground] Bug Fix: validateUrl no longer accepts a sentence that merely contains a URL - #9097
Conversation
…e that merely contains a URL urlRegExp is unanchored, so urlRegExp.test(url) answers "does this string contain something URL shaped" rather than "is this string a URL". Pasting "check out https://example.com today" over a selection satisfies the LinkExtension paste gate, and the whole sentence becomes the href. Anchoring the pattern with ^ and $ is the obvious fix and it regresses real URLs. The host class has no colon, the path class has no parentheses and the query class has no comma, so $ is unreachable for http://localhost:3000, https://example.com:8080/path, https://en.wikipedia.org/wiki/Foo_(bar), https://example.com/#/spa/route and https://example.com/?a=1,2, every one of which validates today. A URL cannot contain raw whitespace, so rejecting any trimmed input that holds whitespace is enough to turn "contains a URL" into "is a URL". The trim is deliberate: copying a URL off its own line carries a trailing newline along with it, and that still has to link.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Why trim at all, is there a use case where spaces should exist before or after the url? A regex with |
|
On the trim: On anchoring, I agree in principle and tried it first. Anchoring the pattern as it stands rejects all of these, which pass today: The host class has no colon, the path class no parentheses and the query class no comma, so It does work if the character classes are widened at the same time. This one accepts everything above plus const urlRegExp = new RegExp(
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]{1,256}@)?[A-Za-z0-9.-]{1,256}(?::\d{1,5})?|(?:www\.|[-;:&=+$,\w]{1,256}@)[A-Za-z0-9.-]{1,256}(?::\d{1,5})?)((?:\/[+~%/.\w\-_()',]{0,256})?\??(?:[-+=&;%@.\w_/,~()]{0,256})#?(?:[\w\-/.]{0,256}))?)/,
);Happy to switch to that if you would rather validation were the pattern's job than a separate guard. It is a bigger change to something you tuned for linear time matching, so I did not want to make that call unasked. |
…rd returns a non string
|
It’s really not worth making partial marginal fixes, if we’re taking the time to make an improvement it should be to the best known possible state unless there are significant tradeoffs. Here it seems straightforward to write the regex correctly to validate URLs in an anchored way without ReDoS issues. |
…ad of a pattern validateUrl tested a borrowed StackOverflow pattern that is unanchored, so it answered "does this string contain something URL shaped" rather than "is this string a URL". Anchoring that pattern rejects ports, parenthesised paths and hash routes, and the earlier commits on this branch worked around it with a whitespace guard, which left the pattern itself unfixed and added a trim. new URL() is the anchored answer. It consumes the whole string or throws, it has no backtracking to blow up on, and it is already the parser sanitizeUrl uses eight lines above to decide which protocols may be rendered. Validation and rendering now agree on one list instead of two rules. Nothing is rewritten before parsing, so the string that validates is the string the caller stores as the href. That settles the trim question by measuring what each kind of padding renders as. Trailing whitespace stays valid. A URL copied off its own line carries a newline, and the URL parser and the href attribute both ignore it, so the link resolves to the URL. Leading whitespace is now rejected. formatUrl in @lexical/link prepends a scheme in front of whatever was stored, so " https://example.com" becomes the href "https:// https://example.com", which resolves to nothing, and a leading tab becomes a link to the host "https". The old pattern accepted both. Interior whitespace stays rejected, because the parser deletes every ASCII tab and newline anywhere in its input: a two line paste of https://example.com and foo would otherwise parse as the single host example.comfoo. Behavior changes worth naming: tel: and sms: now validate. Both are on the supported protocol list, but the old pattern wanted a host after the scheme and + was not in its host class. javascript:, data: and vbscript: no longer validate, and neither do ftp:, ssh: and other schemes outside the allowlist. A bare host and port with no scheme goes the same way, since localhost:3000 and www.example.com:8080 are a scheme and a path to the parser. All of these can be linked today and then render dead: LinkNode.sanitizeUrl in @lexical/link rewrites anything outside the same five protocols to about:blank when the anchor is built. One working link is lost. A bare email address such as [email protected] matched the old pattern and renders as a mailto: link, because formatUrl prepends that scheme for anything containing an at sign. It no longer validates. Typing one still auto links. A space inside a path no longer validates either. The parser would percent encode it, but that is the same leniency that splices the two line paste, so one rule covers both. urlRegExp has no other consumer in the repo and is deleted.
|
Rewritten. The parser consumes the whole string or throws, so it is anchored by construction with nothing to backtrack over, and it is the same parser On the trim: there isn't one now, and the answer to your question turned out to differ at the two ends. Nothing is rewritten before parsing, so the string that validates is the string the caller stores as the href, and I measured what each kind of padding renders as through Trailing whitespace stays valid. A URL copied off its own line carries a newline, and both the URL parser and the href attribute ignore it, so Leading whitespace is now rejected. Interior whitespace still has to be rejected here rather than left to the parser, which deletes every ASCII tab and newline anywhere in its input, so On narrowing: only the five protocols in One working link does get lost, and I'd rather you called it than me: a bare email address. Two gains: |
…e that merely contains a URL (meta#9097)
Description
validateUrlinpackages/lexical-playground/src/utils/url.tsis what the playground handsLinkExtension. It testedurlRegExp, a pattern copied from StackOverflow, and that pattern is unanchored, so it answered "does this string contain something URL shaped" rather than "is this string a URL".registerLinkgates itsPASTE_COMMANDlistener on that predicate (packages/lexical-link/src/LexicalLinkExtension.ts,if (!validateUrl(clipboardText)) { return false; }), so pastingcheck out https://example.com todayover a selection made the whole sentence the href.The first pass at this kept the pattern and rejected any input holding whitespace. Reviewing, @etrepum asked why the input was trimmed at all and said an anchored pattern would be the better validator. Anchoring
urlRegExpregresses ports, parenthesised paths and hash routes, so the answer is not a better pattern. It is no pattern.new URL()parses the whole string or throws. It is anchored by construction, it has no backtracking to blow up on, and it is already the parsersanitizeUrluses eight lines above in the same file to decide which protocols may be rendered. Validation and rendering now agree on one list instead of running two unrelated rules.urlRegExphas no other consumer in the repo and is deleted, along with its StackOverflow comment block.On the trim
There is no trim any more, and no need for one. The WHATWG URL parser ignores leading and trailing C0 control characters and spaces, so
'https://example.com\n'and' https://example.com 'both parse without help. That is the case that motivated the trim in the first place, a URL copied off its own line, and the parser covers it for free. Measured, all rows returningtruefromvalidateUrlwith nothing trimmed:new URL(input).href"https://example.com\n"https://example.com/" https://example.com "https://example.com/"\thttps://example.com"https://example.com/"\rhttps://example.com\r"https://example.com/"\u0000https://example.com"https://example.com/Non ASCII whitespace is not in that set.
"\u00A0https://example.com", a non breaking space in front, throws and is rejected. It was accepted before, becauseString.prototype.trimdoes strip U+00A0 and the raw padded string then became the href anyway. Rejecting it is the better answer.One thing the parser is too lenient about
The parser deletes every ASCII tab and newline anywhere in its input, not only at the ends. So
new URL('https://example.com\nfoo')succeeds and yields the hostexample.comfoo, and a two line paste would become a link to a host that appears nowhere in what the user pasted. That is the same defect this PR exists to fix, so it is closed here rather than left to the parser.The rule is that the input has to be one whitespace free token:
/^\s*(\S*)\s*$/. Both quantifiers are anchored and match disjoint character classes, so no input makes them backtrack. This is the same single token shape asisSingleTokenPastein #9091, which gates the auto embed menu; the two are independent, that one decides whether the embed menu opens and this one decides whether a link is created at all.A side effect worth stating:
https://example.com/a bno longer validates. The parser would accept it and percent encode the space, and the string arguably is a URL. But it is accepted by the same leniency that splices the two line paste above, and one rule covering both is worth more than the case it costs.Behavior changes
Stated plainly, because they are real.
Protocols narrow to the allowlist.
validateUrlnow requiresparsed.protocolto be one of the five inSUPPORTED_URL_PROTOCOLS:http:,https:,mailto:,sms:,tel:. The old pattern accepted any scheme matching[A-Za-z]{3,9}:, softp:,ssh:,irc:,chrome:andabout:validated, and so didjavascript:,data:andvbscript:.None of those schemes produced a working link. They can be created today and then render dead:
sanitizeUrlin this file rewrites anything outside the same five protocols toabout:blank, and so doesLinkNode.sanitizeUrlin@lexical/linkwhen the anchor is built (anchor.href = this.sanitizeUrl(this.__url)inupdateLinkDOM). Measured, by building the DOM for aLinkNodeon each:ftp://example.com/file.txt,ssh://host.example.comandirc://chat.example.comall renderhref="about:blank"on main. Refusing them at validation is the same outcome, reached before a node exists.tel:andsms:start validating. Both are on the supported list, but the old pattern wanted a host after the scheme and+was not in its host class, sotel:+15551234was rejected whilemailto:[email protected]was accepted. That inconsistency goes away.A bare email address stops validating. This is the one case that did work and now does not.
[email protected]matched the old pattern's@alternative, andformatUrlin@lexical/linkturns it intomailto:at render, so the anchor came out ashref="mailto:[email protected]". It is not a URL, so it no longer passes here. Typing one still auto links, because the playground registersautoLinkEmailMatcherand that is a separate path. Happy to add amailto:fallback next to thewww.one if you would rather keep it.ratio:3stops validating. The old pattern read[A-Za-z]{3,9}:followed by3as a host. This is whyaspect ratio:3 is bestused to make it through.TOGGLE_LINK_COMMANDconsultsvalidateUrltoo, so all of the above applies to setting a link from the link editor, not only to paste.sanitizeUrlis refactored onto the sameparseUrlhelper. Its behavior is unchanged and the new tests pin it.Closes #9094
Test plan
packages/lexical-playground/src/__tests__/unit/url.test.tsis rewritten around protocols rather than whitespace. 41 tests. The non string cases stay, because the e2e clipboard stand in returnsundefinedfor a type it was never given and a throw inside the paste listener breaks paste.https://example.comhttp://localhost:3000https://example.com:8080/pathhttps://en.wikipedia.org/wiki/Foo_(bar)https://example.com/#/spa/routehttps://example.com/?a=1,2https://ru.wikipedia.org/wiki/Кириллицаwww.example.comwww.host, as beforemailto:[email protected]tel:+15551234sms:+15551234https://"https://example.com\n"" https://example.com ""\thttps://example.com"check out https://example.com todaysee https://example.comhttps://example.com and then somejust some proseaspect ratio:3 is bestratio:3a b"https://example.com\nfoo"example.comfoo"https://example.com\nhttps://other.example.com""https://exam\tple.com"https://example.com/a bjavascript:alert(1)JaVaScRiPt:alert(1)data:text/html,hellovbscript:msgbox(1)ftp://example.com/file.txtfile:///etc/hostsundefinednullPlus three
sanitizeUrlblocks pinning that the refactor changed nothing: allowlisted protocols pass through unchanged, non allowlisted ones becomeabout:blank, and unparseable input comes back as it went in.Before
The new tests against the previous commit on this branch, the whitespace guard version,
vitest run --project unit packages/lexical-playground/src/__tests__/unit/url.test.ts:The same tests against
url.tsas it is on main:After
vitest run --project unit packages/lexical-playground packages/lexical-link:Whole unit project,
vitest run --project unit:tsc --noEmitexits 0.eslintandprettier --list-differentreport nothing on the two changed files.Backtracking
The pattern on main is already capped at
{1,256}per run, so it is linear, and this is not a ReDoS fix. It is worth recording anyway that the parser has no backtracking at all, and is faster on the input the caps were added for, a long run of word characters with no@:Not run
Browser mode and e2e were not run. I read the paste paths for what this could move.
registerLinkinpackages/lexical-link/src/LexicalLinkExtension.tsonly calls the predicate it is configured with and passes the raw clipboard text on toTOGGLE_LINK_COMMAND; it does not depend on any particular scheme being accepted, and both of its own test files supply their own validators rather than the playground's.packages/lexical-playground/__tests__/e2e/AutoLinks.spec.mjsdoes mentionftp://example.com, as a protocol that must not auto link, and auto linking does not go throughvalidateUrlat all.