Skip to content

[lexical-playground] Bug Fix: validateUrl no longer accepts a sentence that merely contains a URL - #9097

Merged
etrepum merged 3 commits into
meta:mainfrom
Om-singhaI:fix/validate-url-reject-whitespace
Aug 25, 2026
Merged

etrepum merged 3 commits into
meta:mainfrom
Om-singhaI:fix/validate-url-reject-whitespace

Conversation

@Om-singhaI

@Om-singhaI Om-singhaI commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

validateUrl in packages/lexical-playground/src/utils/url.ts is what the playground hands LinkExtension. It tested urlRegExp, 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". registerLink gates its PASTE_COMMAND listener on that predicate (packages/lexical-link/src/LexicalLinkExtension.ts, if (!validateUrl(clipboardText)) { return false; }), so pasting check out https://example.com today over 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 urlRegExp regresses 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 parser sanitizeUrl uses 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. urlRegExp has 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 returning true from validateUrl with nothing trimmed:

input 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, because String.prototype.trim does 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 host example.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 as isSingleTokenPaste in #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 b no 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. validateUrl now requires parsed.protocol to be one of the five in SUPPORTED_URL_PROTOCOLS: http:, https:, mailto:, sms:, tel:. The old pattern accepted any scheme matching [A-Za-z]{3,9}:, so ftp:, ssh:, irc:, chrome: and about: validated, and so did javascript:, data: and vbscript:.

None of those schemes produced a working link. They can be created today and then render dead: sanitizeUrl in this file rewrites anything outside the same five protocols to about:blank, and so does LinkNode.sanitizeUrl in @lexical/link when the anchor is built (anchor.href = this.sanitizeUrl(this.__url) in updateLinkDOM). Measured, by building the DOM for a LinkNode on each: ftp://example.com/file.txt, ssh://host.example.com and irc://chat.example.com all render href="about:blank" on main. Refusing them at validation is the same outcome, reached before a node exists.

