This commit is contained in:
Javier Casares 2026-11-04 17:27:19 +00:00
commit 121c35737d
18 changed files with 1398 additions and 2198 deletions

View file

@ -6,6 +6,56 @@ Updates should follow the [Keep a CHANGELOG](https://keepachangelog.com/) princi
## [Unreleased][unreleased]
## [2.10.7] - 2026-10-31
### Fixed
- Fixed `AutolinkExtension` keeping trailing punctuation inside very long URLs containing long runs of punctuation, and removed the excessive regex backtracking that caused it (#1170)
## [2.10.6] - 2026-10-30
### Fixed
- Fixed `ExternalLinkExtension` not treating some links as external when browsers would navigate to an external host, such as `https:///example.com`, `http:example.com`, or `///example.com`; hosts are now determined the way browsers do (#1169)
## [2.10.5] - 2026-10-30
### Fixed
- Fixed link reference definitions keeping a partially parsed title when the title on the following line is never closed or is followed by other text; the definition now has no title, as the spec requires (#1162)
- Fixed task list items being recognized when the `[ ]` or `[x]` marker is directly followed by other content (`- [x]done`); the GFM spec requires whitespace after the marker (#1164)
- Fixed the content indentation of a list item whose content is a single character after two to four spaces (`- a`): it was computed as if one space followed the marker, so the next line could be read as part of the item, nesting a following item inside it (#1163)
- Fixed a table inside a block quote or list item absorbing the lines that follow it as table rows when those lines are lazy continuation lines (not prefixed with `>` or indented); they now end the container as in GitHub's `cmark-gfm` (#1165)
- Fixed link reference definitions accepting an unescaped `(` inside a parenthesized title (#1168)
## [2.10.4] - 2026-10-17
### Fixed
- Fixed `HeadingPermalinkExtension` overwriting an `id` set on a heading by the `AttributesExtension` when `heading_permalink/apply_id_to_heading` is enabled; the existing `id` is now used (with the configured prefix) for both the heading and its permalink (#1159, #1160)
- Fixed Symfony `DebugClassLoader` deprecation notice about `ArrayCollection::offsetGet()` by adding an explicit `@return` annotation (#1158)
## [2.10.3] - 2026-09-21
### Fixed
- Fixed footnote links and backlinks pointing at the wrong anchor when `footnote/footnote_id_prefix` or `footnote/ref_id_prefix` contains an uppercase character; the configured prefix is now emitted verbatim in the `href` as it already was in the matching `id` (#524)
- Fixed inline raw HTML tags being escaped when the tag name or an attribute name contains an uppercase letter, such as `<svg viewBox="...">` or `<Warning>` (#1096)
## [2.10.2] - 2026-09-21
This is a **security release** to address a denial of service vulnerability in the `Table` extension and a raw HTML filtering bypass in the `DisallowedRawHtml` extension.
### Changed
- Improved performance of parsing table delimiter rows and splitting table rows into cells by scanning bytes directly instead of stepping a `Cursor` (roughly 4x faster for delimiter rows and 6x for cell splitting, and more on multibyte rows)
### Fixed
- Fixed `DisallowedRawHtmlRenderer` not blocking raw HTML that ends with a disallowed tag name, such as a line containing only `<script` (GHSA-97jj-33gv-5xf9)
- Fixed quadratic-time parsing of long paragraphs when the `Table` extension is enabled (GHSA-3q6v-r5mr-hxv8)
- Fixed table detection to match the GFM spec and reference implementation:
- Header rows no longer require a `|` character
- Header rows must now have the same number of cells as the delimiter row (previously, fewer cells were accepted)
## [2.10.1] - 2026-09-07
### Fixed
- Accept `unordered_list_markers` config in InlinesOnlyExtension (#1015, #1151)
## [2.10.0] - 2026-08-11
This is a **security release** to address a denial of service vulnerability in the `AttributesExtension`.
@ -834,7 +884,14 @@ No changes were introduced since the previous release.
- Alternative 1: Use `CommonMarkConverter` or `GithubFlavoredMarkdownConverter` if you don't need to customize the environment
- Alternative 2: Instantiate a new `Environment` and add the necessary extensions yourself
[unreleased]: https://github.com/thephpleague/commonmark/compare/2.10.0...HEAD
[unreleased]: https://github.com/thephpleague/commonmark/compare/2.10.7...HEAD
[2.10.7]: https://github.com/thephpleague/commonmark/compare/2.10.6...2.10.7
[2.10.6]: https://github.com/thephpleague/commonmark/compare/2.10.5...2.10.6
[2.10.5]: https://github.com/thephpleague/commonmark/compare/2.10.4...2.10.5
[2.10.4]: https://github.com/thephpleague/commonmark/compare/2.10.3...2.10.4
[2.10.3]: https://github.com/thephpleague/commonmark/compare/2.10.2...2.10.3
[2.10.2]: https://github.com/thephpleague/commonmark/compare/2.10.1...2.10.2
[2.10.1]: https://github.com/thephpleague/commonmark/compare/2.10.0...2.10.1
[2.10.0]: https://github.com/thephpleague/commonmark/compare/2.9.2...2.10.0
[2.9.2]: https://github.com/thephpleague/commonmark/compare/2.9.1...2.9.2
[2.9.1]: https://github.com/thephpleague/commonmark/compare/2.9.0...2.9.1

View file

@ -133,7 +133,7 @@ When a new **major** version is released (e.g. `1.6` -> `2.0`), the previous one
## 👷‍♀️ Contributing
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure with us.
To report a security vulnerability, please see our [security policy](.github/SECURITY.md).
If you encounter a bug in the spec, please report it to the [CommonMark] project. Any resulting fix will eventually be implemented in this project as well.

View file

@ -107,13 +107,8 @@ final class UrlAutolinkParser implements InlineParserInterface
return false;
}
$url = $matches[0];
// Does the URL end with punctuation that should be stripped?
if (\preg_match('/(.+?)([?!.,:*_~]+)$/', $url, $matches)) {
// Add the punctuation later
$url = $matches[1];
}
// Strip trailing punctuation; it's left on the cursor to be parsed as text
$url = \rtrim($matches[0], '?!.,:*_~');
// Does the URL end with something that looks like an entity reference?
if (\preg_match('/(.+)(&[A-Za-z0-9]+;)$/', $url, $matches)) {

View file

@ -123,7 +123,7 @@ final class ListBlockStartParser implements BlockStartParserInterface, Configura
}
}
$blankItem = $cursor->peek() === null;
$blankItem = $cursor->isAtEnd();
$spacesAfterMarker = $cursor->getColumn() - $spacesStartCol;
if ($spacesAfterMarker >= 5 || $spacesAfterMarker < 1 || $blankItem) {

View file

@ -45,9 +45,11 @@ final class DisallowedRawHtmlRenderer implements NodeRendererInterface, Configur
return $rendered;
}
$regex = \sprintf('/<(\/?(?:%s)[\s\/>])/i', \implode('|', \array_map('preg_quote', $tags)));
// The tag name may also end the rendered HTML: the block parser accepts a bare
// `<script` line, and browsers treat the following block as its attributes.
$regex = \sprintf('/<(\/?(?:%s)(?:[\s\/>]|$))/i', \implode('|', \array_map('preg_quote', $tags)));
// Match these types of tags: <title> </title> <title x="sdf"> <title/> <title />
// Match these types of tags: <title> </title> <title x="sdf"> <title/> <title /> <title
return \preg_replace($regex, '&lt;$1', $rendered);
}

View file

@ -43,9 +43,9 @@ final class ExternalLinkProcessor
continue;
}
$host = \parse_url($link->getUrl(), PHP_URL_HOST);
if (! \is_string($host)) {
// Something is terribly wrong with this URL
$host = self::getHost($link->getUrl());
if ($host === null) {
// Relative links and non-network schemes like mailto: have no host to compare
continue;
}
@ -97,6 +97,28 @@ final class ExternalLinkProcessor
}
}
/**
* Determines which host a browser would navigate to, which parse_url() doesn't always agree with
* on its own (for example, it finds no host in "https:///example.com" or "///example.com")
*/
private static function getHost(string $url): ?string
{
// Browsers ignore these characters, so links not created by the parser could use them to obscure the host
$url = \str_replace(["\t", "\n", "\r"], '', \trim($url, "\x00..\x20"));
// For these "special" schemes (and scheme-relative URLs), browsers accept any number of slashes before the
// host, even none, and treat "\" like "/". parse_url() needs exactly "//", so we rewrite the URL to match.
// Without slashes ("https:example.com") a browser may instead resolve the URL relative to the current page,
// but we can't know the page's scheme, so we assume the worst and treat it as a host.
if (\preg_match('~^(?:(?:https?|ftp|wss?):|(?=[/\\\\]{2}))~i', $url, $matches) === 1) {
$url = '//' . \ltrim(\strtr(\substr($url, \strlen($matches[0])), '\\', '/'), '/');
}
$host = \parse_url($url, PHP_URL_HOST);
return \is_string($host) && $host !== '' ? $host : null;
}
/**
* @internal This method is only public so we can easily test it. DO NOT USE THIS OUTSIDE OF THIS EXTENSION!
*

View file

@ -44,7 +44,13 @@ final class FootnoteBackrefRenderer implements NodeRendererInterface, XmlNodeRen
$attrs->append('class', $this->config->get('footnote/backref_class'));
$attrs->set('rev', 'footnote');
$attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8'));
// The configured prefix is emitted verbatim in the target's id, so only lowercase the label.
$destination = $node->getReference()->getDestination();
$hrefPrefix = '#' . $this->config->get('footnote/ref_id_prefix');
$href = \strncmp($destination, $hrefPrefix, \strlen($hrefPrefix)) === 0
? $hrefPrefix . \mb_strtolower(\substr($destination, \strlen($hrefPrefix)), 'UTF-8')
: \mb_strtolower($destination, 'UTF-8');
$attrs->set('href', $href);
$attrs->set('role', 'doc-backlink');
$symbol = $this->config->get('footnote/backref_symbol');

View file

@ -40,7 +40,13 @@ final class FootnoteRefRenderer implements NodeRendererInterface, XmlNodeRendere
$attrs = $node->data->getData('attributes');
$attrs->append('class', $this->config->get('footnote/ref_class'));
$attrs->set('href', \mb_strtolower($node->getReference()->getDestination(), 'UTF-8'));
// The configured prefix is emitted verbatim in the target's id, so only lowercase the label.
$destination = $node->getReference()->getDestination();
$hrefPrefix = '#' . $this->config->get('footnote/footnote_id_prefix');
$href = \strncmp($destination, $hrefPrefix, \strlen($hrefPrefix)) === 0
? $hrefPrefix . \mb_strtolower(\substr($destination, \strlen($hrefPrefix)), 'UTF-8')
: \mb_strtolower($destination, 'UTF-8');
$attrs->set('href', $href);
$attrs->set('role', 'doc-noteref');
$idPrefix = $this->config->get('footnote/ref_id_prefix');

View file

@ -74,6 +74,10 @@ final class HeadingPermalinkProcessor implements EnvironmentAwareInterface
]);
if ($applyToHeading) {
if ($heading->data->has('attributes/id')) {
$slug = $heading->data->get('attributes/id');
}
$heading->data->set('attributes/id', $idPrefix . $slug);
}

View file

@ -30,6 +30,7 @@ final class InlinesOnlyExtension implements ConfigurableExtensionInterface
'use_underscore' => Expect::bool(true),
'enable_strong' => Expect::bool(true),
'enable_em' => Expect::bool(true),
'unordered_list_markers' => Expect::listOf('string')->min(1)->default(['*', '+', '-'])->mergeDefaults(false),
]));
}

View file

@ -61,6 +61,13 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
private int $remainingAutocompletedCells;
/**
* Whether the current line may be added to the table as a lazy continuation line
*
* @psalm-readonly-allow-private-mutation
*/
private bool $canHaveLazyContinuationLines = false;
/**
* @param array<int, string|null> $columns
* @param array<int, string> $headerCells
@ -80,7 +87,7 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
public function canHaveLazyContinuationLines(): bool
{
return true;
return $this->canHaveLazyContinuationLines;
}
public function getBlock(): Table
@ -90,7 +97,11 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
public function tryContinue(Cursor $cursor, BlockContinueParserInterface $activeBlockParser): ?BlockContinue
{
if (\strpos($cursor->getLine(), '|') === false) {
// A line without a pipe can still become a row via lazy continuation. This is only reached when all
// enclosing containers matched; lines whose containers didn't match must not be added lazily.
$this->canHaveLazyContinuationLines = \strpos($cursor->getLine(), '|') === false;
if ($this->canHaveLazyContinuationLines) {
return BlockContinue::none();
}
@ -99,6 +110,8 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
public function addLine(string $line): void
{
$this->canHaveLazyContinuationLines = false;
if ($this->nextIsSeparatorLine) {
$this->nextIsSeparatorLine = false;
} else {
@ -168,24 +181,28 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
*/
public static function split(string $line): array
{
$cursor = new Cursor(\trim($line));
// Scan raw bytes: the only significant characters are ASCII, and copying the other bytes through one at a
// time reassembles multibyte sequences unchanged. This is several times faster than stepping a Cursor.
$line = \trim($line);
$length = \strlen($line);
if ($cursor->getCurrentCharacter() === '|') {
$cursor->advanceBy(1);
$i = 0;
if ($length > 0 && $line[0] === '|') {
$i = 1;
}
$cells = [];
$sb = '';
while (! $cursor->isAtEnd()) {
switch ($c = $cursor->getCurrentCharacter()) {
for (; $i < $length; $i++) {
switch ($c = $line[$i]) {
case '\\':
if ($cursor->peek() === '|') {
if ($i + 1 < $length && $line[$i + 1] === '|') {
// Pipe is special for table parsing. An escaped pipe doesn't result in a new cell, but is
// passed down to inline parsing as an unescaped pipe. Note that that applies even for the `\|`
// in an input like `\\|` - in other words, table parsing doesn't support escaping backslashes.
$sb .= '|';
$cursor->advanceBy(1);
$i++;
} else {
// Preserve backslash before other characters or at end of line.
$sb .= '\\';
@ -199,8 +216,6 @@ final class TableParser extends AbstractBlockContinueParser implements BlockCont
default:
$sb .= $c;
}
$cursor->advanceBy(1);
}
if ($sb !== '') {

View file

@ -33,10 +33,12 @@ final class TableStartParser implements BlockStartParserInterface
public function tryStart(Cursor $cursor, MarkdownParserStateInterface $parserState): ?BlockStart
{
$paragraph = $parserState->getParagraphContent();
if ($paragraph === null || \strpos($paragraph, '|') === false) {
if ($paragraph === null) {
return BlockStart::none();
}
// Check the (short) current line for a delimiter row before touching the paragraph content. Scanning the
// paragraph on every line would be quadratic, and GFM does not require a pipe in the header row anyway.
$columns = self::parseSeparator($cursor);
if (\count($columns) === 0) {
return BlockStart::none();
@ -45,8 +47,9 @@ final class TableStartParser implements BlockStartParserInterface
$lastLineBreak = \strrpos($paragraph, "\n");
$lastLine = $lastLineBreak === false ? $paragraph : \substr($paragraph, $lastLineBreak + 1);
// Per the GFM spec, the header row must have the same number of cells as the delimiter row
$headerCells = TableParser::split($lastLine);
if (\count($headerCells) > \count($columns)) {
if (\count($headerCells) !== \count($columns)) {
return BlockStart::none();
}
@ -76,14 +79,20 @@ final class TableStartParser implements BlockStartParserInterface
*/
private static function parseSeparator(Cursor $cursor): array
{
// Scan the raw bytes rather than stepping the Cursor: every character allowed in a delimiter row is ASCII,
// so any multibyte character is simply invalid, and byte indexing avoids the per-character method calls
// (and, on multibyte lines, the character-to-byte offset translation) that the Cursor incurs.
$line = $cursor->getRemainder();
$length = \strlen($line);
$columns = [];
$pipes = 0;
$valid = false;
while (! $cursor->isAtEnd()) {
switch ($c = $cursor->getCurrentCharacter()) {
for ($i = 0; $i < $length;) {
switch ($c = $line[$i]) {
case '|':
$cursor->advanceBy(1);
$i++;
$pipes++;
if ($pipes > 1) {
// More than one adjacent pipe not allowed
@ -104,17 +113,20 @@ final class TableStartParser implements BlockStartParserInterface
$right = false;
if ($c === ':') {
$left = true;
$cursor->advanceBy(1);
$i++;
}
if ($cursor->matchInPlace('/\G-+/') === null) {
$dashes = \strspn($line, '-', $i);
if ($dashes === 0) {
// Need at least one dash
return [];
}
if ($cursor->getCurrentCharacter() === ':') {
$i += $dashes;
if ($i < $length && $line[$i] === ':') {
$right = true;
$cursor->advanceBy(1);
$i++;
}
$columns[] = self::getAlignment($left, $right);
@ -124,7 +136,7 @@ final class TableStartParser implements BlockStartParserInterface
case ' ':
case "\t":
// White space is allowed between pipes and columns
$cursor->advanceToNextNonSpaceOrTab();
$i += \strspn($line, " \t", $i);
break;
default:
// Any other character is invalid

View file

@ -18,6 +18,7 @@ use League\CommonMark\Node\Block\Paragraph;
use League\CommonMark\Parser\Inline\InlineParserInterface;
use League\CommonMark\Parser\Inline\InlineParserMatch;
use League\CommonMark\Parser\InlineParserContext;
use League\CommonMark\Util\RegexHelper;
final class TaskListItemMarkerParser implements InlineParserInterface
{
@ -40,7 +41,9 @@ final class TaskListItemMarkerParser implements InlineParserInterface
$cursor->advanceBy(3);
if ($cursor->getNextNonSpaceCharacter() === null) {
// The marker must be followed by whitespace before any other content
$nextCharacter = $cursor->getCurrentCharacter();
if ($nextCharacter === null || ! RegexHelper::isWhitespace($nextCharacter) || $cursor->getNextNonSpaceCharacter() === null) {
$cursor->restoreState($oldState);
return false;

View file

@ -38,7 +38,11 @@ interface BlockContinueParserInterface
public function isContainer(): bool;
/**
* Return whether we are interested in possibly lazily parsing any subsequent lines
* Return whether the current line may be added to this block even though it wasn't continued by tryContinue()
*
* This is checked per line, after tryContinue() (which is skipped if an enclosing container did not match), so
* the answer may depend on the current line. Block start parsers may also consult it to decide whether a new
* block can interrupt this one.
*/
public function canHaveLazyContinuationLines(): bool;

View file

@ -76,6 +76,11 @@ final class ReferenceParser
*/
public function getReferences(): iterable
{
if ($this->referenceValid && $this->state === self::TITLE) {
// The title was never closed, so the definition has no title
$this->title = '';
}
$this->finishReference();
return $this->references;
@ -268,7 +273,9 @@ final class ReferenceParser
$title = LinkParserHelper::parsePartialLinkTitle($cursor, $this->titleDelimiter);
if ($title === null) {
// Invalid title, stop
// Invalid title, stop. The title collected so far must not be used.
$this->title = '';
return false;
}
@ -293,6 +300,9 @@ final class ReferenceParser
$cursor->advanceToNextNonSpaceOrTab();
if (! $cursor->isAtEnd()) {
// spec: No further non-whitespace characters may occur on the line.
// The title collected so far must not be used.
$this->title = '';
return false;
}

View file

@ -106,6 +106,8 @@ final class ArrayCollection implements \IteratorAggregate, \Countable, \ArrayAcc
*
* @phpstan-param int $offset
*
* @return mixed|null
*
* @phpstan-return T|null
*/
#[\ReturnTypeWillChange]

View file

@ -82,8 +82,10 @@ final class LinkParserHelper
public static function parsePartialLinkTitle(Cursor $cursor, string $endDelimiter): ?string
{
// spec: a parenthesized title may only contain `(` or `)` if backslash-escaped
$excluded = \preg_quote($endDelimiter === ')' ? '()' : $endDelimiter, '/');
$endDelimiter = \preg_quote($endDelimiter, '/');
$regex = \sprintf('/(%s|[^%s\x00])*(?:%s)?/', RegexHelper::PARTIAL_ESCAPED_CHAR, $endDelimiter, $endDelimiter);
$regex = \sprintf('/(%s|[^%s\x00])*(?:%s)?/', RegexHelper::PARTIAL_ESCAPED_CHAR, $excluded, $endDelimiter);
if (($partialTitle = $cursor->matchInPlace($regex)) === null) {
return null;
}

View file

@ -40,9 +40,9 @@ final class RegexHelper
public const PARTIAL_IN_PARENS = '\\((' . self::PARTIAL_ESCAPED_CHAR . '|[^)\x00])*\\)';
public const PARTIAL_REG_CHAR = '[^\\\\()\x00-\x20]';
public const PARTIAL_IN_PARENS_NOSP = '\((' . self::PARTIAL_REG_CHAR . '|' . self::PARTIAL_ESCAPED_CHAR . '|\\\\)*\)';
public const PARTIAL_TAGNAME = '[a-z][a-z0-9-]*';
public const PARTIAL_TAGNAME = '[A-Za-z][A-Za-z0-9-]*';
public const PARTIAL_BLOCKTAGNAME = '(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)';
public const PARTIAL_ATTRIBUTENAME = '[a-z_:][a-z0-9:._-]*';
public const PARTIAL_ATTRIBUTENAME = '[A-Za-z_:][A-Za-z0-9:._-]*';
public const PARTIAL_UNQUOTEDVALUE = '[^"\'=<>`\x00-\x20]+';
public const PARTIAL_SINGLEQUOTEDVALUE = '\'[^\']*\'';
public const PARTIAL_DOUBLEQUOTEDVALUE = '"[^"]*"';