Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

`TextElement.toString()` puts the element text back at the first `><` of the start tag, so an attribute value containing `><` swallows the text of `<style>`, `<script>`, `<title>` and `<textarea>`

Aperta Adatta ai principianti
#341 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
javascript, node.js
Ambito
backend

Direzione di ricerca

Leggi esm/html/text-element.js, in particolare il metodo toString() descritto nell’issue. Segui il modo in cui viene serializzato il suo clone senza figli, poi usa la riproduzione fornita per style, script, title e textarea per confermare il problema e verificare che il testo di ciascun elemento e il valore di data-src vengano mantenuti durante la serializzazione e l’analisi.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Environment

  • linkedom 0.18.13 (latest on npm, published 2026-07-07). esm/html/text-element.js is byte-identical on main at 3fcf145c.
  • Node 22.18.0, ESM.
  • Reproduction: the full script is in the collapsed section at the end (the inline version is below).

What happens

TextElement (the base of HTMLStyleElement, HTMLScriptElement, HTMLTitleElement and HTMLTextAreaElement) serializes by cloning itself without children and splicing its text between the start and end tag, esm/html/text-element.js line 12:

return outerHTML.replace('><', () => `>${this.textContent}<`);

String.prototype.replace with a string pattern replaces only the first match. The childless clone serializes as <tag attrs></tag>, so the intended match is the >< between the two tags, but a >< inside an attribute value is found first. The text is then inserted inside the attribute value, and the element body is empty.

Minimal reproduction

import { parseHTML } from 'linkedom';

const { document } = parseHTML('<!doctype html><html><head></head><body></body></html>');
const style = document.createElement('style');
style.setAttribute('data-src', 'a><b.css');
style.textContent = '.caption{color:red}';

console.log(style.outerHTML);
// actual:   <style data-src="a>.caption{color:red}<b.css"></style>
// expected: <style data-src="a><b.css">.caption{color:red}</style>

(A serializer that also escapes < and > in attribute values, as the current HTML Standard asks, would write a&gt;&lt;b.css; the point here is only where the text goes.)

Parsing the actual output gives an empty <style> and the attribute value a>.caption{color:red}<b.css: the stylesheet is gone and the attribute is corrupted, with no error. The attached script shows the same result for style, script, title and textarea. jsdom produces the expected output.

Expected behavior

The element text is always the content of the element, whatever the attribute values contain.

Suggested change

The childless clone serializes as <tag attrs></tag>; the boundary between the two tags is always the last ><, because everything after it is the end tag:

toString() {
  const outerHTML = toString.call(this.cloneNode());
  const at = outerHTML.lastIndexOf('><');
  return `${outerHTML.slice(0, at + 1)}${this.textContent}${outerHTML.slice(at + 1)}`;
}

This keeps the callback-style replacement from #293 (no special replacement patterns in the text). the verification script in the collapsed section at the end applies it in-process: all four elements keep their text and attribute, and attribute-free and empty elements serialize as before.

Related, not part of this report

<title> and <textarea> text goes through the same method unescaped, while the parser decodes <title> content, so a <title> with &amp;amp; loses a level per cycle. #304 and its discussion cover the title question; I am not asking for a decision on it here.

Why it matters

The failure needs no hostile input. A file name such as a><b.css stored in a data-* attribute of an inlined <style> made our generated document ship without its stylesheet, and nothing reported it.

repro-text-element-first-match.mjs (run with npm install [email protected] && node repro-text-element-first-match.mjs)
// Minimal reproduction 2 of 2: TextElement.toString() re-inserts the element text at the
// FIRST "><" of the serialized start tag, which can be inside an attribute value.
//
//   npm install [email protected] && node repro-text-element-first-match.mjs
//
// Exit code 1 = the defect reproduces; 0 = the element text stays between its tags.
//
// Cause (esm/html/text-element.js): the text is put back with
//   toString.call(this.cloneNode()).replace('><', () => `>${this.textContent}<`)
// String.prototype.replace with a string pattern replaces only the first match. The clone has
// no children, so the only "><" that is guaranteed to be the end of the start tag is the one
// before the closing tag; any "><" inside an attribute value comes first.
// HTMLStyleElement, HTMLScriptElement, HTMLTitleElement and HTMLTextAreaElement all extend
// TextElement.
import { createRequire } from 'node:module';
import { parseHTML } from 'linkedom';

const { version } = createRequire(import.meta.url)('linkedom/package.json');
console.log(`linkedom ${version}`);

const SHELL = '<!doctype html><html><head></head><body></body></html>';
const TEXT = '.caption{color:red}';
const ATTRIBUTE_VALUE = 'a><b.css';