tel: and sms: 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, so tel:+15551234 was rejected while mailto:[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, and formatUrl in @lexical/link turns it into mailto: at render, so the anchor came out as href="mailto:[email protected]". It is not a URL, so it no longer passes here. Typing one still auto links, because the playground registers autoLinkEmailMatcher and that is a separate path. Happy to add a mailto: fallback next to the www. one if you would rather keep it.

ratio:3 stops validating. The old pattern read [A-Za-z]{3,9}: followed by 3 as a host. This is why aspect ratio:3 is best used to make it through.

TOGGLE_LINK_COMMAND consults validateUrl too, so all of the above applies to setting a link from the link editor, not only to paste.

sanitizeUrl is refactored onto the same parseUrl helper. Its behavior is unchanged and the new tests pin it.

Closes #9094

Test plan

packages/lexical-playground/src/__tests__/unit/url.test.ts is rewritten around protocols rather than whitespace. 41 tests. The non string cases stay, because the e2e clipboard stand in returns undefined for a type it was never given and a throw inside the paste listener breaks paste.

expect input why
accept https://example.com plain
accept http://localhost:3000 port
accept https://example.com:8080/path port and path
accept https://en.wikipedia.org/wiki/Foo_(bar) parentheses in the path
accept https://example.com/#/spa/route hash route
accept https://example.com/?a=1,2 comma in the query
accept https://ru.wikipedia.org/wiki/Кириллица non ASCII path
accept www.example.com bare www. host, as before
accept mailto:[email protected] allowlisted protocol
accept tel:+15551234 allowlisted, newly passing
accept sms:+15551234 allowlisted, newly passing
accept https:// the placeholder the link UI seeds
accept "https://example.com\n" copied off its own line, no trim
accept " https://example.com " padded, no trim
accept "\thttps://example.com" padded, no trim
reject check out https://example.com today contains a URL, is not one
reject see https://example.com same
reject https://example.com and then some same
reject just some prose same
reject aspect ratio:3 is best same
reject ratio:3 scheme shaped, is not a URL
reject a b same
reject "https://example.com\nfoo" parser would splice to example.comfoo
reject "https://example.com\nhttps://other.example.com" same
reject "https://exam\tple.com" same
reject https://example.com/a b interior space
reject javascript:alert(1) protocol not allowlisted
reject JaVaScRiPt:alert(1) case does not help
reject data:text/html,hello protocol not allowlisted
reject vbscript:msgbox(1) protocol not allowlisted
reject ftp://example.com/file.txt protocol not allowlisted
reject file:///etc/hosts protocol not allowlisted
reject undefined clipboard stand in, must not throw
reject null same

Plus three sanitizeUrl blocks pinning that the refactor changed nothing: allowlisted protocols pass through unchanged, non allowlisted ones become about: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:

 ❯ |unit| packages/lexical-playground/src/__tests__/unit/url.test.ts (41 tests | 8 failed) 7ms
     × accepts "tel:+15551234" 3ms
     × accepts "sms:+15551234" 0ms
     × rejects "ratio:3" 0ms
     × rejects the unsupported protocol in "javascript:alert(1)" 0ms
     × rejects the unsupported protocol in "JaVaScRiPt:alert(1)" 0ms
     × rejects the unsupported protocol in "data:text/html,hello" 0ms
     × rejects the unsupported protocol in "vbscript:msgbox(1)" 0ms
     × rejects the unsupported protocol in "ftp://example.com/file.txt" 0ms

 Test Files  1 failed (1)
      Tests  8 failed | 33 passed (41)

The same tests against url.ts as it is on main:

 ❯ |unit| packages/lexical-playground/src/__tests__/unit/url.test.ts (41 tests | 16 failed) 7ms
     × accepts "tel:+15551234" 3ms
     × accepts "sms:+15551234" 0ms
     × rejects "check out https://example.com today" 0ms
     × rejects "see https://example.com" 0ms
     × rejects "https://example.com and then some" 0ms
     × rejects "aspect ratio:3 is best" 0ms
     × rejects "ratio:3" 0ms
     × rejects "https://example.com\nfoo", which the parser would otherwise splice 0ms
     × rejects "https://example.com\nhttps://other.example.com", which the parser would otherwise splice 0ms
     × rejects "https://exam\tple.com", which the parser would otherwise splice 0ms
     × rejects "https://example.com/a b", which the parser would otherwise splice 0ms
     × rejects the unsupported protocol in "javascript:alert(1)" 0ms
     × rejects the unsupported protocol in "JaVaScRiPt:alert(1)" 0ms
     × rejects the unsupported protocol in "data:text/html,hello" 0ms
     × rejects the unsupported protocol in "vbscript:msgbox(1)" 0ms
     × rejects the unsupported protocol in "ftp://example.com/file.txt" 0ms

 Test Files  1 failed (1)
      Tests  16 failed | 25 passed (41)

After

 Test Files  1 passed (1)
      Tests  41 passed (41)

vitest run --project unit packages/lexical-playground packages/lexical-link:

 Test Files  34 passed (34)
      Tests  516 passed (516)

Whole unit project, vitest run --project unit:

 Test Files  265 passed (265)
      Tests  4397 passed | 1 skipped (4398)

tsc --noEmit exits 0. eslint and prettier --list-different report 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 @:

n        old urlRegExp (ms)    new validateUrl (ms)
5000     4.11                  0.07
10000    8.24                  0.06
20000    16.49                 0.11
40000    32.63                 0.10
80000    65.08                 0.15

Not run

Browser mode and e2e were not run. I read the paste paths for what this could move. registerLink in packages/lexical-link/src/LexicalLinkExtension.ts only calls the predicate it is configured with and passes the raw clipboard text on to TOGGLE_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.mjs does mention ftp://example.com, as a protocol that must not auto link, and auto linking does not go through validateUrl at all.

…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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 25, 2026
@vercel

vercel Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Aug 25, 2026 7:23am
lexical-playground Ready Ready Preview Aug 25, 2026 7:23am

Request Review

@etrepum

etrepum commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

Why trim at all, is there a use case where spaces should exist before or after the url? A regex with ^ and $ would generally be better for validation.

@Om-singhaI

Copy link
Copy Markdown
Contributor Author

On the trim: 'https://example.com\n' passes on main today, and copying a URL off its own line usually brings the newline with it, so dropping the trim would stop those pastes linking. That is the only case I found that actually needs it. If you would rather not trim, that is fine by me, it costs just that one.

On anchoring, I agree in principle and tried it first. Anchoring the pattern as it stands rejects all of these, which pass today:

http://localhost:3000
https://example.com:8080/path
https://en.wikipedia.org/wiki/Foo_(bar)
https://example.com/#/spa/route
https://example.com/?a=1,2

The host class has no colon, the path class no parentheses and the query class no comma, so $ is never reachable for any of them.

It does work if the character classes are widened at the same time. This one accepts everything above plus mailto: and www. forms, and still rejects the prose cases:

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.

@etrepum

etrepum commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

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.
@Om-singhaI

Copy link
Copy Markdown
Contributor Author

Rewritten. validateUrl is built on new URL() now, and urlRegExp is deleted; it had no other consumer in the repo.

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 sanitizeUrl uses eight lines up. Validation and rendering agree on one protocol list instead of two unrelated rules.

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 LinkNode.sanitizeUrl.

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 "https://example.com\n" resolves to https://example.com/.

Leading whitespace is now rejected. formatUrl prepends a scheme in front of whatever was stored, so " https://example.com" renders as the href "https:// https://example.com", which resolves to nothing, and "\thttps://example.com" renders as a link to the host https. The old pattern accepted both. Nothing that renders dead should validate, so that is the use case answer: after the URL yes, before it no.

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 "https://example.com\nfoo" would parse as the host example.comfoo. That leaves one rule beside the parse, /^\S*\s*$/, anchored, with disjoint classes and nothing to backtrack over.

On narrowing: only the five protocols in SUPPORTED_URL_PROTOCOLS validate now, so ftp:, ssh:, about: and the rest stop, and so does a bare host and port such as localhost:3000, which the parser reads as a scheme and a path. All of those are already about:blank at render through LinkNode.sanitizeUrl, so no working link is lost there.

One working link does get lost, and I'd rather you called it than me: a bare email address. [email protected] matched the old pattern and renders as a real mailto: link, since formatUrl adds that scheme for anything with an at sign. It no longer validates. Typing one still auto links through autoLinkEmailMatcher, so this is paste and the link editor only. Happy to add a mailto: fallback if you want it back.

Two gains: tel: and sms: validate for the first time, since the old pattern wanted a host after the scheme and + is not in its host class.

@etrepum
etrepum added this pull request to the merge queue Aug 25, 2026
Merged via the queue into meta:main with commit 24767ca Aug 25, 2026
48 checks passed
unix-max pushed a commit to unix-max/lexical that referenced this pull request Aug 28, 2026
@etrepum etrepum mentioned this pull request Aug 31, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 49bcb13d Deployed Aug 25, 2026 by vercel[bot]
Preview – lexical-playground — 49bcb13d Deployed Aug 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Autolink with plain text links the selected text when pasted

2 participants