Skip to content

Commit

Permalink
Fix double encoding in new url transform
Browse files Browse the repository at this point in the history
Closes GH-797.
  • Loading branch information
wooorm committed Nov 13, 2023
1 parent 55d8d83 commit d8e3787
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
24 changes: 22 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@
import {unreachable} from 'devlop'
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {urlAttributes} from 'html-url-attributes'
import {sanitizeUri} from 'micromark-util-sanitize-uri'
// @ts-expect-error: untyped.
import {Fragment, jsx, jsxs} from 'react/jsx-runtime'
import remarkParse from 'remark-parse'
Expand Down Expand Up @@ -297,5 +296,26 @@ export function Markdown(options) {
* Safe URL.
*/
export function defaultUrlTransform(value) {
return sanitizeUri(value, safeProtocol)
// Same as:
// <https://github.com/micromark/micromark/blob/929275e/packages/micromark-util-sanitize-uri/dev/index.js#L34>
// But without the `encode` part.
const colon = value.indexOf(':')
const questionMark = value.indexOf('?')
const numberSign = value.indexOf('#')
const slash = value.indexOf('/')

if (
// If there is no protocol, it’s relative.
colon < 0 ||
// If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.
(slash > -1 && colon > slash) ||
(questionMark > -1 && colon > questionMark) ||
(numberSign > -1 && colon > numberSign) ||
// It is a protocol, it should be allowed.
safeProtocol.test(value.slice(0, colon))
) {
return value
}

return ''
}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@
"hast-util-to-jsx-runtime": "^2.0.0",
"html-url-attributes": "^3.0.0",
"mdast-util-to-hast": "^13.0.0",
"micromark-util-sanitize-uri": "^2.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.0.0",
"unified": "^11.0.0",
Expand Down
7 changes: 7 additions & 0 deletions test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,13 @@ test('react-markdown', async function (t) {
)
})

await t.test('should support hash (`&`) in a URL', function () {
assert.equal(
asHtml(<Markdown children="[](a?b&c=d)" />),
'<p><a href="a?b&amp;c=d"></a></p>'
)
})

await t.test('should support hash (`#`) in a URL', function () {
assert.equal(
asHtml(<Markdown children="[](a#javascript:alert(1))" />),
Expand Down

0 comments on commit d8e3787

Please sign in to comment.