Skip to content

: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.

feat(toolbar): show the toolbar in a browser extension side panel (#116638)

posthog[bot]15e9d0dadc2d
diff --git a/.agents/skills/building-the-toolbar/SKILL.md b/.agents/skills/building-the-toolbar/SKILL.md
new file mode 100644
index 000000000000..2071d93dd8f4
--- /dev/null
+++ b/.agents/skills/building-the-toolbar/SKILL.md
@@ -0,0 +1,79 @@
+---
+name: building-the-toolbar
+description: Builds, watches, checks and verifies the PostHog toolbar in both of its forms, the floating toolbar that posthog-js loads on customer pages and the browser extension that shows the toolbar in a Chrome side panel or Firefox sidebar. Use when changing anything under frontend/src/toolbar/ (floating toolbar or extension), frontend/toolbar-config.mjs, or the toolbar build and guard scripts, or when asked to build, watch, load unpacked, or test the toolbar or the toolbar extension in a browser. Covers `pnpm build:toolbars` and `pnpm watch:toolbars`, the check-toolbar-size, check-toolbar-graph and check-toolbar-csp-eval guards, why both forms must be built and kept in sync, and how to check each one in a real browser.
+---
+
+# Building the toolbar
+
+One source tree, `frontend/src/toolbar/`, ships in two forms.
+Both builds live in `frontend/toolbar-config.mjs` and share its toolbar module plugin, which swaps app modules for the toolbar's shims and keeps denylisted packages out.
+
+| Form | Entry | Output (under `frontend/dist/`) | Runs in |
+| ----------------- | -------------------------------------- | --------------------------------------------------- | ------------------------------------------------ |
+| Floating toolbar | `src/toolbar/index.tsx` | `toolbar.js` loader, `toolbar/` app chunks | Customer pages, loaded by posthog-js |
+| Browser extension | `src/toolbar/extension/panel.tsx` etc. | `toolbar-extension/<browser>/`, one zip per browser | Chrome side panel, Firefox sidebar (Manifest V3) |
+
+## Build both, every time
+
+Its panel imports the floating toolbar's own modules, such as `toolbarConfigLogic`, `toolbarEntitlementsLogic` and `toolbarPosthogJS`, and goes through the same module plugin.
+So any change under `frontend/src/toolbar/`, or in `toolbar-config.mjs`, can break either form, even when you only meant to touch one.
+
+- Build and check both forms for every toolbar change.
+- Fix shared toolbar code in the general way.
+ Do not add an extension-only branch to shared code when a fix that serves both forms exists.
+ When a branch is unavoidable, keep it in one place and say why in a comment.
+
+From `frontend/`:
+
+```sh
+pnpm build:toolbars # production floating toolbar, then the extension
+pnpm watch:toolbars # rebuild both on change
+```
+
+To build one form only:
+
+| Form | Build | Watch |
+| ----------------- | ------------------------------ | ------------------------------ |
+| Floating toolbar | `node ./bin/build-toolbar.mjs` | `pnpm watch:toolbar` |
+| Browser extension | `pnpm build:toolbar-extension` | `pnpm watch:toolbar-extension` |
+
+The dev stack (`hogli start`) already runs `pnpm watch:toolbar` through `start-vite`.
+While it runs, start `pnpm watch:toolbar-extension` alone, so two watchers don't write the same files.
+
+## Run the guards
+
+The guards read `toolbar-esbuild-meta.json` and `dist/toolbar*`, which the floating toolbar build writes.
+CI runs them on a production build, so run them after `pnpm build:toolbars`, not after a watch build:
+
+```sh
+pnpm check-toolbar-size # loader size, eager-set budget, every file under the CloudFront gzip limit
+pnpm check-toolbar-graph # no new toolbar-to-app import edges, no denylisted packages
+pnpm check-toolbar-csp-eval # no eval, new Function or string timers in shipped code
+```
+
+Each script's header comment explains its limits.
+When `check-toolbar-graph` fails, cut the new import rather than add it to `bin/toolbar-graph-baseline.json`.
+
+These guards cover the floating toolbar bundle only.
+The extension has no guard script, but Manifest V3 refuses `eval` and remote scripts, so a break there shows when you load the extension.
+
+Also run the toolbar tests and the logic types:
+
+```sh
+pnpm exec jest src/toolbar
+pnpm typegen:write # then check that git diff shows no drift in logic types
+```
+
+## Check it in a real browser
+
+Tests and builds don't show a broken overlay, a missing style, or a CSP refusal. Load the build.
+
+- **Extension.** Load `dist/toolbar-extension/chrome` unpacked in Chrome and `dist/toolbar-extension/firefox` as a temporary add-on in Firefox.
+ The steps are in [the extension README](../../../frontend/src/toolbar/extension/README.md#build-and-install); read it before you load the extension the first time.
+ After a rebuild, reload the extension, then close and open the panel.
+ Check both browsers when you change the extension.
+- **Floating toolbar.** Start the dev stack (see `/run-posthog`), open the Toolbar page at `http://localhost:8010/toolbar`, add a test site that loads posthog-js to the authorized URLs, and launch the toolbar on it.
+ `Toolbar.stories.tsx` renders the floating toolbar in Storybook when you only need to look at a component.
+
+Check the forms you didn't mean to change as well.
+A change to a shared logic shows up in both.
diff --git a/.github/workflows/ci-toolbar-extension.yml b/.github/workflows/ci-toolbar-extension.yml
new file mode 100644
index 000000000000..ae08dc19b115
--- /dev/null
+++ b/.github/workflows/ci-toolbar-extension.yml
@@ -0,0 +1,50 @@
+name: Toolbar extension
+
+# Builds the toolbar browser extension and uploads the Chrome and Firefox zips as a run artifact, so a reviewer can
+# install the build from a PR. The workflow never publishes to a browser store.
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/ci-toolbar-extension.yml'
+ - 'frontend/bin/build-toolbar-extension.mjs'
+ - 'frontend/toolbar-config.mjs'
+ - 'frontend/src/toolbar/**'
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Build toolbar extension
+ runs-on: depot-ubuntu-24.04-4
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Install pnpm dependencies
+ uses: ./.github/actions/pnpm-install
+ with:
+ install-command: pnpm --filter=@posthog/frontend... install --frozen-lockfile
+
+ - name: Prepare frontend
+ run: bin/turbo --filter=@posthog/frontend prepare
+
+ - name: Build products
+ run: pnpm --filter=@posthog/frontend build:products
+
+ - name: Build extension
+ run: pnpm --filter=@posthog/frontend build:toolbar-extension
+
+ - name: Upload extension zips
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: toolbar-extension
+ path: frontend/dist/toolbar-extension/*.zip
+ if-no-files-found: error
+ retention-days: 14
diff --git a/AGENTS.md b/AGENTS.md
index 10e762fca959..4120d396fb4b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -321,6 +321,7 @@ ALWAYS invoke the matching skill **first** — do not skip it, and do not attemp
- `/modifying-taxonomic-filter` — any TaxonomicFilter change
- `/profiling-slow-api-endpoints` — an endpoint, list, picker, or scene is slow, a p95 latency number needs explaining, or a Postgres query plan needs checking against production rather than a local database
- `/placing-product-frontend-code` — adding a frontend file or directory for a product, or deciding between `products/<name>/frontend/` and `frontend/src/scenes/<name>/`
+- `/building-the-toolbar`: any change under `frontend/src/toolbar/`, floating toolbar or extension. Build and check both, and keep them in sync
- [`products/conversations/skills/organizing-conversations-code/SKILL.md`](products/conversations/skills/organizing-conversations-code/SKILL.md) — adding, moving, renaming, or reviewing files under `products/conversations/`
- `/integrating-with-posthog-ai` — making a product surface work with PostHog AI: injecting scene context or custom instructions, reacting to the agent's tool calls, or rendering your product's tool cards in a thread
- `/sending-notifications` — adding notification support
diff --git a/frontend/bin/build-toolbar-extension.mjs b/frontend/bin/build-toolbar-extension.mjs
new file mode 100644
index 000000000000..a05c971f8f7f
--- /dev/null
+++ b/frontend/bin/build-toolbar-extension.mjs
@@ -0,0 +1,42 @@
+#!/usr/bin/env node
+/**
+ * Builds the toolbar browser extension into dist/toolbar-extension/<browser>/.
+ * Pass --dev to watch and rebuild.
+ */
+import * as path from 'path'
+import { fileURLToPath } from 'url'
+
+import { buildInParallel } from '@posthog/esbuilder'
+
+import {
+ cleanToolbarExtensionBuild,
+ finalizeToolbarExtensionBuild,
+ getToolbarExtensionBuildConfig,
+ getToolbarExtensionScriptsBuildConfig,
+} from '../toolbar-config.mjs'
+
+const __dirname = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+
+cleanToolbarExtensionBuild(__dirname)
+
+await buildInParallel(
+ [
+ {
+ ...getToolbarExtensionBuildConfig(__dirname),
+ absWorkingDir: __dirname,
+ bundle: true,
+ },
+ {
+ ...getToolbarExtensionScriptsBuildConfig(__dirname),
+ absWorkingDir: __dirname,
+ bundle: true,
+ },
+ ],
+ {
+ onBuildComplete(config, buildResponse) {
+ if (buildResponse) {
+ finalizeToolbarExtensionBuild(__dirname)
+ }
+ },
+ }
+)
diff --git a/frontend/package.json b/frontend/package.json
index 7a24f91a6dc2..e89e2de3133d 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -53,6 +53,10 @@
"start-vite": "pnpm build:products && concurrently --kill-others-on-fail -n VITE,TOOLBAR,WORKERS -c green,magenta,cyan \"vite --host 0.0.0.0\" \"pnpm watch:toolbar\" \"pnpm watch:workers\"",
"watch:workers": "node ./bin/watch-workers.mjs --dev",
"watch:toolbar": "node ./bin/build-toolbar.mjs --dev",
+ "build:toolbar-extension": "node ./bin/build-toolbar-extension.mjs",
+ "watch:toolbar-extension": "node ./bin/build-toolbar-extension.mjs --dev",
+ "build:toolbars": "node ./bin/build-toolbar.mjs && node ./bin/build-toolbar-extension.mjs",
+ "watch:toolbars": "concurrently --kill-others-on-fail -n TOOLBAR,EXTENSION -c magenta,blue \"pnpm watch:toolbar\" \"pnpm watch:toolbar-extension\"",
"mobile-replay:web:schema:build:json": "ts-json-schema-generator -f ./tsconfig.json --path 'node_modules/posthog-js/dist/rrweb-types.d.ts' --type 'eventWithTime' --expose all --no-top-ref --no-type-check --out ./src/scenes/session-recordings/mobile-replay/schema/web/rr-web-schema.json && oxfmt ./src/scenes/session-recordings/mobile-replay/schema/web/rr-web-schema.json",
"mobile-replay:mobile:schema:build:json": "ts-json-schema-generator -f ./tsconfig.json --path './src/scenes/session-recordings/mobile-replay/mobile.types.ts' --type 'mobileEventWithTime' --expose all --no-top-ref --no-type-check --out ./src/scenes/session-recordings/mobile-replay/schema/mobile/rr-mobile-schema.json && oxfmt ./src/scenes/session-recordings/mobile-replay/schema/mobile/rr-mobile-schema.json",
"mobile-replay:schema:build:json": "pnpm mobile-replay:web:schema:build:json && pnpm mobile-replay:mobile:schema:build:json",
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
index 2ca3ad1bb3b2..cab531cae354 100644
--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
@@ -15,12 +15,12 @@ import {
SuggestedDomain,
appEditorUrl,
authorizedUrlListLogic,
- checkUrlIsAuthorized,
checkUrlIsSafeToFrame,
directToolbarUrl,
filterNotAuthorizedUrls,
validateProposedUrl,
} from './authorizedUrlListLogic'
+import { checkUrlIsAuthorized } from './authorizedUrlMatching'
describe('the authorized urls list logic', () => {
let logic: ReturnType<typeof authorizedUrlListLogic.build>
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
index d5996bb4f1a0..664cb33b7a5d 100644
--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.ts
@@ -20,6 +20,10 @@ import { encodeParams, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
+import {
+ checkUrlIsAuthorized,
+ sanitizePossibleWildCardedURL,
+} from 'lib/components/AuthorizedUrlList/authorizedUrlMatching'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProductIntent } from 'lib/utils/product-intents'
@@ -46,15 +50,6 @@ export enum AuthorizedUrlListType {
WEB_EXPERIMENTS = 'WEB_EXPERIMENTS',
}
-/**
- * Firefox does not allow you construct a new URL with e.g. https://*.example.com (which is to be fair more standards compliant than Chrome)
- * when used to probe for e.g. for authorized urls we only care if the proposed URL has a path so we can safely replace the wildcard with a character
- */
-export function sanitizePossibleWildCardedURL(url: string): URL {
- const deWildCardedURL = url.replace(/\*/g, 'x')
- return new URL(deWildCardedURL)
-}
-
/**
* Checks if the URL has a wildcard (*) in the port position e.g. http://localhost:*
*/
@@ -200,53 +195,6 @@ export function directToolbarUrl(
return `${appUrl}#__posthog=${state}`
}
-/** Treat www.domain.com and domain.com as equivalent. */
-const stripWww = (host: string): string => (host.startsWith('www.') ? host.slice(4) : host)
-
-export const checkUrlIsAuthorized = (url: string | URL, authorizedUrls: string[]): boolean => {
- try {
- const parsedUrl = typeof url === 'string' ? sanitizePossibleWildCardedURL(url) : url
- const urlWithoutPath = parsedUrl.protocol + '//' + parsedUrl.host
- const hostNormalized = stripWww(parsedUrl.hostname)
-
- return authorizedUrls.some((authorizedUrl) => {
- // Wildcard entries (subdomain or port wildcards, e.g. `https://*.example.com`). Anchor the
- // pattern with ^…$ so a `*` cannot match a suffix of an unrelated origin such as
- // `https://app.example.com.evil.com`.
- if (authorizedUrl.includes('*')) {
- try {
- const regex = new RegExp('^' + authorizedUrl.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$')
- return regex.test(urlWithoutPath)
- } catch {
- return false
- }
- }
-
- // Exact entries: compare by origin (protocol + host) instead of a substring check, so a
- // different domain cannot be authorized merely by being a prefix/substring of an entry
- // (e.g. `https://example.co` against `https://example.com`).
- try {
- const authorizedUrlParsed = sanitizePossibleWildCardedURL(authorizedUrl)
- if (authorizedUrlParsed.protocol + '//' + authorizedUrlParsed.host === urlWithoutPath) {
- return true
- }
- // www-equivalence: same protocol, hostnames equal with www. stripped. The protocol
- // check keeps an http origin from matching an https-only authorized entry.
- return (
- authorizedUrlParsed.protocol === parsedUrl.protocol &&
- stripWww(authorizedUrlParsed.hostname) === hostNormalized
- )
- } catch {
- return false
- }
- })
- } catch {
- // Ignore invalid URLs
- }
-
- return false
-}
-
/**
* Schemes allowed to be rendered in the Site preview iframe. That iframe runs with
* `allow-scripts allow-same-origin`, so a `javascript:`/`data:`/`blob:` src would execute in the
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlMatching.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlMatching.ts
new file mode 100644
index 000000000000..332d34e62087
--- /dev/null
+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlMatching.ts
@@ -0,0 +1,57 @@
+// Kept free of app imports so the toolbar browser extension can bundle it.
+
+/**
+ * Firefox does not allow you construct a new URL with e.g. https://*.example.com (which is to be fair more standards compliant than Chrome)
+ * when used to probe for e.g. for authorized urls we only care if the proposed URL has a path so we can safely replace the wildcard with a character
+ */
+export function sanitizePossibleWildCardedURL(url: string): URL {
+ const deWildCardedURL = url.replace(/\*/g, 'x')
+ return new URL(deWildCardedURL)
+}
+
+/** Treat www.domain.com and domain.com as equivalent. */
+const stripWww = (host: string): string => (host.startsWith('www.') ? host.slice(4) : host)
+
+export const checkUrlIsAuthorized = (url: string | URL, authorizedUrls: string[]): boolean => {
+ try {
+ const parsedUrl = typeof url === 'string' ? sanitizePossibleWildCardedURL(url) : url
+ const urlWithoutPath = parsedUrl.protocol + '//' + parsedUrl.host
+ const hostNormalized = stripWww(parsedUrl.hostname)
+
+ return authorizedUrls.some((authorizedUrl) => {
+ // Wildcard entries (subdomain or port wildcards, e.g. `https://*.example.com`). Anchor the
+ // pattern with ^…$ so a `*` cannot match a suffix of an unrelated origin such as
+ // `https://app.example.com.evil.com`.
+ if (authorizedUrl.includes('*')) {
+ try {
+ const regex = new RegExp('^' + authorizedUrl.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$')
+ return regex.test(urlWithoutPath)
+ } catch {
+ return false
+ }
+ }
+
+ // Exact entries: compare by origin (protocol + host) instead of a substring check, so a
+ // different domain cannot be authorized merely by being a prefix/substring of an entry
+ // (e.g. `https://example.co` against `https://example.com`).
+ try {
+ const authorizedUrlParsed = sanitizePossibleWildCardedURL(authorizedUrl)
+ if (authorizedUrlParsed.protocol + '//' + authorizedUrlParsed.host === urlWithoutPath) {
+ return true
+ }
+ // www-equivalence: same protocol, hostnames equal with www. stripped. The protocol
+ // check keeps an http origin from matching an https-only authorized entry.
+ return (
+ authorizedUrlParsed.protocol === parsedUrl.protocol &&
+ stripWww(authorizedUrlParsed.hostname) === hostNormalized
+ )
+ } catch {
+ return false
+ }
+ })
+ } catch {
+ // Ignore invalid URLs
+ }
+
+ return false
+}
diff --git a/frontend/src/toolbar/extension/ExtensionFeatureList.tsx b/frontend/src/toolbar/extension/ExtensionFeatureList.tsx
new file mode 100644
index 000000000000..05ef358fba78
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionFeatureList.tsx
@@ -0,0 +1,62 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBolt, IconCursorClick, IconExternal, IconFlask, IconPieChart, IconToggle } from '@posthog/icons'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { ToolbarFeatureGateStatus, toolbarFeatureGateStatus } from '~/toolbar/toolbarEntitlementsLogic'
+import { useToolbarFeatureFlag } from '~/toolbar/toolbarPosthogJS'
+
+import { EXTENSION_FEATURE_ENTRY_POINTS, ExtensionFeatureEntryPoint, ExtensionFeatureKey } from './extensionFeatures'
+import { extensionPanelLogic } from './extensionPanelLogic'
+
+const FEATURE_ICONS: Record<ExtensionFeatureKey, JSX.Element> = {
+ heatmaps: <IconCursorClick />,
+ actions: <IconBolt />,
+ 'feature-flags': <IconToggle />,
+ 'web-vitals': <IconPieChart />,
+ experiments: <IconFlask />,
+}
+
+const GATE_DISABLED_REASONS: Record<ToolbarFeatureGateStatus, string | null> = {
+ available: null,
+ checking: 'Checking plan access…',
+ unknown: "Couldn't check plan access. Close and open the panel to try again.",
+ locked: 'Needs a pay-as-you-go subscription',
+}
+
+function ExtensionFeatureButton({ entryPoint }: { entryPoint: ExtensionFeatureEntryPoint }): JSX.Element {
+ const { entitlements } = useValues(extensionPanelLogic)
+ const { openFeature } = useActions(extensionPanelLogic)
+ // Hooks run unconditionally, so features without a gate read the flag and ignore it.
+ const rolloutEnabled = useToolbarFeatureFlag(entryPoint.gate?.rolloutFlag ?? FEATURE_FLAGS.TOOLBAR_PAID_HEATMAPS)
+ const gateStatus = entryPoint.gate
+ ? toolbarFeatureGateStatus(entryPoint.gate.feature, rolloutEnabled, entitlements, false)
+ : 'available'
+
+ return (
+ <LemonButton
+ fullWidth
+ icon={FEATURE_ICONS[entryPoint.key]}
+ sideIcon={<IconExternal />}
+ disabledReason={GATE_DISABLED_REASONS[gateStatus]}
+ tooltip={`${entryPoint.description}. Opens in PostHog.`}
+ onClick={() => openFeature(entryPoint.key, entryPoint.path)}
+ data-attr={`toolbar-extension-feature-${entryPoint.key}`}
+ >
+ {entryPoint.label}
+ </LemonButton>
+ )
+}
+
+export function ExtensionFeatureList({ origin }: { origin: string }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="text-secondary text-xs">Toolbar tools for {new URL(origin).host}</div>
+ {EXTENSION_FEATURE_ENTRY_POINTS.map((entryPoint) => (
+ <ExtensionFeatureButton key={entryPoint.key} entryPoint={entryPoint} />
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionPanel.tsx b/frontend/src/toolbar/extension/ExtensionPanel.tsx
new file mode 100644
index 000000000000..7c3eaa449e16
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionPanel.tsx
@@ -0,0 +1,109 @@
+import { useActions, useValues } from 'kea'
+
+import { Logo } from 'lib/brand'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import { urls } from '~/toolbar/urls'
+
+import { ExtensionFeatureList } from './ExtensionFeatureList'
+import { extensionPanelLogic } from './extensionPanelLogic'
+import { ExtensionPanelSettings } from './ExtensionPanelSettings'
+import type { ExtensionPanelState, UnsupportedPageReason } from './extensionPanelState'
+
+const UNSUPPORTED_PAGE_MESSAGES: Record<UnsupportedPageReason, string> = {
+ 'browser-page': "The toolbar can't run on this page. Open your website to use it.",
+ 'insecure-page': 'The toolbar needs a secure page. Open the https version of this site.',
+ 'posthog-app': 'This is the PostHog app. Open your website to use the toolbar.',
+ 'extension-store': "Browsers don't let extensions run on this page. Open your website to use the toolbar.",
+}
+
+function ExtensionPanelBody({ panelState }: { panelState: ExtensionPanelState }): JSX.Element {
+ const { uiHost, user } = useValues(extensionPanelLogic)
+ const { requestHostPermission, openPostHogPath, openProjectPath, retry } = useActions(extensionPanelLogic)
+ const host = new URL(uiHost).host
+ const projectName = user?.team.name ?? 'this project'
+
+ switch (panelState.kind) {
+ case 'checking':
+ return (
+ <div className="flex items-center gap-2 text-secondary">
+ <Spinner />
+ Checking access…
+ </div>
+ )
+ case 'unsupported-page':
+ return <LemonBanner type="info">{UNSUPPORTED_PAGE_MESSAGES[panelState.reason]}</LemonBanner>
+ case 'host-permission-needed':
+ return (
+ <LemonBanner
+ type="info"
+ action={{
+ children: 'Allow access',
+ onClick: requestHostPermission,
+ 'data-attr': 'toolbar-extension-allow-host',
+ }}
+ >
+ Allow the extension to use your PostHog login on {host}.
+ </LemonBanner>
+ )
+ case 'signed-out':
+ return (
+ <LemonBanner
+ type="info"
+ action={{
+ children: 'Log in',
+ onClick: () => openPostHogPath('/login'),
+ 'data-attr': 'toolbar-extension-log-in',
+ }}
+ >
+ Log in to PostHog on {host}, then come back to this tab.
+ </LemonBanner>
+ )
+ case 'no-toolbar-access':
+ return (
+ <LemonBanner type="warning">
+ You don't have toolbar access in {projectName}. Ask a project admin for access, or switch to another
+ project.
+ </LemonBanner>
+ )
+ case 'unauthorized-url':
+ return (
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Open authorized URLs',
+ onClick: () => openProjectPath(urls.settings('project-toolbar', 'authorized-urls')),
+ 'data-attr': 'toolbar-extension-authorized-urls',
+ }}
+ >
+ {panelState.origin} isn't an authorized URL for {projectName}. Add it to use the toolbar here.
+ </LemonBanner>
+ )
+ case 'error':
+ return (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: retry, 'data-attr': 'toolbar-extension-retry' }}
+ >
+ Couldn't reach PostHog on {host}. Check your connection and try again.
+ </LemonBanner>
+ )
+ case 'ready':
+ return <ExtensionFeatureList origin={panelState.origin} />
+ }
+}
+
+export function ExtensionPanel(): JSX.Element {
+ const { panelState } = useValues(extensionPanelLogic)
+
+ return (
+ <div className="flex min-h-screen flex-col gap-3 p-3">
+ <h1 className="m-0 flex">
+ <Logo size="xs" title="PostHog" />
+ </h1>
+ <ExtensionPanelBody panelState={panelState} />
+ <ExtensionPanelSettings />
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/ExtensionPanelSettings.tsx b/frontend/src/toolbar/extension/ExtensionPanelSettings.tsx
new file mode 100644
index 000000000000..c8b709ecdf7a
--- /dev/null
+++ b/frontend/src/toolbar/extension/ExtensionPanelSettings.tsx
@@ -0,0 +1,115 @@
+import { useActions, useValues } from 'kea'
+import { useId, useState } from 'react'
+
+import { IconChevronRight, IconGear } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
+import { cn } from 'lib/utils/css-classes'
+
+import { canonicalizeUiHost } from '~/toolbar/toolbarConfigLogic'
+
+import { extensionPanelLogic } from './extensionPanelLogic'
+
+const CLOUD_HOSTS = ['https://us.posthog.com', 'https://eu.posthog.com']
+const CUSTOM_HOST = 'custom'
+
+export function ExtensionPanelSettings(): JSX.Element {
+ const { uiHost, user, projectSwitchFailed, settingsExpanded } = useValues(extensionPanelLogic)
+ const { setUiHost, switchProject, setSettingsExpanded } = useActions(extensionPanelLogic)
+ const settingsId = useId()
+ const isCloudHost = CLOUD_HOSTS.includes(uiHost)
+ const [editingCustomHost, setEditingCustomHost] = useState(false)
+ const [customHost, setCustomHost] = useState(isCloudHost ? '' : uiHost)
+ const canonicalCustomHost = canonicalizeUiHost(customHost)
+ const host = new URL(uiHost).host
+
+ return (
+ <div className="mt-auto flex flex-col gap-2 border-t pt-2">
+ <LemonButton
+ size="xsmall"
+ fullWidth
+ icon={<IconGear />}
+ sideIcon={
+ <IconChevronRight
+ className={cn(
+ 'transition-transform motion-reduce:transition-none',
+ settingsExpanded && 'rotate-90'
+ )}
+ />
+ }
+ onClick={() => setSettingsExpanded(!settingsExpanded)}
+ aria-expanded={settingsExpanded}
+ aria-controls={settingsExpanded ? settingsId : undefined}
+ data-attr="toolbar-extension-settings-toggle"
+ >
+ <span className="truncate text-xs text-secondary">{user ? `${user.team.name} · ${host}` : host}</span>
+ </LemonButton>
+ {settingsExpanded ? (
+ <div id={settingsId} className="flex flex-col gap-2">
+ {user ? (
+ <>
+ <LemonLabel>Project</LemonLabel>
+ <LemonSelect
+ size="small"
+ fullWidth
+ value={user.team.id}
+ onChange={(teamId) => switchProject(teamId)}
+ options={user.organization.teams.map((team) => ({ value: team.id, label: team.name }))}
+ data-attr="toolbar-extension-project"
+ />
+ {projectSwitchFailed ? (
+ <div className="text-danger text-xs">Couldn't switch the project. Try again.</div>
+ ) : null}
+ </>
+ ) : null}
+ <LemonLabel>PostHog host</LemonLabel>
+ <LemonSelect
+ size="small"
+ fullWidth
+ value={editingCustomHost || !isCloudHost ? CUSTOM_HOST : uiHost}
+ onChange={(value) => {
+ setEditingCustomHost(value === CUSTOM_HOST)
+ if (value !== CUSTOM_HOST) {
+ setUiHost(value)
+ }
+ }}
+ options={[
+ { value: 'https://us.posthog.com', label: 'PostHog Cloud US' },
+ { value: 'https://eu.posthog.com', label: 'PostHog Cloud EU' },
+ { value: CUSTOM_HOST, label: isCloudHost ? 'Self-hosted' : new URL(uiHost).host },
+ ]}
+ data-attr="toolbar-extension-host"
+ />
+ {editingCustomHost ? (
+ <div className="flex gap-2">
+ <LemonInput
+ size="small"
+ className="flex-1"
+ placeholder="https://posthog.example.com"
+ value={customHost}
+ onChange={setCustomHost}
+ />
+ <LemonButton
+ size="small"
+ type="primary"
+ disabledReason={canonicalCustomHost ? null : 'Enter the address of your PostHog app'}
+ onClick={() => {
+ if (canonicalCustomHost) {
+ setUiHost(canonicalCustomHost)
+ setEditingCustomHost(false)
+ }
+ }}
+ data-attr="toolbar-extension-save-host"
+ >
+ Save
+ </LemonButton>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/frontend/src/toolbar/extension/README.md b/frontend/src/toolbar/extension/README.md
new file mode 100644
index 000000000000..af236d59c13a
--- /dev/null
+++ b/frontend/src/toolbar/extension/README.md
@@ -0,0 +1,38 @@
+# Toolbar browser extension
+
+The extension gives the toolbar tools to a page without the floating toolbar.
+It opens from the extension button as a side panel in Chrome and as a sidebar in Firefox, and shows `panel.html`.
+The panel follows the active tab of its window.
+
+## Build and install
+
+Build both browser folders from `frontend/`:
+
+```sh
+pnpm build:toolbar-extension # one build
+pnpm watch:toolbar-extension # rebuild on change
+```
+
+The build writes `dist/toolbar-extension/chrome/` and `dist/toolbar-extension/firefox/`.
+Only `manifest.json` is different between them.
+It also zips each folder into `dist/toolbar-extension/posthog-toolbar-<browser>-<version>.zip`.
+
+A pull request that changes the extension runs the "Toolbar extension" workflow.
+Download the `toolbar-extension` artifact from the run to install that build without building it yourself.
+
+### Chrome (116 or later)
+
+1. Open `chrome://extensions` and turn on **Developer mode**.
+2. Click **Load unpacked** and select `frontend/dist/toolbar-extension/chrome`, or the unzipped Chrome folder from the artifact.
+3. Pin the extension, then click its button to open the side panel.
+
+After a rebuild, click the reload icon on the extension card, then close and open the side panel.
+
+### Firefox (128 or later)
+
+1. Open `about:debugging#/runtime/this-firefox`.
+2. Click **Load Temporary Add-on** and select `frontend/dist/toolbar-extension/firefox/manifest.json`, or the Firefox zip from the artifact.
+3. Click the extension button to open the sidebar.
+
+Firefox removes a temporary add-on when it quits.
+A permanent install needs an add-on signed by addons.mozilla.org.
diff --git a/frontend/src/toolbar/extension/background.ts b/frontend/src/toolbar/extension/background.ts
new file mode 100644
index 000000000000..de7243066421
--- /dev/null
+++ b/frontend/src/toolbar/extension/background.ts
@@ -0,0 +1,3 @@
+import { openPanelFromToolbarButton } from './extensionBrowser'
+
+openPanelFromToolbarButton()
diff --git a/frontend/src/toolbar/extension/extensionBrowser.ts b/frontend/src/toolbar/extension/extensionBrowser.ts
new file mode 100644
index 000000000000..e54ce0af92eb
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionBrowser.ts
@@ -0,0 +1,145 @@
+// Firefox and Chrome both expose the promise-based `chrome.*` namespace to Manifest V3 extensions.
+// Only the calls the side panel and the background script make are typed here.
+interface ExtensionTab {
+ id?: number
+ url?: string
+}
+
+interface ExtensionPermissions {
+ origins: string[]
+}
+
+interface TabActiveInfo {
+ tabId: number
+ windowId: number
+}
+
+interface TabChangeInfo {
+ url?: string
+ status?: string
+}
+
+interface ExtensionEvent<Listener> {
+ addListener: (listener: Listener) => void
+ removeListener: (listener: Listener) => void
+}
+
+interface ExtensionBrowserApi {
+ tabs: {
+ query: (query: { active: true; windowId?: number; currentWindow?: true }) => Promise<ExtensionTab[]>
+ create: (properties: { url: string }) => Promise<unknown>
+ onActivated: ExtensionEvent<(activeInfo: TabActiveInfo) => void>
+ onUpdated: ExtensionEvent<
+ (
+ tabId: number,
+ changeInfo: TabChangeInfo,
+ tab: ExtensionTab & { active?: boolean; windowId?: number }
+ ) => void
+ >
+ }
+ windows: {
+ getCurrent: () => Promise<{ id?: number }>
+ }
+ storage: {
+ local: {
+ get: (key: string) => Promise<Record<string, unknown>>
+ set: (items: Record<string, unknown>) => Promise<void>
+ }
+ }
+ permissions: {
+ contains: (permissions: ExtensionPermissions) => Promise<boolean>
+ request: (permissions: ExtensionPermissions) => Promise<boolean>
+ }
+ action: {
+ onClicked: ExtensionEvent<() => void>
+ }
+ sidePanel?: {
+ setPanelBehavior: (behavior: { openPanelOnActionClick: boolean }) => Promise<void>
+ }
+ sidebarAction?: {
+ toggle: () => Promise<void>
+ }
+}
+
+// Firefox puts its own APIs, such as `sidebarAction`, only on `browser`.
+const extensionBrowser = ((globalThis as unknown as { browser?: ExtensionBrowserApi }).browser ??
+ (globalThis as unknown as { chrome: ExtensionBrowserApi }).chrome) as ExtensionBrowserApi
+
+// pinned: extension storage key, renaming it resets the saved PostHog host
+const UI_HOST_STORAGE_KEY = 'posthogUiHost'
+
+export function openPanelFromToolbarButton(): void {
+ if (extensionBrowser.sidePanel) {
+ void extensionBrowser.sidePanel.setPanelBehavior({ openPanelOnActionClick: true })
+ return
+ }
+ const sidebarAction = extensionBrowser.sidebarAction
+ if (sidebarAction) {
+ // Firefox opens a sidebar only from a user action, so the toggle must run in the click listener without an await.
+ extensionBrowser.action.onClicked.addListener(() => void sidebarAction.toggle())
+ }
+}
+
+export async function getActiveTab(): Promise<ExtensionTab | null> {
+ const [tab] = await extensionBrowser.tabs.query({ active: true, currentWindow: true })
+ return tab ?? null
+}
+
+/** Returns a function that removes the listeners. */
+export function onActiveTabChange(handler: (tab: ExtensionTab | null) => void): () => void {
+ let panelWindowId: number | undefined
+ void extensionBrowser.windows.getCurrent().then((panelWindow) => {
+ panelWindowId = panelWindow.id
+ })
+ const onActivated = ({ windowId }: TabActiveInfo): void => {
+ if (windowId === panelWindowId) {
+ void getActiveTab().then(handler, () => handler(null))
+ }
+ }
+ const onUpdated = (
+ _tabId: number,
+ changeInfo: TabChangeInfo,
+ tab: ExtensionTab & { active?: boolean; windowId?: number }
+ ): void => {
+ // A reload keeps the URL but removes everything the extension added to the page.
+ if (tab.active && tab.windowId === panelWindowId && (changeInfo.url || changeInfo.status === 'complete')) {
+ handler(tab)
+ }
+ }
+ extensionBrowser.tabs.onActivated.addListener(onActivated)
+ extensionBrowser.tabs.onUpdated.addListener(onUpdated)
+ return () => {
+ extensionBrowser.tabs.onActivated.removeListener(onActivated)
+ extensionBrowser.tabs.onUpdated.removeListener(onUpdated)
+ }
+}
+
+export async function openTab(url: string): Promise<void> {
+ await extensionBrowser.tabs.create({ url })
+}
+
+export async function getStoredUiHost(): Promise<string | null> {
+ const stored = await extensionBrowser.storage.local.get(UI_HOST_STORAGE_KEY)
+ const value = stored[UI_HOST_STORAGE_KEY]
+ return typeof value === 'string' ? value : null
+}
+
+export async function setStoredUiHost(uiHost: string): Promise<void> {
+ await extensionBrowser.storage.local.set({ [UI_HOST_STORAGE_KEY]: uiHost })
+}
+
+function originPattern(uiHost: string): ExtensionPermissions {
+ // Match patterns cover every port of a host, and Firefox rejects a pattern that names one.
+ const { protocol, hostname } = new URL(uiHost)
+ return { origins: [`${protocol}//${hostname}/*`] }
+}
+
+/** The manifest asks for every site, but the user can take access back for a site in the browser's settings. */
+export async function hasHostPermission(uiHost: string): Promise<boolean> {
+ return await extensionBrowser.permissions.contains(originPattern(uiHost))
+}
+
+/** Must run inside the click handler: browsers show the permission prompt only for a user gesture. */
+export async function requestHostPermission(uiHost: string): Promise<boolean> {
+ return await extensionBrowser.permissions.request(originPattern(uiHost))
+}
diff --git a/frontend/src/toolbar/extension/extensionFeatures.ts b/frontend/src/toolbar/extension/extensionFeatures.ts
new file mode 100644
index 000000000000..df40feda25a5
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionFeatures.ts
@@ -0,0 +1,52 @@
+import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
+
+import { urls } from '~/toolbar/urls'
+import { AvailableFeature } from '~/types'
+
+// pinned: sent as the `feature` property of `toolbar extension feature opened`
+export type ExtensionFeatureKey = 'heatmaps' | 'actions' | 'feature-flags' | 'experiments' | 'web-vitals'
+
+export interface ExtensionFeatureEntryPoint {
+ key: ExtensionFeatureKey
+ label: string
+ description: string
+ /** PostHog app path, relative to the project. */
+ path: string
+ /** The plan gate the floating toolbar applies to this feature. */
+ gate?: { feature: AvailableFeature; rolloutFlag: FeatureFlagKey }
+}
+
+/** The floating toolbar's menus, in toolbar order. */
+export const EXTENSION_FEATURE_ENTRY_POINTS: ExtensionFeatureEntryPoint[] = [
+ {
+ key: 'heatmaps',
+ label: 'Heatmaps',
+ description: 'See where people click and how far they scroll',
+ path: urls.heatmaps(),
+ gate: { feature: AvailableFeature.TOOLBAR_HEATMAPS, rolloutFlag: FEATURE_FLAGS.TOOLBAR_PAID_HEATMAPS },
+ },
+ {
+ key: 'actions',
+ label: 'Actions',
+ description: 'Define actions from elements on your pages',
+ path: urls.actions(),
+ },
+ {
+ key: 'feature-flags',
+ label: 'Feature flags',
+ description: 'Review and override flags',
+ path: urls.featureFlags(),
+ },
+ {
+ key: 'web-vitals',
+ label: 'Web vitals',
+ description: 'Check page load performance',
+ path: urls.webAnalyticsWebVitals(),
+ },
+ {
+ key: 'experiments',
+ label: 'Experiments',
+ description: 'Create and review web experiments',
+ path: urls.experiments(),
+ },
+]
diff --git a/frontend/src/toolbar/extension/extensionPanelLogic.ts b/frontend/src/toolbar/extension/extensionPanelLogic.ts
new file mode 100644
index 000000000000..dda4b46da51c
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionPanelLogic.ts
@@ -0,0 +1,459 @@
+import { MakeLogicType, actions, afterMount, beforeUnmount, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { getOrganizationsProjectsRetrieveUrl, getUsersRetrieveUrl } from '~/generated/core/api'
+import type {
+ ProjectBackwardCompatApi,
+ ToolbarEntitlementsApiEntitlements,
+ UserApi,
+} from '~/generated/core/api.schemas'
+import { canonicalizeUiHost } from '~/toolbar/toolbarConfigLogic'
+import { fetchToolbarEntitlements } from '~/toolbar/toolbarEntitlementsLogic'
+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+import { joinWithUiHost, safeFetch } from '~/toolbar/utils'
+
+import {
+ getActiveTab,
+ getStoredUiHost,
+ hasHostPermission,
+ onActiveTabChange,
+ openTab,
+ requestHostPermission,
+ setStoredUiHost,
+} from './extensionBrowser'
+import type { ExtensionFeatureKey } from './extensionFeatures'
+import {
+ ExtensionPanelState,
+ SessionUserResult,
+ ToolbarAccessResult,
+ getExtensionPanelState,
+} from './extensionPanelState'
+
+const DEFAULT_UI_HOST = 'https://us.posthog.com'
+
+// Matches the toolbar's entitlements request timeout.
+const REQUEST_TIMEOUT_MS = 5000
+
+const REFRESH_ON_TAB_CHANGE_MS = 30 * 1000
+
+const RECHECK_ON_TAB_CHANGE: ExtensionPanelState['kind'][] = [
+ 'signed-out',
+ 'no-toolbar-access',
+ 'unauthorized-url',
+ 'error',
+]
+
+// States the user may fix with the project or host settings, for example a session on the other cloud region.
+const OPEN_SETTINGS_IN: ExtensionPanelState['kind'][] = [
+ 'host-permission-needed',
+ 'signed-out',
+ 'no-toolbar-access',
+ 'error',
+]
+
+/** Sends the PostHog session cookie, like the toolbar's own entitlements request. */
+async function fetchWithSession(uiHost: string, path: string): Promise<{ status: number; data: unknown }> {
+ return await readResponse(
+ safeFetch(`${uiHost}${path}`, { credentials: 'include', signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) })
+ )
+}
+
+async function readResponse(request: Promise<Response>): Promise<{ status: number; data: unknown }> {
+ try {
+ const response = await request
+ const data = response.ok ? await response.json() : null
+ return { status: response.status, data }
+ } catch {
+ // 0 keeps a network failure apart from every HTTP status.
+ return { status: 0, data: null }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPanelLogicValues {
+ authorizedUrls: string[] | 'error' | null
+ authorizedUrlsLoading: boolean
+ entitlements: ToolbarEntitlementsApiEntitlements | null
+ hostPermission: boolean | null
+ panelState: ExtensionPanelState
+ projectSwitchFailed: boolean
+ projectUrl: (path: string) => string
+ sessionUser: SessionUserResult | null
+ sessionUserLoading: boolean
+ settingsExpanded: boolean
+ settingsNeeded: boolean
+ tabUrl: string | null | undefined
+ toolbarAccess: ToolbarAccessResult | null
+ toolbarAccessLoading: boolean
+ uiHost: string
+ user: UserApi | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPanelLogicActions {
+ loadAuthorizedUrls: ({ organizationId, projectId }: { organizationId: string; projectId: number }) => {
+ organizationId: string
+ projectId: number
+ }
+ loadAuthorizedUrlsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAuthorizedUrlsSuccess: (
+ authorizedUrls: string[] | 'error' | null,
+ payload?: {
+ organizationId: string
+ projectId: number
+ }
+ ) => {
+ authorizedUrls: string[] | 'error' | null
+ payload?: {
+ organizationId: string
+ projectId: number
+ }
+ }
+ loadSessionUser: () => any
+ loadSessionUserFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSessionUserSuccess: (
+ sessionUser: SessionUserResult | null,
+ payload?: any
+ ) => {
+ sessionUser: SessionUserResult | null
+ payload?: any
+ }
+ loadToolbarAccess: () => any
+ loadToolbarAccessFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadToolbarAccessSuccess: (
+ toolbarAccess: ToolbarAccessResult | null,
+ payload?: any
+ ) => {
+ toolbarAccess: ToolbarAccessResult | null
+ payload?: any
+ }
+ openFeature: (
+ feature: ExtensionFeatureKey,
+ path: string
+ ) => {
+ feature: ExtensionFeatureKey
+ path: string
+ }
+ openPostHogPath: (path: string) => {
+ path: string
+ }
+ openProjectPath: (path: string) => {
+ path: string
+ }
+ requestHostPermission: () => {
+ value: true
+ }
+ retry: () => {
+ value: true
+ }
+ setHostPermission: (granted: boolean) => {
+ granted: boolean
+ }
+ setProjectSwitchFailed: (failed: boolean) => {
+ failed: boolean
+ }
+ setSettingsExpanded: (expanded: boolean) => {
+ expanded: boolean
+ }
+ setTabUrl: (tabUrl: string | null) => {
+ tabUrl: string | null
+ }
+ setUiHost: (uiHost: string) => {
+ uiHost: string
+ }
+ switchProject: (teamId: number) => {
+ teamId: number
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface extensionPanelLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ user: (sessionUser: SessionUserResult | null) => UserApi | null
+ projectUrl: (uiHost: string, user: UserApi | null) => (path: string) => string
+ entitlements: (toolbarAccess: ToolbarAccessResult | null) => ToolbarEntitlementsApiEntitlements | null
+ panelState: (
+ tabUrl: string | null | undefined,
+ uiHost: string,
+ hostPermission: boolean | null,
+ sessionUser: SessionUserResult | null,
+ toolbarAccess: ToolbarAccessResult | null,
+ authorizedUrls: string[] | 'error' | null
+ ) => ExtensionPanelState
+ settingsNeeded: (panelState: ExtensionPanelState, projectSwitchFailed: boolean) => boolean
+ }
+}
+
+export type extensionPanelLogicType = MakeLogicType<
+ extensionPanelLogicValues,
+ extensionPanelLogicActions,
+ Record<string, any>,
+ extensionPanelLogicMeta
+>
+
+export const extensionPanelLogic = kea<extensionPanelLogicType>([
+ path(['toolbar', 'extension', 'extensionPanelLogic']),
+ actions({
+ setTabUrl: (tabUrl: string | null) => ({ tabUrl }),
+ setUiHost: (uiHost: string) => ({ uiHost }),
+ setHostPermission: (granted: boolean) => ({ granted }),
+ requestHostPermission: true,
+ switchProject: (teamId: number) => ({ teamId }),
+ openPostHogPath: (path: string) => ({ path }),
+ openProjectPath: (path: string) => ({ path }),
+ openFeature: (feature: ExtensionFeatureKey, path: string) => ({ feature, path }),
+ retry: true,
+ setProjectSwitchFailed: (failed: boolean) => ({ failed }),
+ setSettingsExpanded: (expanded: boolean) => ({ expanded }),
+ }),
+ reducers({
+ tabUrl: [undefined as string | null | undefined, { setTabUrl: (_, { tabUrl }) => tabUrl }],
+ uiHost: [DEFAULT_UI_HOST as string, { setUiHost: (_, { uiHost }) => uiHost }],
+ projectSwitchFailed: [
+ false,
+ { setProjectSwitchFailed: (_, { failed }) => failed, switchProject: () => false, setUiHost: () => false },
+ ],
+ hostPermission: [
+ null as boolean | null,
+ { setUiHost: () => null, setHostPermission: (_, { granted }) => granted },
+ ],
+ settingsExpanded: [false, { setSettingsExpanded: (_, { expanded }) => expanded }],
+ }),
+ loaders(({ values }) => ({
+ sessionUser: [
+ null as SessionUserResult | null,
+ {
+ loadSessionUser: async (): Promise<SessionUserResult | null> => {
+ const uiHost = values.uiHost
+ const { status, data } = await fetchWithSession(uiHost, getUsersRetrieveUrl('@me'))
+ if (values.uiHost !== uiHost) {
+ return null
+ }
+ if (status === 401 || status === 403) {
+ return { status: 'signed-out' }
+ }
+ const user = data as UserApi | null
+ if (status !== 200 || !user?.team) {
+ return { status: 'error' }
+ }
+ return { status: 'signed-in', user }
+ },
+ },
+ ],
+ toolbarAccess: [
+ null as ToolbarAccessResult | null,
+ {
+ loadToolbarAccess: async (): Promise<ToolbarAccessResult | null> => {
+ const uiHost = values.uiHost
+ const { status, data } = await readResponse(fetchToolbarEntitlements(uiHost))
+ if (values.uiHost !== uiHost) {
+ return null
+ }
+ if (status === 200) {
+ const entitlements = (data as { entitlements?: ToolbarEntitlementsApiEntitlements } | null)
+ ?.entitlements
+ return { status: 'allowed', entitlements: entitlements ?? null }
+ }
+ if (status === 401) {
+ return { status: 'signed-out' }
+ }
+ return status === 403 ? { status: 'denied' } : { status: 'error' }
+ },
+ },
+ ],
+ authorizedUrls: [
+ null as string[] | 'error' | null,
+ {
+ loadAuthorizedUrls: async ({
+ organizationId,
+ projectId,
+ }: {
+ organizationId: string
+ projectId: number
+ }): Promise<string[] | 'error' | null> => {
+ const uiHost = values.uiHost
+ const { status, data } = await fetchWithSession(
+ uiHost,
+ getOrganizationsProjectsRetrieveUrl(organizationId, projectId)
+ )
+ if (values.uiHost !== uiHost) {
+ return null
+ }
+ if (status !== 200 || !data) {
+ return 'error'
+ }
+ return ((data as ProjectBackwardCompatApi).app_urls ?? []).filter(
+ (url): url is string => typeof url === 'string' && url.length > 0
+ )
+ },
+ },
+ ],
+ })),
+ reducers({
+ sessionUser: { setUiHost: () => null, switchProject: () => null, retry: () => null },
+ toolbarAccess: { setUiHost: () => null, switchProject: () => null, retry: () => null },
+ authorizedUrls: { setUiHost: () => null, switchProject: () => null, retry: () => null },
+ }),
+ selectors({
+ user: [
+ (s) => [s.sessionUser],
+ (sessionUser: SessionUserResult | null): UserApi | null =>
+ sessionUser?.status === 'signed-in' ? sessionUser.user : null,
+ ],
+ projectUrl: [
+ (s) => [s.uiHost, s.user],
+ (uiHost: string, user: UserApi | null) =>
+ (path: string): string =>
+ joinWithUiHost(uiHost, user ? `/project/${user.team.id}${path}` : path),
+ ],
+ entitlements: [
+ (s) => [s.toolbarAccess],
+ (toolbarAccess: ToolbarAccessResult | null): ToolbarEntitlementsApiEntitlements | null =>
+ toolbarAccess?.status === 'allowed' ? toolbarAccess.entitlements : null,
+ ],
+ panelState: [
+ (s) => [s.tabUrl, s.uiHost, s.hostPermission, s.sessionUser, s.toolbarAccess, s.authorizedUrls],
+ (
+ tabUrl: string | null | undefined,
+ uiHost: string,
+ hostPermission: boolean | null,
+ sessionUser: SessionUserResult | null,
+ toolbarAccess: ToolbarAccessResult | null,
+ authorizedUrls: string[] | 'error' | null
+ ): ExtensionPanelState =>
+ getExtensionPanelState({
+ tabUrl,
+ uiHost,
+ hostPermission,
+ sessionStatus: sessionUser?.status ?? null,
+ toolbarAccess,
+ authorizedUrls,
+ }),
+ ],
+ settingsNeeded: [
+ (s) => [s.panelState, s.projectSwitchFailed],
+ (panelState: ExtensionPanelState, projectSwitchFailed: boolean): boolean =>
+ projectSwitchFailed || OPEN_SETTINGS_IN.includes(panelState.kind),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ setUiHost: async ({ uiHost }) => {
+ void setStoredUiHost(uiHost)
+ actions.setHostPermission(await hasHostPermission(uiHost))
+ },
+ requestHostPermission: async () => {
+ // No await before this call: the prompt needs the click's user gesture.
+ const granted = await requestHostPermission(values.uiHost)
+ actions.setHostPermission(granted)
+ },
+ setHostPermission: ({ granted }) => {
+ if (granted) {
+ actions.loadSessionUser()
+ actions.loadToolbarAccess()
+ }
+ },
+ retry: () => {
+ if (values.hostPermission) {
+ actions.loadSessionUser()
+ actions.loadToolbarAccess()
+ }
+ },
+ setTabUrl: () => {
+ // The panel stays open while the user logs in, switches project or adds an authorized URL in another
+ // tab, so check again when the user comes back.
+ if (RECHECK_ON_TAB_CHANGE.includes(values.panelState.kind)) {
+ actions.retry()
+ return
+ }
+ if (values.hostPermission && Date.now() - (cache.lastRefresh ?? 0) > REFRESH_ON_TAB_CHANGE_MS) {
+ cache.lastRefresh = Date.now()
+ actions.loadSessionUser()
+ actions.loadToolbarAccess()
+ toolbarPosthogJS.reloadFeatureFlags()
+ }
+ },
+ loadSessionUserSuccess: ({ sessionUser }) => {
+ if (sessionUser?.status !== 'signed-in') {
+ return
+ }
+ const { user } = sessionUser
+ if (user.distinct_id) {
+ // Evaluates toolbar rollout flags for this person, as the floating toolbar does.
+ toolbarPosthogJS.identify(user.distinct_id)
+ }
+ actions.loadAuthorizedUrls({ organizationId: user.organization.id, projectId: user.team.project_id })
+ },
+ switchProject: async ({ teamId }) => {
+ // The app's project-switch path moves the session's current project, which is the project
+ // toolbar authentication uses.
+ const { status } = await fetchWithSession(values.uiHost, `/project/${teamId}`)
+ if (status >= 200 && status < 300) {
+ toolbarPosthogJS.capture('toolbar extension project switched')
+ } else {
+ actions.setProjectSwitchFailed(true)
+ }
+ actions.loadSessionUser()
+ actions.loadToolbarAccess()
+ },
+ openPostHogPath: ({ path }) => {
+ void openTab(joinWithUiHost(values.uiHost, path))
+ },
+ openProjectPath: ({ path }) => {
+ void openTab(values.projectUrl(path))
+ },
+ openFeature: ({ feature, path }) => {
+ toolbarPosthogJS.capture('toolbar extension feature opened', { feature })
+ actions.openProjectPath(path)
+ },
+ })),
+ subscriptions(({ actions }) => ({
+ settingsNeeded: (settingsNeeded: boolean, previous: boolean | undefined) => {
+ // Opens the settings when a problem starts and closes them when it ends, so the user can still toggle
+ // them in between.
+ if (settingsNeeded || previous) {
+ actions.setSettingsExpanded(settingsNeeded)
+ }
+ },
+ panelState: (panelState: ExtensionPanelState, previous: ExtensionPanelState | undefined) => {
+ if (panelState.kind === 'checking' || panelState.kind === previous?.kind) {
+ return
+ }
+ // pinned: analytics event name, renaming it breaks the extension adoption insights
+ toolbarPosthogJS.capture('toolbar extension panel state', {
+ state: panelState.kind,
+ unsupported_reason: panelState.kind === 'unsupported-page' ? panelState.reason : undefined,
+ })
+ },
+ })),
+ afterMount(({ actions, cache }) => {
+ toolbarPosthogJS.opt_in_capturing()
+ void getStoredUiHost().then((stored) => actions.setUiHost(canonicalizeUiHost(stored) ?? DEFAULT_UI_HOST))
+ void getActiveTab().then(
+ (tab) => actions.setTabUrl(tab?.url ?? null),
+ () => actions.setTabUrl(null)
+ )
+ cache.removeActiveTabListener = onActiveTabChange((tab) => actions.setTabUrl(tab?.url ?? null))
+ }),
+ beforeUnmount(({ cache }) => {
+ cache.removeActiveTabListener?.()
+ }),
+])
diff --git a/frontend/src/toolbar/extension/extensionPanelState.test.ts b/frontend/src/toolbar/extension/extensionPanelState.test.ts
new file mode 100644
index 000000000000..44649190acc4
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionPanelState.test.ts
@@ -0,0 +1,70 @@
+import { ExtensionPanelInputs, getExtensionPanelState } from './extensionPanelState'
+
+const READY_INPUTS: ExtensionPanelInputs = {
+ tabUrl: 'https://www.example.com/pricing',
+ uiHost: 'https://us.posthog.com',
+ hostPermission: true,
+ sessionStatus: 'signed-in',
+ toolbarAccess: { status: 'allowed', entitlements: { toolbar_heatmaps: true } },
+ authorizedUrls: ['https://example.com'],
+}
+
+describe('getExtensionPanelState', () => {
+ test.each<[string, Partial<ExtensionPanelInputs>, ReturnType<typeof getExtensionPanelState>]>([
+ ['authorized page', {}, { kind: 'ready', origin: 'https://www.example.com' }],
+ ['tab not read yet', { tabUrl: undefined }, { kind: 'checking' }],
+ ['browser page', { tabUrl: 'chrome://extensions' }, { kind: 'unsupported-page', reason: 'browser-page' }],
+ ['no tab url', { tabUrl: null }, { kind: 'unsupported-page', reason: 'browser-page' }],
+ [
+ 'plain http on a public host',
+ { tabUrl: 'http://example.com' },
+ { kind: 'unsupported-page', reason: 'insecure-page' },
+ ],
+ [
+ 'plain http on loopback',
+ { tabUrl: 'http://localhost:3000/', authorizedUrls: ['http://localhost:3000'] },
+ { kind: 'ready', origin: 'http://localhost:3000' },
+ ],
+ [
+ 'extension store',
+ { tabUrl: 'https://addons.mozilla.org/en-US/firefox/' },
+ { kind: 'unsupported-page', reason: 'extension-store' },
+ ],
+ [
+ 'the PostHog app itself',
+ { tabUrl: 'https://us.posthog.com/project/1' },
+ { kind: 'unsupported-page', reason: 'posthog-app' },
+ ],
+ [
+ 'unsupported page wins over a missing session',
+ { tabUrl: 'about:blank', sessionStatus: 'signed-out' },
+ { kind: 'unsupported-page', reason: 'browser-page' },
+ ],
+ ['host permission pending', { hostPermission: null }, { kind: 'checking' }],
+ ['host permission missing', { hostPermission: false }, { kind: 'host-permission-needed' }],
+ ['session loading', { sessionStatus: null }, { kind: 'checking' }],
+ ['signed out', { sessionStatus: 'signed-out' }, { kind: 'signed-out' }],
+ [
+ 'session expired before the access check',
+ { toolbarAccess: { status: 'signed-out' } },
+ { kind: 'signed-out' },
+ ],
+ ['session request failed', { sessionStatus: 'error' }, { kind: 'error' }],
+ ['toolbar access loading', { toolbarAccess: null }, { kind: 'checking' }],
+ ['toolbar access denied', { toolbarAccess: { status: 'denied' } }, { kind: 'no-toolbar-access' }],
+ ['authorized URLs loading', { authorizedUrls: null }, { kind: 'checking' }],
+ ['authorized URLs failed', { authorizedUrls: 'error' }, { kind: 'error' }],
+ [
+ 'page not in authorized URLs',
+ { authorizedUrls: ['https://example.co'] },
+ { kind: 'unauthorized-url', origin: 'https://www.example.com' },
+ ],
+ [
+ 'access denial wins over an unauthorized page',
+ { toolbarAccess: { status: 'denied' }, authorizedUrls: [] },
+ { kind: 'no-toolbar-access' },
+ ],
+ ])('%s', (_, overrides, expected) => {
+ expect(getExtensionPanelState({ ...READY_INPUTS, ...overrides })).toEqual(expected)
+ })
+})
diff --git a/frontend/src/toolbar/extension/extensionPanelState.ts b/frontend/src/toolbar/extension/extensionPanelState.ts
new file mode 100644
index 000000000000..00e8c8cefe6a
--- /dev/null
+++ b/frontend/src/toolbar/extension/extensionPanelState.ts
@@ -0,0 +1,119 @@
+import { checkUrlIsAuthorized } from 'lib/components/AuthorizedUrlList/authorizedUrlMatching'
+
+import type { ToolbarEntitlementsApiEntitlements, UserApi } from '~/generated/core/api.schemas'
+
+export type UnsupportedPageReason = 'browser-page' | 'insecure-page' | 'posthog-app' | 'extension-store'
+
+export type SessionUserResult = { status: 'signed-in'; user: UserApi } | { status: 'signed-out' } | { status: 'error' }
+
+export type ToolbarAccessResult =
+ | { status: 'allowed'; entitlements: ToolbarEntitlementsApiEntitlements | null }
+ | { status: 'denied' }
+ | { status: 'signed-out' }
+ | { status: 'error' }
+
+export type ExtensionPanelState =
+ | { kind: 'checking' }
+ | { kind: 'unsupported-page'; reason: UnsupportedPageReason }
+ | { kind: 'host-permission-needed' }
+ | { kind: 'signed-out' }
+ | { kind: 'no-toolbar-access' }
+ | { kind: 'unauthorized-url'; origin: string }
+ | { kind: 'error' }
+ | { kind: 'ready'; origin: string }
+
+export interface ExtensionPanelInputs {
+ /** `undefined` while the active tab is still being read. */
+ tabUrl: string | null | undefined
+ uiHost: string
+ /** `null` while the permission check is pending. */
+ hostPermission: boolean | null
+ /** `null` while the session loads. */
+ sessionStatus: SessionUserResult['status'] | null
+ toolbarAccess: ToolbarAccessResult | null
+ /** The project's authorized URLs, `null` while they load. */
+ authorizedUrls: string[] | 'error' | null
+}
+
+// Browsers block every extension from scripting their own add-on stores.
+const EXTENSION_STORE_HOSTNAMES = new Set(['chromewebstore.google.com', 'chrome.google.com', 'addons.mozilla.org'])
+
+const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]'])
+
+/** Mirrors the toolbar OAuth rules: http(s) only, and plain http only on loopback hosts. */
+function unsupportedPageReason(tabUrl: string | null, uiHost: string): UnsupportedPageReason | null {
+ if (!tabUrl) {
+ return 'browser-page'
+ }
+ let parsed: URL
+ try {
+ parsed = new URL(tabUrl)
+ } catch {
+ return 'browser-page'
+ }
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
+ return 'browser-page'
+ }
+ if (parsed.protocol === 'http:' && !LOOPBACK_HOSTNAMES.has(parsed.hostname)) {
+ return 'insecure-page'
+ }
+ if (EXTENSION_STORE_HOSTNAMES.has(parsed.hostname)) {
+ return 'extension-store'
+ }
+ if (parsed.origin === uiHost) {
+ return 'posthog-app'
+ }
+ return null
+}
+
+export function getExtensionPanelState(inputs: ExtensionPanelInputs): ExtensionPanelState {
+ if (inputs.tabUrl === undefined) {
+ return { kind: 'checking' }
+ }
+ const reason = unsupportedPageReason(inputs.tabUrl, inputs.uiHost)
+ if (reason || !inputs.tabUrl) {
+ return { kind: 'unsupported-page', reason: reason ?? 'browser-page' }
+ }
+ const origin = new URL(inputs.tabUrl).origin
+
+ if (inputs.hostPermission === null) {
+ return { kind: 'checking' }
+ }
+ if (!inputs.hostPermission) {
+ return { kind: 'host-permission-needed' }
+ }
+
+ if (!inputs.sessionStatus) {
+ return { kind: 'checking' }
+ }
+ if (inputs.sessionStatus === 'signed-out') {
+ return { kind: 'signed-out' }
+ }
+ if (inputs.sessionStatus === 'error') {
+ return { kind: 'error' }
+ }
+
+ if (!inputs.toolbarAccess) {
+ return { kind: 'checking' }
+ }
+ if (inputs.toolbarAccess.status === 'signed-out') {
+ return { kind: 'signed-out' }
+ }
+ if (inputs.toolbarAccess.status === 'denied') {
+ return { kind: 'no-toolbar-access' }
+ }
+ if (inputs.toolbarAccess.status === 'error') {
+ return { kind: 'error' }
+ }
+
+ if (inputs.authorizedUrls === null) {
+ return { kind: 'checking' }
+ }
+ if (inputs.authorizedUrls === 'error') {
+ return { kind: 'error' }
+ }
+ if (!checkUrlIsAuthorized(inputs.tabUrl, inputs.authorizedUrls)) {
+ return { kind: 'unauthorized-url', origin }
+ }
+ return { kind: 'ready', origin }
+}
diff --git a/frontend/src/toolbar/extension/panel.html b/frontend/src/toolbar/extension/panel.html
new file mode 100644
index 000000000000..21f82f9ce341
--- /dev/null
+++ b/frontend/src/toolbar/extension/panel.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>PostHog</title>
+ <link rel="stylesheet" href="panel.css" />
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="panel.js"></script>
+ </body>
+</html>
diff --git a/frontend/src/toolbar/extension/panel.tsx b/frontend/src/toolbar/extension/panel.tsx
new file mode 100644
index 000000000000..e954eedfa052
--- /dev/null
+++ b/frontend/src/toolbar/extension/panel.tsx
@@ -0,0 +1,17 @@
+import '~/styles'
+
+import { resetContext } from 'kea'
+import { loadersPlugin } from 'kea-loaders'
+import { subscriptionsPlugin } from 'kea-subscriptions'
+import { createRoot } from 'react-dom/client'
+
+import { ExtensionPanel } from './ExtensionPanel'
+import { extensionPanelLogic } from './extensionPanelLogic'
+
+resetContext({ plugins: [loadersPlugin, subscriptionsPlugin] })
+extensionPanelLogic.mount()
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<ExtensionPanel />)
+}
diff --git a/frontend/src/toolbar/toolbarEntitlementsLogic.ts b/frontend/src/toolbar/toolbarEntitlementsLogic.ts
index 178f60957bdd..1207b40a7dd3 100644
--- a/frontend/src/toolbar/toolbarEntitlementsLogic.ts
+++ b/frontend/src/toolbar/toolbarEntitlementsLogic.ts
@@ -18,6 +18,16 @@ const ENTITLEMENTS_PATH = '/api/user/toolbar_entitlements'
// Matches the toolbar's other blocking check, the uiHost reachability HEAD request.
const ENTITLEMENTS_TIMEOUT_MS = 5000
+/** Sends the PostHog session cookie. The extension panel makes the same request to check toolbar access. */
+export function fetchToolbarEntitlements(uiHost: string): Promise<Response> {
+ return safeFetch(`${uiHost}${ENTITLEMENTS_PATH}`, {
+ credentials: 'include',
+ // A stall would hold the gate closed for the whole page session,
+ // because the retry lives in the failed branch, not the pending one.
+ signal: AbortSignal.timeout(ENTITLEMENTS_TIMEOUT_MS),
+ })
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarEntitlementsLogicValues {
isAuthenticated: boolean // toolbarConfigLogic
@@ -87,12 +97,7 @@ export const toolbarEntitlementsLogic = kea<toolbarEntitlementsLogicType>([
// 0 keeps a network failure distinguishable from an HTTP status in telemetry.
let status = 0
try {
- const response = await safeFetch(`${values.uiHost}${ENTITLEMENTS_PATH}`, {
- credentials: 'include',
- // A stall would hold the gate closed for the whole page session,
- // because the retry lives in the failed branch, not the pending one.
- signal: AbortSignal.timeout(ENTITLEMENTS_TIMEOUT_MS),
- })
+ const response = await fetchToolbarEntitlements(values.uiHost)
status = response.status
if (!response.ok) {
toolbarLogger.warn('entitlements', 'Entitlements request failed', { status })
diff --git a/frontend/src/toolbar/toolbarPosthogJS.ts b/frontend/src/toolbar/toolbarPosthogJS.ts
index af2d41306b8d..e5267fbdad5c 100644
--- a/frontend/src/toolbar/toolbarPosthogJS.ts
+++ b/frontend/src/toolbar/toolbarPosthogJS.ts
@@ -8,6 +8,8 @@ const DEFAULT_API_KEY = 'sTMFPsFhdP1Ssg'
const runningOnPosthog = !!window.POSTHOG_APP_CONTEXT
const apiKey = runningOnPosthog ? window.JS_POSTHOG_API_KEY : DEFAULT_API_KEY
const apiHost = runningOnPosthog ? window.JS_POSTHOG_HOST : 'https://internal-cf.posthog.com'
+// Manifest V3 forbids remote code in an extension, and the browser stores reject it.
+const runningInBrowserExtension = !!(globalThis as { chrome?: { runtime?: { id?: string } } }).chrome?.runtime?.id
const initResult = posthog.init(
apiKey || DEFAULT_API_KEY,
@@ -32,6 +34,7 @@ const initResult = posthog.init(
disable_scroll_properties: true,
disable_product_tours: true,
disable_session_recording: true,
+ disable_external_dependency_loading: runningInBrowserExtension,
session_recording: {
// we want to capture the toolbar (which is marked with ph-no-capture
// so customer sessions don't see it), but also respect the customer's
diff --git a/frontend/src/toolbar/urls.test.ts b/frontend/src/toolbar/urls.test.ts
index 91cb66d92156..29a3c72acb01 100644
--- a/frontend/src/toolbar/urls.test.ts
+++ b/frontend/src/toolbar/urls.test.ts
@@ -15,6 +15,7 @@ describe('toolbar urls duplicate', () => {
featureFlag: [[123], ['my-flag']],
featureFlags: [[], ['history']],
heatmap: [['hm-abc123'], [123]],
+ heatmaps: [[], ['tab=saved'], ['?tab=saved']],
organizationBilling: [[], [['product_analytics']], [['product_analytics', 'session_replay']]],
productTour: [['tour-id'], ['tour-id', 'step=2'], ['tour-id', '?step=2']],
sessionProfile: [['session-uuid']],
diff --git a/frontend/src/toolbar/urls.ts b/frontend/src/toolbar/urls.ts
index e721e7b84088..311c68c69f22 100644
--- a/frontend/src/toolbar/urls.ts
+++ b/frontend/src/toolbar/urls.ts
@@ -24,6 +24,8 @@ export const urls = {
featureFlag: (id: string | number): string => `/feature-flags/${id}`,
featureFlags: (tab?: string): string => `/feature-flags${tab ? `?tab=${tab}` : ''}`,
heatmap: (id: string | number): string => `/heatmaps/${id}`,
+ heatmaps: (params?: string): string =>
+ `/heatmaps${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,
organizationBilling: (products?: string[]): string =>
`/organization/billing${products && products.length ? `?products=${products.join(',')}` : ''}`,
productTour: (id: string, params?: string): string =>
diff --git a/frontend/toolbar-config.mjs b/frontend/toolbar-config.mjs
index b801d33b2ec1..ecd5bb308b8c 100644
--- a/frontend/toolbar-config.mjs
+++ b/frontend/toolbar-config.mjs
@@ -1,3 +1,4 @@
+import { zipSync } from 'fflate'
import * as fs from 'fs'
import * as path from 'path'
@@ -245,3 +246,156 @@ export async function finalizeToolbarBuild(dirname, buildResponse) {
},
})
}
+
+// The browser extension ships one panel bundle in a folder per browser. Only the manifest differs:
+//
+// dist/toolbar-extension/<browser>/manifest.json
+// dist/toolbar-extension/<browser>/panel.html, panel.js, panel.css, background.js, assets/, icons/
+//
+// Load the folder unpacked in Chrome, or as a temporary add-on in Firefox.
+const TOOLBAR_EXTENSION_BROWSERS = ['chrome', 'firefox']
+
+const TOOLBAR_EXTENSION_VERSION = '0.1.0'
+
+const TOOLBAR_EXTENSION_BUILD_DIR = 'toolbar-extension-build'
+
+const TOOLBAR_EXTENSION_ICONS = {
+ 16: 'icons/favicon-16x16.png',
+ 32: 'icons/favicon-32x32.png',
+ 192: 'icons/android-chrome-192x192.png',
+}
+
+export function cleanToolbarExtensionBuild(dirname) {
+ fs.rmSync(path.resolve(dirname, 'dist', TOOLBAR_EXTENSION_BUILD_DIR), { recursive: true, force: true })
+}
+
+/** panel.html isn't an esbuild input, so watch mode rebuilds on its edits only through this. */
+function watchExtensionPagesPlugin(dirname) {
+ return {
+ name: 'watch-toolbar-extension-pages',
+ setup(build) {
+ build.onLoad({ filter: /extension[\\/]panel\.tsx$/ }, (args) => ({
+ contents: fs.readFileSync(args.path, 'utf8'),
+ loader: 'tsx',
+ watchFiles: [path.resolve(dirname, 'src/toolbar/extension/panel.html')],
+ }))
+ },
+ }
+}
+
+function toolbarExtensionBaseConfig(dirname) {
+ return {
+ outdir: path.resolve(dirname, 'dist', TOOLBAR_EXTENSION_BUILD_DIR),
+ // The pages and scripts name their files directly, so they carry no hash.
+ entryNames: '[name]',
+ // Extension pages resolve assets against their own folder, so URLs stay relative.
+ publicPath: undefined,
+ loader: { ...commonConfig.loader, '.svg': 'dataurl' },
+ define: {
+ ...commonConfig.define,
+ __POSTHOG_TOOLBAR_PUBLIC_PATH__: JSON.stringify(''),
+ },
+ }
+}
+
+export function getToolbarExtensionBuildConfig(dirname) {
+ return {
+ ...toolbarExtensionBaseConfig(dirname),
+ name: 'Toolbar extension',
+ entryPoints: { panel: 'src/toolbar/extension/panel.tsx' },
+ format: 'esm',
+ // Keeps lazily imported code (such as hedgehog mode, reached through lemon-ui) out of panel.js.
+ splitting: true,
+ chunkNames: 'chunks/[name]-[hash]',
+ extraPlugins: [createToolbarModulePlugin(dirname), watchExtensionPagesPlugin(dirname)],
+ }
+}
+
+/** Firefox doesn't run a module as a background script, so the background script is one classic script. */
+export function getToolbarExtensionScriptsBuildConfig(dirname) {
+ return {
+ ...toolbarExtensionBaseConfig(dirname),
+ name: 'Toolbar extension scripts',
+ entryPoints: { background: 'src/toolbar/extension/background.ts' },
+ format: 'iife',
+ splitting: false,
+ extraPlugins: [createToolbarModulePlugin(dirname)],
+ }
+}
+
+// Asks for every http and https site, because the panel follows the active tab without a click on the extension
+// button, which `activeTab` needs.
+function buildToolbarExtensionManifest(browser) {
+ const manifest = {
+ manifest_version: 3,
+ name: 'PostHog',
+ description: 'Use the PostHog toolbar in a side panel next to your website.',
+ version: TOOLBAR_EXTENSION_VERSION,
+ icons: TOOLBAR_EXTENSION_ICONS,
+ action: {
+ default_title: 'Open PostHog',
+ default_icon: TOOLBAR_EXTENSION_ICONS,
+ },
+ permissions: ['storage'],
+ host_permissions: ['http://*/*', 'https://*/*'],
+ }
+ if (browser === 'firefox') {
+ manifest.sidebar_action = {
+ default_title: 'PostHog',
+ default_panel: 'panel.html',
+ default_icon: TOOLBAR_EXTENSION_ICONS,
+ open_at_install: false,
+ }
+ // Firefox needs an add-on ID for MV3 storage, and 128 is the first release that grants Manifest V3 host
+ // permissions at install.
+ manifest.browser_specific_settings = { gecko: { id: '[email protected]', strict_min_version: '128.0' } }
+ // Firefox runs Manifest V3 background code as an event page, not as a service worker.
+ manifest.background = { scripts: ['background.js'] }
+ } else {
+ manifest.permissions.push('sidePanel')
+ manifest.side_panel = { default_path: 'panel.html' }
+ // 116 is the first release with `sidePanel.setPanelBehavior`, which opens the panel from the toolbar button.
+ manifest.minimum_chrome_version = '116'
+ manifest.background = { service_worker: 'background.js' }
+ }
+ return manifest
+}
+
+export function finalizeToolbarExtensionBuild(dirname) {
+ const buildDir = path.resolve(dirname, 'dist', TOOLBAR_EXTENSION_BUILD_DIR)
+ for (const browser of TOOLBAR_EXTENSION_BROWSERS) {
+ const outDir = path.resolve(dirname, 'dist', 'toolbar-extension', browser)
+ fs.rmSync(outDir, { recursive: true, force: true })
+ fs.cpSync(buildDir, outDir, { recursive: true })
+ fs.copyFileSync(path.resolve(dirname, 'src/toolbar/extension/panel.html'), path.resolve(outDir, 'panel.html'))
+ for (const icon of Object.values(TOOLBAR_EXTENSION_ICONS)) {
+ fs.mkdirSync(path.dirname(path.resolve(outDir, icon)), { recursive: true })
+ fs.copyFileSync(path.resolve(dirname, 'public', icon), path.resolve(outDir, icon))
+ }
+ fs.writeFileSync(
+ path.resolve(outDir, 'manifest.json'),
+ JSON.stringify(buildToolbarExtensionManifest(browser), null, 4) + '\n'
+ )
+ fs.writeFileSync(
+ path.resolve(
+ dirname,
+ 'dist',
+ 'toolbar-extension',
+ `posthog-toolbar-${browser}-${TOOLBAR_EXTENSION_VERSION}.zip`
+ ),
+ zipSync(readDirectoryFiles(outDir))
+ )
+ }
+}
+
+function readDirectoryFiles(directory) {
+ const files = {}
+ for (const entry of fs.readdirSync(directory, { recursive: true, withFileTypes: true })) {
+ // Source maps stay in the unpacked folders for local debugging, but would triple the size of the zips.
+ if (entry.isFile() && !entry.name.endsWith('.map')) {
+ const filePath = path.join(entry.parentPath, entry.name)
+ files[path.relative(directory, filePath).split(path.sep).join('/')] = fs.readFileSync(filePath)
+ }
+ }
+ return files
+}
diff --git a/products/web_analytics/frontend/heatmaps/components/HeatmapsForbiddenURL.tsx b/products/web_analytics/frontend/heatmaps/components/HeatmapsForbiddenURL.tsx
index 24cd159134a1..696d3d52ce0e 100644
--- a/products/web_analytics/frontend/heatmaps/components/HeatmapsForbiddenURL.tsx
+++ b/products/web_analytics/frontend/heatmaps/components/HeatmapsForbiddenURL.tsx
@@ -8,9 +8,9 @@ import {
AuthorizedUrlListType,
authorizedUrlListLogic,
defaultAuthorizedUrlProperties,
- sanitizePossibleWildCardedURL,
validateProposedUrl,
} from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
+import { sanitizePossibleWildCardedURL } from 'lib/components/AuthorizedUrlList/authorizedUrlMatching'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { heatmapsBrowserLogic } from './heatmapsBrowserLogic'