From 9ddfd764ed79e1d776e515a2cd5d4676bf673523 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 00:02:49 +0100 Subject: [PATCH 1/2] pat-inject: Autoformat. --- src/pat/inject/documentation.md | 6 +- src/pat/inject/index.html | 949 +++++++++++++++----------------- src/pat/inject/inject.js | 34 +- src/pat/inject/inject.test.js | 144 ++--- 4 files changed, 530 insertions(+), 603 deletions(-) diff --git a/src/pat/inject/documentation.md b/src/pat/inject/documentation.md index d439ac896..2eb10504d 100644 --- a/src/pat/inject/documentation.md +++ b/src/pat/inject/documentation.md @@ -302,9 +302,9 @@ after: Next month - … + …
- … + …
### Modals @@ -332,7 +332,7 @@ After injection was triggered: -### Configurable error pages. +### Configurable error pages In cases of AJAX errors, you can provide custom error pages by providing custom meta tags. For example, if you add this meta tag to the html ``: diff --git a/src/pat/inject/index.html b/src/pat/inject/index.html index 179b64565..0c70c464e 100644 --- a/src/pat/inject/index.html +++ b/src/pat/inject/index.html @@ -1,580 +1,505 @@ - - Injection pattern - - - - - - - - - - - - - -
- scroll to bottom -
- -
-

+ + Injection pattern + + + + + + + + + + + + + +

+ scroll to bottom +
+ +
+

In this example, a - Single HTML source + Single HTML source is used for various injections. -

- + +
+
+

+ ? +

- -
-

Inject and scroll demos

-
+
+ +
+

Inject and scroll demos

+ - -
-
-

- ? -

-
-
- -
-
-

- ? -

-
-
- -
    -
  • + +
  • +
+ +
+
+

+ ? +

+
+
+ +
+
+

+ ? +

+
+
+ + -
- -
-

Shows a fallback message on error

