Skip to content

fix(hydrogen): pass CSP nonces to WebMCP scripts - #4352

Open
frandiox wants to merge 1 commit into
mainfrom
fd-webmcp-nonce
Open

frandiox wants to merge 1 commit into
mainfrom
fd-webmcp-nonce

Conversation

@frandiox

Copy link
Copy Markdown
Contributor

WebMCP's script is inserted after hydration without the document's CSP nonce. A nonce-only script-src-elem blocks it even when ShopifyScripts receives the nonce. Forward that existing value through browser initialization to the dynamic script loader.

Before

const csp = createContentSecurityPolicy({
  directives: { scriptSrcElem: [] },
});

Server-rendered Shopify scripts receive csp.nonce, but the dynamically inserted WebMCP script does not and is blocked by this policy.

After

React and Vue forward the existing <ShopifyScripts nonce={nonce} /> value to WebMCP automatically. Custom framework integrations can pass the same document nonce when initializing scripts:

initializeShopifyScripts({ nonce: csp.nonce });

What this changes

  • Pass the nonce through initializeShopifyScripts and the WebMCP loader to the script's attributes before insertion.
  • Cover React/Vue forwarding, present/absent/empty nonce values, and loader attribute assignment.
  • Update generated API documentation.

Developer impact

Adds an optional nonce field to InitializeShopifyScriptsOptions. React and Vue integrations use the nonce already supplied to ShopifyScripts.

Includes a patch changeset for fixing nonce propagation to an existing dynamically loaded script. No new exports.

Verified in the built React Router template and its dev server: the CSP response header, SSR bootstrap, and dynamically inserted WebMCP script share the same nonce with no hydration errors. The browser probe supplied WebMCP support and intercepted its CDN response. A separate Chromium check confirmed that a nonce-only policy blocks a dynamic script without its nonce and allows it with the nonce.

How to Test

  1. From the repository root, run pnpm install && pnpm run build:pkgs and then pnpm dev:rr. Use the local URL printed by Vite.

  2. Open the template in a browser with WebMCP enabled (navigator.modelContext or document.modelContext must be present). Without a configured store, the template uses its tokenless mock.shop fallback.

  3. In DevTools, confirm the shopify-webmcp script loads. Compare its nonce with the bootstrap's:

    document.querySelector('#shopify-webmcp')?.nonce
    document.querySelector('#shopify-global-bootstrap')?.nonce
  4. Confirm both values match the nonce in the document's CSP response header. Read .nonce; browsers conceal the value from getAttribute('nonce').

Nonce-only script policies block WebMCP because its script is inserted after hydration without the document nonce. Forward the nonce through browser initialization and framework bindings, with regression tests and updated public API docs.

Co-authored-by: Codex <codex@openai.com>
@frandiox
frandiox requested a review from a team as a code owner November 10, 2026 08:33
@shopify

shopify Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Oxygen deployed a preview of your fd-webmcp-nonce branch. Details:

Storefront Status Preview link Deployment details Last update (UTC)
Skeleton (skeleton.hydrogen.shop) ✅ Successful (Logs) Preview deployment Inspect deployment November 10, 2026 8:35 AM

Learn more about Hydrogen's GitHub integration.

@fredericoo fredericoo 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.

all good thank you for catching that!

only one test that i was able to make pass with bad data, if you can fix that it'd be great (suggested a fix right there)

Comment on lines +835 to 850
it.each([undefined, "test-nonce", ""])("loads WebMCP with nonce %s", async (nonce) => {
(navigator as any).modelContext = { registerTool: vi.fn() };

await expect(initializeShopifyScripts({ routes: emptyRouteTemplates })).resolves.toBe(true);
await expect(initializeShopifyScripts({ routes: emptyRouteTemplates, nonce })).resolves.toBe(
true,
);

expect(loadScript).toHaveBeenCalledWith(SHOPIFY_STOREFRONT_WEBMCP_SCRIPT, {
in: "head",
attributes: { id: "shopify-webmcp", crossorigin: "anonymous" },
attributes: {
id: "shopify-webmcp",
crossorigin: "anonymous",
...(nonce !== undefined ? { nonce } : {}),
},
});
});

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.

non-blocking: the undefined case can't catch a nonce="undefined" regression.

toHaveBeenCalledWith ignores undefined properties, so if webmcp.ts always passed nonce, loadScript would setAttribute("nonce", "undefined") and this still passes. The expected value also re-implements the production spread, so it mirrors the implementation rather than pinning it.

Reproduced: swapped the spread in webmcp.ts for nonce: nonce as string and all 3 cases still pass. With the version below, the undefined case fails.

Suggested change
it.each([undefined, "test-nonce", ""])("loads WebMCP with nonce %s", async (nonce) => {
(navigator as any).modelContext = { registerTool: vi.fn() };
await expect(initializeShopifyScripts({ routes: emptyRouteTemplates })).resolves.toBe(true);
await expect(initializeShopifyScripts({ routes: emptyRouteTemplates, nonce })).resolves.toBe(
true,
);
expect(loadScript).toHaveBeenCalledWith(SHOPIFY_STOREFRONT_WEBMCP_SCRIPT, {
in: "head",
attributes: { id: "shopify-webmcp", crossorigin: "anonymous" },
attributes: {
id: "shopify-webmcp",
crossorigin: "anonymous",
...(nonce !== undefined ? { nonce } : {}),
},
});
});
it.each([
{ nonce: undefined, attributes: { id: "shopify-webmcp", crossorigin: "anonymous" } },
{
nonce: "test-nonce",
attributes: { id: "shopify-webmcp", crossorigin: "anonymous", nonce: "test-nonce" },
},
{ nonce: "", attributes: { id: "shopify-webmcp", crossorigin: "anonymous", nonce: "" } },
])("loads WebMCP with nonce $nonce", async ({ nonce, attributes }) => {
(navigator as any).modelContext = { registerTool: vi.fn() };
await expect(initializeShopifyScripts({ routes: emptyRouteTemplates, nonce })).resolves.toBe(
true,
);
expect(vi.mocked(loadScript).mock.lastCall).toStrictEqual([
SHOPIFY_STOREFRONT_WEBMCP_SCRIPT,
{ in: "head", attributes },
]);
});

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants