From c4c67ced77fd930a5b3f6ebe6d2dfa4b6f0a5c75 Mon Sep 17 00:00:00 2001 From: Mathias Elle Date: Tue, 1 Dec 2026 14:13:32 +0100 Subject: [PATCH 1/3] =?UTF-8?q?fix(inspector):=20preserve=20strict=20CSP?= =?UTF-8?q?=20compatibility=20on=20Hyv=C3=A4=20Checkout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Skip data-mageforge-* attribute injection on non-inspectable/CSP-governed root elements (
` blocks and prevents + * `@alpinejs/csp` (used by Hyvä Checkout under strict CSP) from evaluating + * `x-data` on MageForge root elements before their `Alpine.data()` factories + * have been registered. + */ + +let fallbackScheduled = false; + +function hasAlpineScriptTag() { + return Boolean( + document.querySelector( + 'script[src*="alpine"], script[data-mageforge-alpine-fallback]', + ), + ); +} + +/** + * Load the bundled local Alpine.js script only when the active theme does not + * provide Alpine.js itself (e.g. Luma / Blank). + * + * @param {string} fallbackUrl + */ +export function ensureAlpineFallback(fallbackUrl) { + if (!fallbackUrl || fallbackScheduled) { + return; + } + fallbackScheduled = true; + + const loadIfMissing = () => { + if (typeof window.Alpine !== "undefined" || hasAlpineScriptTag()) { + return; + } + + const alpineScript = document.createElement("script"); + alpineScript.src = fallbackUrl; + alpineScript.defer = true; + alpineScript.setAttribute("data-mageforge-alpine-fallback", "1"); + alpineScript.onerror = () => { + console.error("[MageForge Inspector] Failed to load bundled Alpine.js"); + }; + document.head.appendChild(alpineScript); + }; + + if (document.readyState === "loading") { + document.addEventListener( + "DOMContentLoaded", + () => setTimeout(loadIfMissing, 0), + { once: true }, + ); + } else { + setTimeout(loadIfMissing, 0); + } +} + +/** + * Register an Alpine.data() component and initialize matching `[x-data]` roots + * regardless of whether Alpine.js (standard or CSP build) executes before or + * after this ES module. + * + * @param {string} name + * @param {() => object} factory + */ +export function bootstrapAlpineComponent(name, factory) { + const selector = `[x-data="${name}"]`; + const firstEl = document.querySelector(selector); + const fallbackUrl = firstEl?.getAttribute("data-alpine-url") || ""; + ensureAlpineFallback(fallbackUrl); + + const registerAndUnignore = () => { + Alpine.data(name, factory); + document.querySelectorAll(selector).forEach((el) => { + el.removeAttribute("x-ignore"); + delete el._x_ignore; + }); + }; + + if (typeof Alpine !== "undefined") { + registerAndUnignore(); + queueMicrotask(() => { + document.querySelectorAll(selector).forEach((el) => { + if (!el._x_dataStack && typeof Alpine.initTree === "function") { + Alpine.initTree(el); + } + }); + }); + } else { + document.addEventListener("alpine:init", registerAndUnignore, { + once: true, + }); + } +} diff --git a/src/view/frontend/web/js/inspector.js b/src/view/frontend/web/js/inspector.js index 51cff9c0..e56a5cfc 100644 --- a/src/view/frontend/web/js/inspector.js +++ b/src/view/frontend/web/js/inspector.js @@ -2,6 +2,7 @@ * MageForge Inspector - Unified DevTools Element & Magento Block Inspector */ +import { bootstrapAlpineComponent } from "./alpine-loader.js"; import { domMethods } from "./inspector/dom.js"; import { uiMethods } from "./inspector/ui.js"; import { pickerMethods } from "./inspector/picker.js"; @@ -16,8 +17,8 @@ import { blockDataMap } from "./inspector/blockData.js"; const ICON_PICKER_CURSOR = ''; -function _registerMageforgeInspector() { - Alpine.data("mageforgeInspector", () => ({ +function _createMageforgeInspector() { + return { isOpen: false, isPickerActive: false, isPinned: false, @@ -365,18 +366,7 @@ function _registerMageforgeInspector() { ...vitalsMethods, ...draggableMethods, ...ideMethods, - })); + }; } -if (typeof Alpine !== "undefined") { - _registerMageforgeInspector(); - document - .querySelectorAll('[x-data="mageforgeInspector"]') - .forEach(function (el) { - if (typeof Alpine.initTree === "function") { - Alpine.initTree(el); - } - }); -} else { - document.addEventListener("alpine:init", _registerMageforgeInspector); -} +bootstrapAlpineComponent("mageforgeInspector", _createMageforgeInspector); diff --git a/src/view/frontend/web/js/inspector/performance.js b/src/view/frontend/web/js/inspector/performance.js index 4b70af06..797287d7 100644 --- a/src/view/frontend/web/js/inspector/performance.js +++ b/src/view/frontend/web/js/inspector/performance.js @@ -56,7 +56,7 @@ export const performanceMethods = { warningDiv.innerHTML = `
-
Full Page Cache Bypassed
+
Full Page Cache Bypassed
Layout XML declares cacheable="false" on this page.
`; diff --git a/src/view/frontend/web/js/inspector/tabs.js b/src/view/frontend/web/js/inspector/tabs.js index 64ec3acb..c956d72f 100644 --- a/src/view/frontend/web/js/inspector/tabs.js +++ b/src/view/frontend/web/js/inspector/tabs.js @@ -112,7 +112,7 @@ export const tabsMethods = { inheritanceNote.innerHTML = ` ${ICON_INHERITED}
-
Rendered inside Parent Block
+
Rendered inside Parent Block
Element <${element.tagName.toLowerCase()}> belongs to the Magento block below.
`; @@ -164,7 +164,7 @@ export const tabsMethods = { inheritanceNote.innerHTML = ` ${ICON_INHERITED}
-
Inherited from Parent Block
+
Inherited from Parent Block
Element <${element.tagName.toLowerCase()}> is rendered inside this Magento block.
`; diff --git a/src/view/frontend/web/js/toolbar.js b/src/view/frontend/web/js/toolbar.js index ecae5a9f..c2662e6f 100644 --- a/src/view/frontend/web/js/toolbar.js +++ b/src/view/frontend/web/js/toolbar.js @@ -2,12 +2,13 @@ * MageForge Toolbar – Unified DevTools Dock & Audit Center. */ +import { bootstrapAlpineComponent } from "./alpine-loader.js"; import { matchesShortcut } from "./shortcut-parser.js"; import { uiMethods } from "./toolbar/ui.js"; import { auditMethods } from "./toolbar/audits.js"; -function _registerMageforgeToolbar() { - Alpine.data("mageforgeToolbar", () => ({ +function _createMageforgeToolbar() { + return { menuOpen: false, /** @type {Set} Keys of currently active audits */ @@ -160,18 +161,7 @@ function _registerMageforgeToolbar() { ...uiMethods, ...auditMethods, - })); + }; } -if (typeof Alpine !== "undefined") { - _registerMageforgeToolbar(); - document - .querySelectorAll('[x-data="mageforgeToolbar"]') - .forEach(function (el) { - if (typeof Alpine.initTree === "function") { - Alpine.initTree(el); - } - }); -} else { - document.addEventListener("alpine:init", _registerMageforgeToolbar); -} +bootstrapAlpineComponent("mageforgeToolbar", _createMageforgeToolbar); diff --git a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php index fc0cf1a9..5ee8b8dd 100644 --- a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php +++ b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php @@ -12,6 +12,7 @@ use Magento\Framework\View\TemplateEngineInterface; use OpenForgeProject\MageForge\Model\TemplateEngine\Decorator\InspectorHints; use OpenForgeProject\MageForge\Service\Inspector\Cache\BlockCacheCollector; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; @@ -242,4 +243,87 @@ public function testRenderDetectsParentBlockAndAlias(): void $this->assertSame('parent.block', $metadata['parent']); $this->assertSame('child.block', $metadata['alias']); } + + /** + * @return array + */ + public static function nonInspectableRootTagProvider(): array + { + return [ + 'inline script with CSP nonce' => [ + '', + ], + 'uppercase script tag' => [ + '', + ], + 'inline style with CSP nonce' => [ + '', + ], + 'stylesheet link' => [ + '', + ], + 'meta element' => [ + '', + ], + 'alpine template fragment' => [ + '', + ], + ]; + } + + #[DataProvider('nonInspectableRootTagProvider')] + public function testRenderSkipsNonInspectableAndCspGovernedRootElements(string $markup): void + { + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($markup); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/script.phtml'); + + $this->assertSame($markup, $result); + } + + public function testRenderSkipsDuplicateInjectionWhenRootElementAlreadyAnnotated(): void + { + $alreadyAnnotated = '
Hello
'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($alreadyAnnotated); + $this->random->method('getRandomString')->willReturn('outer456'); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/container.phtml'); + + $this->assertSame($alreadyAnnotated, $result); + } + + public function testRenderStillAnnotatesOuterElementWhenOnlyChildIsAnnotated(): void + { + $nestedMarkup = '
' + . '
Inner
' + . '
'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($nestedMarkup); + $this->random->method('getRandomString')->willReturn('parent999'); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/outer.phtml'); + + $this->assertStringStartsWith('
assertStringContainsString('data-mageforge-id="mageforge-child"', $result); + } + + public function testRenderHandlesGreaterThanInsideQuotedRootAttribute(): void + { + $markup = '
Visible
'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($markup); + $this->random->method('getRandomString')->willReturn('quote123'); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/alpine.phtml'); + + $this->assertStringStartsWith('
assertStringContainsString('x-show="items.length > 0" class="wrapper">Visible
', $result); + } } From 35626178a3579457169a7ad5412d9be65f948c28 Mon Sep 17 00:00:00 2001 From: Mathias Elle Date: Tue, 1 Dec 2026 14:33:54 +0100 Subject: [PATCH 2/3] fix(inspector): refine attribute detection and Alpine fallback loading Parse root opening-tag attributes with a quote-aware tokenizer so data-mageforge-id substrings inside quoted attribute values no longer skip root block annotation. Resolve the bundled Alpine.js fallback via import.meta.url instead of a DOM attribute (eliminating DOM-to-script.src taint), match candidate Alpine scripts strictly by runtime filename/package path rather than arbitrary URL substrings, and recheck window.Alpine after candidate scripts load before suppressing the fallback. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Decorator/InspectorHints.php | 34 +++++- src/view/frontend/templates/inspector.phtml | 3 +- src/view/frontend/web/js/alpine-loader.js | 106 ++++++++++++------ .../Decorator/InspectorHintsTest.php | 29 +++++ 4 files changed, 137 insertions(+), 35 deletions(-) diff --git a/src/Model/TemplateEngine/Decorator/InspectorHints.php b/src/Model/TemplateEngine/Decorator/InspectorHints.php index 027697f2..cc075b06 100644 --- a/src/Model/TemplateEngine/Decorator/InspectorHints.php +++ b/src/Model/TemplateEngine/Decorator/InspectorHints.php @@ -51,6 +51,14 @@ class InspectorHints implements TemplateEngineInterface */ private const ROOT_REGEX = '/^(\s*<([a-zA-Z][a-zA-Z0-9-]*))(?=\s|\/|>)((?:[^>"\']++|"[^"]*+"|\'[^\']*+\')*+)>/s'; + /** + * Quote-aware pattern matching individual HTML attributes inside an opening tag. + * + * Group 1 captures each attribute name while consuming any quoted or unquoted + * attribute value so `data-mageforge-id=` mentions inside quoted values are ignored. + */ + private const ATTR_REGEX = '/([^\s=\/>"\']++)(?:\s*+=\s*+(?:"[^"]*+"|\'[^\']*+\'|[^\s\/>]*+))?/s'; + /** * @var string */ @@ -218,7 +226,7 @@ private function injectInspectorAttributes( } $existingAttributes = $matches[3]; - if (preg_match('/\sdata-mageforge-id\s*=/i', $existingAttributes) === 1) { + if ($this->hasInspectorAttribute($existingAttributes)) { return $html; } @@ -283,6 +291,30 @@ private function injectInspectorAttributes( ); } + /** + * Check whether the opening tag already carries a MageForge inspector attribute + * + * @param string $existingAttributes + * @return bool + */ + private function hasInspectorAttribute(string $existingAttributes): bool + { + $attributeMatches = []; + $matchCount = preg_match_all(self::ATTR_REGEX, $existingAttributes, $attributeMatches); + if ($matchCount === false || $matchCount === 0) { + return false; + } + + foreach ($attributeMatches[1] as $attributeName) { + $normalizedName = strtolower($attributeName); + if ($normalizedName === 'data-mageforge-id' || $normalizedName === 'data-mageforge-block') { + return true; + } + } + + return false; + } + /** * Get relative path from Magento root * diff --git a/src/view/frontend/templates/inspector.phtml b/src/view/frontend/templates/inspector.phtml index 1e779086..e3ad2b14 100644 --- a/src/view/frontend/templates/inspector.phtml +++ b/src/view/frontend/templates/inspector.phtml @@ -10,7 +10,8 @@ use OpenForgeProject\MageForge\Block\Inspector; * * Initializes the Alpine.js toolbar and inspector components without inline * scripts or inline styles so strict CSP pages (e.g. Hyvä Checkout) remain - * unaffected. + * unaffected. Existing Alpine.js instances (`typeof Alpine !== 'undefined'`) + * are detected in `alpine-loader.js` before loading the local fallback bundle. * * @var Inspector $block * @var Escaper $escaper diff --git a/src/view/frontend/web/js/alpine-loader.js b/src/view/frontend/web/js/alpine-loader.js index 1e011cf7..92f42df8 100644 --- a/src/view/frontend/web/js/alpine-loader.js +++ b/src/view/frontend/web/js/alpine-loader.js @@ -7,51 +7,93 @@ * have been registered. */ +const LOCAL_ALPINE_URL = new URL("./lib/alpine.min.js", import.meta.url).href; +const ALPINE_RUNTIME_FILE_PATTERN = + /^alpine(?:js)?(?:\d+)?(?:-csp|\.csp)?(?:\.esm)?(?:\.min)?\.m?js$/i; +const ALPINE_PACKAGE_PATH_PATTERN = /\/(?:@alpinejs\/csp|alpinejs)(?:@|\/)/i; + let fallbackScheduled = false; -function hasAlpineScriptTag() { - return Boolean( - document.querySelector( - 'script[src*="alpine"], script[data-mageforge-alpine-fallback]', +function isAlpineRuntimeScript(script) { + const rawSrc = script.getAttribute("src"); + if (!rawSrc || rawSrc.includes("OpenForgeProject_MageForge/")) { + return false; + } + + try { + const pathname = new URL(rawSrc, window.location.href).pathname; + const filename = pathname.split("/").pop() || ""; + return ( + ALPINE_RUNTIME_FILE_PATTERN.test(filename) || + ALPINE_PACKAGE_PATH_PATTERN.test(pathname) + ); + } catch { + return false; + } +} + +function findCandidateAlpineScripts() { + return Array.from( + document.querySelectorAll( + "script[src]:not([data-mageforge-alpine-fallback])", ), - ); + ).filter(isAlpineRuntimeScript); +} + +function injectLocalAlpineFallback() { + if ( + typeof window.Alpine !== "undefined" || + document.querySelector("script[data-mageforge-alpine-fallback]") + ) { + return; + } + + const alpineScript = document.createElement("script"); + alpineScript.src = LOCAL_ALPINE_URL; + alpineScript.defer = true; + alpineScript.setAttribute("data-mageforge-alpine-fallback", "1"); + alpineScript.onerror = () => { + console.error("[MageForge Inspector] Failed to load bundled Alpine.js"); + }; + document.head.appendChild(alpineScript); +} + +function resolveAlpineOrLoadFallback() { + if (typeof window.Alpine !== "undefined") { + return; + } + + const candidates = findCandidateAlpineScripts(); + if (candidates.length === 0 || document.readyState === "complete") { + injectLocalAlpineFallback(); + return; + } + + const recheckAfterLoad = () => setTimeout(injectLocalAlpineFallback, 0); + candidates.forEach((script) => { + script.addEventListener("load", recheckAfterLoad, { once: true }); + script.addEventListener("error", recheckAfterLoad, { once: true }); + }); + window.addEventListener("load", recheckAfterLoad, { once: true }); } /** * Load the bundled local Alpine.js script only when the active theme does not * provide Alpine.js itself (e.g. Luma / Blank). - * - * @param {string} fallbackUrl */ -export function ensureAlpineFallback(fallbackUrl) { - if (!fallbackUrl || fallbackScheduled) { +export function ensureAlpineFallback() { + if (fallbackScheduled || typeof window.Alpine !== "undefined") { return; } fallbackScheduled = true; - const loadIfMissing = () => { - if (typeof window.Alpine !== "undefined" || hasAlpineScriptTag()) { - return; - } - - const alpineScript = document.createElement("script"); - alpineScript.src = fallbackUrl; - alpineScript.defer = true; - alpineScript.setAttribute("data-mageforge-alpine-fallback", "1"); - alpineScript.onerror = () => { - console.error("[MageForge Inspector] Failed to load bundled Alpine.js"); - }; - document.head.appendChild(alpineScript); - }; - + const scheduleCheck = () => setTimeout(resolveAlpineOrLoadFallback, 0); if (document.readyState === "loading") { - document.addEventListener( - "DOMContentLoaded", - () => setTimeout(loadIfMissing, 0), - { once: true }, - ); + document.addEventListener("DOMContentLoaded", scheduleCheck, { + once: true, + }); } else { - setTimeout(loadIfMissing, 0); + scheduleCheck(); } } @@ -65,9 +107,7 @@ export function ensureAlpineFallback(fallbackUrl) { */ export function bootstrapAlpineComponent(name, factory) { const selector = `[x-data="${name}"]`; - const firstEl = document.querySelector(selector); - const fallbackUrl = firstEl?.getAttribute("data-alpine-url") || ""; - ensureAlpineFallback(fallbackUrl); + ensureAlpineFallback(); const registerAndUnignore = () => { Alpine.data(name, factory); diff --git a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php index 5ee8b8dd..36f77dcd 100644 --- a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php +++ b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php @@ -326,4 +326,33 @@ public function testRenderHandlesGreaterThanInsideQuotedRootAttribute(): void $this->assertStringStartsWith('
assertStringContainsString('x-show="items.length > 0" class="wrapper">Visible
', $result); } + + public function testRenderAnnotatesRootElementWhenMageforgeAttributeOnlyAppearsInsideQuotedValue(): void + { + $markup = '
Hi
'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($markup); + $this->random->method('getRandomString')->willReturn('quoted789'); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/quoted-attr.phtml'); + + $this->assertStringStartsWith('
assertStringContainsString( + 'x-data="{ html: \'Hi\' }">Hi
', + $result, + ); + } + + public function testRenderSkipsCaseInsensitiveExistingInspectorAttributes(): void + { + $alreadyAnnotated = '
Hello
'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($alreadyAnnotated); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/container.phtml'); + + $this->assertSame($alreadyAnnotated, $result); + } } From 9942546904207a5db9d7435ccefd4ccb9a3b42ab Mon Sep 17 00:00:00 2001 From: Mathias Elle Date: Tue, 1 Dec 2026 14:41:22 +0100 Subject: [PATCH 3/3] fix(inspector): consume slashes inside unquoted HTML attribute values Allow '/' inside unquoted attribute values in InspectorHints::ATTR_REGEX per HTML5 attribute tokenization so unquoted URLs such as href=/data-mageforge-id do not suppress root block annotation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../TemplateEngine/Decorator/InspectorHints.php | 5 +++-- .../Decorator/InspectorHintsTest.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/Model/TemplateEngine/Decorator/InspectorHints.php b/src/Model/TemplateEngine/Decorator/InspectorHints.php index cc075b06..3cffab8d 100644 --- a/src/Model/TemplateEngine/Decorator/InspectorHints.php +++ b/src/Model/TemplateEngine/Decorator/InspectorHints.php @@ -55,9 +55,10 @@ class InspectorHints implements TemplateEngineInterface * Quote-aware pattern matching individual HTML attributes inside an opening tag. * * Group 1 captures each attribute name while consuming any quoted or unquoted - * attribute value so `data-mageforge-id=` mentions inside quoted values are ignored. + * attribute value (including `/` in unquoted URLs per HTML5 § 13.2.5.38) so + * `data-mageforge-id` substrings inside attribute values are ignored. */ - private const ATTR_REGEX = '/([^\s=\/>"\']++)(?:\s*+=\s*+(?:"[^"]*+"|\'[^\']*+\'|[^\s\/>]*+))?/s'; + private const ATTR_REGEX = '/([^\s=\/>"\']++)(?:\s*+=\s*+(?:"[^"]*+"|\'[^\']*+\'|[^\s>]*+))?/s'; /** * @var string diff --git a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php index 36f77dcd..0b1da9fe 100644 --- a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php +++ b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php @@ -355,4 +355,18 @@ public function testRenderSkipsCaseInsensitiveExistingInspectorAttributes(): voi $this->assertSame($alreadyAnnotated, $result); } + + public function testRenderAnnotatesRootElementWhenUnquotedUrlContainsMageforgeAttributeName(): void + { + $markup = 'Link'; + $block = $this->createBlock(); + $this->subject->method('render')->willReturn($markup); + $this->random->method('getRandomString')->willReturn('unquotedurl'); + + $inspector = $this->createInspectorHints(); + $result = $inspector->render($block, '/var/www/html/link.phtml'); + + $this->assertStringStartsWith('assertStringContainsString('href=/data-mageforge-id class=card>Link', $result); + } }