Skip to content

enable page plugin contributions for public routes and enhance GTM plugin - #156

Open
ryota-yamada-jp wants to merge 19 commits into
emdash-cms:mainfrom
ryota-yamada-jp:feat/plugin-gtm
Open

ryota-yamada-jp wants to merge 19 commits into
emdash-cms:mainfrom
ryota-yamada-jp:feat/plugin-gtm

Conversation

@ryota-yamada-jp

Copy link
Copy Markdown

What does this PR do?

This PR enables the Google Tag Manager (GTM) plugin to function correctly on public pages and adds the missing advanced configuration options for GTM.

1. Enable Page Plugin Contributions for Public Routes
Previously, the Astro middleware (onRequest in middleware.ts) bypassed EmDashRuntime initialization for unauthenticated public requests as a performance optimization. This inadvertently prevented trusted plugins from injecting scripts via the page:fragments and page:metadata hooks on public pages, effectively breaking plugins like Google Tag Manager that need to run for all visitors.

  • Removed the early return for public requests so getRuntime(config) is properly initialized.
  • Exposed collectPageMetadata and collectPageFragments methods on locals.emdash so Astro components like EmDashBodyStart can correctly render the injected HTML.
  • Added comprehensive unit tests in middleware.test.ts to ensure runtime initialization and method binding work as expected even without an active session.

2. GTM Plugin Enhancements

  • Added advanced options to customize the Data Layer Variable Name (defaults to dataLayer), GTM Script URL (defaults to https://www.googletagmanager.com/gtm.js), and GTM NoScript URL (defaults to https://www.googletagmanager.com/ns.html) to support Server-Side GTM (SGTM) setups.

Type of change

  • Bug fix
  • Feature (requires approved Discussion)
  • Refactor (no behavior change)
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

AI-generated code disclosure

  • This PR includes AI-generated code

Screenshots / test output

**Test Output**
✓ tests/unit/astro/middleware.test.ts (1 test)
  ✓ EmDash Middleware (1)
    ✓ initializes runtime and attaches methods for all pages

@changeset-bot

changeset-bot Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 75d4ada

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions

github-actions Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@ryota-yamada-jp ryota-yamada-jp changed the title Feat/plugin gtm enable page plugin contributions for public routes and enhance GTM plugin Apr 3, 2026
@ryota-yamada-jp

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

@ryota-yamada-jp

Copy link
Copy Markdown
Author

recheck

github-actions Bot added a commit that referenced this pull request Apr 3, 2026
@ryota-yamada-jp

Copy link
Copy Markdown
Author

recheck

@z-ryota-yamada

Copy link
Copy Markdown

I have read the CLA Document and I hereby sign the CLA

github-actions Bot added a commit that referenced this pull request Apr 3, 2026
@ascorbic

Copy link
Copy Markdown
Member

Hey! #119 fixed the issue with hooks for anonymous visitors, so this will need some reworking.

@ryota-yamada-jp

Copy link
Copy Markdown
Author

@ascorbic Okay! I will fix this. Please wait a moment.

@ryota-yamada-jp
ryota-yamada-jp marked this pull request as draft April 15, 2026 11:01

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR description claims two changes: (1) middleware fixes to enable page:fragments/page:metadata for public routes, and (2) GTM plugin enhancements. The actual diff contains only a new @emdash-cms/plugin-google-tag-manager package. The middleware narrative is stale—the fixes described were already merged to main in a prior release (see packages/core/CHANGELOG.md line 713 and the current middleware.ts). Reviewers should ignore the description and evaluate only the new plugin.

The plugin is a reasonable addition, but the implementation introduces stored XSS vulnerabilities and has several convention gaps that need fixing before merge:

  1. Unescaped user input in page:fragments. The hook interpolates KV values (gtmScriptUrl, gtmNoScriptUrl, dataLayerName, containerId) directly into JavaScript string literals and HTML attributes without escaping or validation. A single quote in a URL breaks the JS string; a double quote breaks the HTML attribute. The core renderFragment helper does not protect against this—for inline-script it only escapes </, and for html it returns the markup verbatim.
  2. No input validation on the admin form. Arbitrary strings are persisted to KV. URLs should be validated as https:// and the container ID should match the GTM-XXXXXXX format.
  3. Deprecated capability. The plugin uses "page:inject", which is in the deprecation window. New plugins should use "hooks.page-fragments:register".
  4. Missing changeset. A new published package needs a changeset to trigger a release.
  5. No tests. Other plugins in packages/plugins/ have unit/integration tests; this package has none.
  6. Missing approved Discussion. Per AGENTS.md, feature PRs require a prior approved Discussion.

Sandboxed plugins currently have no Lingui integration path (none of the existing plugins localize Block Kit strings), so I’m not flagging the hardcoded English as a dedicated finding—it’s a systemic gap.

Once the XSS/validation issues are fixed, the capability is updated, tests are added, and a changeset is included, this plugin is good to merge.

Comment on lines +22 to +26
code: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'${gtmScriptUrl}?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${containerId}');`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The page:fragments hook interpolates user-controlled KV values (gtmScriptUrl, dataLayerName, containerId) into single-quoted JavaScript string literals without escaping. A single quote or backslash in any of these values breaks the string literal and allows arbitrary code execution on every public page. For example, a gtmScriptUrl of https://evil.com/x';alert(1);var x=' would execute alert(1). The core renderFragment helper only escapes </ sequences in inline scripts; it does not escape single quotes. The plugin must sanitize before interpolation—at minimum by escaping \ and ', or by segmenting the values safely, and ideally by validating against expected formats.

{
kind: "html",
placement: "body:start",
html: `<noscript><iframe src="${gtmNoScriptUrl}?id=${containerId}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The html fragment interpolates gtmNoScriptUrl and containerId directly into an <iframe src> attribute without HTML-escaping or URL-encoding. A double quote in either value breaks out of the src attribute and injects arbitrary HTML. An ampersand in containerId injects extra query parameters. The renderFragment helper returns html contributions verbatim, so the plugin must escape attribute metacharacters (" → &quot;, & → &amp;) and use encodeURIComponent for the query string.

