Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,15 @@ function addMetaTagToHead(htmlChunk: string, metaTagsStr: string): string {
return htmlChunk;
}

const content = `<head>${metaTagsStr}`;
return htmlChunk.replace('<head>', content);
// Skip quoted attribute values so we don't match <head> inside e.g. data-code="...<head>..."
let replaced = false;
return htmlChunk.replace(/"[^"]*"|'[^']*'|(<head>)/g, (match, headTag) => {
Comment thread
andreiborza marked this conversation as resolved.
if (headTag && !replaced) {
replaced = true;
return `<head>${metaTagsStr}`;
}
return match;
});
}

function getMetaTagsStr({
Expand Down
49 changes: 49 additions & 0 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,55 @@ describe('sentryMiddleware', () => {
expect(resultFromNext).toBe(originalResponse);
});

it('does not inject meta tags into <head> inside attribute values', async () => {
const middleware = handleRequest();

const ctx = {
...DYNAMIC_REQUEST_CONTEXT,
};

const bodyWithHeadInAttr =
'<head><meta name="something" content=""/></head><body><button data-code="&lt;html&gt;&lt;head&gt;&lt;/head&gt;"></button></body>';
const next = vi.fn(() =>
Promise.resolve(
new Response(bodyWithHeadInAttr, {
headers: new Headers({ 'content-type': 'text/html' }),
}),
),
);

// @ts-expect-error, a partial ctx object is fine here
const resultFromNext = await middleware(ctx, next);
const html = await resultFromNext?.text();

expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/>');
expect(html).not.toContain('data-code="&lt;html&gt;&lt;head&gt;<meta name="sentry-route-name"');
});

it('does not inject meta tags into <head> inside quoted attribute values in the same chunk', async () => {
const middleware = handleRequest();

const ctx = {
...DYNAMIC_REQUEST_CONTEXT,
};

const htmlWithHeadInDataAttr = '<head></head><body><div data-content="<head>should not be modified"></div></body>';
const next = vi.fn(() =>
Promise.resolve(
new Response(htmlWithHeadInDataAttr, {
headers: new Headers({ 'content-type': 'text/html' }),
}),
),
);

// @ts-expect-error, a partial ctx object is fine here
const resultFromNext = await middleware(ctx, next);
const html = await resultFromNext?.text();

expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/>');
expect(html).toContain('data-content="<head>should not be modified"');
});

it("no-ops if there's no <head> tag in the response", async () => {
const middleware = handleRequest();

Expand Down
Loading