Skip to content

Commit 6ba40cb

Browse files
domeniccodex
andcommitted
Fix and simplify option propagation
Derive the HTML parser's scripting flag when creating each window so includeNodeLocations and iframe loading preserve the requested runScripts mode. Previously these paths could treat <noscript> contents as text even when script execution was disabled. Pass storageQuota to child windows so localStorage and sessionStorage in frames cannot bypass the configured limit. Apply Document defaults without mutating incoming options, copy parser options before overriding scripting state, and remove unused option forwarding and the redundant document global reference. Closes #1128. Co-authored-by: codex <[email protected]>
1 parent 3b3be70 commit 6ba40cb

8 files changed

Lines changed: 99 additions & 70 deletions

File tree

‎lib/api.js‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -254,8 +254,7 @@ function transformOptions(options, encoding, mimeType) {
254254
contentType: "text/html",
255255
parsingMode: "html",
256256
parseOptions: {
257-
sourceCodeLocationInfo: false,
258-
scriptingEnabled: false
257+
sourceCodeLocationInfo: false
259258
},
260259
runScripts: undefined,
261260
encoding,
@@ -295,7 +294,7 @@ function transformOptions(options, encoding, mimeType) {
295294
throw new TypeError("Cannot set includeNodeLocations to true with an XML content type");
296295
}
297296

298-
transformed.windowOptions.parseOptions = { sourceCodeLocationInfo: true };
297+
transformed.windowOptions.parseOptions.sourceCodeLocationInfo = true;
299298
}
300299