Comment on lines +54 to +65
if (interaction.type === "form_submit" && interaction.action_id === "save_gtm") {
const values = interaction.values || {};
await ctx.kv.set("settings:gtmContainerId", values.gtm_container_id || "");
await ctx.kv.set("settings:gtmDataLayerName", values.gtm_data_layer_name || "dataLayer");
await ctx.kv.set(
"settings:gtmScriptUrl",
values.gtm_script_url || "https://www.googletagmanager.com/gtm.js",
);
await ctx.kv.set(
"settings:gtmNoScriptUrl",
values.gtm_noscript_url || "https://www.googletagmanager.com/ns.html",
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The admin form submission handler stores arbitrary strings from interaction.values directly into KV without validation. gtm_script_url and gtm_noscript_url should be validated as HTTPS URLs (or at least valid URLs), and gtm_container_id should match the expected GTM-XXXXXXX format. Without validation, invalid or malicious input can break every public page or be exploited as stored XSS via the page:fragments hook.

format: "standard",
entrypoint: "@emdash-cms/plugin-google-tag-manager/sandbox",
options: {},
capabilities: ["page:inject"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The plugin declares the deprecated capability "page:inject". This name exists only in the deprecation window and is normalized to "hooks.page-fragments:register" at runtime. New plugins should use the current canonical capability name to avoid future breakage.

Suggested change
capabilities: ["page:inject"],
capabilities: ["hooks.page-fragments:register"],

],
"author": "Your Name",
"license": "MIT",
"dependencies": {},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The author field contains the placeholder value "Your Name". Update it to the actual author or remove the field.

Suggested change
"dependencies": {},
"author": "Ryota Yamada",

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels May 31, 2026
@github-actions github-actions Bot added stale and removed stale labels Jun 26, 2026
@github-actions github-actions Bot added stale and removed stale labels Jul 15, 2026
@github-actions github-actions Bot added stale and removed stale labels Jul 30, 2026
@github-actions github-actions Bot added stale and removed stale labels Aug 13, 2026
@github-actions github-actions Bot added stale and removed stale labels Aug 28, 2026
@github-actions github-actions Bot added stale and removed stale labels Sep 11, 2026
@github-actions github-actions Bot added stale and removed stale labels Sep 26, 2026
@swissky swissky added the ci:run Approve and re-run CI on the PR's latest commit label Sep 28, 2026
@github-actions github-actions Bot removed the ci:run Approve and re-run CI on the PR's latest commit label Sep 28, 2026
@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet and removed review/awaiting-author Reviewed; waiting on the author to respond labels Oct 9, 2026
@swissky swissky added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels Nov 4, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A GTM plugin built on page-fragment contributions is a reasonable fit for EmDash, but this version is not ready to merge. The diff contains only the new @emdash-cms/plugin-google-tag-manager package (plus lockfile); the middleware changes in the PR description are already on main. The main blockers are stored XSS from unescaped KV values in the fragment hook, missing validation on the settings form, and an entry point that fails to load. Both reviewers found none of the earlier findings addressed. The entry-point failure (definePlugin without an id) and the four sequential KV queries per anonymous page render come from one reviewer's static analysis and are not contradicted by the other. Other open items: the deprecated capability, a missing changeset, no tests, a placeholder author, and no approved Discussion for a feature PR. Nothing was run; this is a static review.


Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.

Comment on lines +7 to +16
const containerId = await ctx.kv.get<string>("settings:gtmContainerId");
if (!containerId) return null;

const dataLayerName = (await ctx.kv.get<string>("settings:gtmDataLayerName")) || "dataLayer";
const gtmScriptUrl =
(await ctx.kv.get<string>("settings:gtmScriptUrl")) ||
"https://www.googletagmanager.com/gtm.js";
const gtmNoScriptUrl =
(await ctx.kv.get<string>("settings:gtmNoScriptUrl")) ||
"https://www.googletagmanager.com/ns.html";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The page:fragments hook interpolates user-controlled KV values (gtmScriptUrl, dataLayerName, containerId) into single-quoted JavaScript string literals without escaping. A single quote or backslash breaks the literal and allows arbitrary code execution on every public page. For example, a gtmScriptUrl of https://evil.com/x';alert(1);var x=' would run alert(1). renderFragment only escapes </ for inline scripts, not quotes. Escape or serialize values safely (e.g. JSON.stringify with </ handling) and validate against expected formats; dataLayerName should be a valid JS identifier.

Comment on lines +7 to +16
const containerId = await ctx.kv.get<string>("settings:gtmContainerId");
if (!containerId) return null;

const dataLayerName = (await ctx.kv.get<string>("settings:gtmDataLayerName")) || "dataLayer";
const gtmScriptUrl =
(await ctx.kv.get<string>("settings:gtmScriptUrl")) ||
"https://www.googletagmanager.com/gtm.js";
const gtmNoScriptUrl =
(await ctx.kv.get<string>("settings:gtmNoScriptUrl")) ||
"https://www.googletagmanager.com/ns.html";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The html fragment interpolates gtmNoScriptUrl and containerId directly into an <iframe src> attribute without escaping. A double quote breaks out of the attribute and injects HTML, and an ampersand in containerId injects extra query parameters. renderFragment returns html verbatim, so the plugin must escape attribute metacharacters (" → &quot;, & → &amp;) and use encodeURIComponent for the query string.

Comment on lines +7 to +16
const containerId = await ctx.kv.get<string>("settings:gtmContainerId");
if (!containerId) return null;

const dataLayerName = (await ctx.kv.get<string>("settings:gtmDataLayerName")) || "dataLayer";
const gtmScriptUrl =
(await ctx.kv.get<string>("settings:gtmScriptUrl")) ||
"https://www.googletagmanager.com/gtm.js";
const gtmNoScriptUrl =
(await ctx.kv.get<string>("settings:gtmNoScriptUrl")) ||
"https://www.googletagmanager.com/ns.html";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The admin form handler stores arbitrary strings from interaction.values in KV with no validation. Require gtm_script_url and gtm_noscript_url to be valid https:// URLs, gtm_container_id to match GTM-[A-Z0-9]+, and the data layer name to be a valid JS identifier. Without this, bad input can break every public page or be exploited as stored XSS through the page:fragments hook.

@@ -0,0 +1,38 @@
{
"name": "@emdash-cms/plugin-google-tag-manager",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] This adds a new published package but the PR has no changeset under .changeset/, so it will not be released. Add one per .changeset/README.md, naming the plugin, describing that it injects the GTM container snippet on public pages, and listing the advanced options (data layer name, custom script/noscript URLs for server-side GTM).

@@ -0,0 +1,38 @@
{
"name": "@emdash-cms/plugin-google-tag-manager",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The author field contains the placeholder "Your Name". Update it to the actual author or remove the field.

Suggested change
"name": "@emdash-cms/plugin-google-tag-manager",
"author": "Ryota Yamada",

import { definePlugin } from "emdash";
import type { PluginContext } from "emdash";

export default definePlugin({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] definePlugin from emdash now accepts native plugin definitions and requires an id, which this object lacks. packages/core/src/plugins/define-plugin.ts throws in that case, so importing the /sandbox entry fails before any hook or settings page can run. The native route contract also takes a single context argument, unlike the two-argument handler below. Since the descriptor declares format: "standard", export a bare { hooks, routes } object typed with satisfies SandboxedPlugin from emdash/plugin, as other standard-format plugins do. Add a regression test that loads this entry through the descriptor/adapter and exercises its settings route.

Comment on lines +7 to +16
const containerId = await ctx.kv.get<string>("settings:gtmContainerId");
if (!containerId) return null;

const dataLayerName = (await ctx.kv.get<string>("settings:gtmDataLayerName")) || "dataLayer";
const gtmScriptUrl =
(await ctx.kv.get<string>("settings:gtmScriptUrl")) ||
"https://www.googletagmanager.com/gtm.js";
const gtmNoScriptUrl =
(await ctx.kv.get<string>("settings:gtmNoScriptUrl")) ||
"https://www.googletagmanager.com/ns.html";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] On a configured site this hook makes four sequential database queries on every anonymous page render. ctx.kv.get("settings:…") goes through createSettingsAccess to OptionsRepository.get, which issues a separate SELECT each time with no settings cache on this path. The runtime's page-contribution cache only deduplicates within a page context, not across requests. Store the configuration as one settings object or use a batched settings read, so the logged-out hot path makes a single round trip.

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants