From 8172d2708939e0ad5f2acc5f448605da26505271 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:23:03 -0600 Subject: [PATCH] feat(cloud): browser product analytics through a same-origin PostHog proxy (#22012) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Cloud runs the same app for hosted customers, and the same UI ships in the npm package. > - The PostHog project for Cloud gets only server events today. It has no page views, sessions, replays or people. > - So the Product and Web analytics pages are empty, and we cannot see how Cloud users move through the board. > - This pull request adds browser analytics for Cloud only. It is off until an operator sets two switches on a Cloud stack. > - Self-hosted installs do not change: they never download posthog-js and never serve the PostHog proxy. > - The benefit is real page views, sessions, heatmaps, Web Vitals and masked session replays for Cloud, linked to the user and the workspace. ## Linked Issues or Issue Description **Subsystem affected** Board UI (analytics bootstrap and privacy markers), server session payload and a new same-origin proxy route, shared validators. **Problem or motivation** Cloud sends only server events to PostHog. There is no browser SDK, so PostHog has no page views, sessions, replays or identified people for Cloud. We cannot see where Cloud users get stuck. **Proposed solution** The signed-in session gives the UI a PostHog config only on a Cloud-managed stack with `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. The UI loads posthog-js after the page settles. Events go through a strict same-origin proxy at `/_ph`, so ad blockers do not drop them. Replay masks all text and all inputs by default. **Alternatives considered** Bake a key into the UI build: refused, because the same build ships to self-hosted users. A generic reverse proxy: refused, because it would forward any path. Mask only content areas: refused, because a missed surface would leak; masking is deny by default. **Additional context** This is the browser part of the Cloud direct PostHog plan. The server direct sender is already on master (#22006). Fleet configuration is a separate change. PostHog person deletion on account deletion is a follow-up. ## What Changed - Uses the shared Cloud PostHog config (`resolveCloudPostHogConfig` in `server/src/services/cloud-posthog-config.ts`, already on master from the server direct-sending change). This PR does not change it. - `server/src/services/cloud-posthog-browser.ts`: `resolveBrowserAnalyticsConfig` returns `{ token, apiHost: "/_ph", uiHost, environment, stackId, replayEnabled }` only when `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `environment` is always set: the explicit variable, else `staging` for a `*.staging.paperclip.app` host, else `production`. - `GET /api/auth/get-session` carries the new optional `browserAnalytics` field (the existing signed-in bootstrap request, so no new request on the cold path). `packages/shared` has `browserAnalyticsConfigSchema` and the session schema field. - `server/src/routes/posthog-proxy.ts`: a strict proxy, mounted before the body parsers and only when browser analytics is on. It forwards only these requests and answers 404 to all others without contacting PostHog: - `POST /e/`, `/i/v0/e/`, `/batch/`, `/s/`, `/flags/`, `/decide/` to the ingest host. - `GET /array//config(.js)` and `GET /static/[/].js` to the assets host (derived from the ingest host). - `stream.pipeline` joins the streams, so an error on either side (PostHog closes the connection partway through a response, or the browser goes away) closes both and never goes unhandled. It builds a new header set from an allowlist plus `X-Forwarded-For`. It never forwards the inbound Host, Cookie or Authorization headers. It drops `Set-Cookie` from responses. Bodies stream; nothing is buffered. It refuses bodies over 64 MiB (413, also for chunked bodies that grow past the limit) and limits requests in flight to 16 per client address and 256 in total (429). - `ui/src/lib/analytics/product-analytics.ts` (the only module that talks to posthog-js) and `ui/src/components/ProductAnalyticsGate.tsx`: - posthog-js loads after the page settles (or at a 15 s deadline), only when the session has a config. It loads as PostHog's browser script `/_ph/static/array.js` through the proxy, the same way posthog-js itself loads its extensions (recorder, web vitals). It is not an npm dependency and is in no bundle chunk. - Init: page views on history change, page leave, autocapture, Web Vitals, heatmaps, `person_profiles: "identified_only"`, `tracing_headers` for our own host only, replay only when `replayEnabled`. Surveys, product tours, web experiments and conversations are off. - Super properties on every event: `deployment_source: "cloud"` and `environment`. - After sign-in: `identify(session.userId, { email, name })` (person properties only). `session.userId` is the authenticated actor's user id verbatim (for example `paperclip-id:...`): `GET /api/auth/get-session` copies `req.actor.userId` into it, and server events use that same actor id as `distinct_id`, so browser and server events land on one person. Tests: `auth-routes.test.ts` (the session returns the actor id verbatim) and `ProductAnalyticsGate.test.tsx` (identify uses it) and `group("workspace", stackId)`. On sign-out: `reset()`, then the super properties again. `useSignOut` calls it before it leaves the page, because Cloud sign-out navigates away while the session query is still populated. - Privacy (`ui/src/lib/analytics/privacy.ts`), deny by default: - Replay masks every text node (`maskTextSelector: "*"` with `maskTextFn`) and every input value (`maskAllInputs`). - Only elements with `ANALYTICS_UNMASK_PROPS` show their text: sidebar items whose label is a fixed string (`analyticsChrome`, added at the 99 call sites with literal labels), and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only when its caller passes `analyticsChrome`. None of them opts in by default, because they also render customer text (agent names, document titles). Sidebar items with dynamic labels (recent tasks, agents, projects) stay masked. - Replay masks attribute values too (`maskAttributeFn`, deny by default). Only layout attributes (`class`, `style`, `role`, `data-state`, SVG geometry), rrweb metadata and stylesheet links keep their values. `title`, `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` and element references (`id`, `for`, `aria-labelledby`, `aria-describedby`, `aria-controls`, which often embed names or slugs) are always masked, even on unmasked chrome. So the organization switcher's `aria-label`, task titles in `title` attributes, image sources and download links with file paths never reach a replay. - `before_send` (`scrubCapturedEvent`) drops the `title` property from every event, because posthog-js copies `document.title` (task and organization names) into page views. Every URL string in every event, including replay meta events, keeps only its origin and path: query and hash values never leave (they can hold tokens, `code`/`state`, file paths or search text), and the token segment of `/board-claim/` and `/invite/` is redacted. It recurses only into plain objects and arrays, so the `Date` timestamp stays intact. - `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked chrome: `MarkdownBody` (task and issue bodies, comments, chat messages, documents and artifact markdown), `MarkdownEditor`, the task chat thread, the issue chat thread, the comment timeline, the file viewer (source, markdown and CSV views) and the organization name in the organization switcher. Text in any `contenteditable` editor is always masked. - `ANALYTICS_NO_CAPTURE_CLASS` (`ph-no-capture`, a blank box in replay) on every password-type `Input` (about 40 secret, token and API key fields), environment variable values and new secret values. - Autocapture never records element text or attribute values (`mask_all_text`, `mask_all_element_attributes`). - Connected-account content (Google user data and Slack data: email bodies, calendar events, Slack messages in tasks, chat, tool results, previews) never appears unmasked in a replay. Replay masks all text by default; nothing that renders connected-account content is in the unmask allowlist; autocapture records no element text anywhere (`mask_all_text`). `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: only 7 files may spread the unmask attribute, sidebar opt-ins need a literal label, and any `analyticsChrome` opt-in on `Button`/`Label`/`TabsTrigger`/`EmptyState` fails until it is added to a reviewed list (empty today). The same test renders Gmail, Calendar and Slack-style tool results next to unmasked navigation and checks they are masked. - Guard test: UI code must never call `capture()` with a `PAPERCLIP_EVENTS` name, so each event has one sender. - Docs: `doc/cloud-browser-analytics.md` (switches, per-stack opt-out, proxy allowlist, identity, privacy) and a link from `doc/observability.md`. - No new npm dependency and no lockfile change: posthog-js comes from PostHog through the proxy at run time. (An earlier revision added `posthog-js` to `ui/package.json`; the Runner support suite requires every `ui` dependency in the reviewed lockfile, which a pull request cannot update, so the script approach replaced it.) ## Verification - `pnpm verify`: see the result below. - Focused tests: - `server/src/__tests__/cloud-posthog-browser.test.ts`: exposure matrix (self-hosted with every switch set, Cloud without token, without stack ID, without the browser switch, switch not `1`, enabled, replay off), environment fallback, proxy mount only when enabled, allowed routes, 404 for disallowed methods and paths (including `//host` and `..` paths) with no upstream contact, Host/Cookie/Authorization stripped, `Set-Cookie` dropped, 502 when PostHog is down, and no unhandled error when PostHog closes a response partway (red on the old `pipe()` code, green now). - `server/src/__tests__/auth-routes.test.ts`: the session carries `browserAnalytics` only on Cloud with the token and the switch. - `ui/src/lib/analytics/*.test.ts`, `ui/src/components/ProductAnalyticsGate.test.tsx`: no import of posthog-js without a config or when signed out; load after the page settles, once; identify, group, reset with a mocked posthog; email and name never become event properties; deny-by-default replay masking; guard test. - Real run (local, headless Chromium, production UI build, never the real PostHog project): - Self-hosted server, no env: 0 requests for PostHog's script and 0 requests to `/_ph` in 9 cold loads and in a 40 s session with navigation. `browserAnalytics` is `null`. `/_ph/e/` falls through to the UI. - Cloud config: a full Cloud boot needs S3, a managed database and the control plane. So a small local stand-in served the same production UI build, mounted the real proxy from `server/src/routes/posthog-proxy.ts`, added the real `resolveBrowserAnalyticsConfig()` output to the session, and forwarded other API calls to the local server. `PAPERCLIP_POSTHOG_HOST` pointed at a local capture server. - Captured through `/_ph` only (0 requests to any posthog.com host): `$pageview` on each client navigation (5), `$identify` with `$set: { email, name }`, `$groupidentify`, `$groups: { workspace: }` on events, `environment` and `deployment_source` on every event, `$web_vitals`, `$autocapture` with no `$el_text`, `$$heatmap`, and 10 `$snapshot` replay events. A search of every decoded `/e/` and `/s/` payload (events, replay text and replay attributes) found the email only in `$identify`'s `$set`, and found none of: the task body, the typed comment, the task title, the organization name. No Cookie header reached the capture server. 96 of 113 API requests carried `X-POSTHOG-SESSION-ID` (the others ran before posthog-js loaded). - Client-side visits to `/invite/INVITESECRET123` and `/cli-auth/abc?token=CLISECRET456` reached PostHog as `/invite/REDACTED` and `/cli-auth/abc` (no query); neither secret was in any payload. - Disallowed proxy requests (`PUT /_ph/e/`, `GET /_ph/api/projects/`, `POST /_ph/static/x.js`) answered 404. - Sample replay payload (decoded rrweb text nodes from a captured `/s/` request). The task body, the typed comment, the task title, the organization name and the email were not in any replay payload: ```json {"text_nodes": [ {"parentTag": "title", "textContent": "****** ** * *********"}, {"parentTag": "a", "textContent": "**** ** **** *******"}, {"parentTag": "span", "textContent": "****** **"}, {"parentTag": "span", "textContent": "*** ****"}, {"parentTag": "span", "textContent": "Tasks"}, {"parentTag": "span", "textContent": "Inbox"}, {"parentTag": "h2", "textContent": "******* *******"}, {"parentTag": "p", "textContent": "****** *** * ******* ** ******"} ]} ``` - Cold load, 9 fresh-profile loads each, median, same stand-in with analytics off and on: | | DOMContentLoaded | Board content visible | | --- | --- | --- | | Analytics off | 128 ms | 336 ms | | Analytics on | 126 ms | 334 ms | Final head. The difference is inside run-to-run noise (earlier pairs: 332/335 ms and 335/348 ms). PostHog's script loads only after the content is visible. ## Risks - Inert by default. Without a Cloud-managed stack, a project token, a stack ID and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`, the session field is `null`, the proxy is not mounted and no analytics code runs. The OSS package does not change behavior. - Per-stack opt-out: `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` turns replay off; unsetting `PAPERCLIP_POSTHOG_BROWSER_ENABLED` turns all browser analytics off. Both apply on the next restart. - Replay text shown in the clear comes only from fixed sidebar labels and from shared components whose caller opts in. Today no `Button`, `Label`, `TabsTrigger` or `EmptyState` call site opts in, so replays show layout, clicks and navigation with most copy masked. Opting in fixed-label call sites is a follow-up. Review sample replays on staging before production. - Image `src` values are masked, so images record as empty boxes. Sandboxed iframes (HTML artifacts, MCP apps) also record as empty boxes. Replays therefore show layout and product copy, not customer media. - PostHog's script is not version-pinned: the assets host serves its current browser build, as for any PostHog snippet install, and posthog-js already loads its extensions from that host at run time. It runs only on Cloud stacks with the browser switch on. - The proxy needs no sign-in, like PostHog's documented proxies: posthog-js sends some events while a page unloads, and the proxy can only reach the two PostHog hosts, on the listed paths, with the public project token. Body size and in-flight limits bound the load one client can add. - posthog-js rejects bots (including headless browsers) on its own, which is the wanted production behavior. - `SidebarNavItem.production.tsx`, `Sidebar*.tsx` and the shared `ui/*` components changed by one attribute each; no visual change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, headless browser runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/cloud-browser-analytics.md | 122 +++++++ doc/observability.md | 3 + packages/shared/src/index.ts | 2 + packages/shared/src/validators/access.ts | 24 ++ packages/shared/src/validators/index.ts | 2 + server/src/__tests__/auth-routes.test.ts | 35 ++ .../__tests__/board-skill-ui-guidance.test.ts | 2 +- .../__tests__/cloud-posthog-browser.test.ts | 295 +++++++++++++++++ server/src/app.ts | 5 + server/src/routes/auth.ts | 4 + server/src/routes/posthog-proxy.ts | 238 ++++++++++++++ server/src/services/cloud-posthog-browser.ts | 65 ++++ .../runner-e2e/source-sdk-public-inputs.json | 6 +- ui/src/components/AppsSidebar.production.tsx | 6 +- ui/src/components/AppsSidebar.tsx | 4 +- ui/src/components/CommentThread.tsx | 3 +- .../CompanySettingsSidebar.production.tsx | 28 +- ui/src/components/CompanySettingsSidebar.tsx | 26 +- ui/src/components/CoordinatorSidebar.tsx | 6 +- ui/src/components/DesignSidebar.tsx | 20 +- ui/src/components/EmptyState.tsx | 6 +- ui/src/components/FileViewerSheet.tsx | 5 +- ui/src/components/IssueChatThread.tsx | 3 +- ui/src/components/MarkdownBody.tsx | 3 + ui/src/components/MarkdownEditor.tsx | 3 + .../components/ProductAnalyticsGate.test.tsx | 128 ++++++++ ui/src/components/ProductAnalyticsGate.tsx | 59 ++++ .../components/RoutineContextualSidebar.tsx | 4 +- ui/src/components/Sidebar.production.tsx | 42 +-- ui/src/components/Sidebar.tsx | 54 ++-- .../SidebarCompanyMenu.production.tsx | 4 +- ui/src/components/SidebarCompanyMenu.tsx | 4 +- .../components/SidebarNavItem.production.tsx | 5 + ui/src/components/SidebarNavItem.tsx | 5 + ui/src/components/SkillsContextualSidebar.tsx | 8 +- ui/src/components/TaskChatThread.tsx | 3 + .../CreateSecretPopover.tsx | 3 +- .../environment-variables-editor/Row.tsx | 3 +- ui/src/components/ui/button.tsx | 5 + ui/src/components/ui/input.tsx | 3 + ui/src/components/ui/label.tsx | 8 +- ui/src/components/ui/tabs.tsx | 8 +- ui/src/hooks/useSignOut.test.tsx | 6 + ui/src/hooks/useSignOut.ts | 4 + ui/src/lib/analytics/privacy.test.ts | 117 +++++++ ui/src/lib/analytics/privacy.ts | 124 +++++++ .../product-analytics-events.test.ts | 48 +++ .../lib/analytics/product-analytics.test.ts | 197 ++++++++++++ ui/src/lib/analytics/product-analytics.ts | 302 ++++++++++++++++++ ui/src/lib/analytics/shared-chrome.test.tsx | 59 ++++ ui/src/lib/analytics/unmask-allowlist.test.ts | 102 ++++++ ui/src/main.tsx | 2 + 52 files changed, 2109 insertions(+), 114 deletions(-) create mode 100644 doc/cloud-browser-analytics.md create mode 100644 server/src/__tests__/cloud-posthog-browser.test.ts create mode 100644 server/src/routes/posthog-proxy.ts create mode 100644 server/src/services/cloud-posthog-browser.ts create mode 100644 ui/src/components/ProductAnalyticsGate.test.tsx create mode 100644 ui/src/components/ProductAnalyticsGate.tsx create mode 100644 ui/src/lib/analytics/privacy.test.ts create mode 100644 ui/src/lib/analytics/privacy.ts create mode 100644 ui/src/lib/analytics/product-analytics-events.test.ts create mode 100644 ui/src/lib/analytics/product-analytics.test.ts create mode 100644 ui/src/lib/analytics/product-analytics.ts create mode 100644 ui/src/lib/analytics/shared-chrome.test.tsx create mode 100644 ui/src/lib/analytics/unmask-allowlist.test.ts diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md new file mode 100644 index 00000000000..27bb253688e --- /dev/null +++ b/doc/cloud-browser-analytics.md @@ -0,0 +1,122 @@ +# Cloud Browser Product Analytics + +On Paperclip Cloud, the board UI can send page views, sessions, autocapture +clicks, heatmaps, Web Vitals and session replays to PostHog. Self-hosted +installs never do this: they do not download `posthog-js` and do not serve the +PostHog proxy. + +## Who gets it + +The server decides, in `server/src/services/cloud-posthog-browser.ts`. The +authenticated `GET /api/auth/get-session` response carries a +`browserAnalytics` object only when all of these hold: + +1. The instance is cloud managed (`isCloudManagedInstance`). +2. `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_CLOUD_STACK_ID` are set. +3. `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. + +Otherwise the field is `null`, and the browser loads nothing. When it is set, +the browser loads PostHog's browser script (`/_ph/static/array.js`, through the +proxy) only after the page settles (first paint, page reads finished, browser +idle), so cold loads do not wait for it. posthog-js is not an npm dependency +of the board and is in no bundle chunk; PostHog serves it, as it serves the +extensions posthog-js loads at run time (recorder, web vitals). + +## Configuration + +| Variable | Default | Meaning | +| --- | --- | --- | +| `PAPERCLIP_POSTHOG_PROJECT_TOKEN` | โ€” | PostHog project token. It is public by design: it can send events but cannot read data. | +| `PAPERCLIP_POSTHOG_HOST` | `https://us.i.posthog.com` | PostHog ingest host. The proxy forwards to it. | +| `PAPERCLIP_POSTHOG_ENVIRONMENT` | โ€” | `staging` or `production`. Added to every event as `environment`. | +| `PAPERCLIP_POSTHOG_BROWSER_ENABLED` | off | `1` turns browser analytics on for this stack. Leave it unset to keep it off. | +| `PAPERCLIP_POSTHOG_REPLAY_ENABLED` | on (when browser analytics is on) | `0` turns session replay off for this stack and keeps the other browser analytics. | + +### Per-stack opt-out + +For a customer whose contract forbids recording, set +`PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` on that stack. To turn off all browser +analytics for a stack, unset `PAPERCLIP_POSTHOG_BROWSER_ENABLED`. Both take +effect on the next server restart. + +## Reverse proxy + +The browser sends to `/_ph` on its own origin, so ad blockers do not drop +events. `server/src/routes/posthog-proxy.ts` is not a generic proxy. It +forwards only the requests posthog-js makes: + +| Method | Path | Upstream | +| --- | --- | --- | +| `POST` | `/e/`, `/i/v0/e/`, `/batch/` | ingest host | +| `POST` | `/s/` (session replay) | ingest host | +| `POST` | `/flags/`, `/decide/` | ingest host | +| `GET` | `/array//config`, `/array//config.js` | assets host | +| `GET` | `/static/.js` | assets host | + +The ingest host is `PAPERCLIP_POSTHOG_HOST`. The assets host is derived from it +(`us.i.posthog.com` โ†’ `us-assets.i.posthog.com`). Every other method or path +answers 404 without contacting PostHog. The proxy streams bodies, builds a new +header set from an allowlist plus `X-Forwarded-For`, and never forwards the +inbound Host, Cookie or Authorization headers. It drops `Set-Cookie` from +responses. It refuses bodies over 64 MiB (413) and limits requests in +flight to 16 per client address and 256 in total (429). It is mounted only when +browser analytics is on. It does not require a session: posthog-js sends some +events while a page unloads, and the proxy can only reach the two PostHog hosts +with the public project token, like PostHog's own ingest endpoint. + +## Identity + +- After sign-in: `identify(session.userId, { email, name })`. `session.userId` + is the authenticated actor's user id verbatim (`req.actor.userId`, for + example `paperclip-id:...`), the same id server events use as `distinct_id`. Email and name are person + properties only, never event properties. +- `group("workspace", stackId)`. +- Every event carries `deployment_source: "cloud"` and `environment`. Without + `PAPERCLIP_POSTHOG_ENVIRONMENT`, `environment` is `staging` on a + `*.staging.paperclip.app` host and `production` otherwise. +- Sign-out: `reset()`, called by `useSignOut` before it leaves the page. +- API requests to our own host carry PostHog tracing headers, so server events + link to the browser session. + +## Privacy + +Masking is deny by default. A surface that nobody marked stays masked. + +- Session replay masks every input value and every text node. + `maskReplayText` in `ui/src/lib/analytics/privacy.ts` shows text only inside + elements with `ANALYTICS_UNMASK_PROPS`: sidebar items whose label is a fixed + string, and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only + when its caller passes `analyticsChrome`. None of them opts in by default, + because they also render customer text such as agent names and titles. +- Replay also masks attribute values (`maskReplayAttribute`): only layout + attributes (`class`, `style`, `role`, `data-state`, SVG geometry and similar), + rrweb metadata and stylesheet links keep their values. `title`, + `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` values and + element references (`id`, `for`, `aria-labelledby`) are always masked, even on unmasked chrome, so images record as empty boxes and + link targets (for example download links with file paths) never leave. +- `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked + chrome: rendered markdown (task bodies, comments, chat messages, documents), + task and issue chat threads, the comment timeline, the rich editor and the + file viewer. Text in a `contenteditable` editor is always masked. +- `ANALYTICS_NO_CAPTURE_CLASS` replaces secrets with a blank box in replays: + every password-type `Input`, environment variable values and new secret + values. +- Every event and replay meta event goes through `scrubCapturedEvent` + (`before_send`). Every URL keeps only its origin and path: query and hash + values never leave, because they can hold credentials, file paths or search + text. The token segment of `/board-claim/` and `/invite/` is + redacted (`redactAnalyticsUrl`). Other strings only have secret + `key=value` pairs redacted. +- Events never carry the page title (`before_send` drops `title`), because + Paperclip page titles name the task and the organization. +- Autocapture never records element text or attribute values + (`mask_all_text`, `mask_all_element_attributes`). It keeps the click, the + element tree and the page. +- Connected-account content (Gmail bodies, Calendar events, Slack messages + in tasks, chat, tool results and previews) is Google user data or Slack + data. No human may read it in a replay (Google API Limited Use). It is never + inside the unmask allowlist, and autocapture records no element text at all. + `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: a new + unmask needs a reviewed entry there. +- The UI never captures an event that the server already sends + (`PAPERCLIP_EVENTS`); `product-analytics-events.test.ts` enforces this. diff --git a/doc/observability.md b/doc/observability.md index 77a0b1d8e66..f9aaac0700f 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -154,6 +154,9 @@ for this workload; everything else from - **Browser page-load tracing** on hosted instances needs `PAPERCLIP_BROWSER_TRACES_ENDPOINT`. See [browser performance tracing](browser-performance-tracing.md). +- **Browser product analytics** (PostHog) on Paperclip Cloud needs + `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. + See [Cloud browser product analytics](cloud-browser-analytics.md). ## Sentry Error Monitoring diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e17ff48b580..793b9067f01 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2451,6 +2451,7 @@ export { currentUserProfileSchema, authSessionSchema, browserTracingConfigSchema, + browserAnalyticsConfigSchema, updateCurrentUserProfileSchema, updateCompanyMemberSchema, updateCompanyMemberWithPermissionsSchema, @@ -2477,6 +2478,7 @@ export { type CurrentUserProfile, type AuthSession, type BrowserTracingConfig, + type BrowserAnalyticsConfig, type UpdateCurrentUserProfile, type UpdateCompanyMember, type UpdateCompanyMemberWithPermissions, diff --git a/packages/shared/src/validators/access.ts b/packages/shared/src/validators/access.ts index eb1c2ab3cc6..110a49f427a 100644 --- a/packages/shared/src/validators/access.ts +++ b/packages/shared/src/validators/access.ts @@ -216,6 +216,27 @@ export const browserTracingConfigSchema = z.object({ export type BrowserTracingConfig = z.infer; +/** + * Browser product analytics (PostHog) settings for a hosted Paperclip Cloud + * instance. The server sends a value only when the instance is cloud managed, + * `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_CLOUD_STACK_ID` are set, and + * `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `token` is a PostHog project token, + * which is public by design (it can only send events). `apiHost` is the + * same-origin reverse proxy path, and `uiHost` is the PostHog app host for + * links, or null when it is not a PostHog Cloud host. `environment` is + * always set, so every browser event carries it. + */ +export const browserAnalyticsConfigSchema = z.object({ + token: z.string().min(1), + apiHost: z.string().min(1), + uiHost: z.string().url().nullable(), + environment: z.string().min(1), + stackId: z.string().min(1), + replayEnabled: z.boolean(), +}); + +export type BrowserAnalyticsConfig = z.infer; + export const authSessionSchema = z.object({ session: z.object({ id: z.string().min(1), @@ -234,6 +255,9 @@ export const authSessionSchema = z.object({ // Null or absent leaves browser performance tracing off. Optional for // browser/server version skew. browserTracing: browserTracingConfigSchema.nullable().optional(), + // Null or absent leaves browser product analytics off; the browser then never + // downloads posthog-js. Optional for browser/server version skew. + browserAnalytics: browserAnalyticsConfigSchema.nullable().optional(), }); export type AuthSession = z.infer; diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index b0bc5449eb5..c8cbf1aea75 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -775,6 +775,7 @@ export { currentUserProfileSchema, authSessionSchema, browserTracingConfigSchema, + browserAnalyticsConfigSchema, updateCurrentUserProfileSchema, updateCompanyMemberSchema, updateCompanyMemberWithPermissionsSchema, @@ -797,6 +798,7 @@ export { type CurrentUserProfile, type AuthSession, type BrowserTracingConfig, + type BrowserAnalyticsConfig, type UpdateCurrentUserProfile, type UpdateCompanyMember, type UpdateCompanyMemberWithPermissions, diff --git a/server/src/__tests__/auth-routes.test.ts b/server/src/__tests__/auth-routes.test.ts index 381c99b517a..8098f990864 100644 --- a/server/src/__tests__/auth-routes.test.ts +++ b/server/src/__tests__/auth-routes.test.ts @@ -96,6 +96,41 @@ describe("auth routes", () => { sentryDsn: null, sentryEnvironment: null, browserTracing: null, + browserAnalytics: null, + }); + }); + + it("returns the authenticated actor's user id verbatim, the id browser analytics identifies with", async () => { + const actorId = "paperclip-id:uf2X8Ha4H9hNdAMnc1rOy91VIRos5pch"; + const actor = { type: "board", userId: actorId, source: "cloud_tenant" } as Express.Request["actor"]; + const res = await request(createApp(actor, { ...baseUser, id: actorId })).get("/api/auth/get-session"); + expect(res.status).toBe(200); + // ProductAnalyticsGate calls identify(session.userId); server events use the actor id as distinct_id. + expect(res.body.session.userId).toBe(actorId); + }); + + it("sends browserAnalytics only on Cloud with a PostHog token and the browser switch", async () => { + const actor = { type: "board", userId: "user-1", source: "session" } as Express.Request["actor"]; + vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token"); + vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "stack-1"); + vi.stubEnv("PAPERCLIP_POSTHOG_PROJECT_TOKEN", "phc_test"); + vi.stubEnv("PAPERCLIP_POSTHOG_BROWSER_ENABLED", undefined); + + const off = await request(createApp(actor, baseUser)).get("/api/auth/get-session"); + expect(off.status).toBe(200); + expect(off.body.browserAnalytics).toBeNull(); + + vi.stubEnv("PAPERCLIP_POSTHOG_BROWSER_ENABLED", "1"); + vi.stubEnv("PAPERCLIP_POSTHOG_ENVIRONMENT", "staging"); + const on = await request(createApp(actor, baseUser)).get("/api/auth/get-session"); + expect(on.status).toBe(200); + expect(on.body.browserAnalytics).toEqual({ + token: "phc_test", + apiHost: "/_ph", + uiHost: "https://us.posthog.com", + environment: "staging", + stackId: "stack-1", + replayEnabled: true, }); }); diff --git a/server/src/__tests__/board-skill-ui-guidance.test.ts b/server/src/__tests__/board-skill-ui-guidance.test.ts index 877c7271f87..d177137832d 100644 --- a/server/src/__tests__/board-skill-ui-guidance.test.ts +++ b/server/src/__tests__/board-skill-ui-guidance.test.ts @@ -31,7 +31,7 @@ describe("paperclip-board skill web UI guidance", () => { it("keeps the overlay promise to the shortcut and describes the sidebar Search item as full search", () => { // The classic sidebar Search item is a link to the full search page, not the overlay. - expect(read("ui/src/components/Sidebar.tsx")).toMatch(/]*\bto="\/search" label="Search"/); expect(section).toMatch(/sidebar \*\*Search\*\* item[^\n]*opens the full search page/); expect(section).not.toMatch(/search icon[^\n]*opens over the current page/i); }); diff --git a/server/src/__tests__/cloud-posthog-browser.test.ts b/server/src/__tests__/cloud-posthog-browser.test.ts new file mode 100644 index 00000000000..8cf1863a8ce --- /dev/null +++ b/server/src/__tests__/cloud-posthog-browser.test.ts @@ -0,0 +1,295 @@ +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import express from "express"; +import request from "supertest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + posthogAssetsOrigin, + posthogUiHost, + resolveBrowserAnalyticsConfig, +} from "../services/cloud-posthog-browser.js"; +import { resolveCloudPostHogConfig } from "../services/cloud-posthog-config.js"; +import { + posthogProxyRoutes, + posthogUpstreamUrl, + resolvePostHogProxyMount, +} from "../routes/posthog-proxy.js"; + +const CLOUD = { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token", PAPERCLIP_CLOUD_STACK_ID: "stack-1" }; +const TOKEN = { PAPERCLIP_POSTHOG_PROJECT_TOKEN: "phc_test" }; +const BROWSER = { PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1" }; + +describe("browser analytics config exposure", () => { + const cases: Array<[string, Record, boolean, boolean | null]> = [ + ["self-hosted, even with every PostHog switch set", { ...TOKEN, ...BROWSER, PAPERCLIP_CLOUD_STACK_ID: "stack-1" }, false, null], + ["Cloud without a token", { ...CLOUD, ...BROWSER }, false, null], + ["Cloud without a stack ID", { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "t", ...TOKEN, ...BROWSER }, false, null], + ["Cloud with a token but no browser switch", { ...CLOUD, ...TOKEN }, false, null], + ["Cloud with the browser switch set to something other than 1", { ...CLOUD, ...TOKEN, PAPERCLIP_POSTHOG_BROWSER_ENABLED: "true" }, false, null], + ["Cloud with browser analytics on", { ...CLOUD, ...TOKEN, ...BROWSER }, true, true], + ["Cloud with browser analytics on and replay off", { ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_REPLAY_ENABLED: "0" }, true, false], + ]; + + it.each(cases)("%s", (_name, env, exposed, replayEnabled) => { + const config = resolveBrowserAnalyticsConfig(env); + if (!exposed) { + expect(config).toBeNull(); + return; + } + expect(config).toEqual({ + token: "phc_test", + apiHost: "/_ph", + uiHost: "https://us.posthog.com", + environment: "production", + stackId: "stack-1", + replayEnabled, + }); + }); + + it("always sends an environment: the explicit variable, else staging or production from the host", () => { + const on = { ...CLOUD, ...TOKEN, ...BROWSER }; + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_POSTHOG_ENVIRONMENT: "qa" })?.environment).toBe("qa"); + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_PRIMARY_HOST: "acme.staging.paperclip.app" })?.environment).toBe("staging"); + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_PRIMARY_HOST: "acme.paperclip.app" })?.environment).toBe("production"); + }); + + it("never turns replay on without the browser switch", () => { + expect(resolveCloudPostHogConfig({ ...CLOUD, ...TOKEN, PAPERCLIP_POSTHOG_REPLAY_ENABLED: "1" })?.replayEnabled).toBe(false); + }); + + it("keeps browser analytics off for an invalid host", () => { + expect(resolveBrowserAnalyticsConfig({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: "not a url" })).toBeNull(); + }); + + it("maps PostHog Cloud hosts to their assets and app hosts", () => { + expect(posthogAssetsOrigin("https://us.i.posthog.com")).toBe("https://us-assets.i.posthog.com"); + expect(posthogAssetsOrigin("https://eu.i.posthog.com")).toBe("https://eu-assets.i.posthog.com"); + expect(posthogAssetsOrigin("http://127.0.0.1:9999")).toBe("http://127.0.0.1:9999"); + expect(posthogUiHost("https://eu.i.posthog.com")).toBe("https://eu.posthog.com"); + expect(posthogUiHost("http://127.0.0.1:9999")).toBeNull(); + }); +}); + +describe("PostHog proxy mount", () => { + it("is not mounted unless browser analytics is on", () => { + expect(resolvePostHogProxyMount({})).toBeNull(); + expect(resolvePostHogProxyMount({ ...TOKEN, ...BROWSER, PAPERCLIP_CLOUD_STACK_ID: "s" })).toBeNull(); + expect(resolvePostHogProxyMount({ ...CLOUD, ...TOKEN })).toBeNull(); + expect(resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER })?.path).toBe("/_ph"); + }); + + it("routes static assets to the assets host and events to the ingest host", () => { + const host = "https://us.i.posthog.com"; + expect(posthogUpstreamUrl(host, "GET", "/static/recorder.js?v=1")?.href) + .toBe("https://us-assets.i.posthog.com/static/recorder.js?v=1"); + expect(posthogUpstreamUrl(host, "GET", "/array/phc_x/config.js")?.origin).toBe("https://us-assets.i.posthog.com"); + expect(posthogUpstreamUrl(host, "GET", "/array/phc_x/config")?.origin).toBe("https://us-assets.i.posthog.com"); + expect(posthogUpstreamUrl(host, "GET", "/static/1.442.1/lazy-recorder.js")?.href) + .toBe("https://us-assets.i.posthog.com/static/1.442.1/lazy-recorder.js"); + expect(posthogUpstreamUrl(host, "POST", "/e/?ip=0")?.href).toBe("https://us.i.posthog.com/e/?ip=0"); + expect(posthogUpstreamUrl(host, "POST", "/i/v0/e/")?.origin).toBe("https://us.i.posthog.com"); + expect(posthogUpstreamUrl(host, "POST", "/s/?compression=gzip-js")?.pathname).toBe("/s/"); + expect(posthogUpstreamUrl(host, "POST", "/flags/?v=2")?.pathname).toBe("/flags/"); + }); + + it.each([ + ["GET", "/e/"], + ["PUT", "/e/"], + ["DELETE", "/s/"], + ["OPTIONS", "/flags/"], + ["POST", "/static/recorder.js"], + ["GET", "/api/projects/"], + ["POST", "/api/surveys/"], + ["GET", "/static/../api/x.js"], + ["GET", "/static/recorder.css"], + ["GET", "/static/v1/../x.js"], + ["GET", "/static/a/b/c.js"], + ["GET", "//evil.example/static/x.js"], + ["POST", "//evil.example/e/"], + ["GET", "/array/phc_x/../../api"], + ["GET", "/"], + ])("refuses %s %s", (method, path) => { + expect(posthogUpstreamUrl("https://us.i.posthog.com", method, path)).toBeNull(); + }); +}); + +describe("PostHog proxy forwarding", () => { + let upstream: http.Server; + let upstreamUrl: string; + let seen: Array<{ method?: string; url?: string; headers: http.IncomingHttpHeaders; body: string }>; + + beforeEach(async () => { + seen = []; + upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + seen.push({ method: req.method, url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString() }); + res.writeHead(200, { "content-type": "application/json", "set-cookie": "upstream=1" }); + res.end(JSON.stringify({ status: 1 })); + }); + }); + await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve)); + upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; + }); + + afterEach(async () => { + await new Promise((resolve) => upstream.close(() => resolve())); + }); + + function proxyApp() { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: upstreamUrl }); + expect(mount).not.toBeNull(); + const app = express(); + app.use(mount!.path, mount!.router); + // A body parser after the proxy, as in app.ts, must never see proxied bodies. + app.use(express.json()); + return app; + } + + it("streams the request body and strips Host, Cookie, Authorization and set-cookie", async () => { + const res = await request(proxyApp()) + .post("/_ph/e/?compression=gzip-js") + .set("Host", "acme.paperclip.app") + .set("Content-Type", "application/json") + .set("Cookie", "paperclip.session=secret") + .set("Authorization", "Bearer secret") + .set("X-POSTHOG-SESSION-ID", "s1") + .send(JSON.stringify({ event: "$pageview" })); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ status: 1 }); + expect(res.headers["set-cookie"]).toBeUndefined(); + expect(seen).toHaveLength(1); + expect(seen[0]!.method).toBe("POST"); + expect(seen[0]!.url).toBe("/e/?compression=gzip-js"); + expect(seen[0]!.body).toBe(JSON.stringify({ event: "$pageview" })); + expect(seen[0]!.headers.host).toBe(new URL(upstreamUrl).host); + expect(seen[0]!.headers.cookie).toBeUndefined(); + expect(seen[0]!.headers.authorization).toBeUndefined(); + expect(seen[0]!.headers["x-posthog-session-id"]).toBeUndefined(); + expect(seen[0]!.headers["x-forwarded-for"]).toBeTruthy(); + }); + + it.each([ + ["GET", "/_ph/api/projects/@current"], + ["PUT", "/_ph/e/"], + ["DELETE", "/_ph/e/"], + ["GET", "/_ph/e/"], + ["POST", "/_ph/static/recorder.js"], + ])("answers 404 to %s %s without contacting PostHog", async (method, path) => { + const res = await request(proxyApp())[method.toLowerCase() as "get"](path); + expect(res.status).toBe(404); + expect(seen).toHaveLength(0); + }); + + it("refuses a declared body over the limit without contacting PostHog", async () => { + const app = express(); + app.use("/_ph", posthogProxyRoutes(upstreamUrl, { maxBodyBytes: 10, maxInFlightPerClient: 16, maxInFlight: 256 })); + const res = await request(app).post("/_ph/e/").set("Content-Type", "text/plain").send("x".repeat(11)); + expect(res.status).toBe(413); + expect(seen).toHaveLength(0); + }); + + it("cuts off a streamed body that grows past the limit", async () => { + const app = express(); + app.use("/_ph", posthogProxyRoutes(upstreamUrl, { maxBodyBytes: 10, maxInFlightPerClient: 16, maxInFlight: 256 })); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + const port = (server.address() as AddressInfo).port; + try { + const status = await new Promise((resolve) => { + const req = http.request({ host: "127.0.0.1", port, path: "/_ph/e/", method: "POST", headers: { "content-type": "text/plain", "transfer-encoding": "chunked" } }, (res) => { + res.resume(); + resolve(res.statusCode ?? 0); + }); + req.on("error", () => resolve("error")); + req.write("x".repeat(8)); + req.write("x".repeat(8)); + req.end(); + }); + expect([413, "error"]).toContain(status); + expect(seen.every((entry) => entry.body.length <= 10)).toBe(true); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + it("limits requests in flight from one client", async () => { + let release: () => void = () => {}; + const held = new Promise((resolve) => { release = resolve; }); + const slow = http.createServer(async (_req, res) => { await held; res.end("ok"); }); + await new Promise((resolve) => slow.listen(0, "127.0.0.1", resolve)); + const app = express(); + app.use("/_ph", posthogProxyRoutes(`http://127.0.0.1:${(slow.address() as AddressInfo).port}`, { maxBodyBytes: 1024, maxInFlightPerClient: 1, maxInFlight: 256 })); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + try { + const first = request(server).get("/_ph/static/array.js").then((res) => res.status); + await new Promise((resolve) => setTimeout(resolve, 50)); + const second = await request(server).get("/_ph/static/array.js"); + expect(second.status).toBe(429); + release(); + expect(await first).toBe(200); + // The slot frees up once the first request finishes. + expect((await request(server).get("/_ph/static/array.js")).status).toBe(200); + } finally { + release(); + await new Promise((resolve) => server.close(() => resolve())); + await new Promise((resolve) => slow.close(() => resolve())); + } + }); + + it("never forwards the inbound Host header", async () => { + await request(proxyApp()).get("/_ph/static/recorder.js").set("Host", "acme.paperclip.app"); + expect(seen[0]!.headers.host).toBe(new URL(upstreamUrl).host); + }); + + it("answers 502 when PostHog cannot be reached", async () => { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: "http://127.0.0.1:1" }); + const app = express(); + app.use(mount!.path, mount!.router); + const res = await request(app).get("/_ph/static/array.js"); + expect(res.status).toBe(502); + }); + + it("survives PostHog closing the connection partway through a response", async () => { + const broken = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "application/javascript", "content-length": "100000" }); + res.write("partial"); + setTimeout(() => res.socket?.destroy(), 20); + }); + await new Promise((resolve) => broken.listen(0, "127.0.0.1", resolve)); + const brokenUrl = `http://127.0.0.1:${(broken.address() as AddressInfo).port}`; + const errors: unknown[] = []; + const onUncaught = (err: unknown) => errors.push(err); + process.on("uncaughtException", onUncaught); + try { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: brokenUrl }); + const app = express(); + app.use(mount!.path, mount!.router); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + const port = (server.address() as AddressInfo).port; + const outcome = await new Promise((resolve) => { + http.get(`http://127.0.0.1:${port}/_ph/static/recorder.js`, (res) => { + res.on("data", () => {}); + res.on("end", () => resolve("end")); + res.on("error", () => resolve("error")); + res.on("aborted", () => resolve("aborted")); + }).on("error", () => resolve("error")); + }); + // The browser sees a cut-off response, not a complete one. + expect(outcome).not.toBe("end"); + await new Promise((resolve) => setTimeout(resolve, 50)); + // The proxy keeps serving after the broken response. + const health = await request(server).put("/_ph/e/"); + expect(health.status).toBe(404); + await new Promise((resolve) => server.close(() => resolve())); + } finally { + process.off("uncaughtException", onUncaught); + await new Promise((resolve) => broken.close(() => resolve())); + } + expect(errors).toEqual([]); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index 2715922012e..4be9c420154 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -179,6 +179,7 @@ import { } from "./routes/instance-database-backups.js"; import { llmRoutes } from "./routes/llms.js"; import { authRoutes } from "./routes/auth.js"; +import { resolvePostHogProxyMount } from "./routes/posthog-proxy.js"; import { assetRoutes } from "./routes/assets.js"; import { accessRoutes } from "./routes/access.js"; import { pluginRoutes } from "./routes/plugins.js"; @@ -535,6 +536,10 @@ export async function createApp( // Default is unset โ†’ Express trusts nothing, which is the only safe choice // when the server may be reachable without a known reverse proxy in front. applyTrustProxy(app, parseTrustProxyEnv(process.env.TRUST_PROXY)); + // Browser analytics on Paperclip Cloud only. Mounted before every body + // parser so PostHog payloads stream through unread; see routes/posthog-proxy.ts. + const posthogProxy = resolvePostHogProxyMount(process.env); + if (posthogProxy) app.use(posthogProxy.path, posthogProxy.router); app.use( COMPANY_IMPORT_API_PATH, diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index 602287aa1d5..0da917b6bcf 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -13,6 +13,7 @@ import { resolveSentryDsns } from "../sentry-dsn.js"; import { resolveBrowserTracingConfig, warnOnce } from "../browser-tracing-config.js"; import { logger } from "../middleware/logger.js"; import { loadBoardBootstrap } from "../services/board-bootstrap.js"; +import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js"; async function loadCurrentUserProfile(db: Db, userId: string) { const user = await db @@ -73,6 +74,9 @@ export function authRoutes(db: Db) { // Hosted Paperclip Cloud only; null everywhere else. The ingest key is // ingest-only by construction โ€” see `server/src/browser-tracing-config.ts`. browserTracing: resolveBrowserTracingConfig(process.env, warnBrowserTracing), + // Hosted Paperclip Cloud with PAPERCLIP_POSTHOG_BROWSER_ENABLED=1 only; + // null everywhere else. See `server/src/services/cloud-posthog-browser.ts`. + browserAnalytics: resolveBrowserAnalyticsConfig(process.env), }); res.json({ ...session, ...(boardBootstrap ? { boardBootstrap } : {}) }); }); diff --git a/server/src/routes/posthog-proxy.ts b/server/src/routes/posthog-proxy.ts new file mode 100644 index 00000000000..f1964ffbf91 --- /dev/null +++ b/server/src/routes/posthog-proxy.ts @@ -0,0 +1,238 @@ +// Same-origin reverse proxy for browser PostHog traffic on Paperclip Cloud. +// +// Ad blockers drop requests to PostHog's own hosts, so the board UI sends to +// `/_ph` on its own origin and this proxy forwards them. +// +// It is not a generic proxy. It forwards only the requests posthog-js makes: +// the method and path must match `POSTHOG_PROXY_ROUTES`, and the upstream is +// always the configured ingest host or its static assets host. Everything +// else answers 404 without contacting PostHog. +// +// `app.ts` mounts it only when browser analytics is on (see +// `services/cloud-posthog-browser.ts`), before any body parser, so request and +// response bodies stream through without buffering. It carries no Paperclip +// data and grants nothing: it builds a fresh header set from an allowlist, so +// the browser's Host, Cookie and Authorization headers never leave. + +import http from "node:http"; +import https from "node:https"; +import { pipeline, Transform } from "node:stream"; +import type { IncomingHttpHeaders, OutgoingHttpHeaders } from "node:http"; +import { Router, type Request, type Response } from "express"; +import { logger } from "../middleware/logger.js"; +import type { CloudInstanceEnv } from "../services/cloud-instance.js"; +import { + POSTHOG_PROXY_PATH, + posthogAssetsOrigin, + resolveBrowserPostHogConfig, +} from "../services/cloud-posthog-browser.js"; + +const UPSTREAM_TIMEOUT_MS = 30_000; + +export type PostHogProxyLimits = { + /** Largest request body forwarded (PostHog's own proxy guide uses 64 MiB). */ + maxBodyBytes: number; + /** Requests in flight from one client address. */ + maxInFlightPerClient: number; + /** Requests in flight for the whole proxy. */ + maxInFlight: number; +}; + +export const DEFAULT_POSTHOG_PROXY_LIMITS: PostHogProxyLimits = { + maxBodyBytes: 64 * 1024 * 1024, + maxInFlightPerClient: 16, + maxInFlight: 256, +}; + +const BODY_TOO_LARGE = "posthog_proxy_body_too_large"; + +type PostHogUpstream = "ingest" | "assets"; + +/** + * Every request posthog-js makes with surveys, product tours, web experiments + * and conversations turned off (see `ui/src/lib/analytics/product-analytics.ts`). + */ +const POSTHOG_PROXY_ROUTES: ReadonlyArray<{ method: "GET" | "POST"; path: RegExp; upstream: PostHogUpstream }> = [ + // Event batches, including the newer `/i/v0/e/` endpoint. + { method: "POST", path: /^\/(?:i\/v0\/)?e\/?$/, upstream: "ingest" }, + { method: "POST", path: /^\/batch\/?$/, upstream: "ingest" }, + // Session replay snapshots. + { method: "POST", path: /^\/s\/?$/, upstream: "ingest" }, + // Remote settings (they carry the project's replay and autocapture switches). + { method: "POST", path: /^\/(?:flags|decide)\/?$/, upstream: "ingest" }, + // Project config and lazily loaded extensions (recorder, web vitals, ...). + { method: "GET", path: /^\/array\/[A-Za-z0-9_-]+\/config(?:\.js)?$/, upstream: "assets" }, + // posthog-js first asks for a versioned path (`/static/1.442.1/x.js`). + { method: "GET", path: /^\/static\/(?:\d+\.\d+\.\d+\/)?[A-Za-z0-9_-][A-Za-z0-9._-]*\.js$/, upstream: "assets" }, +]; + +/** Request headers PostHog needs. Host, cookies, auth and tracing headers never leave. */ +const FORWARDED_REQUEST_HEADERS = [ + "accept", + "accept-encoding", + "accept-language", + "content-encoding", + "content-length", + "content-type", + "user-agent", +] as const; + +/** Response headers that describe the connection or set state on our origin. */ +const DROPPED_RESPONSE_HEADERS = new Set([ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-connection", + "set-cookie", + "strict-transport-security", + "transfer-encoding", + "upgrade", +]); + +/** + * The upstream URL for an allowed request, or null. `requestUrl` is the path + * and query below the proxy mount. + */ +export function posthogUpstreamUrl(ingestHost: string, method: string, requestUrl: string): URL | null { + const queryAt = requestUrl.indexOf("?"); + const path = queryAt === -1 ? requestUrl : requestUrl.slice(0, queryAt); + const query = queryAt === -1 ? "" : requestUrl.slice(queryAt); + const route = POSTHOG_PROXY_ROUTES.find((candidate) => candidate.method === method && candidate.path.test(path)); + if (!route) return null; + const origin = route.upstream === "assets" ? posthogAssetsOrigin(ingestHost) : new URL(ingestHost).origin; + // The path matched a fixed pattern, so it cannot name another host. + return new URL(`${origin}${path}${query}`); +} + +export function posthogForwardRequestHeaders( + headers: IncomingHttpHeaders, + clientIp: string | undefined, + upstreamHost: string, +): OutgoingHttpHeaders { + const forwarded: OutgoingHttpHeaders = { host: upstreamHost }; + for (const name of FORWARDED_REQUEST_HEADERS) { + const value = headers[name]; + if (value !== undefined) forwarded[name] = value; + } + // PostHog derives the visitor's location from this header behind a proxy. + if (clientIp) forwarded["x-forwarded-for"] = clientIp; + return forwarded; +} + +export function posthogProxyRoutes(ingestHost: string, limits: PostHogProxyLimits = DEFAULT_POSTHOG_PROXY_LIMITS) { + const router = Router(); + let inFlight = 0; + const inFlightByClient = new Map(); + + router.use((req: Request, res: Response) => { + let upstream: URL | null; + try { + upstream = posthogUpstreamUrl(ingestHost, req.method, req.url); + } catch { + upstream = null; + } + if (!upstream) { + res.status(404).json({ error: "not_found" }); + return; + } + const target = upstream; + let received = 0; + let bodyTooLarge = false; + + const declaredLength = Number(req.headers["content-length"] ?? 0); + if (Number.isFinite(declaredLength) && declaredLength > limits.maxBodyBytes) { + res.status(413).json({ error: "payload_too_large" }); + return; + } + + // Bound the work one browser, or all of them, can put on this process. + const client = req.ip ?? "unknown"; + const clientInFlight = inFlightByClient.get(client) ?? 0; + if (inFlight >= limits.maxInFlight || clientInFlight >= limits.maxInFlightPerClient) { + res.setHeader("Retry-After", "1"); + res.status(429).json({ error: "too_many_requests" }); + return; + } + inFlight += 1; + inFlightByClient.set(client, clientInFlight + 1); + res.once("close", () => { + inFlight -= 1; + const remaining = (inFlightByClient.get(client) ?? 1) - 1; + if (remaining > 0) inFlightByClient.set(client, remaining); + else inFlightByClient.delete(client); + }); + + const transport = target.protocol === "https:" ? https : http; + const upstreamReq = transport.request(target, { + method: req.method, + headers: posthogForwardRequestHeaders(req.headers, req.ip, target.host), + timeout: UPSTREAM_TIMEOUT_MS, + }); + + upstreamReq.on("response", (upstreamRes) => { + const headers: OutgoingHttpHeaders = {}; + for (const [name, value] of Object.entries(upstreamRes.headers)) { + if (value !== undefined && !DROPPED_RESPONSE_HEADERS.has(name)) headers[name] = value; + } + res.writeHead(upstreamRes.statusCode ?? 502, headers); + // pipeline() handles an error on either side (PostHog closing the + // connection mid-response, the browser going away) by destroying both + // streams, so no stream error goes unhandled. + pipeline(upstreamRes, res, (err) => { + if (err) logger.debug({ err, path: target.pathname }, "PostHog proxy response ended early"); + }); + }); + upstreamReq.on("timeout", () => { + upstreamReq.destroy(new Error("posthog_proxy_timeout")); + }); + upstreamReq.on("error", (err) => { + logger.debug({ err, path: target.pathname }, "PostHog proxy request failed"); + if (!res.headersSent && bodyTooLarge) { + res.status(413).json({ error: "payload_too_large" }); + } else if (!res.headersSent) { + res.status(502).json({ error: "analytics_upstream_unavailable" }); + } else { + res.destroy(); + } + }); + // The browser went away: stop the upstream request too. + res.on("close", () => { + if (!res.writableFinished) upstreamReq.destroy(); + }); + + // A body without (or with a false) Content-Length is counted as it + // streams and cut off at the limit. + const sizeLimit = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + received += chunk.length; + if (received > limits.maxBodyBytes) { + bodyTooLarge = true; + callback(new Error(BODY_TOO_LARGE)); + } else { + callback(null, chunk); + } + }, + }); + // An aborted or oversized browser upload destroys the upstream request, + // whose error listener above answers or closes the browser response. + pipeline(req, sizeLimit, upstreamReq, () => {}); + }); + + return router; +} + +/** + * The proxy mount for this instance, or null when browser analytics is off. + * Self-hosted installs always get null, so `/_ph` falls through to the UI. + */ +export function resolvePostHogProxyMount(env: CloudInstanceEnv = process.env) { + const config = resolveBrowserPostHogConfig(env); + if (!config) return null; + try { + posthogAssetsOrigin(config.host); + } catch { + logger.warn("PAPERCLIP_POSTHOG_HOST is not a valid URL; the PostHog proxy is off"); + return null; + } + return { path: POSTHOG_PROXY_PATH, router: posthogProxyRoutes(config.host) }; +} diff --git a/server/src/services/cloud-posthog-browser.ts b/server/src/services/cloud-posthog-browser.ts new file mode 100644 index 00000000000..a0331033f1b --- /dev/null +++ b/server/src/services/cloud-posthog-browser.ts @@ -0,0 +1,65 @@ +// Browser product analytics (PostHog) for hosted Paperclip Cloud instances. +// +// The signed-in session hands the board UI a `browserAnalytics` config only +// when `resolveCloudPostHogConfig` returns a config (cloud managed, project +// token and stack ID set) and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. Every +// other instance gets `null`, so self-hosted installs, local development and +// tests never download posthog-js and never mount the PostHog proxy. +// +// The browser sends to `POSTHOG_PROXY_PATH` on its own origin, not to PostHog, +// so ad blockers do not drop the events. See `routes/posthog-proxy.ts`. + +import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; +import { isCloudStagingInstance, type CloudInstanceEnv } from "./cloud-instance.js"; +import { resolveCloudPostHogConfig, type CloudPostHogConfig } from "./cloud-posthog-config.js"; + +/** Same-origin path that the PostHog reverse proxy serves. */ +export const POSTHOG_PROXY_PATH = "/_ph"; + +const POSTHOG_CLOUD_INGEST_HOST = /^(us|eu)\.i\.posthog\.com$/i; + +/** The browser analytics part of the Cloud PostHog config, or null when it is off. */ +export function resolveBrowserPostHogConfig(env: CloudInstanceEnv = process.env): CloudPostHogConfig | null { + const config = resolveCloudPostHogConfig(env); + return config?.browserEnabled ? config : null; +} + +/** + * PostHog serves its static scripts (`/static/*`, `/array/*`) from a separate + * assets host. A self-run or test host serves both from one origin. + */ +export function posthogAssetsOrigin(ingestHost: string): string { + const url = new URL(ingestHost); + const match = POSTHOG_CLOUD_INGEST_HOST.exec(url.hostname); + if (match) url.hostname = `${match[1]!.toLowerCase()}-assets.i.posthog.com`; + return url.origin; +} + +/** The PostHog app host (for toolbar and replay links), or null for a non-PostHog host. */ +export function posthogUiHost(ingestHost: string): string | null { + const url = new URL(ingestHost); + const match = POSTHOG_CLOUD_INGEST_HOST.exec(url.hostname); + return match ? `https://${match[1]!.toLowerCase()}.posthog.com` : null; +} + +export function resolveBrowserAnalyticsConfig(env: CloudInstanceEnv = process.env): BrowserAnalyticsConfig | null { + const config = resolveBrowserPostHogConfig(env); + if (!config) return null; + let uiHost: string | null; + try { + uiHost = posthogUiHost(config.host); + } catch { + // An invalid host cannot be proxied either; keep browser analytics off. + return null; + } + return { + token: config.token, + apiHost: POSTHOG_PROXY_PATH, + uiHost, + // Every browser event carries an environment. Without the explicit + // variable, a staging host name means staging; anything else production. + environment: config.environment ?? (isCloudStagingInstance(env) ? "staging" : "production"), + stackId: config.stackId, + replayEnabled: config.replayEnabled, + }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c1d8b7c91ec..dfa279c54b1 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "e17ff48b5807bf070dcacec86c2edcab48b341f9", + "packages/shared/src/index.ts": "793b9067f01fd57e8e33e4abea87f828d90d861a", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -444,7 +444,7 @@ "packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739", "packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d", "packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1", - "packages/shared/src/validators/access.ts": "eb1c2ab3cc6616477f6cf68d2745a1d1de16640e", + "packages/shared/src/validators/access.ts": "110a49f427a9deb194b51d671c6007120c2af0a6", "packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81", "packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893", "packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545", @@ -487,7 +487,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "b0bc5449eb5c21fc89064d9d5243223ab33cf5e0", + "packages/shared/src/validators/index.ts": "c8cbf1aea7577e7f7a07b4ca733dabb9b23b0458", "packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903", "packages/shared/src/validators/instance.ts": "d801db219659707f0c9a8c1fbad06e862be4892d", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", diff --git a/ui/src/components/AppsSidebar.production.tsx b/ui/src/components/AppsSidebar.production.tsx index bf50e5d4b2c..cc5153b7f85 100644 --- a/ui/src/components/AppsSidebar.production.tsx +++ b/ui/src/components/AppsSidebar.production.tsx @@ -66,8 +66,8 @@ export function AppsSidebar() { Connectors
- - +
- + {developerTabs.map((tab) => (
- - + +

Timeline ({timeline.length + queuedComments.length})

- + {showPage("instance.profile") && ( - )} {showPage("company.members") && ( - ))} {showPage("company.invites") && ( - + )} {showPage("company.secrets") && ( - + )} {showPage("instance.environments") && ( - )} - + {showPage("instance.access") && ( - )} {showPage("instance.heartbeats") && ( - )} {showPage("company.export") && ( - + )} {!isCloud && showPage("company.import") && ( - + )} {showPage("instance.experimental") && ( - )} {showPlugins && ( - ) : null} {showPage("instance.adapters") && ( -
- +