Skip to content

Commit

Permalink
fix: [#1647] Fixes problem with children of created documents not bei…
Browse files Browse the repository at this point in the history
…ng considered as connected to the DOM that was introduced in v16
  • Loading branch information
capricorn86 committed Dec 27, 2024
1 parent d58fc61 commit 08e7ae0
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 22 deletions.
2 changes: 1 addition & 1 deletion packages/happy-dom/src/css/rules/CSSStyleRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import CSSStyleDeclaration from '../declaration/CSSStyleDeclaration.js';
*/
export default class CSSStyleRule extends CSSRule {
public readonly type = CSSRule.STYLE_RULE;
public readonly selectorText = '';
public readonly styleMap = new Map();
public selectorText = '';
public [PropertySymbol.cssText] = '';
#style: CSSStyleDeclaration | null = null;

Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/src/nodes/document/Document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class Document extends Node {
public [PropertySymbol.isFirstWrite] = true;
public [PropertySymbol.isFirstWriteAfterOpen] = false;
public [PropertySymbol.nodeType] = NodeTypeEnum.documentNode;
public [PropertySymbol.isConnected] = false;
public [PropertySymbol.isConnected] = true;
public [PropertySymbol.adoptedStyleSheets]: CSSStyleSheet[] = [];
public [PropertySymbol.implementation] = new DOMImplementation(this);
public [PropertySymbol.readyState] = DocumentReadyStateEnum.interactive;
Expand Down
26 changes: 18 additions & 8 deletions packages/happy-dom/src/nodes/html-element/HTMLElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -613,10 +613,15 @@ export default class HTMLElement extends Element {
public override [PropertySymbol.connectedToDocument](): void {
super[PropertySymbol.connectedToDocument]();

this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'connectedCallback'
);
if (
this[PropertySymbol.ownerDocument][PropertySymbol.window].document ===
this[PropertySymbol.ownerDocument]
) {
this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'connectedCallback'
);
}
}

/**
Expand All @@ -625,10 +630,15 @@ export default class HTMLElement extends Element {
public override [PropertySymbol.disconnectedFromDocument](): void {
super[PropertySymbol.disconnectedFromDocument]();

this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'disconnectedCallback'
);
if (
this[PropertySymbol.ownerDocument][PropertySymbol.window].document ===
this[PropertySymbol.ownerDocument]
) {
this[PropertySymbol.window][PropertySymbol.customElementReactionStack].enqueueReaction(
this,
'disconnectedCallback'
);
}
}

/**
Expand Down
11 changes: 0 additions & 11 deletions packages/happy-dom/src/window/BrowserWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,17 +835,6 @@ export default class BrowserWindow extends EventTarget implements INodeJSGlobal
// Document
this.document = new this.HTMLDocument();
this.document[PropertySymbol.defaultView] = this;
this.document[PropertySymbol.isConnected] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.isConnected] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.nodeArray][0][
PropertySymbol.isConnected
] = true;

this.document[PropertySymbol.nodeArray][0][PropertySymbol.nodeArray][1][
PropertySymbol.isConnected
] = true;

// Ready state manager
this[PropertySymbol.readyStateManager].waitUntilComplete().then(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/test/dom-parser/DOMParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ describe('DOMParser', () => {
'text/html'
);

expect(newDocument.isConnected).toBe(false);
expect(newDocument.isConnected).toBe(true);
expect(newDocument.defaultView).toBe(window);

const customElement = <CustomElement>newDocument.querySelector('custom-element');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import Document from '../../../src/nodes/document/Document.js';
import HTMLStyleElement from '../../../src/nodes/html-style-element/HTMLStyleElement.js';
import { beforeEach, describe, it, expect } from 'vitest';
import HTMLElement from '../../../src/nodes/html-element/HTMLElement.js';
import DOMImplementation from '../../../src/dom-implementation/DOMImplementation.js';
import CSSStyleRule from '../../../src/css/rules/CSSStyleRule.js';

describe('HTMLStyleElement', () => {
let window: Window;
Expand Down Expand Up @@ -185,5 +187,73 @@ describe('HTMLStyleElement', () => {

expect(documentElementComputedStyle.backgroundColor).toBe('blue');
});

it('Returns an CSSStyleSheet instance with its text content as style rules for #1647.', () => {
const StyleTagRegexp = /<style[^>]*>(?<content>.*?)<\/style>/gis;

function getScopedCssRules(html: string, scope: string, dom?: DOMImplementation): string {
const css = Array.from(html.matchAll(StyleTagRegexp))
.map(({ groups }) => groups?.content ?? '')
.join('\n');

if (!css) {
return '';
}

// Use the browser's CSSOM to parse CSS
const doc = (dom ?? document.implementation).createHTMLDocument();
const styleElement = doc.createElement('style');
styleElement.textContent = css;
doc.body.appendChild(styleElement);

return Array.from(styleElement.sheet?.cssRules ?? [])
.map((rule) => {
if (rule instanceof CSSStyleRule) {
rule.selectorText = rule.selectorText
.split(',')
.map((selector) => `${scope} ${selector}`)
.join(',');
}

return rule.cssText;
})
.join('\n');
}

function scopeCssSelectors(html: string, scope: string, dom?: DOMImplementation): string {
const scopedCss = getScopedCssRules(html, scope, dom);

return `${scopedCss ? `<style>${scopedCss}</style>` : ''}${html.replace(
StyleTagRegexp,
''
)}`;

Check failure

Code scanning / CodeQL

Incomplete multi-character sanitization High test

This string may still contain
<style
, which may cause an HTML element injection vulnerability.
}

const html = `
<style>
#document h1, #document h2 {
background: red;
}
</style>
<h1>I love this</h1>
<STYLE type="text/css">
h3 {
color: white;
}
</STYLE>
`;

expect(scopeCssSelectors(html, '.scope'))
.toEqual(`<style>.scope #document h1,.scope #document h2 { background: red; }
.scope h3 { color: white; }</style>
<h1>I love this</h1>
`);
});
});
});

0 comments on commit 08e7ae0

Please sign in to comment.