: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(csp): serve the emoji picker data ourselves (#103237)
Tom Piccirelloef80e50c70df
diff --git a/.semgrep/rules/security/frimousse-via-emoji-picker-panel.test.ts b/.semgrep/rules/security/frimousse-via-emoji-picker-panel.test.tsnew file mode 100644index 000000000000..298322db8a4d--- /dev/null+++ b/.semgrep/rules/security/frimousse-via-emoji-picker-panel.test.ts@@ -0,0 +1,43 @@+// @ts-nocheck+// Test fixture for the frimousse-via-emoji-picker-panel rule.++// ruleid: frimousse-via-emoji-picker-panel+import { EmojiPicker } from 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+import frimousse from 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+import * as Frimousse from 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+import 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+const dynamic = import('frimousse')++// ruleid: frimousse-via-emoji-picker-panel+const required = require('frimousse')++// A module that re-exports the package hands the CDN default to every file that imports it.+// ruleid: frimousse-via-emoji-picker-panel+export { EmojiPicker as ReexportedPicker } from 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+export * from 'frimousse'++// ruleid: frimousse-via-emoji-picker-panel+export * as FrimousseReexport from 'frimousse'++// ok: frimousse-via-emoji-picker-panel+import { EmojiPickerPanel } from 'lib/components/EmojiPicker/EmojiPickerPanel'++// ok: frimousse-via-emoji-picker-panel+import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'++// A package whose name merely starts with the same word is not this one.+// ok: frimousse-via-emoji-picker-panel+import { other } from 'frimousse-helpers'++// ok: frimousse-via-emoji-picker-panel+export * from 'frimousse-helpers'diff --git a/.semgrep/rules/security/frimousse-via-emoji-picker-panel.yaml b/.semgrep/rules/security/frimousse-via-emoji-picker-panel.yamlnew file mode 100644index 000000000000..2ad1dcd88c5a--- /dev/null+++ b/.semgrep/rules/security/frimousse-via-emoji-picker-panel.yaml@@ -0,0 +1,49 @@+rules:+ - id: frimousse-via-emoji-picker-panel+ message: |+ `frimousse` imported or re-exported directly. Render `EmojiPickerPanel` or `EmojiPickerPopover`+ from `lib/components/EmojiPicker` instead.++ frimousse fetches its emoji data from the `emojibaseUrl` prop of `EmojiPicker.Root`,+ and the prop defaults to `https://cdn.jsdelivr.net/npm/emojibase-data@latest`. A+ picker that does not pass the prop silently takes that default. The URL lives inside+ the dependency, not in our source, so searching the repository for the CDN does not+ find those call sites.++ The app's `connect-src` does not list jsdelivr, and should not: an open CDN there+ lets anyone publish the bytes the app reads. The browser refuses the fetch, and+ frimousse has no error state, so the picker shows "Loading…" forever.++ The panel passes the same-origin URL that the build serves the pinned+ `emojibase-data` files from, so the policy needs no CDN entry.++ If you genuinely need frimousse directly, put+ `// nosemgrep: frimousse-via-emoji-picker-panel` on the line before the import+ with a reason, and pass a same-origin `emojibaseUrl` to `EmojiPicker.Root`.+ severity: ERROR+ languages: [typescript, javascript]+ paths:+ # The leading slash pins these to the repository root, which is where the app+ # and the panel live. Without it semgrep warns that it will anchor them anyway.+ include:+ - /frontend/src+ - /products+ - /common+ exclude:+ # The panel is the one place that may import the package.+ - /frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx+ pattern-either:+ - pattern: import { ... } from 'frimousse'+ - pattern: import $X from 'frimousse'+ - pattern: import * as $X from 'frimousse'+ - pattern: import 'frimousse'+ - pattern: import('frimousse')+ - pattern: require('frimousse')+ # Named re-exports already match the import patterns above. This one covers+ # `export * from` and `export * as $X from`, which they miss.+ - pattern: export * from 'frimousse'+ metadata:+ category: security+ confidence: HIGH+ references:+ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-srcdiff --git a/common/storybook/.storybook/main.ts b/common/storybook/.storybook/main.tsindex 6826ca9dc3f2..713ea28e470d 100644--- a/common/storybook/.storybook/main.ts+++ b/common/storybook/.storybook/main.ts@@ -54,6 +54,8 @@ const config: StorybookConfig = {// story whose play function is still running when it fires.{ from: '../.workers', to: '/static' },{ from: '../../../frontend/node_modules/@posthog/hedgehog-mode/assets', to: '/static/hedgehog-mode' },+ // EmojiPickerPanel loads frimousse's emoji data from here. The app build copies the same files into dist.+ { from: '../../../frontend/node_modules/emojibase-data/en', to: '/static/emoji/en' },// The replay player mounts rrweb into this document rather than the app's, so a recorded// page is judged against its policy instead of ours. Django renders the same file; serving// it here keeps stories on the real path rather than a Storybook-only stand-in.diff --git a/frontend/build.mjs b/frontend/build.mjsindex ce0ded138cc9..ebcd7ae15230 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -30,6 +30,7 @@ copyPublicFolder(path.resolve(__dirname, 'node_modules', '@posthog', 'hedgehog-mode', 'assets'),path.resolve(__dirname, 'dist', 'hedgehog-mode'))+copyEmojibaseData()copySnappyWASMFile(__dirname)copyRRWebWorkerFiles(__dirname)@@ -185,6 +186,18 @@ export function writePreloadManifest(outputs = {}) {fs.writeFileSync(path.resolve(distDir, 'preload-manifest.json'), JSON.stringify(manifest, null, 2))}+// EmojiPickerPanel loads frimousse's emoji data from /static/emoji rather than from a CDN. frimousse+// requests only these two files for the `en` locale. The Vite public-assets plugin copies the same files+// in development.+function copyEmojibaseData() {+ const from = path.resolve(__dirname, 'node_modules', 'emojibase-data', 'en')+ const to = path.resolve(__dirname, 'dist', 'emoji', 'en')+ fs.mkdirSync(to, { recursive: true })+ for (const file of ['data.json', 'messages.json']) {+ fs.copyFileSync(path.resolve(from, file), path.resolve(to, file))+ }+}+export function writeIndexHtml(chunks = {}, entrypoints = []) {copyIndexHtml(__dirname, 'src/index.html', 'dist/index.html', 'index', chunks, entrypoints)copyIndexHtml(__dirname, 'src/layout.html', 'dist/layout.html', 'index', chunks, entrypoints)diff --git a/frontend/package.json b/frontend/package.jsonindex 5e9834f54d76..46711c114a9b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -214,6 +214,7 @@"dompurify": "^3.4.0","elkjs": "^0.10.0","emoji-regex": "^10.4.0",+ "emojibase-data": "17.0.0","eventsource-parser": "^3.0.0","fast-equals": "catalog:","fastpriorityqueue": "^0.7.5",diff --git a/frontend/plugins/vite-public-assets-plugin.ts b/frontend/plugins/vite-public-assets-plugin.tsindex 36d4feb29528..5a38be2db26a 100644--- a/frontend/plugins/vite-public-assets-plugin.ts+++ b/frontend/plugins/vite-public-assets-plugin.ts@@ -1,4 +1,13 @@-import { existsSync, mkdirSync, readFileSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'fs'+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmdirSync,+ unlinkSync,+ writeFileSync,+} from 'fs'import { dirname, join, relative, resolve } from 'path'import type { Plugin } from 'vite'@@ -113,6 +122,17 @@ function copyPublicAssets(): void {} else {console.warn('⚠️ Hedgehog-mode assets directory does not exist')}++ // EmojiPickerPanel loads frimousse's emoji data from /static/emoji. build.mjs copies the same files for production.+ // A missing file leaves the picker on "Loading…" with no error in the UI, so a failed copy stops the dev server+ // rather than logging a warning that is easy to miss.+ const emojibaseSrc = resolve('.', 'node_modules', 'emojibase-data', 'en')+ const emojibaseDest = resolve('.', 'dist', 'emoji', 'en')+ mkdirSync(emojibaseDest, { recursive: true })+ for (const file of ['data.json', 'messages.json']) {+ copyFileSync(join(emojibaseSrc, file), join(emojibaseDest, file))+ }+ console.info('✅ Copied emojibase data to dist/emoji/en')}export function publicAssetsPlugin(): Plugin {diff --git a/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.test.tsx b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.test.tsxnew file mode 100644index 000000000000..a6652a4eb4ae--- /dev/null+++ b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.test.tsx@@ -0,0 +1,51 @@+import '@testing-library/jest-dom'++import { cleanup, render, waitFor } from '@testing-library/react'+import emojibaseData from 'emojibase-data/en/data.json'+import emojibaseMessages from 'emojibase-data/en/messages.json'++import { EmojiPickerPanel } from './EmojiPickerPanel'++// The two files the build copies to /static/emoji. Any other URL, such as the frimousse CDN default,+// has no same-origin copy and the app's connect-src refuses it, so the mock refuses it too.+const SERVED: Record<string, unknown> = {+ '/static/emoji/en/data.json': emojibaseData,+ '/static/emoji/en/messages.json': emojibaseMessages,+}++describe('EmojiPickerPanel', () => {+ const originalFetch = globalThis.fetch+ let fetchMock: jest.Mock++ beforeEach(() => {+ // frimousse caches the data in localStorage and skips the fetch on a hit.+ localStorage.clear()+ sessionStorage.clear()+ fetchMock = jest.fn(async (url: string) => {+ if (!(url in SERVED)) {+ throw new TypeError(`Failed to fetch ${url}`)+ }+ return { json: async () => SERVED[url], headers: { get: () => null } }+ })+ globalThis.fetch = fetchMock as unknown as typeof fetch+ })++ afterEach(() => {+ cleanup()+ globalThis.fetch = originalFetch+ })++ it('renders emojis from the same-origin files the build serves', async () => {+ const { container } = render(<EmojiPickerPanel onEmojiSelect={jest.fn()} />)++ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))+ expect(fetchMock.mock.calls.map(([url]) => url).sort()).toEqual([+ '/static/emoji/en/data.json',+ '/static/emoji/en/messages.json',+ ])+ // frimousse also renders a hidden sizer row with the same button; real rows carry role="row".+ await waitFor(() =>+ expect(container.querySelector('[role="row"] [data-attr="emoji-picker-button"]')).toBeInTheDocument()+ )+ })+})diff --git a/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsxindex d0b1a11dcbfa..ba5d6f8094e7 100644--- a/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx+++ b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx@@ -6,6 +6,13 @@ import {EmojiPickerListRowProps,} from 'frimousse'+// frimousse fetches `<emojibaseUrl>/<locale>/data.json` and `messages.json`, and the URL defaults to+// cdn.jsdelivr.net. The app's connect-src does not allow that CDN, and frimousse has no error state, so a+// refused fetch leaves the picker on "Loading…". The build copies the pinned emojibase-data files to this+// path: `build.mjs` for production and the public-assets Vite plugin in development. It copies the `en`+// locale only, so a `locale` prop needs that locale copied as well.+const EMOJIBASE_URL = '/static/emoji'+const EmojiPickerCategoryHeader = ({ category, ...props }: EmojiPickerListCategoryHeaderProps): JSX.Element => (<div className="bg-bg-light px-3 pt-3 pb-1.5 font-medium text-neutral-600 text-sm" {...props}>{category.label}@@ -48,6 +55,7 @@ export function EmojiPickerPanel({return (<EmojiPicker.RootclassName={clsx('isolate flex h-[368px] w-fit flex-col bg-bg-light', className)}+ emojibaseUrl={EMOJIBASE_URL}onEmojiSelect={({ emoji }) => {onEmojiSelect(emoji)}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 563a72c6c8db..21dc0557d75a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1040,6 +1040,9 @@ importers:emoji-regex:specifier: ^10.4.0version: 10.4.0+ emojibase-data:+ specifier: 17.0.0+ version: 17.0.0([email protected])eventsource-parser:specifier: ^3.0.0version: 3.0.0@@ -15885,6 +15888,15 @@ packages:resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}+ resolution: {integrity: sha512-Yvgb5AWoHViHV/gq1qr5ZAarcBip+B27/ZLRsUJkbgAEaLlZ/fof9g882LTpmEpyhBNEC0m2SEmItljHsTygjA==}+ peerDependencies:+ emojibase: '*'++ resolution: {integrity: sha512-bXdpf4HPY3p41zK5swVKZdC/VynsMZ4LoLxdYDE+GucqkFwzcM1GVc4ODfYAlwoKaf2U2oNNUoOO78N96ovpBA==}+ engines: {node: '>=18.12.0'}+resolution: {integrity: sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==}engines: {node: '>=14'}@@ -36239,6 +36251,12 @@ snapshots:+ dependencies:+ emojibase: 17.0.0++ [email protected]: {}+