:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): decode html entities in tracked email link hrefs (#62074)
Meikel Ratza4e9fd64846f
diff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.test.tsindex 01eb6bff5d08..8eab42b80ae1 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.test.ts@@ -16,7 +16,7 @@ import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { closeHub, createHub } from '~/utils/db/hub'import { Hub, Team } from '../../../types'-import { PIXEL_GIF } from './email-tracking.service'+import { PIXEL_GIF, addTrackingToEmail, decodeHtmlEntitiesInHref } from './email-tracking.service'import { generateEmailTrackingCode } from './helpers/tracking-code'describe('EmailTrackingService', () => {@@ -35,6 +35,79 @@ describe('EmailTrackingService', () => {await closeHub(hub)})+ describe('addTrackingToEmail', () => {+ const invocation = {+ functionId: 'fn-1',+ id: 'inv-1',+ teamId: 1,+ } as any++ const extractTarget = (html: string): string => {+ const match = html.match(/href="[^"]*target=([^"&]+)/)+ if (!match) {+ throw new Error(`no tracking href in: ${html}`)+ }+ return decodeURIComponent(match[1])+ }++ it.each([+ [+ 'named entity &',+ '<body><a href="https://example.com/?foo=bar&baz=bop">x</a></body>',+ 'https://example.com/?foo=bar&baz=bop',+ ],+ [+ 'decimal numeric entity &',+ '<body><a href="https://example.com/?a=1&b=2">x</a></body>',+ 'https://example.com/?a=1&b=2',+ ],+ [+ 'hex numeric entity &',+ '<body><a href="https://example.com/?a=1&b=2">x</a></body>',+ 'https://example.com/?a=1&b=2',+ ],+ [+ 'plain URL with no entities',+ '<body><a href="https://example.com/path">x</a></body>',+ 'https://example.com/path',+ ],+ ])('decodes %s in the redirect target', (_name, html, expected) => {+ expect(extractTarget(addTrackingToEmail(html, invocation))).toBe(expected)+ })++ it('skips literal javascript: hrefs', () => {+ const html = '<body><a href="javascript:alert(1)">x</a></body>'+ const out = addTrackingToEmail(html, invocation)+ expect(out).toContain('href="javascript:alert(1)"')+ expect(out).not.toContain('target=')+ })++ it('skips entity-encoded javascript: hrefs after decoding', () => {+ const html = '<body><a href="javascript:alert(1)">x</a></body>'+ const out = addTrackingToEmail(html, invocation)+ expect(out).toContain('href="javascript:alert(1)"')+ expect(out).not.toContain('target=')+ })+ })++ describe('decodeHtmlEntitiesInHref', () => {+ it.each([+ ['https://example.com/?a=1&b=2', 'https://example.com/?a=1&b=2'],+ ['https://example.com/?a=1&b=2', 'https://example.com/?a=1&b=2'],+ ['https://example.com/?a=1&b=2', 'https://example.com/?a=1&b=2'],+ ['https://example.com/?a=1&b=2&c=3', 'https://example.com/?a=1&b=2&c=3'],+ ['https://example.com/path', 'https://example.com/path'],+ // Non-entity ampersands (legacy unencoded HTML) pass through untouched.+ ['https://example.com/?a=1&b=2', 'https://example.com/?a=1&b=2'],+ // Out-of-range code points (> 0x10FFFF) must not throw RangeError;+ // the entity is left as-is.+ ['https://example.com/?x=�', 'https://example.com/?x=�'],+ ['https://example.com/?x=�', 'https://example.com/?x=�'],+ ])('decodes %s to %s', (input, expected) => {+ expect(decodeHtmlEntitiesInHref(input)).toBe(expected)+ })+ })+describe('api', () => {// NOTE: These tests are done via the CdpApi router so we can get full coverage of the codelet api: CdpApidiff --git a/nodejs/src/cdp/services/messaging/email-tracking.service.ts b/nodejs/src/cdp/services/messaging/email-tracking.service.tsindex f0c172e10a17..47d66ea7ad8e 100644--- a/nodejs/src/cdp/services/messaging/email-tracking.service.ts+++ b/nodejs/src/cdp/services/messaging/email-tracking.service.ts@@ -44,11 +44,34 @@ export const generateTrackingRedirectUrl = (return `${defaultConfig.CDP_EMAIL_TRACKING_URL}/public/m/redirect?ph_id=${generateEmailTrackingCode(invocation)}&target=${encodeURIComponent(targetUrl)}`}+// HTML attribute values arrive entity-encoded (e.g. `&`, `&`). Decode before+// percent-encoding for the tracking redirect, otherwise `?a=1&b=2` round-trips+// through `target=` as a literal `&` and breaks the destination page's query string.+const HTML_ENTITY_REGEX = /&(?:(amp|lt|gt|quot|apos)|#(\d+)|#x([0-9a-fA-F]+));/g+const NAMED_ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }++export const decodeHtmlEntitiesInHref = (value: string): string => {+ return value.replace(HTML_ENTITY_REGEX, (_match, named, dec, hex) => {+ if (named) {+ return NAMED_ENTITIES[named]+ }+ const code = dec ? parseInt(dec, 10) : parseInt(hex, 16)+ // `String.fromCodePoint` throws RangeError above 0x10FFFF — `Number.isFinite` alone+ // wouldn't catch e.g. `�` since `parseInt` happily returns a finite value.+ return code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : _match+ })+}+export const addTrackingToEmail = (html: string, invocation: CyclotronJobInvocationHogFunction): string => {const trackingUrl = generateEmailTrackingPixelUrl(invocation)html = html.replace(LINK_REGEX, (m, d, s, u) => {- const href = d || s || u || ''+ const href = decodeHtmlEntitiesInHref(d || s || u || '')+ // LINK_REGEX skips literal `javascript:` hrefs, but an attacker could entity-encode+ // the scheme (e.g. `javascript:`) to slip past it; re-check after decoding.+ if (/^\s*javascript:/i.test(href)) {+ return m+ }const tracked = generateTrackingRedirectUrl(invocation, href)// replace just the href in the original tag to preserve other attributes