let failed = 0;
for (const tag of ['style', 'script', 'title', 'textarea']) {
  const { document } = parseHTML(SHELL);
  const el = document.createElement(tag);
  el.setAttribute('data-src', ATTRIBUTE_VALUE);
  el.textContent = TEXT;

  const html = el.outerHTML;
  const reparsed = parseHTML(`<!doctype html><html><body>${html}</body></html>`);
  const back = reparsed.document.querySelector(tag);
  const textBack = back?.textContent;
  const attributeBack = back?.getAttribute('data-src');

  const ok = textBack === TEXT && attributeBack === ATTRIBUTE_VALUE;
  if (!ok) failed += 1;
  console.log(
    `${ok ? 'ok  ' : 'FAIL'} <${tag} data-src=${JSON.stringify(ATTRIBUTE_VALUE)}> with text ${JSON.stringify(TEXT)}\n` +
      `       outerHTML:        ${html}\n` +
      `       text after parse: ${JSON.stringify(textBack)}   (expected ${JSON.stringify(TEXT)})\n` +
      `       attr after parse: ${JSON.stringify(attributeBack)}   (expected ${JSON.stringify(ATTRIBUTE_VALUE)})`,
  );
}

console.log(failed === 0 ? 'RESULT: element text stays inside the element' : `RESULT: ${failed} of 4 elements corrupted, defect reproduces`);
process.exit(failed === 0 ? 0 : 1);
verify-suggested-fixes.mjs (applies the suggested changes in-process)
// Verifies the two patches proposed in the two reports (Attr.toString and TextElement.toString).
// It patches linkedom in-process only, to show that each proposal removes the failure
// reproduced by repro-attr-html-escape.mjs and repro-text-element-first-match.mjs.
//
//   npm install [email protected] && node verify-suggested-fixes.mjs
import { createRequire } from 'node:module';
import { parseHTML } from 'linkedom';

const { version } = createRequire(import.meta.url)('linkedom/package.json');
console.log(`linkedom ${version}`);

const { document } = parseHTML('<!doctype html><html><head></head><body></body></html>');
const HTMLStyleElementProto = Object.getPrototypeOf(document.createElement('style'));
const TextElementProto = Object.getPrototypeOf(HTMLStyleElementProto); // esm/html/text-element.js
const HTMLElementProto = Object.getPrototypeOf(TextElementProto);
const AttrProto = Object.getPrototypeOf(document.createAttribute('x')); // esm/interface/attr.js

// Proposal 2: put the text back at the LAST "><" of the childless clone's serialization, which
// is always the boundary between the start tag and the end tag.
const elementToString = HTMLElementProto.toString;
TextElementProto.toString = function toString() {
  const outerHTML = elementToString.call(this.cloneNode());
  const at = outerHTML.lastIndexOf('><');
  return `${outerHTML.slice(0, at + 1)}${this.textContent}${outerHTML.slice(at + 1)}`;
};

// Proposal 1: escape `&` and U+00A0 (and keep `"`) in HTML-document attribute values.
// Empty values keep linkedom's own boolean-attribute shorthand.
const attrToString = AttrProto.toString;
AttrProto.toString = function toString() {
  const { value } = this;
  if (!value) return attrToString.call(this);
  const escaped = value.replace(/&/g, '&amp;').replace(/\u00a0/g, '&nbsp;').replace(/"/g, '&quot;');
  return `${this.name}="${escaped}"`;
};

let failed = 0;
const check = (label, ok) => {
  if (!ok) failed += 1;
  console.log(`${ok ? 'ok  ' : 'FAIL'} ${label}`);
};

for (const value of ['A &amp; B', '&#0 ', 'a & b', 'a b']) {
  const doc = parseHTML('<!doctype html><html><body><div id="t"></div></body></html>').document;
  const el = doc.getElementById('t');
  el.setAttribute('data-x', value);
  const back = parseHTML(`<!doctype html><html><body>${el.outerHTML}</body></html>`).document
    .getElementById('t')
    .getAttribute('data-x');
  check(`attribute value ${JSON.stringify(value)} survives serialize + parse`, back === value);
}

for (const tag of ['style', 'script', 'title', 'textarea']) {
  const doc = parseHTML('<!doctype html><html><head></head><body></body></html>').document;
  const el = doc.createElement(tag);
  el.setAttribute('data-src', 'a><b.css');
  el.textContent = '.caption{color:red}';
  const back = parseHTML(`<!doctype html><html><body>${el.outerHTML}</body></html>`).document.querySelector(tag);
  check(
    `<${tag}> keeps its text and its attribute value`,
    back.textContent === '.caption{color:red}' && back.getAttribute('data-src') === 'a><b.css',
  );
}

// Elements without attributes, with `$` patterns in the text, and with empty text still serialize as before.
const plain = parseHTML('<!doctype html><html><head></head><body></body></html>').document.createElement('style');
plain.textContent = "a{content:'$&'}";
check('childless attribute-free <style> serializes as <style>text</style>', plain.outerHTML === "<style>a{content:'$&'}</style>");
const empty = parseHTML('<!doctype html><html><head></head><body></body></html>').document.createElement('script');
check('empty <script> serializes as <script></script>', empty.outerHTML === '<script></script>');

console.log(failed === 0 ? 'RESULT: both proposals fix the reproductions' : `RESULT: ${failed} check(s) failed`);
process.exit(failed === 0 ? 0 : 1);
Lingua principale
HTML
Stelle
2.1k
Fork
110
Merge medio
11g 1h
PR unite (30g)
1

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di WebReflection/linkedom

Tutte le issue di WebReflection/linkedom

Issue simili

Altre issue su Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.