- + +
  • + Place "Cocteau" in the second frame on this page and + scroll towards it. +
  • + +
    + +
    +

    Shows a fallback message on error

    + Show me some error! - -
    - -
    -
    -

    Inject and fix URLs of options

    - - injection happens here! Call for help - -
    -
    - - - - - - - - -
    -

    Can replace itself

    - Like -
    - -
    -

    Can replace itself when a button in a form

    - -
    - -
    -
    - -
    -

    Inject history example

    -

    - Inject some text and record the history -

    - -

    here goes the injection

    -
    - -
    -

    Inject history example 2

    -

    - Go to the second inject-history example on a dedicated page -

    -
    - -
    -

    Inject autosubmit with form using GET and POST

    - -
    - - -
    - -

    - here goes the injection -

    -
    - -
    -

    Call something without injecting anything

    -

    + data-pat-inject="target: self::element" + >Like + +

    + +
    +

    Inject history example

    +

    + Inject some text and record the history +

    + +

    here goes the injection

    +
    + +
    +

    Inject history example 2

    +

    + Go to the second inject-history example on a dedicated page +

    +
    + +
    +

    Inject autosubmit with form using GET and POST

    + +
    + + +
    + +

    + here goes the injection +

    +
    + +
    +

    Call something without injecting anything

    +

    You need to open your network inspector to actually validate that the request is sent. It works if you see a call to demo/backend-action.html in the list of requested items. -

    - - Trigger something, but don't inject results -
    - -
    -

    +

    + + Trigger something, but don't inject results +

    + +
    +

    Inject nothing into the target, effectively destroying whatever is in there. -

    -

    + +

    The source is nothing and the target is given, so when triggering the injection, the target is removed. -

    -

    +

    +

    I will be killed once you click the link below -

    - Do something, but don't replace any content, just kill the - target. -
    - -
    - scroll to top -
    - - - + + diff --git a/src/pat/inject/inject.js b/src/pat/inject/inject.js index 0e75b6873..424d7a339 100644 --- a/src/pat/inject/inject.js +++ b/src/pat/inject/inject.js @@ -78,12 +78,12 @@ const inject = { if (el.nodeName === "A" && $(cfgs[0].nextHref).length > 0) { log.debug( "Skipping as next href is anchor, which already exists", - cfgs[0].nextHref + cfgs[0].nextHref, ); // TODO: reconsider how the injection enters exhausted state el.setAttribute( "href", - (window.location.href.split("#")[0] || "") + cfgs[0].nextHref + (window.location.href.split("#")[0] || "") + cfgs[0].nextHref, ); return $el; } @@ -117,7 +117,7 @@ const inject = { (e) => { if ( e.submitter?.matches( - "[type=submit], button:not([type=button]), [type=image]" + "[type=submit], button:not([type=button]), [type=image]", ) ) { // make sure the submitting button is sent @@ -125,7 +125,7 @@ const inject = { ajax.onClickSubmit(e); } this.onTrigger(e); - } + }, ); } else if (el?.matches(".pat-subform")) { log.debug("Initializing subform with injection"); @@ -145,7 +145,7 @@ const inject = { const delayed_trigger = (uuid_) => { // Check if the element has been removed from the dom const still_there = document.querySelector( - `[data-pat-inject-uuid="${uuid_}"]` + `[data-pat-inject-uuid="${uuid_}"]`, ); if (!still_there) { return false; @@ -159,7 +159,7 @@ const inject = { }; window.setTimeout( delayed_trigger.bind(null, uuid), - cfgs[0].delay + cfgs[0].delay, ); } break; @@ -472,7 +472,9 @@ const inject = { const method = cfg.sourceMod === "content" ? "innerHTML" : "outerHTML"; // There might be multiple sources, so we need to loop over them. // Access them with "innerHTML" or "outerHTML" depending on the sourceMod. - const sources_string = [...$sources].map(source => source[method]).join("\n"); + const sources_string = [...$sources] + .map((source) => source[method]) + .join("\n"); wrapper.innerHTML = sources_string; for (const img of wrapper.content.querySelectorAll("img")) { @@ -483,7 +485,7 @@ const inject = { (e) => { $(e.currentTarget).trigger("pat-inject-content-loaded"); }, - { once: true } + { once: true }, ); } } @@ -562,7 +564,7 @@ const inject = { const scroll_container = dom.find_scroll_container( scroll_target, null, - window + window, ); if (cfg.scroll === "top") { @@ -573,7 +575,7 @@ const inject = { } el.dispatchEvent( - new Event("pat-inject-success", { bubbles: true, cancelable: true }) + new Event("pat-inject-success", { bubbles: true, cancelable: true }), ); }, @@ -614,7 +616,7 @@ const inject = { sources$[idx1], cfg, ev.target, - $title + $title, ); } } @@ -754,13 +756,13 @@ const inject = { do_close_panel = false; // Re-trigger close-panel event if it was caught while injection was in progress. el.dispatchEvent( - new Event("close-panel", { bubbles: true, cancelable: true }) + new Event("close-panel", { bubbles: true, cancelable: true }), ); } }); $el.on("pat-ajax-error.pat-inject", this._onInjectError.bind(this, $el, cfgs)); $el.on("pat-ajax-success.pat-inject pat-ajax-error.pat-inject", () => - $el.removeData("pat-inject-triggered") + $el.removeData("pat-inject-triggered"), ); // Prevent closing the panel while injection is in progress. @@ -935,7 +937,7 @@ const inject = { for (const [pattern_name, opts] of Object.entries(this._rebaseOptions)) { for (const el_ of dom.querySelectorAllAndMe( page, - `[data-pat-${pattern_name}]` + `[data-pat-${pattern_name}]`, )) { const pattern = registry.patterns?.[pattern_name]; const pattern_parser = pattern?.parser; @@ -962,7 +964,7 @@ const inject = { if (changed) { el_.setAttribute( `data-pat-${pattern_name}`, - JSON.stringify(options.length === 1 ? options[0] : options) + JSON.stringify(options.length === 1 ? options[0] : options), ); } } @@ -1157,7 +1159,7 @@ $(document).on("patterns-injected.inject", async (ev, cfg, trigger, injected) => detail: { injected: injected, }, - }) + }), ); } }); diff --git a/src/pat/inject/inject.test.js b/src/pat/inject/inject.test.js index 9850a8821..9a0fa9d49 100644 --- a/src/pat/inject/inject.test.js +++ b/src/pat/inject/inject.test.js @@ -47,7 +47,7 @@ describe("pat-inject", function () { describe("1 - The next-href argument", function () { it("1.1 - allows you to specify the href to be applied to the clicked element after injection", async function () { var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").append($a).append($div); @@ -98,7 +98,7 @@ describe("pat-inject", function () { it("2.2 - can be set to another string value which then gets added to the target while content is still loading'", async function () { const spy_ajax = jest.spyOn($, "ajax").mockImplementation(() => deferred); var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -123,7 +123,7 @@ describe("pat-inject", function () { it("2.3 - can be set to an empty string value so that nothing gets added to the target while content is still loading'", async function () { const spy_ajax = jest.spyOn($, "ajax"); var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -173,7 +173,7 @@ describe("pat-inject", function () { it("3.2 - can be set to 'never' to never ask for confirmation", async function () { var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -200,7 +200,7 @@ describe("pat-inject", function () { it("3.3 - can be set to 'always' to always ask for confirmation before injecting", async function () { var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -227,7 +227,7 @@ describe("pat-inject", function () { it("3.4 - can be set to 'form-data' to ask for confirmation before injecting over form fields changed by the user", async function () { var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -261,7 +261,7 @@ describe("pat-inject", function () { describe("3.5 - The confirm-message argument", function () { it("3.5.1 - can be used to provide a custom confirmation prompt message", async function () { var $a = $( - 'link' + 'link', ); var $div = $('
    '); $("#lab").empty().append($a).append($div); @@ -291,7 +291,7 @@ describe("pat-inject", function () { describe("4 - rebaseURL", function () { it("4.1 - Keep URL with scheme", function () { expect( - pattern._rebaseURL("http://example.com/foo/", "http://other.com/me") + pattern._rebaseURL("http://example.com/foo/", "http://other.com/me"), ).toBe("http://other.com/me"); }); @@ -301,13 +301,13 @@ describe("pat-inject", function () { it("4.3 - Rebase to base with filename", function () { expect( - pattern._rebaseURL("http://example.com/foo/index.html", "me/page.html") + pattern._rebaseURL("http://example.com/foo/index.html", "me/page.html"), ).toBe("http://example.com/foo/me/page.html"); }); it("4.4 - Rebase to base with directory path", function () { expect(pattern._rebaseURL("http://example.com/foo/", "me/page.html")).toBe( - "http://example.com/foo/me/page.html" + "http://example.com/foo/me/page.html", ); }); @@ -315,7 +315,7 @@ describe("pat-inject", function () { expect( pattern ._rebaseURL("/foo/", "me/page.html") - .indexOf("/foo/me/page.html") > 0 + .indexOf("/foo/me/page.html") > 0, ).toBe(true); }); @@ -323,7 +323,7 @@ describe("pat-inject", function () { expect( pattern ._rebaseURL("example.com/foo/", "me/page.html") - .indexOf("example.com/foo/me/page.html") > 0 + .indexOf("example.com/foo/me/page.html") > 0, ).toBe(true); }); @@ -331,8 +331,8 @@ describe("pat-inject", function () { expect( pattern._rebaseURL( "http://example.com/foo/", - "data:image-base64gibberish" - ) + "data:image-base64gibberish", + ), ).toBe("data:image-base64gibberish"); }); }); @@ -342,27 +342,27 @@ describe("pat-inject", function () { expect( pattern._rebaseHTML( "base", - "\n

    This is a simple test

    " - ) + "\n

    This is a simple test

    ", + ), ).toBe("

    This is a simple test

    "); }); it("5.2 - Basic markup", function () { expect( - pattern._rebaseHTML("base", "

    This is a simple test

    ") + pattern._rebaseHTML("base", "

    This is a simple test

    "), ).toBe("

    This is a simple test

    "); }); it("5.3 - Recover from unclosed tags", function () { expect(pattern._rebaseHTML("base", "

    This is a simple test

    ")).toBe( - "

    This is a simple test

    " + "

    This is a simple test

    ", ); }); it("5.4 - Anchor element without href attribute", function () { var spy_rebaseURL = jest.spyOn(pattern, "_rebaseURL"); expect(pattern._rebaseHTML("base", "This is a test")).toBe( - "This is a test" + "This is a test", ); expect(spy_rebaseURL).not.toHaveBeenCalled(); @@ -373,10 +373,10 @@ describe("pat-inject", function () { expect( pattern._rebaseHTML( "http://example.com/test/", - 'This is a test' - ) + 'This is a test', + ), ).toBe( - 'This is a test' + 'This is a test', ); }); @@ -384,16 +384,16 @@ describe("pat-inject", function () { expect( pattern._rebaseHTML( "http://example.com/test/", - 'This is a test' - ) + 'This is a test', + ), ).toBe( - 'This is a test' + 'This is a test', ); }); it("5.7 - Check if image is rebased correctly", function () { expect( - pattern._rebaseHTML("http://example.com/test/", '') + pattern._rebaseHTML("http://example.com/test/", ''), ).toBe(''); }); @@ -401,8 +401,8 @@ describe("pat-inject", function () { expect( pattern._rebaseHTML( "base", - "

    This string has src = \"foo\" , src= bar , and SrC='foo'

    " - ) + "

    This string has src = \"foo\" , src= bar , and SrC='foo'

    ", + ), ).toBe("

    This string has src = \"foo\" , src= bar , and SrC='foo'

    "); }); @@ -420,7 +420,7 @@ describe("pat-inject", function () { data-pat-date-picker="i18n:./i18n" data-pat-datetime-picker="i18n:./path/to/i18n" data-pat-collapsible="load-content:../load/content/from/here" - />` + />`, ); const el = document.createElement("div"); @@ -466,7 +466,7 @@ describe("pat-inject", function () { "/> - ` + `, ); const el = document.createElement("div"); @@ -482,7 +482,7 @@ describe("pat-inject", function () { expect(test1_config[0].source).toEqual("#one"); expect(test1_config[0].target).toEqual(".two"); expect(test1_config[1].url).toEqual( - "https://example.com/test/./index2.html" + "https://example.com/test/./index2.html", ); expect(test1_config[1].source).toEqual("#okay"); expect(test1_config[2]["loading-class"]).toEqual("some"); @@ -493,7 +493,7 @@ describe("pat-inject", function () { const res = pattern._rebaseHTML( "https://example.com/test/", - '
    ' + '
    ', ); const el = document.createElement("div"); @@ -839,7 +839,7 @@ describe("pat-inject", function () { $a.trigger("click"); answer( - '
    new replacement
    ' + '
    new replacement
    ', ); await utils.timeout(1); // wait a tick for async to settle. expect($div.html()).toBe("new replacement"); @@ -861,7 +861,7 @@ describe("pat-inject", function () { "" + '
    repl1
    ' + '
    repl2
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -880,7 +880,7 @@ describe("pat-inject", function () { $a.trigger("click"); answer( - "" + '
    repl
    ' + "" + "" + '
    repl
    ' + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -898,7 +898,7 @@ describe("pat-inject", function () { answer( "" + '
    repl
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -917,7 +917,7 @@ describe("pat-inject", function () { answer( "" + '
    repl
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -928,7 +928,7 @@ describe("pat-inject", function () { it("9.1.11 - allows ::before and ::after in target selector", async function () { $a.attr( "data-pat-inject", - "target: #target1::after && target: #target2::before" + "target: #target1::after && target: #target2::before", ); var $target1 = $('
    content
    '), $target2 = $('
    content
    '); @@ -939,7 +939,7 @@ describe("pat-inject", function () { $a.trigger("click"); answer( - "" + '
    repl
    ' + "" + "" + '
    repl
    ' + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -956,7 +956,7 @@ describe("pat-inject", function () { $a.trigger("click"); answer( - "" + '
    repl
    ' + "" + "" + '
    repl
    ' + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1078,7 +1078,7 @@ describe("pat-inject", function () { $form[0].dispatchEvent(submitEvent); answer( - "" + '
    repl
    ' + "" + "" + '
    repl
    ' + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1189,10 +1189,10 @@ describe("pat-inject", function () { describe("9.2.4.4 - formaction attribute on submit buttons", function () { it("9.2.4.4.1 - use submit button formaction value as action URL", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ); $form.append($submit1).append($submit2); @@ -1227,7 +1227,7 @@ describe("pat-inject", function () { $submit[0].addEventListener("click", async () => { await utils.timeout(1); // wait a tick for click event reaching form before submitting. $submit[0].form.dispatchEvent( - events.submit_event({ submitter: $submit[0] }) + events.submit_event({ submitter: $submit[0] }), ); }); @@ -1243,10 +1243,10 @@ describe("pat-inject", function () { it("9.2.4.4.3 - use fragment in formaction value as source + target selector", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ), $target = $('
    '); @@ -1261,7 +1261,7 @@ describe("pat-inject", function () { answer( "" + '
    other
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1275,10 +1275,10 @@ describe("pat-inject", function () { it("9.2.4.4.4 - use fragment in formaction value as source selector, respect target", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ), $target = $('
    '); @@ -1294,7 +1294,7 @@ describe("pat-inject", function () { answer( "" + '
    other
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1308,17 +1308,17 @@ describe("pat-inject", function () { it("9.2.4.4.5 - formaction works with multiple targets", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ), $target1 = $('
    '), $target2 = $('
    '); $form.attr( "data-pat-inject", - "target: #target1 && target: #target2" + "target: #target1 && target: #target2", ); $form.append($submit1).append($submit2); $div.append($target1).append($target2); @@ -1331,7 +1331,7 @@ describe("pat-inject", function () { answer( "" + '
    other
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1346,17 +1346,17 @@ describe("pat-inject", function () { it("9.2.4.4.6 - formaction works with multiple sources", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ), $target1 = $('
    '), $target2 = $('
    '); $form.attr( "data-pat-inject", - "#someid #target1 && #otherid #target2" + "#someid #target1 && #otherid #target2", ); $form.append($submit1).append($submit2); $div.append($target1).append($target2); @@ -1370,7 +1370,7 @@ describe("pat-inject", function () { "" + '
    some
    ' + '
    other
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1385,17 +1385,17 @@ describe("pat-inject", function () { it("9.2.4.4.7 - formaction works source and target on the button", async function () { var $submit1 = $( - '' + '', ), $submit2 = $( - '' + '', ), $target1 = $('
    '), $target2 = $('
    '); $submit2.attr( "data-pat-inject", - "#someid #target1 && #otherid #target2" + "#someid #target1 && #otherid #target2", ); $form.append($submit1).append($submit2); $div.append($target1).append($target2); @@ -1409,7 +1409,7 @@ describe("pat-inject", function () { "" + '
    some
    ' + '
    other
    ' + - "" + "", ); await utils.timeout(1); // wait a tick for async to settle. @@ -1453,7 +1453,7 @@ describe("pat-inject", function () { await utils.timeout(1); // wait a tick for async to settle. expect(document.querySelector("form").innerHTML.trim()).toBe( - "other" + "other", ); }); @@ -1482,7 +1482,7 @@ describe("pat-inject", function () { await utils.timeout(1); // wait a tick for async to settle. expect( - document.querySelector("form span").innerHTML.trim() + document.querySelector("form span").innerHTML.trim(), ).toBe("other"); }); @@ -1728,7 +1728,7 @@ describe("pat-inject", function () { const modal = document.querySelector("#pat-modal"); expect(modal).toBeTruthy(); expect(modal.innerHTML.replace(/\s/g, "")).toBe( - "

    hello

    " + "

    hello

    ", ); }); @@ -2085,7 +2085,7 @@ describe("pat-inject", function () {

    oh-nose!

    - `) + `), ); // apparently is empty if we do not set it. @@ -2134,7 +2134,7 @@ describe("pat-inject", function () { ], { jqxhr: { status: 404 }, - } + }, ); await utils.timeout(1); // wait a tick for async to settle. @@ -2160,7 +2160,7 @@ describe("pat-inject", function () {

    oh-nose!

    - `) + `), ); // apparently is empty if we do not set it. @@ -2240,7 +2240,7 @@ describe("pat-inject", function () { await utils.timeout(1); // wait a tick for async to settle. expect(document.querySelector("#error-message").innerHTML.trim()).toEqual( - "

    oh no, what did you do?!

    " + "

    oh no, what did you do?!

    ", ); }); @@ -2259,7 +2259,7 @@ describe("pat-inject", function () { - `) + `), ); // Configure fallback error page with a error zone selector #error-message @@ -2300,7 +2300,7 @@ describe("pat-inject", function () { await utils.timeout(1); // wait a tick for async to settle. expect(document.querySelector("#error-message").innerHTML.trim()).toEqual( - "

    this is a message from your operator.

    " + "

    this is a message from your operator.

    ", ); global.fetch.mockClear(); @@ -2336,7 +2336,7 @@ describe("pat-inject", function () { await utils.timeout(1); // wait a tick for async to settle. expect(document.querySelector("#error-message").innerHTML.trim()).toEqual( - "" + "", ); expect(document.body.hasAttribute("data-error-message")).toBeTruthy(); From 63762ee2cfd31c6ccfa4b4d936e757bcce705a94 Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 26 Nov 2026 01:10:50 +0100 Subject: [PATCH 2/2] feat(pat-inject): Add "scripts" option to execute injected scripts. "scripts: remove" (default) removes scripts from the injected content. "scripts: execute" injects and executes them. The option is applied per injection rule. Script URLs are resolved against the requested page. External scripts run in document order unless they are async. SVG scripts keep their namespace. Also: - Parse responses with DOMParser in an inert document instead of with regular expressions. Images in the response are no longer loaded and their event handlers no longer run while parsing, including for content that is not injected. - Remove scripts from nested template contents. - Remove scripts at injection time, which also applies to content from other type handlers like pat-markdown. Assisted-by: Claude Opus 5.5 --- src/pat/inject/documentation.md | 35 +++++ src/pat/inject/inject.js | 120 ++++++++++----- src/pat/inject/inject.test.js | 250 ++++++++++++++++++++++++++++++-- 3 files changed, 351 insertions(+), 54 deletions(-) diff --git a/src/pat/inject/documentation.md b/src/pat/inject/documentation.md index 2eb10504d..8f5ffb475 100644 --- a/src/pat/inject/documentation.md +++ b/src/pat/inject/documentation.md @@ -371,6 +371,41 @@ You can customise the behaviour of injection through options in the `data-pat-in | `loading-class` | 'injecting' | | A class which will be added to the injection target while content is still being loaded. Multiple classes can be specified (separated with spaces), or leave empty if no class should be added. | String | | `history` | | `none` `record` | If set to `record` then injection will update the URL history and the title tag of the HTML page. | String or null. | | `scroll` | | `none`, `top`, `target`, CSS selector | After injection is done, scroll to to given position. The default or `none` is to not do any scrolling. `top` scrolls to the top of the scroll container. `target` scrolls to the pat-inject target. CSS selector scrolls to the given selector. Note: You have to define a scroll container by setting overflow classes, otherwise `window` is used. | String, CSS selector | +| `scripts` | `remove` | `remove`, `execute` | What to do with scripts in the injected content. `remove` removes them. `execute` injects and runs them. See [Executing scripts](#executing-scripts). | String | + +#### Executing scripts + +By default, scripts are removed from the injected content (`scripts: remove`). +With `scripts: execute`, they are injected and executed. +With `&&`, set the option on each injection rule that needs it. + + + Load widget + + +`scripts: execute` lets scripts in the injected fragment execute in the current page, +subject to its Content Security Policy. Relative script URLs resolve against the +requested page URL. + +Some details: + +- Only scripts within the selected source are injected. Scripts in the `` of a + full HTML document response are always dropped. +- External scripts run in document order, unless they have an `async` attribute. + Inline scripts run right away and do not wait for earlier external scripts to load. +- Inline scripts run before patterns are initialized on the injected content. External + scripts usually run afterwards, once they are loaded. +- With a nonce-based Content Security Policy, injected scripts only run if they carry + the nonce of the current page, which a separately requested response usually does not. +- Without a `url`, the source is taken from the current page. Choose the source + carefully, so the page's own scripts are not executed a second time. + +Use pat-inject with trusted HTML. Other active content, including inline event handlers +and embedded documents, can remain with the default settings. Enable scripts only in +application-controlled markup and only for responses you trust to execute code in the +current page. Set the option on the trigger where possible, since descendant triggers +can inherit it from an ancestor. ## Developer documentation diff --git a/src/pat/inject/inject.js b/src/pat/inject/inject.js index 424d7a339..d7592635e 100644 --- a/src/pat/inject/inject.js +++ b/src/pat/inject/inject.js @@ -38,6 +38,7 @@ parser.addArgument("class"); // Add a class to the injected content. parser.addArgument("history", "none", ["none", "record"]); parser.addArgument("push-marker"); parser.addArgument("scroll"); +parser.addArgument("scripts", "remove", ["remove", "execute"]); // Note: this should not be here but the parser would bail on unknown // parameters and expand/collapsible need to pass the url to us. @@ -468,6 +469,7 @@ const inject = { * element to inject. */ const wrapper = document.createElement("template"); + let content = wrapper.content; if ($sources.length > 0) { const method = cfg.sourceMod === "content" ? "innerHTML" : "outerHTML"; // There might be multiple sources, so we need to loop over them. @@ -477,7 +479,16 @@ const inject = { .join("\n"); wrapper.innerHTML = sources_string; - for (const img of wrapper.content.querySelectorAll("img")) { + if (cfg.scripts === "execute") { + // Import into the current document and recreate the scripts + // before insertion. Parsed scripts would not be executed. + content = document.importNode(content, true); + this._recreateScripts(content); + } else { + this._removeScripts(content); + } + + for (const img of content.querySelectorAll("img")) { events.add_event_listener( img, "load", @@ -490,8 +501,8 @@ const inject = { } } - // Copy, because after insertion wrapper.children is empty. - const source_nodes = [...wrapper.content.childNodes]; + // Copy, because after insertion content.childNodes is empty. + const source_nodes = [...content.childNodes]; // Now the injection actually happens. if (this._inject(trigger, source_nodes, target, cfg)) { @@ -502,6 +513,36 @@ const inject = { } }, + _recreateScripts(root) { + for (const script of root.querySelectorAll("script")) { + // Keep the namespace, so that SVG scripts stay SVG scripts. + const new_script = document.createElementNS(script.namespaceURI, "script"); + for (const attr of script.attributes) { + new_script.setAttributeNS(attr.namespaceURI, attr.name, attr.value); + } + if (new_script instanceof HTMLScriptElement && !script.hasAttribute("async")) { + // Script-inserted scripts are async by default. Run external + // scripts in document order, like parser-inserted scripts. + new_script.async = false; + } + new_script.textContent = script.textContent; + script.replaceWith(new_script); + } + }, + + _removeScripts(root) { + const fragments = [root]; + for (const fragment of fragments) { + for (const script of fragment.querySelectorAll("script")) { + script.remove(); + } + // Template contents are separate fragments and may be inserted later. + for (const template of fragment.querySelectorAll("template")) { + fragments.push(template.content); + } + } + }, + _update_history(cfg, trigger, $title) { // History support. if subform is submitted, append form params if (cfg.history !== "record" || !history?.pushState) { @@ -828,7 +869,6 @@ const inject = { elementbefore: "before", }[cfg.action]; - // Inject the content HERE! target[method](...source_nodes); return true; @@ -877,6 +917,7 @@ const inject = { form: "action", img: "src", object: "data", + script: "src", source: "src", video: "src", }, @@ -897,16 +938,7 @@ const inject = { return base.slice(0, base.lastIndexOf("/") + 1) + url; }, - _rebaseHTML(base, html) { - if (html === "") { - // Special case, source is none - return ""; - } - - // Parse the html string into a DOM tree. - const page = document.createElement("div"); - page.innerHTML = html; - + _rebaseElements(base, page) { // Create efficient selector for any tag with it's corresponding // attribute from _rebaseAttrs. Note: the current data structure allows // only for one attribute to be rebased per tag. @@ -914,9 +946,20 @@ const inject = { .map(([tag, attr]) => `${tag}[${attr}]`) .join(", "); for (const el_ of page.querySelectorAll(rebase_selector)) { - const attr = this._rebaseAttrs[el_.nodeName.toLowerCase()]; + const tag = el_.nodeName.toLowerCase(); + const attr = this._rebaseAttrs[tag]; let value = el_.getAttribute(attr); + if (tag === "script" && value) { + try { + const response_base = new URL(base || "", document.baseURI); + el_.setAttribute(attr, new URL(value, response_base).href); + } catch (e) { + log.warn("Could not resolve script URL:", value, e); + } + continue; + } + if ( value && value.slice(0, 2) !== "@@" && @@ -935,10 +978,7 @@ const inject = { } for (const [pattern_name, opts] of Object.entries(this._rebaseOptions)) { - for (const el_ of dom.querySelectorAllAndMe( - page, - `[data-pat-${pattern_name}]`, - )) { + for (const el_ of page.querySelectorAll(`[data-pat-${pattern_name}]`)) { const pattern = registry.patterns?.[pattern_name]; const pattern_parser = pattern?.parser; if (!pattern_parser) { @@ -969,32 +1009,37 @@ const inject = { } } } - - return page.innerHTML.trim(); }, _parseRawHtml(html, url = "") { - // remove script tags and head and replace body by a div - const title = html.match(/\(.*)\<\/title\>/); - let clean_html = html - .replace(/)<[^<]*)*<\/script>/gi, "") - .replace(/)<[^<]*)*<\/head>/gi, "") - .replace(/]*?)>/gi, "") - .replace(/<\/html([^>]*?)>/gi, "") - .replace(/]*?)>/gi, '
    ') - .replace(/<\/body([^>]*?)>/gi, "
    "); - - if (title && title.length == 2) { - clean_html = title[0] + clean_html; + const template = document.createElement("template"); + const page = template.content.ownerDocument.createElement("div"); + // Only parse document-shaped responses as documents. Fragment parsing + // keeps leading elements such as script and style in the fragment. + const is_document = + /^(?:\s|)*<(?:!doctype\s|(?:html|head|body)(?=[\s/>]))/i.test(html); + if (is_document) { + const doc = new DOMParser().parseFromString(html, "text/html"); + const title = doc.head.querySelector("title"); + if (title) { + page.append(title); + } + const body = page.ownerDocument.createElement("div"); + body.id = "__original_body"; + body.append(...doc.body.childNodes); + page.append(body); + } else { + page.innerHTML = html.trim(); } + try { - clean_html = this._rebaseHTML(url, clean_html); + this._rebaseElements(url, page); } catch (e) { log.error("Error rebasing urls", e); } - const $html = $("
    ").html(clean_html); + const $html = $(page); if ($html.children().length === 0) { - log.warn("Parsing html resulted in empty jquery object:", clean_html); + log.warn("Parsing html resulted in empty jquery object:", page.innerHTML); } return $html; }, @@ -1124,8 +1169,7 @@ const inject = { sources(cfgs, data) { const sources = cfgs.map((cfg) => cfg.source); sources.push("title"); - const result = this._sourcesFromHtml(data, cfgs[0].url, sources); - return result; + return this._sourcesFromHtml(data, cfgs[0].url, sources); }, }, }, diff --git a/src/pat/inject/inject.test.js b/src/pat/inject/inject.test.js index 9a0fa9d49..0d4475747 100644 --- a/src/pat/inject/inject.test.js +++ b/src/pat/inject/inject.test.js @@ -337,10 +337,17 @@ describe("pat-inject", function () { }); }); - describe("5 - rebaseHTML", function () { + describe("5 - rebaseElements", function () { + const rebaseHTML = (base, html) => { + const template = document.createElement("template"); + template.innerHTML = html; + pattern._rebaseElements(base, template.content); + return template.innerHTML.trim(); + }; + it("5.1 - Basic markup with DOCTYPE", function () { expect( - pattern._rebaseHTML( + rebaseHTML( "base", "\n

    This is a simple test

    ", ), @@ -348,20 +355,20 @@ describe("pat-inject", function () { }); it("5.2 - Basic markup", function () { - expect( - pattern._rebaseHTML("base", "

    This is a simple test

    "), - ).toBe("

    This is a simple test

    "); + expect(rebaseHTML("base", "

    This is a simple test

    ")).toBe( + "

    This is a simple test

    ", + ); }); it("5.3 - Recover from unclosed tags", function () { - expect(pattern._rebaseHTML("base", "

    This is a simple test

    ")).toBe( + expect(rebaseHTML("base", "

    This is a simple test

    ")).toBe( "

    This is a simple test

    ", ); }); it("5.4 - Anchor element without href attribute", function () { var spy_rebaseURL = jest.spyOn(pattern, "_rebaseURL"); - expect(pattern._rebaseHTML("base", "This is a test")).toBe( + expect(rebaseHTML("base", "This is a test")).toBe( "This is a test", ); expect(spy_rebaseURL).not.toHaveBeenCalled(); @@ -371,7 +378,7 @@ describe("pat-inject", function () { it("5.5 - Anchor element with href attribute", function () { expect( - pattern._rebaseHTML( + rebaseHTML( "http://example.com/test/", 'This is a test', ), @@ -382,7 +389,7 @@ describe("pat-inject", function () { it("5.6 - Automatically fix casing of attribute", function () { expect( - pattern._rebaseHTML( + rebaseHTML( "http://example.com/test/", 'This is a test', ), @@ -392,14 +399,14 @@ describe("pat-inject", function () { }); it("5.7 - Check if image is rebased correctly", function () { - expect( - pattern._rebaseHTML("http://example.com/test/", ''), - ).toBe(''); + expect(rebaseHTML("http://example.com/test/", '')).toBe( + '', + ); }); it("5.8 - Leave non attribute occurences of src intact", function () { expect( - pattern._rebaseHTML( + rebaseHTML( "base", "

    This string has src = \"foo\" , src= bar , and SrC='foo'

    ", ), @@ -412,7 +419,7 @@ describe("pat-inject", function () { await import("../date-picker/date-picker"); await import("../datetime-picker/datetime-picker"); - const res = pattern._rebaseHTML( + const res = rebaseHTML( "https://example.com/test/", `
    @@ -449,7 +456,7 @@ describe("pat-inject", function () { // tests for an error where a semicolon at the end of a pattern // config as well as multiple configs were not correctly parsed. - const res = pattern._rebaseHTML( + const res = rebaseHTML( "https://example.com/test/", `
    { await import("../calendar/calendar"); - const res = pattern._rebaseHTML( + const res = rebaseHTML( "https://example.com/test/", '
    ', ); @@ -2035,6 +2042,217 @@ describe("pat-inject", function () { expect(injected.length).toBe(1); }); }); + + describe("9.7 - scripts", () => { + it("9.7.1 - preserves inline script text when parsing an HTML document", () => { + const script = 'const markup = "

    Content

    ";'; + const html = ` + Response + + `; + const $parsed = pattern._parseRawHtml(html, "/page.html"); + + expect($parsed.find("title").text()).toBe("Response"); + expect($parsed.find("script")).toHaveLength(1); + expect($parsed.find("#__original_body > script").text()).toBe(script); + }); + + it("9.7.2 - keeps a leading script in a fragment", () => { + const $parsed = pattern._parseRawHtml( + '', + "/page.html", + ); + + expect($parsed.children("script").text()).toBe("{}"); + }); + + it("9.7.3 - strips scripts from nested template contents", () => { + const wrapper = document.createElement("template"); + wrapper.innerHTML = + ''; + pattern._removeScripts(wrapper.content); + const inner = wrapper.content + .querySelector("template") + .content.querySelector("template"); + + expect(inner.content.querySelector("script")).toBeNull(); + expect(inner.content.querySelector("p").textContent).toBe("Content"); + }); + + it.each([ + ["widget.js", "https://example.com/fragments/widget.js"], + ["/widget.js", "https://example.com/widget.js"], + [ + "https://static.example.com/widget.js", + "https://static.example.com/widget.js", + ], + ])( + "9.7.4 - resolves script src %s against the requested URL", + (src, expected) => { + const $parsed = pattern._parseRawHtml( + ``, + "https://example.com/fragments/page.html?path=/other/", + ); + + expect($parsed.find("script").attr("src")).toBe(expected); + }, + ); + + it.each([ + ["a top-level", ""], + ["a nested", "div"], + ])( + "9.7.5 - executes %s script when allowed", + async (_placement, wrapper) => { + const script = + ''; + const source = wrapper + ? `<${wrapper}>${script}` + : script; + const $trigger = $( + '', + ).appendTo("#lab"); + const target = $("
    ").appendTo("#lab")[0]; + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { responseText: `
    ${source}
    ` }, + }); + + expect(target.dataset.executed).toBe("yes"); + expect(target.firstElementChild.classList.contains("injected")).toBe( + true, + ); + }, + ); + + it("9.7.6 - keeps external scripts in document order unless async", async () => { + const $trigger = $( + '', + ).appendTo("#lab"); + const target = $("
    ").appendTo("#lab")[0]; + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { + responseText: `
    + + +
    `, + }, + }); + + expect(target.querySelector(".ordered").async).toBe(false); + expect(target.querySelector(".async").hasAttribute("async")).toBe(true); + }); + + it("9.7.7 - keeps the namespace of allowed SVG scripts", async () => { + const $trigger = $( + '', + ).appendTo("#lab"); + const target = $("
    ").appendTo("#lab")[0]; + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { + responseText: `
    + +
    `, + }, + }); + + const script = target.querySelector("svg script"); + expect(script.namespaceURI).toBe("http://www.w3.org/2000/svg"); + expect( + script.getAttributeNS("http://www.w3.org/1999/xlink", "href"), + ).toBe("widget.js"); + }); + + it("9.7.8 - executes an allowed script once and keeps its attributes", async () => { + window.__inject_script_runs = 0; + const $trigger = $( + '', + ).appendTo("#lab"); + const target = $("
    ").appendTo("#lab")[0]; + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { + responseText: `
    + +
    `, + }, + }); + + const script = target.querySelector("script"); + expect(window.__inject_script_runs).toBe(1); + expect(script.nonce).toBe("abc"); + expect(script.dataset.test).toBe("yes"); + + delete window.__inject_script_runs; + }); + + it.each(["remove", "run", "script"])( + "9.7.9 - removes scripts with scripts: %s", + async (value) => { + const $trigger = $('') + .attr("data-pat-inject", `target: #target; scripts: ${value}`) + .appendTo("#lab"); + const target = $("
    ").appendTo("#lab")[0]; + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { + responseText: `

    Content

    `, + }, + }); + + expect(target.querySelector("script")).toBeNull(); + expect(target.querySelector("p").textContent).toBe("Content"); + }, + ); + + it.each([true, false])( + "9.7.10 - filters scripts per rule with the opt-in first: %s", + async (allowedFirst) => { + const allowed = + "source: #source; target: #allowed; scripts: execute"; + const blocked = "source: #source; target: #blocked"; + const rules = allowedFirst ? [allowed, blocked] : [blocked, allowed]; + const $trigger = $('') + .attr("data-pat-inject", rules.join(" && ")) + .appendTo("#lab"); + $("#lab").append('
    '); + const cfgs = pattern.extractConfig($trigger); + expect(pattern.verifyConfig(cfgs)).toBe(true); + + await pattern._onInjectSuccess($trigger, cfgs, { + target: $trigger[0], + jqxhr: { + responseText: `

    Content

    `, + }, + }); + + expect(document.querySelector("#allowed script")).not.toBeNull(); + expect(document.querySelector("#blocked script")).toBeNull(); + expect(document.querySelector("#blocked p").textContent).toBe( + "Content", + ); + }, + ); + }); }); describe("10 - Error handling", () => {