301300
transformed.windowOptions.cookieJar = options.cookieJar === undefined ?
@@ -318,9 +317,8 @@ function transformOptions(options, encoding, mimeType) {
318317

319318
if (options.runScripts !== undefined) {
320319
transformed.windowOptions.runScripts = String(options.runScripts);
321-
if (transformed.windowOptions.runScripts === "dangerously") {
322-
transformed.windowOptions.parseOptions.scriptingEnabled = true;
323-
} else if (transformed.windowOptions.runScripts !== "outside-only") {
320+
if (transformed.windowOptions.runScripts !== "dangerously" &&
321+
transformed.windowOptions.runScripts !== "outside-only") {
324322
throw new RangeError(`runScripts must be undefined, "dangerously", or "outside-only"`);
325323
}
326324
}

‎lib/jsdom/browser/Window.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,12 +201,13 @@ function installOwnProperties(window, options) {
201201
encoding: options.encoding,
202202
cookieJar: options.cookieJar,
203203
url: options.url,
204-
lastModified: options.lastModified,
205204
referrer: options.referrer,
206-
parseOptions: options.parseOptions,
205+
parseOptions: {
206+
...options.parseOptions,
207+
scriptingEnabled: options.runScripts === "dangerously"
208+
},
207209
readyState: "loading",
208210
defaultView: window._globalProxy,
209-
global: window,
210211
parentOrigin: options.parentOrigin
211212
}, { alwaysUseDocumentClass: true });
212213

‎lib/jsdom/browser/resources/per-document-resource-loader.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ const { fetchCollected } = require("./jsdom-dispatcher");
66
module.exports = class PerDocumentResourceLoader {
77
constructor(document) {
88
this._document = document;
9-
this._defaultEncoding = document._encoding;
109
const defaultView = document._defaultView;
1110
this._dispatcher = defaultView ? defaultView._dispatcher : null;
1211
this._loadSubresources = defaultView ? defaultView._loadSubresources : false;

‎lib/jsdom/living/nodes/Document-impl.js‎

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -166,61 +166,59 @@ class DocumentImpl extends NodeImpl {
166166
#namedPropertyCollections;
167167
#namedPropertyElementsCache = null;
168168

169-
constructor(globalObject, args, privateData) {
169+
constructor(globalObject, args, {
170+
options: {
171+
parsingMode = "xml",
172+
encoding = "UTF-8",
173+
contentType = parsingMode === "xml" ? "application/xml" : "text/html",
174+
defaultView = null,
175+
cookieJar = new CookieJar(null, { looseMode: true }),
176+
parseOptions,
177+
scriptingDisabled = false,
178+
url: urlOption = "about:blank",
179+
parentOrigin,
180+
referrer = "",
181+
lastModified = new Date(),
182+
readyState = "complete"
183+
} = {},
184+
...privateData
185+
}) {
170186
super(globalObject, args, privateData);
171187

172188
this._initGlobalEvents();
173189

174190
this._ownerDocument = this;
175191
this.nodeType = NODE_TYPE.DOCUMENT_NODE;
176-
if (!privateData.options) {
177-
privateData.options = {};
178-
}
179-
if (!privateData.options.parsingMode) {
180-
privateData.options.parsingMode = "xml";
181-
}
182-
if (!privateData.options.encoding) {
183-
privateData.options.encoding = "UTF-8";
184-
}
185-
if (!privateData.options.contentType) {
186-
privateData.options.contentType = privateData.options.parsingMode === "xml" ? "application/xml" : "text/html";
187-
}
188-
189-
this._parsingMode = privateData.options.parsingMode;
192+
this._parsingMode = parsingMode;
190193

191194
this._implementation = DOMImplementation.createImpl(this._globalObject, [], {
192195
ownerDocument: this
193196
});
194197

195-
this._defaultView = privateData.options.defaultView || null;
196-
this._global = privateData.options.global;
198+
this._defaultView = defaultView;
197199
this._byIdCache = new ByIdCache(this);
198200
this._isInDocumentTree = true;
199201
this._currentScript = null;
200202
this._pageShowingFlag = false;
201-
this._cookieJar = privateData.options.cookieJar;
202-
this._parseOptions = privateData.options.parseOptions || {};
203-
this._scriptingDisabled = privateData.options.scriptingDisabled;
204-
if (this._cookieJar === undefined) {
205-
this._cookieJar = new CookieJar(null, { looseMode: true });
206-
}
203+
this._cookieJar = cookieJar;
204+
this._parseOptions = { ...parseOptions };
205+
this._scriptingDisabled = scriptingDisabled;
207206

208207
if (this._scriptingDisabled) {
209208
this._parseOptions.scriptingEnabled = false;
210209
}
211210

212-
this.contentType = privateData.options.contentType;
213-
this._encoding = privateData.options.encoding;
211+
this.contentType = contentType;
212+
this._encoding = encoding;
214213

215-
const urlOption = privateData.options.url === undefined ? "about:blank" : privateData.options.url;
216214
const parsed = whatwgURL.parseURL(urlOption);
217215
if (parsed === null) {
218216
throw new TypeError(`Could not parse "${urlOption}" as a URL`);
219217
}
220218

221219
this._URL = parsed;
222-
this._origin = urlOption === "about:blank" && privateData.options.parentOrigin ?
223-
privateData.options.parentOrigin :
220+
this._origin = urlOption === "about:blank" && parentOrigin ?
221+
parentOrigin :
224222
whatwgURL.serializeURLOrigin(this._URL);
225223

226224
this._location = Location.createImpl(this._globalObject, [], { relevantDocument: this });
@@ -232,8 +230,8 @@ class DocumentImpl extends NodeImpl {
232230

233231
this._workingNodeIterators = new IterableWeakSet();
234232

235-
this._referrer = privateData.options.referrer || "";
236-
this._lastModified = toLastModifiedString(privateData.options.lastModified || new Date());
233+
this._referrer = referrer;
234+
this._lastModified = toLastModifiedString(lastModified);
237235
this._asyncQueue = new AsyncResourceQueue();
238236
this._queue = new ResourceQueue({ asyncQueue: this._asyncQueue, paused: false });
239237
this._deferQueue = new ResourceQueue({ paused: true });
@@ -244,7 +242,7 @@ class DocumentImpl extends NodeImpl {
244242
this._isDestroyed = false;
245243
this._childDocuments = new Set();
246244
this._parentDocument = null;
247-
this._currentDocumentReadiness = privateData.options.readyState || "complete";
245+
this._currentDocumentReadiness = readyState;
248246

249247
this._lastFocusedElement = null;
250248

‎lib/jsdom/living/nodes/HTMLFrameElement-impl.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,11 @@ function loadFrame(frame, attaching) {
132132
userAgent: parentDoc._defaultView._userAgent,
133133
referrer: parentDoc.URL,
134134
cookieJar: parentDoc._cookieJar,
135-
pool: parentDoc._pool,
136135
encoding: parentDoc._encoding,
137136
runScripts: parentDoc._defaultView._runScripts,
138137
commonForOrigin: parentDoc._defaultView._commonForOrigin,
139-
pretendToBeVisual: parentDoc._defaultView._pretendToBeVisual
138+
pretendToBeVisual: parentDoc._defaultView._pretendToBeVisual,
139+
storageQuota: parentDoc._defaultView._storageQuota
140140
});
141141

142142
const contentDoc = frame._contentDocument = wnd._document;

‎lib/jsdom/living/nodes/HTMLScriptElement-impl.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ class HTMLScriptElementImpl extends HTMLElementImpl {
250250

251251
function processJavaScript(element, code, filename) {
252252
const document = element.ownerDocument;
253-
const window = document && document._global;
253+
const window = document._defaultView;
254254

255255
if (window) {
256256
// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-element
@@ -270,7 +270,7 @@ function processJavaScript(element, code, filename) {
270270
}
271271

272272
try {
273-
vm.runInContext(code, window, { filename, lineOffset, displayErrors: false });
273+
vm.runInContext(code, window._globalObject, { filename, lineOffset, displayErrors: false });
274274
} catch (e) {
275275
reportException(window, e, filename);
276276
} finally {

‎test/api/options-run-scripts.js‎

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -89,32 +89,45 @@ describe("API: runScripts constructor option", () => {
8989
});
9090

9191
describe("<noscript> children", () => {
92-
it("should be considered text when runScripts is set to \"dangerously\"", () => {
93-
const { document } = new JSDOM(
94-
`<body><noscript><div></div></noscript></body>`,
95-
{ runScripts: "dangerously" }
96-
).window;
97-
98-
assert.equal(document.querySelector("noscript").children.length, 0);
99-
assert.equal(document.querySelector("noscript").textContent, "<div></div>");
100-
});
101-
it("should be considered nodes when runScripts is set to \"outside-only\"", () => {
102-
const dom = new JSDOM(
103-
`<body><noscript><div></div></noscript></body>`,
104-
{ runScripts: "outside-only" }
105-
);
106-
const { document } = dom.window;
107-
108-
assert.equal(document.querySelector("noscript").children.length, 1);
109-
assert(document.querySelector("noscript").children[0] instanceof dom.window.HTMLDivElement);
110-
});
111-
it("should be considered nodes when runScripts is left undefined", () => {
112-
const dom = new JSDOM(`<body><noscript><div></div></noscript></body>`).window;
113-
const { document } = dom.window;
92+
const html = `<body><noscript><div></div></noscript></body>`;
93+
const cases = [
94+
{ runScripts: undefined, childInterface: "HTMLDivElement", textContent: "" },
95+
{ runScripts: "outside-only", childInterface: "HTMLDivElement", textContent: "" },
96+
{ runScripts: "dangerously", childInterface: "Text", textContent: "<div></div>" }
97+
];
98+
99+
for (const { runScripts, childInterface, textContent } of cases) {
100+
describe(`when set to ${formatOptionValue(runScripts)}`, () => {
101+
function assertNoscriptContents(window) {
102+
const noscript = window.document.querySelector("noscript");
103+
assert.equal(noscript.childNodes.length, 1);
104+
assert(noscript.firstChild instanceof window[childInterface]);
105+
assert.equal(noscript.textContent, textContent);
106+
}
114107

115-
assert.equal(document.querySelector("noscript").children.length, 1);
116-
assert(document.querySelector("noscript").children[0] instanceof dom.window.HTMLDivElement);
117-
});
108+
it("should parse according to runScripts without node locations", () => {
109+
const dom = new JSDOM(html, { runScripts });
110+
111+
assertNoscriptContents(dom.window);
112+
});
113+
114+
it("should parse according to runScripts with node locations", () => {
115+
const dom = new JSDOM(html, { runScripts, includeNodeLocations: true });
116+
117+
assertNoscriptContents(dom.window);
118+
});
119+
120+
it("should parse loaded iframe contents according to runScripts", async () => {
121+
const dom = new JSDOM(`<iframe src="data:text/html,${encodeURIComponent(html)}"></iframe>`, {
122+
runScripts,
123+
resources: "usable"
124+
});
125+
await once(dom.window, "load");
126+
127+
assertNoscriptContents(dom.window.document.querySelector("iframe").contentWindow);
128+
});
129+
});
130+
}
118131
});
119132

120133
describe("JS spec globals", () => {

‎test/api/options.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,26 @@ describe("API: constructor options", () => {
253253
});
254254

255255
describe("storageQuota", () => {
256+
for (const storageType of ["localStorage", "sessionStorage"]) {
257+
for (const depth of [1, 2]) {
258+
it(`should enforce the custom quota for ${storageType} in frames at depth ${depth}`, () => {
259+
const dom = new JSDOM(``, { url: "https://example.com/", storageQuota: 4 });
260+
let frameWindow = dom.window;
261+
for (let i = 0; i < depth; ++i) {
262+
const iframe = frameWindow.document.createElement("iframe");
263+
frameWindow.document.body.append(iframe);
264+
frameWindow = iframe.contentWindow;
265+
}
266+
267+
const storage = frameWindow[storageType];
268+
storage.setItem("k", "123");
269+
assert.equal(dom.window[storageType].getItem("k"), "123");
270+
assert.throws(() => storage.setItem("k", "1234"), { name: "QuotaExceededError" });
271+
assert.equal(storage.getItem("k"), "123");
272+
});
273+
}
274+
}
275+
256276
describe("not set", () => {
257277
it("should be 5000000 code units by default", () => {
258278
const { localStorage, sessionStorage } = (new JSDOM(``, { url: "https://example.com" })).window;

0 commit comments

Comments
 (0)