feat(cloud): browser product analytics through a same-origin PostHog proxy (#22012)

## 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/<token>/config(.js)` and `GET
/static/[<version>/]<name>.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/<token>`
and `/invite/<token>` 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: <stack id> }`
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 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-17 11:23:03 -06:00
1 parent c366a606b1
commit 8172d27089
52 files changed
+2109 -114

No files matched your search

+122
View File
@@ -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/<token>/config`, `/array/<token>/config.js` | assets host |
| `GET` | `/static/<name>.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/<token>` and `/invite/<token>` 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.
+3
View File
@@ -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
+2
View File
@@ -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,
+24
View File
@@ -216,6 +216,27 @@ export const browserTracingConfigSchema = z.object({
export type BrowserTracingConfig = z.infer<typeof browserTracingConfigSchema>;
/**
* 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<typeof browserAnalyticsConfigSchema>;
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<typeof authSessionSchema>;
+2
View File
@@ -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,
+35
View File
@@ -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,
});
});
@@ -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(/<SidebarNavItem to="\/search" label="Search"/);
expect(read("ui/src/components/Sidebar.tsx")).toMatch(/<SidebarNavItem\b[^>]*\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);
});
@@ -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<string, string>, 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<void>((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<void>((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<void>((resolve) => server.once("listening", () => resolve()));
const port = (server.address() as AddressInfo).port;
try {
const status = await new Promise<number | string>((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<void>((resolve) => server.close(() => resolve()));
}
});
it("limits requests in flight from one client", async () => {
let release: () => void = () => {};
const held = new Promise<void>((resolve) => { release = resolve; });
const slow = http.createServer(async (_req, res) => { await held; res.end("ok"); });
await new Promise<void>((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<void>((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<void>((resolve) => server.close(() => resolve()));
await new Promise<void>((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<void>((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<void>((resolve) => server.once("listening", () => resolve()));
const port = (server.address() as AddressInfo).port;
const outcome = await new Promise<string>((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<void>((resolve) => server.close(() => resolve()));
} finally {
process.off("uncaughtException", onUncaught);
await new Promise<void>((resolve) => broken.close(() => resolve()));
}
expect(errors).toEqual([]);
});
});
+5
View File
@@ -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,
+4
View File
@@ -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 } : {}) });
});
+238
View File
@@ -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<string, number>();
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) };
}
@@ -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,
};
}
@@ -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",
+3 -3
View File
@@ -66,8 +66,8 @@ export function AppsSidebar() {
Connectors
</div>
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/apps" label="Browse" icon={Store} end />
<SidebarNavItem
<SidebarNavItem analyticsChrome to="/apps" label="Browse" icon={Store} end />
<SidebarNavItem analyticsChrome
to="/apps/review"
label="Review"
icon={ShieldQuestion}
@@ -83,7 +83,7 @@ export function AppsSidebar() {
Advanced setup for developers. Most teams never open this.
</p>
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/apps/connections" label="Connections" icon={AppWindow} end />
<SidebarNavItem analyticsChrome to="/apps/connections" label="Connections" icon={AppWindow} end />
{developerTabs.map((tab) => (
<SidebarNavItem
key={tab.key}
+2 -2
View File
@@ -38,8 +38,8 @@ export function AppsSidebar() {
className={contextualSidebarStyles.nav}
>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
<SidebarNavItem to="/apps" label="Browse" icon={Store} end />
<SidebarNavItem
<SidebarNavItem analyticsChrome to="/apps" label="Browse" icon={Store} end />
<SidebarNavItem analyticsChrome
to="/apps/review"
label="Review"
icon={ShieldQuestion}
+2 -1
View File
@@ -1,4 +1,5 @@
import { AgentIdentity } from "./AgentIdentity";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { AgentAvatar } from "@/components/AgentAvatar";
import { memo, useEffect, useMemo, useRef, useState, type ChangeEvent } from "react";
import { Link, useLocation } from "react-router-dom";
@@ -961,7 +962,7 @@ export function CommentThread({
const canSubmit = !submitting && !!body.trim();
return (
<div className="space-y-4">
<div className={cn("space-y-4", ANALYTICS_MASK_CLASS)}>
<h3 className="text-sm font-semibold">Timeline ({timeline.length + queuedComments.length})</h3>
<TimelineList
@@ -100,9 +100,9 @@ export function CompanySettingsSidebar() {
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />
<SidebarNavItem analyticsChrome to="/company/settings" label="General" icon={SlidersHorizontal} end />
{showPage("instance.profile") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`}
label="Profile"
icon={UserRoundPen}
@@ -110,7 +110,7 @@ export function CompanySettingsSidebar() {
/>
)}
{showPage("company.members") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/company/settings/members"
label="Members"
icon={Users}
@@ -130,22 +130,22 @@ export function CompanySettingsSidebar() {
/>
))}
{showPage("company.invites") && (
<SidebarNavItem to="/company/settings/invites" label="Invites" icon={MailPlus} end />
<SidebarNavItem analyticsChrome to="/company/settings/invites" label="Invites" icon={MailPlus} end />
)}
{showPage("company.secrets") && (
<SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />
<SidebarNavItem analyticsChrome to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />
)}
{showPage("instance.environments") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`}
label="Environments"
icon={MonitorCog}
end
/>
)}
<SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end />
<SidebarNavItem analyticsChrome to="/company/settings/connections" label="Connections" icon={Link2} end />
{showPage("instance.access") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
label="Access"
icon={Shield}
@@ -153,7 +153,7 @@ export function CompanySettingsSidebar() {
/>
)}
{showPage("instance.heartbeats") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/heartbeats`}
label="Heartbeats"
icon={Clock3}
@@ -161,20 +161,20 @@ export function CompanySettingsSidebar() {
/>
)}
{showPage("company.export") && (
<SidebarNavItem to="/company/export" label="Export" icon={Download} />
<SidebarNavItem analyticsChrome to="/company/export" label="Export" icon={Download} />
)}
{!isCloud && showPage("company.import") && (
<SidebarNavItem to="/company/import" label="Import" icon={Upload} end />
<SidebarNavItem analyticsChrome to="/company/import" label="Import" icon={Upload} end />
)}
{showPage("instance.experimental") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`}
label="Experimental"
icon={FlaskConical}
/>
)}
{showPlugins && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`}
label="Plugins"
icon={Puzzle}
@@ -202,7 +202,7 @@ export function CompanySettingsSidebar() {
</div>
) : null}
{showPage("instance.adapters") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`}
label="Adapters"
icon={Cpu}
+13 -13
View File
@@ -93,7 +93,7 @@ export function CompanySettingsSidebar() {
className="flex h-(--sz-60px) shrink-0 items-center px-3"
>
<div data-slot="settings-back-group" className={`${primarySidebarStyles.group} w-full`}>
<SidebarNavItem to="/dashboard" label="Back to app" icon={ArrowLeft} />
<SidebarNavItem analyticsChrome to="/dashboard" label="Back to app" icon={ArrowLeft} />
</div>
</div>
<nav
@@ -102,9 +102,9 @@ export function CompanySettingsSidebar() {
className={primarySidebarStyles.nav}
>
<div data-slot="contextual-sidebar-group" className={primarySidebarStyles.group}>
<SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />
<SidebarNavItem analyticsChrome to="/company/settings" label="General" icon={SlidersHorizontal} end />
{showPage("instance.profile") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`}
label="Profile"
icon={UserRoundPen}
@@ -112,7 +112,7 @@ export function CompanySettingsSidebar() {
/>
)}
{showPage("company.members") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/company/settings/members"
label="Members"
icon={Users}
@@ -132,19 +132,19 @@ export function CompanySettingsSidebar() {
/>
))}
{showPage("company.secrets") && (
<SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />
<SidebarNavItem analyticsChrome to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />
)}
{showPage("instance.environments") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`}
label="Environments"
icon={MonitorCog}
end
/>
)}
<SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end />
<SidebarNavItem analyticsChrome to="/company/settings/connections" label="Connections" icon={Link2} end />
{showPage("instance.access") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
label="Access"
icon={Shield}
@@ -152,20 +152,20 @@ export function CompanySettingsSidebar() {
/>
)}
{showPage("company.export") && (
<SidebarNavItem to="/company/export" label="Export" icon={Download} />
<SidebarNavItem analyticsChrome to="/company/export" label="Export" icon={Download} />
)}
{!isCloud && showPage("company.import") && (
<SidebarNavItem to="/company/import" label="Import" icon={Upload} end />
<SidebarNavItem analyticsChrome to="/company/import" label="Import" icon={Upload} end />
)}
{showPage("instance.experimental") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`}
label="Experimental"
icon={FlaskConical}
/>
)}
{showPlugins && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`}
label="Plugins"
icon={Puzzle}
@@ -193,7 +193,7 @@ export function CompanySettingsSidebar() {
</div>
) : null}
{showPage("instance.adapters") && (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`}
label="Adapters"
icon={Cpu}
+3 -3
View File
@@ -167,13 +167,13 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
<div className="design-sidebar-primary">
{rail ? <Tooltip><TooltipTrigger asChild>{newTaskButton}</TooltipTrigger><TooltipContent side="right">New task</TooltipContent></Tooltip> : newTaskButton}
<div className="design-sidebar-primary my-2">
<SidebarNavItem className="design-sidebar-item" to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" />
<div className="group/coordinator-new relative">
<SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} className={cn("design-sidebar-item", !rail && "pr-9")} />
<SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleCheck} className={cn("design-sidebar-item", !rail && "pr-9")} />
{!rail && <button type="button" aria-label="New task" title="New task" onClick={() => openNewIssue()}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover/coordinator-new:opacity-100 group-focus-within/coordinator-new:opacity-100 pointer-coarse:opacity-100 hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"><Plus className="size-4" /></button>}
</div>
<SidebarNavItem className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" />
{orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} rail={rail} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />}
</div>
<Flyout open={moreOpen} onOpenChange={setMoreOpen}>
+10 -10
View File
@@ -30,20 +30,20 @@ export function DesignSidebar({ onNewTask, recentTasks = [] }: { onNewTask: () =
<nav className="design-sidebar-navigation" aria-label="Main navigation">
<div className="design-sidebar-primary">
<Button variant="ghost" className="design-sidebar-new-task" onClick={onNewTask}><CirclePlus aria-hidden />New Task</Button>
<SidebarNavItem className="design-sidebar-item" to={`${root}/dashboard`} label="Dashboard" icon={LayoutDashboard} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/chats`} label="Chat" icon={MessageCircle} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/dashboard`} label="Dashboard" icon={LayoutDashboard} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/chats`} label="Chat" icon={MessageCircle} />
</div>
<SidebarSection label="Work">
<SidebarNavItem className="design-sidebar-item" to={`${root}/issues`} label="Tasks" icon={CircleCheck} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/projects`} label="Projects" icon={FolderOpen} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/routines`} label="Routines" icon={Repeat} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/artifacts`} label="Artifacts" icon={Package} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/issues`} label="Tasks" icon={CircleCheck} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/projects`} label="Projects" icon={FolderOpen} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/routines`} label="Routines" icon={Repeat} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/artifacts`} label="Artifacts" icon={Package} />
</SidebarSection>
<SidebarSection label="Org">
<SidebarNavItem className="design-sidebar-item" to={`${root}/agents`} label="Agents" icon={Users} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/skills`} label="Skills" icon={Boxes} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/apps`} label="Connectors" icon={Unplug} />
<SidebarNavItem className="design-sidebar-item" to={`${root}/activity`} label="Audit" icon={History} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/agents`} label="Agents" icon={Users} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/skills`} label="Skills" icon={Boxes} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/apps`} label="Connectors" icon={Unplug} />
<SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/activity`} label="Audit" icon={History} />
</SidebarSection>
{companyRecentTasks.length > 0 ? <div className="design-sidebar-recents">
<SidebarSection label="Recent Tasks">
+5 -1
View File
@@ -2,6 +2,7 @@ import { Plus } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy";
interface EmptyStateProps {
icon: LucideIcon;
@@ -16,6 +17,8 @@ interface EmptyStateProps {
onAction?: () => void;
/** Hide the leading "+" glyph on the action button (e.g. for a "Set up" CTA). */
hideActionIcon?: boolean;
/** The text is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean;
}
export function EmptyState({
@@ -27,9 +30,10 @@ export function EmptyState({
action,
onAction,
hideActionIcon = false,
analyticsChrome = false,
}: EmptyStateProps) {
return (
<div className={graphic ? "empty-state-artwork flex flex-col items-center justify-center gap-5 py-16 text-center" : "flex flex-col items-center justify-center py-16 text-center"}>
<div {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} className={graphic ? "empty-state-artwork flex flex-col items-center justify-center gap-5 py-16 text-center" : "flex flex-col items-center justify-center py-16 text-center"}>
{graphic ? <div className="empty-state-graphic" aria-hidden="true">{graphic}</div> : <div className="bg-muted/50 p-4 mb-4">
<Icon className="h-10 w-10 text-muted-foreground/50" />
</div>}
+3 -2
View File
@@ -40,6 +40,7 @@ import {
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { fileResourcesApi } from "@/api/file-resources";
import { ApiError } from "@/api/client";
import { queryViewKind } from "@/components/QueryView";
@@ -353,7 +354,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM
role="region"
aria-label={`${resource.title} source`}
tabIndex={0}
className="paperclip-file-viewer-code min-w-0 flex-1 overflow-auto bg-(--code-bg-resolved) focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
className={cn("paperclip-file-viewer-code min-w-0 flex-1 overflow-auto bg-(--code-bg-resolved) focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset", ANALYTICS_MASK_CLASS)}
>
<pre className="m-0 font-mono text-xs leading-5">
{lines.map((lineText, index) => {
@@ -405,7 +406,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM
}
return (
<div className="relative flex min-h-0 flex-1 flex-col">
<div className={cn("relative flex min-h-0 flex-1 flex-col", ANALYTICS_MASK_CLASS)}>
{previewMode === undefined && <div className="absolute right-3 top-3 z-20">
<div
role="group"
+2 -1
View File
@@ -1,4 +1,5 @@
import { createUuid } from "@/lib/uuid";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useCurrentAccountGuard } from "../hooks/useAccountBoundMutation";
import { resolveIssueChatHumanAuthor } from "@/lib/issue-chat-human-author";
import { useCurrentWorkspaceRetry, useWorkspaceBaseRefRecovery, useWorkspaceRetry } from "./WorkspaceBaseRefRecovery";
@@ -6709,7 +6710,7 @@ export function IssueChatThread({
return (
<AssistantRuntimeProvider runtime={runtime}>
<IssueChatCtx.Provider value={chatCtx}>
<div className={cn(variant === "embedded" ? "space-y-3" : "space-y-4")}>
<div className={cn(variant === "embedded" ? "space-y-3" : "space-y-4", ANALYTICS_MASK_CLASS)}>
{resolvedShowJumpToLatest ? (
<div className="flex justify-end">
<button
+3
View File
@@ -10,6 +10,7 @@ import { parseDocumentAnnotationHash } from "@/lib/document-annotation-hash";
import Markdown, { defaultUrlTransform, type Components, type Options } from "react-markdown";
import remarkGfm from "remark-gfm";
import { cn } from "../lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { MarkdownUrlLink } from "./MarkdownUrlLink";
import { recognizeLinkPreview, type LinkPreviewState } from "@paperclipai/shared";
import { Link, useCaseHref } from "@/lib/router";
@@ -1028,6 +1029,8 @@ function MarkdownBodyImpl({
className={cn(
"paperclip-markdown prose prose-sm min-w-0 max-w-full break-words overflow-hidden",
theme === "dark" && "prose-invert",
// Customer content: masked in session replay, skipped by autocapture.
ANALYTICS_MASK_CLASS,
className,
)}
style={mergeWrapStyle(style)}
+3
View File
@@ -63,6 +63,7 @@ import { unescapeEqualsSigns } from "../lib/equals-markdown";
import { preserveTrailingMarkdownSpaces, restoreTrailingMarkdownSpaces } from "../lib/trailing-markdown-spaces";
import { pasteNormalizationPlugin } from "../lib/paste-normalization";
import { cn } from "../lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useEditorAutocomplete, type SlashCommandOption } from "../context/EditorAutocompleteContext";
/* ---- Mention types ---- */
@@ -1432,6 +1433,8 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
{...(canDropFile && !readOnly ? { [FILE_DROP_TARGET_ATTRIBUTE]: "" } : {})}
className={cn(
"relative paperclip-mdxeditor-scope",
// Customer content: masked in session replay, skipped by autocapture.
ANALYTICS_MASK_CLASS,
bordered ? "rounded-md border border-border bg-transparent" : "bg-transparent",
isDragOver && "ring-1 ring-primary/60 bg-accent/20",
className,
@@ -0,0 +1,128 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics";
import { ProductAnalyticsGate } from "./ProductAnalyticsGate";
const getSessionMock = vi.hoisted(() => vi.fn());
const posthogMock = vi.hoisted(() => ({
init: vi.fn(),
register: vi.fn(),
identify: vi.fn(),
group: vi.fn(),
reset: vi.fn(),
}));
vi.mock("@/api/auth", () => ({
authApi: { getSession: () => getSessionMock() },
}));
/** PostHog script elements the module adds to the page. */
function injectedScripts() {
return [...document.querySelectorAll("script")].filter((script) => script.src.includes("/static/array.js"));
}
// jsdom does not fetch scripts: when the module adds PostHog's script, act as
// the browser would after it loads (the script sets `window.posthog`).
const appendChild = document.head.appendChild.bind(document.head);
vi.spyOn(document.head, "appendChild").mockImplementation(<T extends Node>(node: T): T => {
const result = appendChild(node);
if (node instanceof HTMLScriptElement && node.src.includes("/static/array.js")) {
(window as unknown as { posthog: typeof posthogMock }).posthog = posthogMock;
queueMicrotask(() => node.onload?.(new Event("load")));
}
return result;
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
const ACTOR_ID = "paperclip-id:uf2X8Ha4H9hNdAMnc1rOy91VIRos5pch";
const user = { id: ACTOR_ID, email: "jane@example.com", name: "Jane", image: null };
function session(browserAnalytics: unknown) {
return {
session: { id: `paperclip:session:${ACTOR_ID}`, userId: ACTOR_ID },
user,
sentryDsn: null,
browserAnalytics,
};
}
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
}
describe("ProductAnalyticsGate", () => {
let container: HTMLDivElement;
let queryClient: QueryClient;
beforeEach(() => {
vi.useFakeTimers();
container = document.createElement("div");
document.body.appendChild(container);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => {
vi.useRealTimers();
container.remove();
resetProductAnalyticsForTest();
for (const script of injectedScripts()) script.remove();
delete (window as unknown as { posthog?: unknown }).posthog;
vi.clearAllMocks();
});
async function renderGate() {
const root = createRoot(container);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<ProductAnalyticsGate />
</QueryClientProvider>,
);
});
await settle();
return root;
}
it("loads nothing and does nothing when the session has no analytics config (self-hosted)", async () => {
getSessionMock.mockResolvedValue(session(null));
const root = await renderGate();
expect(injectedScripts()).toHaveLength(0);
expect(posthogMock.init).not.toHaveBeenCalled();
act(() => root.unmount());
});
it("loads nothing when signed out", async () => {
getSessionMock.mockResolvedValue(null);
const root = await renderGate();
expect(injectedScripts()).toHaveLength(0);
act(() => root.unmount());
});
it("loads posthog-js and identifies the user when the session carries a config", async () => {
getSessionMock.mockResolvedValue(session({
token: "phc_test",
apiHost: "/_ph",
uiHost: null,
environment: "production",
stackId: "stack-1",
replayEnabled: false,
}));
const root = await renderGate();
// PostHog's script comes through the same-origin proxy, never from PostHog directly.
expect(injectedScripts().map((script) => new URL(script.src).pathname)).toEqual(["/_ph/static/array.js"]);
expect(posthogMock.init).toHaveBeenCalledWith("phc_test", expect.objectContaining({ disable_session_recording: true }));
// Same id, same format, as the server's actor id (its events' distinct_id).
expect(posthogMock.identify).toHaveBeenCalledWith(ACTOR_ID, { email: "jane@example.com", name: "Jane" });
expect(posthogMock.group).toHaveBeenCalledWith("workspace", "stack-1");
expect(posthogMock.register).toHaveBeenCalledWith({ deployment_source: "cloud", environment: "production" });
act(() => root.unmount());
});
});
@@ -0,0 +1,59 @@
import { useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { authApi } from "@/api/auth";
import { queryKeys } from "@/lib/queryKeys";
import { whenPageSettles } from "@/lib/when-page-settles";
import {
cancelPendingProductAnalytics,
PRODUCT_ANALYTICS_LOAD_DEADLINE_MS,
setProductAnalyticsUser,
startProductAnalytics,
} from "@/lib/analytics/product-analytics";
/**
* Browser product analytics for hosted Paperclip Cloud. Renders nothing.
*
* It reads the signed-in session, like `SentryGate` (same query, so no extra
* request). The server sends `browserAnalytics` only for a cloud-managed
* instance with PostHog browser analytics switched on, so self-hosted
* installs, local development and tests never load posthog-js. Sign-out
* clears the session, which resets the PostHog identity.
*/
export function ProductAnalyticsGate() {
const queryClient = useQueryClient();
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
const config = session?.browserAnalytics ?? null;
const configKey = config ? JSON.stringify(config) : null;
// The authenticated actor's user id, verbatim (for example
// "paperclip-id:..."): the server copies `req.actor.userId` into
// `session.userId`, and server events use that same id as `distinct_id`,
// so browser and server events land on one PostHog person.
const userId = session?.session.userId ?? null;
const email = session?.user.email ?? null;
const name = session?.user.name ?? null;
useEffect(() => {
if (!config) return;
startProductAnalytics(config, {
schedule: (start) => {
const cancelSettle = whenPageSettles(queryClient, start);
const deadline = window.setTimeout(start, PRODUCT_ANALYTICS_LOAD_DEADLINE_MS);
return () => {
cancelSettle();
window.clearTimeout(deadline);
};
},
});
return () => cancelPendingProductAnalytics();
// Keyed by value: the config object identity changes on every session refetch.
}, [configKey, queryClient]);
useEffect(() => {
setProductAnalyticsUser(userId ? { id: userId, email, name } : null);
}, [userId, email, name]);
return null;
}
@@ -104,12 +104,12 @@ export function RoutineContextualSidebar({
Operate
</p>
<div className="flex flex-col gap-0.5">
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={routineDetailHref(routineId, "runs")}
label="Runs"
icon={Play}
/>
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={routineDetailHref(routineId, "activity")}
label="Activity"
icon={Activity}
+21 -21
View File
@@ -149,9 +149,9 @@ export function Sidebar() {
width; a nav row also keeps search reachable from the
collapsed rail, where the old header icon was dropped entirely.
Cmd/Ctrl+K remains the keyboard path (command palette). */}
<SidebarNavItem to="/search" label="Search" icon={Search} />
<SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
<SidebarNavItem
<SidebarNavItem analyticsChrome to="/search" label="Search" icon={Search} />
<SidebarNavItem analyticsChrome to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
<SidebarNavItem analyticsChrome
to="/inbox"
label="Inbox"
icon={Inbox}
@@ -161,7 +161,7 @@ export function Sidebar() {
alert={inboxBadge.failedRuns > 0}
/>
{showDecisions ? (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/decisions"
label="Decisions"
icon={ListChecks}
@@ -170,21 +170,21 @@ export function Sidebar() {
/>
) : null}
{showStatusCards ? (
<SidebarNavItem to="/status" label="Status" icon={LayoutGrid} textBadge="beta" />
<SidebarNavItem analyticsChrome to="/status" label="Status" icon={LayoutGrid} textBadge="beta" />
) : null}
{conferenceRoomChatEnabled ? (
<SidebarNavItem to="/board-chat" label="Conference Room" icon={MessagesSquare} />
<SidebarNavItem analyticsChrome to="/board-chat" label="Conference Room" icon={MessagesSquare} />
) : null}
</div>
<SidebarSection label="Work" collapsible={{ open: workOpen, onOpenChange: setWorkOpen }}>
<SidebarNavItem to="/issues" label="Tasks" icon={CircleDot} />
<SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleDot} />
{showCases ? (
<SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" />
<SidebarNavItem analyticsChrome to="/cases" label="Cases" icon={Layers} textBadge="beta" />
) : null}
<SidebarNavItem to="/routines" label="Routines" icon={Repeat} />
<SidebarNavItem analyticsChrome to="/routines" label="Routines" icon={Repeat} />
{showGoalsLink ? (
<SidebarNavItem to="/goals" label="Goals" icon={Target} />
<SidebarNavItem analyticsChrome to="/goals" label="Goals" icon={Target} />
) : goalsLinkPending ? (
<div
data-testid="sidebar-goals-placeholder"
@@ -192,14 +192,14 @@ export function Sidebar() {
aria-hidden="true"
/>
) : null}
<SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} />
<SidebarNavItem to="/skills" label="Skills" icon={Boxes} />
<SidebarNavItem analyticsChrome to="/artifacts" label="Artifacts" icon={Package} />
<SidebarNavItem analyticsChrome to="/skills" label="Skills" icon={Boxes} />
{showWorkspacesLink ? (
<SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} />
<SidebarNavItem analyticsChrome to="/workspaces" label="Workspaces" icon={GitBranch} />
) : null}
{streamlined ? (
<>
<SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} />
<SidebarNavItem analyticsChrome to="/projects" label="Projects" icon={FolderOpen} />
<SidebarStarredProjects />
</>
) : null}
@@ -224,14 +224,14 @@ export function Sidebar() {
<SidebarAgents streamlined={streamlined} />
<SidebarSection label="Company" collapsible={{ open: companyOpen, onOpenChange: setCompanyOpen }}>
<SidebarNavItem to="/org" label="Org" icon={Network} />
{showApps ? <SidebarNavItem to="/apps" label="Connectors" icon={Unplug} /> : null}
<SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} />
<SidebarNavItem to="/costs" label="Costs" icon={DollarSign} />
<SidebarNavItem analyticsChrome to="/org" label="Org" icon={Network} />
{showApps ? <SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} /> : null}
<SidebarNavItem analyticsChrome to="/timeline" label="Timeline" icon={GanttChartSquare} />
<SidebarNavItem analyticsChrome to="/costs" label="Costs" icon={DollarSign} />
{/* One entry — /audit merged into the rich Activity feed (PAP-16302). */}
<SidebarNavItem to="/activity" label="Activity" icon={History} />
<SidebarNavItem to="/activity/commentary" label="Commentary" icon={History} />
<SidebarNavItem to="/company/settings" label="Settings" icon={Settings} />
<SidebarNavItem analyticsChrome to="/activity" label="Activity" icon={History} />
<SidebarNavItem analyticsChrome to="/activity/commentary" label="Commentary" icon={History} />
<SidebarNavItem analyticsChrome to="/company/settings" label="Settings" icon={Settings} />
</SidebarSection>
<PluginSlotOutlet
+27 -27
View File
@@ -176,10 +176,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
width; a nav row also keeps search reachable from the
collapsed rail, where the old header icon was dropped entirely.
Cmd/Ctrl+K remains the keyboard path (command palette). */}
<SidebarNavItem to="/search" label="Search" icon={Search} />
<SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
<SidebarNavItem analyticsChrome to="/search" label="Search" icon={Search} />
<SidebarNavItem analyticsChrome to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} />
{!combinedInboxTasks ? (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/inbox"
label="Inbox"
icon={Inbox}
@@ -189,9 +189,9 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
alert={inboxBadge.failedRuns > 0}
/>
) : null}
{agentChatEnabled && !chatRail ? <SidebarNavItem to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> : null}
{agentChatEnabled && !chatRail ? <SidebarNavItem analyticsChrome to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> : null}
{showDecisions ? (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/decisions"
label="Decisions"
icon={ListChecks}
@@ -200,10 +200,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
/>
) : null}
{showStatusCards ? (
<SidebarNavItem to="/status" label="Status" icon={LayoutGrid} textBadge="beta" />
<SidebarNavItem analyticsChrome to="/status" label="Status" icon={LayoutGrid} textBadge="beta" />
) : null}
{conferenceRoomChatEnabled ? (
<SidebarNavItem to="/board-chat" label="Conference Room" icon={MessagesSquare} />
<SidebarNavItem analyticsChrome to="/board-chat" label="Conference Room" icon={MessagesSquare} />
) : null}
</div>
@@ -212,12 +212,12 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
agents you talk to live in the Chat surface's own secondary rail
(ChatContextualSidebar), not in the primary nav. */}
{chatRail ? (
<SidebarNavItem to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" />
<SidebarNavItem analyticsChrome to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" />
) : null}
{/* Combined Inbox + Task List: Inbox is a view inside Tasks, so the
unread/failed-run badge rides on Tasks. */}
{combinedInboxTasks ? (
<SidebarNavItem
<SidebarNavItem analyticsChrome
to="/issues"
label="Tasks"
icon={CircleCheck}
@@ -227,21 +227,21 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
alert={inboxBadge.failedRuns > 0}
/>
) : (
<SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} />
<SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleCheck} />
)}
{streamlinedUiEnabled ? (
<>
<SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} />
<SidebarNavItem analyticsChrome to="/projects" label="Projects" icon={FolderOpen} />
<SidebarStarredProjects />
</>
) : null}
<SidebarNavItem to="/routines" label="Routines" icon={Repeat} />
<SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} />
<SidebarNavItem analyticsChrome to="/routines" label="Routines" icon={Repeat} />
<SidebarNavItem analyticsChrome to="/artifacts" label="Artifacts" icon={Package} />
{showCases ? (
<SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" />
<SidebarNavItem analyticsChrome to="/cases" label="Cases" icon={Layers} textBadge="beta" />
) : null}
{showGoalsLink ? (
<SidebarNavItem to="/goals" label="Goals" icon={Target} />
<SidebarNavItem analyticsChrome to="/goals" label="Goals" icon={Target} />
) : goalsLinkPending ? (
<div
data-testid="sidebar-goals-placeholder"
@@ -250,7 +250,7 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
/>
) : null}
{showWorkspacesLink ? (
<SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} />
<SidebarNavItem analyticsChrome to="/workspaces" label="Workspaces" icon={GitBranch} />
) : null}
<PluginSlotOutlet
slotTypes={["sidebar"]}
@@ -272,10 +272,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
label="Org"
collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }}
>
<SidebarNavItem to="/agents" label="Agents" icon={Users} />
<SidebarNavItem to="/skills" label="Skills" icon={Boxes} />
<SidebarNavItem to="/apps" label="Connectors" icon={Unplug} />
<SidebarNavItem to="/activity" label="Audit" icon={History} />
<SidebarNavItem analyticsChrome to="/agents" label="Agents" icon={Users} />
<SidebarNavItem analyticsChrome to="/skills" label="Skills" icon={Boxes} />
<SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} />
<SidebarNavItem analyticsChrome to="/activity" label="Audit" icon={History} />
</SidebarSection>
) : null}
@@ -291,13 +291,13 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
label="Organization"
collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }}
>
<SidebarNavItem to="/org" label="Org" icon={Network} />
<SidebarNavItem to="/apps" label="Connectors" icon={Unplug} />
<SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} />
<SidebarNavItem to="/costs" label="Costs" icon={DollarSign} />
<SidebarNavItem to="/activity" label="Activity" icon={History} />
<SidebarNavItem to="/activity/commentary" label="Commentary" icon={History} />
<SidebarNavItem to="/company/settings" label="Settings" icon={Settings} />
<SidebarNavItem analyticsChrome to="/org" label="Org" icon={Network} />
<SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} />
<SidebarNavItem analyticsChrome to="/timeline" label="Timeline" icon={GanttChartSquare} />
<SidebarNavItem analyticsChrome to="/costs" label="Costs" icon={DollarSign} />
<SidebarNavItem analyticsChrome to="/activity" label="Activity" icon={History} />
<SidebarNavItem analyticsChrome to="/activity/commentary" label="Commentary" icon={History} />
<SidebarNavItem analyticsChrome to="/company/settings" label="Settings" icon={Settings} />
</SidebarSection>
</>
)}
@@ -39,6 +39,7 @@ import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { useSignOut } from "@/hooks/useSignOut";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
@@ -271,7 +272,8 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange }: SidebarCompa
: `Open ${switcherNoun} switcher`
}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{/* Customer data: the organization name stays masked in session replay. */}
<span className={cn("flex min-w-0 flex-1 items-center gap-2", ANALYTICS_MASK_CLASS)}>
{selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}
{/* The header has room for ~110px of name beside the collapse
control (~142px on mobile, which hides it) — search moved to
+3 -1
View File
@@ -39,6 +39,7 @@ import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { useSignOut } from "@/hooks/useSignOut";
import { queryKeys } from "@/lib/queryKeys";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { CompanyPatternIcon } from "./CompanyPatternIcon";
import { TruncatedText } from "./TruncatedText";
@@ -275,7 +276,8 @@ function BuiltinCompanyMenu({ open: controlledOpen, onOpenChange, showChevron =
: `Open ${switcherNoun} switcher`
}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{/* Customer data: the organization name stays masked in session replay. */}
<span className={cn("flex min-w-0 flex-1 items-center gap-2", ANALYTICS_MASK_CLASS)}>
{selectedCompany ? <WorkspaceIcon company={selectedCompany} /> : null}
{/* The header has room for ~110px of name beside the collapse
control (~142px on mobile, which hides it) — search moved to
@@ -2,6 +2,7 @@ import { createContext, useContext, type ReactNode } from "react";
import { NavLink } from "@/lib/router";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { LucideIcon } from "lucide-react";
@@ -35,6 +36,8 @@ export function useSidebarNavExpanded() {
interface SidebarNavItemProps {
to: string;
label: string;
/** The label is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean;
icon?: LucideIcon;
/**
* Pre-rendered icon element for rows whose icon isn't a plain Lucide
@@ -72,6 +75,7 @@ interface SidebarNavItemProps {
export function SidebarNavItem({
to,
label,
analyticsChrome = false,
icon: Icon,
iconNode,
end,
@@ -119,6 +123,7 @@ export function SidebarNavItem({
to={to}
state={SIDEBAR_SCROLL_RESET_STATE}
end={end}
{...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})}
aria-label={railAriaLabel}
onClick={() => { if (isMobile) setSidebarOpen(false); }}
className={({ isActive }) =>
+5
View File
@@ -3,6 +3,7 @@ import { NavLink } from "@/lib/router";
import type { IssueNavigationPrefetchHandlers } from "@/hooks/useIssueNavigationPrefetch";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils";
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy";
import { useSidebar } from "../context/SidebarContext";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { LucideIcon } from "lucide-react";
@@ -35,6 +36,8 @@ export function useSidebarNavExpanded() {
interface SidebarNavItemProps {
to: string;
label: string;
/** The label is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean;
icon?: LucideIcon;
/**
* Pre-rendered icon element for rows whose icon isn't a plain Lucide
@@ -74,6 +77,7 @@ interface SidebarNavItemProps {
export function SidebarNavItem({
to,
label,
analyticsChrome = false,
icon: Icon,
iconNode,
end,
@@ -123,6 +127,7 @@ export function SidebarNavItem({
to={to}
state={SIDEBAR_SCROLL_RESET_STATE}
end={end}
{...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})}
aria-label={railAriaLabel}
{...linkHandlers}
onClick={() => { if (isMobile) setSidebarOpen(false); }}
@@ -36,21 +36,21 @@ export function SkillsContextualSidebar() {
className={contextualSidebarStyles.nav}
>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={SKILLS_NAVIGATION_HREFS.installed}
label="Installed"
icon={Library}
active={activeView === "installed"}
end
/>
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={SKILLS_NAVIGATION_HREFS.discover}
label="Discover"
icon={Compass}
active={activeView === "discover"}
end
/>
<SidebarNavItem to={SKILLS_NAVIGATION_HREFS.sources} label="Sources" icon={GithubIcon} active={activeView === "sources"} />
<SidebarNavItem analyticsChrome to={SKILLS_NAVIGATION_HREFS.sources} label="Sources" icon={GithubIcon} active={activeView === "sources"} />
</div>
<div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}>
@@ -67,7 +67,7 @@ export function SkillsContextualSidebar() {
Skills you create, edit, and test.
</p>
<div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}>
<SidebarNavItem
<SidebarNavItem analyticsChrome
to={SKILLS_NAVIGATION_HREFS.authored}
label="My Skills"
icon={PencilRuler}
+3
View File
@@ -133,6 +133,7 @@ import { useSidebar } from "@/context/SidebarContext";
import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
import { useDismissedTaskQuestions } from "@/hooks/useDismissedTaskQuestions";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { Button } from "@/components/ui/button";
import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";
import { isRedundantAiRecoveryNotice, latestSameRunHandoffTimestamp } from "@/lib/issue-chat-messages";
@@ -3382,6 +3383,8 @@ export function TaskChatThread(props: TaskChatThreadProps) {
<div
className={cn(
"relative flex min-h-0 flex-1 flex-col",
// Customer content: masked in session replay, skipped by autocapture.
ANALYTICS_MASK_CLASS,
isMobile && !historyRevealed && "task-chat-history-pending",
)}
data-testid="task-chat-thread"
@@ -2,6 +2,7 @@ import { useState } from "react";
import { Eye, EyeOff, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
import { PopoverTitle, PopoverDescription } from "@/components/ui/popover";
const SECRET_NAME_RE = /^[a-z][a-z0-9_]*$/;
@@ -108,7 +109,7 @@ export function SecretPopoverForm({
<span className="text-(length:--text-micro) font-medium text-muted-foreground">Value</span>
<div className="relative">
<input
className={cn(fieldClass, "pr-8", valueError && "border-destructive focus-visible:ring-destructive/40")}
className={cn(fieldClass, "pr-8", ANALYTICS_NO_CAPTURE_CLASS, valueError && "border-destructive focus-visible:ring-destructive/40")}
type={reveal ? "text" : "password"}
value={value}
readOnly={mode === "store"}
@@ -10,6 +10,7 @@ import {
} from "lucide-react";
import type { CompanySecret, UserSecretDefinition } from "@paperclipai/shared";
import { cn } from "@/lib/utils";
import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
import {
DropdownMenu,
DropdownMenuContent,
@@ -300,7 +301,7 @@ export function EnvironmentVariableRow({
<>
<input
ref={valueInputRef}
className={valueTextInputClass}
className={cn(valueTextInputClass, ANALYTICS_NO_CAPTURE_CLASS)}
placeholder="value"
value={row.textValue}
type={sensitive ? "password" : "text"}
+5
View File
@@ -3,6 +3,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-(--tp-color-background-color-border-color-box-shadow-opacity) disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3) aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
@@ -44,12 +45,15 @@ const Button = React.forwardRef<
React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
/** The label is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean
}
>(function Button({
className,
variant = "default",
size = "default",
asChild = false,
analyticsChrome = false,
...props
}, ref) {
const Comp = asChild ? Slot.Root : "button"
@@ -58,6 +62,7 @@ const Button = React.forwardRef<
<Comp
ref={ref}
data-slot="button"
{...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})}
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
+3
View File
@@ -1,6 +1,7 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
@@ -11,6 +12,8 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-(--tp-color-box-shadow) outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3)",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
// Password fields hold secrets: never recorded by product analytics.
type === "password" && ANALYTICS_NO_CAPTURE_CLASS,
className
)}
{...props}
+7 -1
View File
@@ -2,14 +2,20 @@ import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"
function Label({
className,
analyticsChrome = false,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
}: React.ComponentProps<typeof LabelPrimitive.Root> & {
/** The text is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean
}) {
return (
<LabelPrimitive.Root
data-slot="label"
{...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})}
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
+7 -1
View File
@@ -3,6 +3,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { Tabs as TabsPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"
function Tabs({
className,
@@ -56,11 +57,16 @@ function TabsList({
function TabsTrigger({
className,
analyticsChrome = false,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
}: React.ComponentProps<typeof TabsPrimitive.Trigger> & {
/** The text is fixed product copy, so session replay may show it. */
analyticsChrome?: boolean
}) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
{...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})}
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-(--sz-calc-27) flex-1 items-center justify-center gap-1.5 border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-(--tp-color-background-color-border-color-box-shadow) group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-(length:--rad-3) focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
+6
View File
@@ -12,9 +12,11 @@ import { QUERY_CACHE_PREFIX, startPersistedQueryCache } from "@/lib/persisted-qu
const mockAuthApi = vi.hoisted(() => ({ signOut: vi.fn() }));
const mockNavigateTopLevel = vi.hoisted(() => vi.fn());
const mockResetAnalytics = vi.hoisted(() => vi.fn());
vi.mock("@/api/auth", () => ({ authApi: mockAuthApi }));
vi.mock("@/lib/browserNavigation", () => ({ navigateTopLevel: mockNavigateTopLevel }));
vi.mock("@/lib/analytics/product-analytics", () => ({ resetProductAnalyticsIdentity: mockResetAnalytics }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
@@ -78,6 +80,10 @@ describe("useSignOut", () => {
try {
await act(async () => { await captured!.mutateAsync(); });
expect(onSignedOut).toHaveBeenCalledOnce();
expect(mockResetAnalytics).toHaveBeenCalledOnce();
if (deploymentMode === "cloud") {
expect(mockResetAnalytics.mock.invocationCallOrder[0]).toBeLessThan(mockNavigateTopLevel.mock.invocationCallOrder[0]!);
}
expect(account.isCurrentScope()).toBe(false);
expect(Object.keys(localStorage).filter(key => key.startsWith(QUERY_CACHE_PREFIX))).toEqual([]);
expect(localStorage.getItem("paperclip:private-draft")).toBe("Keep my draft");
+4
View File
@@ -4,6 +4,7 @@ import { navigateTopLevel } from "@/lib/browserNavigation";
import { queryKeys } from "@/lib/queryKeys";
import { invalidateAccountScope } from "@/lib/account-scope";
import { clearPersistedQueryCache } from "@/lib/persisted-query-cache";
import { resetProductAnalyticsIdentity } from "@/lib/analytics/product-analytics";
import { useCloudInstance } from "./useCloudInstance";
const CLOUD_SIGN_OUT_PATH = "/cloud/logout";
@@ -48,6 +49,9 @@ export function useSignOut({ onSignedOut }: UseSignOutOptions = {}) {
return useMutation({
mutationFn: async () => {
// Before anything leaves the page: Cloud sign-out navigates away with the
// session query still populated, so the analytics identity must go now.
resetProductAnalyticsIdentity();
if (cloud) {
clearPersistedQueryCache(queryClient);
invalidateAccountScope(queryClient);
+117
View File
@@ -0,0 +1,117 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import {
ANALYTICS_MASK_CLASS,
ANALYTICS_NO_CAPTURE_CLASS,
ANALYTICS_UNMASK_ATTRIBUTE,
maskReplayAttribute,
maskReplayText,
redactAnalyticsUrl,
} from "./privacy";
function render(html: string) {
document.body.innerHTML = html;
return (id: string) => document.getElementById(id) as HTMLElement;
}
describe("session replay text masking", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("masks text on any surface that nobody marked", () => {
const el = render(`<main><p id="p">Quarterly revenue plan</p></main>`);
expect(maskReplayText("Quarterly revenue plan", el("p"))).toBe("********* ******* ****");
});
it("masks text when the element is unknown", () => {
expect(maskReplayText("hello", null)).toBe("*****");
expect(maskReplayText("hello")).toBe("*****");
});
it("shows text inside opted-in chrome", () => {
const el = render(`<button ${ANALYTICS_UNMASK_ATTRIBUTE}><span id="s">New task</span></button>`);
expect(maskReplayText("New task", el("s"))).toBe("New task");
});
it("keeps customer content masked even inside opted-in chrome", () => {
const el = render(
`<nav ${ANALYTICS_UNMASK_ATTRIBUTE}><div class="${ANALYTICS_MASK_CLASS}"><p id="c">Customer secret</p></div>`
+ `<div contenteditable="true"><p id="e">Draft</p></div>`
+ `<div class="${ANALYTICS_NO_CAPTURE_CLASS}"><span id="k">sk-123</span></div></nav>`,
);
expect(maskReplayText("Customer secret", el("c"))).toBe("******** ******");
expect(maskReplayText("Draft", el("e"))).toBe("*****");
expect(maskReplayText("sk-123", el("k"))).toBe("******");
});
});
describe("session replay attribute masking", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("masks free-text attributes that carry customer data, such as an organization switcher label", () => {
const el = render(
`<button ${ANALYTICS_UNMASK_ATTRIBUTE} id="b" aria-label="Open Verify Co organization switcher" title="Verify Co">`
+ `<span class="${ANALYTICS_MASK_CLASS}" id="n" title="Verify Co">Verify Co</span></button>`
+ `<span id="t" title="Customer task title">Customer task title</span>`
+ `<img id="i" src="/api/attachments/1" alt="Quarterly plan">`,
);
expect(maskReplayAttribute("aria-label", "Open Verify Co organization switcher", el("b")))
.toBe("**** ****** ** ************ ********");
expect(maskReplayAttribute("title", "Verify Co", el("b"))).toBe("****** **");
expect(maskReplayAttribute("title", "Verify Co", el("n"))).toBe("****** **");
expect(maskReplayAttribute("title", "Customer task title", el("t"))).toBe("******** **** *****");
expect(maskReplayAttribute("src", "/api/attachments/1", el("i"))).toBe("******************");
expect(maskReplayAttribute("alt", "Quarterly plan", el("i"))).toBe("********* ****");
expect(maskReplayAttribute("data-anything", "secret", el("t"))).toBe("******");
// Element references often embed names or slugs (for example a skill slug).
expect(maskReplayAttribute("id", "skill-acme-secret-plan", el("t"))).toBe("**********************");
expect(maskReplayAttribute("for", "skill-acme-secret-plan", el("t"))).toBe("**********************");
expect(maskReplayAttribute("aria-labelledby", "label-acme", el("t"))).toBe("**********");
// Fixed layout IDs that page CSS targets keep their value.
expect(maskReplayAttribute("id", "main-content", el("t"))).toBe("main-content");
});
it("keeps layout attributes and masks labels even on opted-in chrome", () => {
const el = render(`<button ${ANALYTICS_UNMASK_ATTRIBUTE} id="b" aria-label="New task" class="btn" data-state="open">New task</button>`);
expect(maskReplayAttribute("aria-label", "New task", el("b"))).toBe("*** ****");
expect(maskReplayAttribute("class", "btn", el("b"))).toBe("btn");
expect(maskReplayAttribute("data-state", "open", el("b"))).toBe("open");
expect(maskReplayAttribute("rr_width", "10px", el("b"))).toBe("10px");
});
it("masks every link href, such as a download link carrying a file path, and keeps stylesheets", () => {
const el = render(
`<a id="nav" href="/VER/issues">Tasks</a>`
+ `<a id="dl" href="/api/files/content?path=customers%2Fplan.md">Download</a>`
+ `<link id="css" rel="stylesheet" href="/assets/index.css">`,
);
expect(maskReplayAttribute("href", "/VER/issues", el("nav"))).toBe("***********");
expect(maskReplayAttribute("href", "/api/files/content?path=customers%2Fplan.md", el("dl"))).not.toContain("plan");
expect(maskReplayAttribute("href", "/assets/index.css", el("css"))).toBe("/assets/index.css");
});
});
describe("analytics URL redaction", () => {
it("redacts claim and invite tokens and secret query values", () => {
expect(redactAnalyticsUrl("/board-claim/abc123")).toBe("/board-claim/REDACTED");
expect(redactAnalyticsUrl("https://x.paperclip.app/invite/tok?x=1")).toBe("https://x.paperclip.app/invite/REDACTED");
expect(redactAnalyticsUrl("https://x.paperclip.app/cli-auth/id1?token=s3cr3t")).not.toContain("s3cr3t");
expect(redactAnalyticsUrl("/VER/issues/VER-1")).toBe("/VER/issues/VER-1");
expect(redactAnalyticsUrl("Desktop")).toBe("Desktop");
// Query and hash never leave: they can hold file paths or search text.
expect(redactAnalyticsUrl("https://x.paperclip.app/VER/files?path=customers/plan.md#L3")).toBe("https://x.paperclip.app/VER/files");
expect(redactAnalyticsUrl("/VER/issues?q=acme%20merger")).toBe("/VER/issues");
// Non-URL strings keep their text; only secret key=value pairs are redacted.
expect(redactAnalyticsUrl("Mozilla/5.0 (Macintosh)")).toBe("Mozilla/5.0 (Macintosh)");
});
it("redacts secrets in stylesheet links in replay", () => {
document.body.innerHTML = `<link id="l" rel="stylesheet" href="/x.css?token=abc">`;
expect(maskReplayAttribute("href", "/x.css?token=abc", document.getElementById("l"))).toBe("/x.css");
document.body.innerHTML = "";
});
});
+124
View File
@@ -0,0 +1,124 @@
// Shared privacy markers for browser product analytics (PostHog).
//
// Session replay masks ALL text and ALL input values by default. Only UI
// chrome that opts in shows its text: sidebar items with a fixed label, and
// any shared `Button`, `Label`, `TabsTrigger` or `EmptyState` whose caller
// passes `analyticsChrome` because its text is fixed product copy. A surface nobody marked stays
// masked. Autocapture never records element text or attribute values at all
// (see `product-analytics.ts`).
//
// Apply these markers instead of PostHog class names, so `product-analytics.ts`
// stays the one place that knows about PostHog. They have no effect when
// analytics is off (self-hosted and local installs).
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
export const ANALYTICS_UNMASK_ATTRIBUTE = "data-analytics-unmask";
/**
* Spread on shared UI chrome whose text is product copy, never customer
* content: `<button {...ANALYTICS_UNMASK_PROPS}>`.
*/
export const ANALYTICS_UNMASK_PROPS = { [ANALYTICS_UNMASK_ATTRIBUTE]: "" } as const;
/**
* Customer content: task and issue bodies, comments, chat messages, documents
* and artifacts. Its text stays masked even inside unmasked chrome, and
* autocapture records nothing from inside it.
*/
export const ANALYTICS_MASK_CLASS = "ph-mask ph-sensitive";
/**
* Secrets and credentials: API keys, tokens, passwords, environment values.
* Session replay records a blank placeholder instead of the element and its
* children, and autocapture records nothing from inside it.
*/
export const ANALYTICS_NO_CAPTURE_CLASS = "ph-no-capture";
/** Session replay sends every text node through `maskReplayText`. */
export const ANALYTICS_MASK_TEXT_SELECTOR = "*";
const FORCED_MASK_SELECTOR = ".ph-mask, .ph-no-capture, [contenteditable]:not([contenteditable=\"false\"])";
const UNMASK_SELECTOR = `[${ANALYTICS_UNMASK_ATTRIBUTE}]`;
/** True only for text inside opted-in chrome and outside customer content. */
export function isReplayTextRevealed(element: Element | null | undefined): boolean {
if (!element || typeof element.closest !== "function") return false;
if (element.closest(FORCED_MASK_SELECTOR)) return false;
return element.closest(UNMASK_SELECTOR) !== null;
}
/** Session replay `maskTextFn`: keeps whitespace so the layout stays readable. */
export function maskReplayText(text: string, element?: HTMLElement | null): string {
return isReplayTextRevealed(element) ? text : text.replace(/\S/g, "*");
}
/**
* Attributes that only describe layout, state or structure. Every other
* attribute (title, alt, aria-label, placeholder, value, src, href, data-*,
* and element references such as id, for and aria-labelledby, which often
* embed names or slugs) can carry customer text, so replay masks it.
*/
const LAYOUT_ATTRIBUTES = new Set([
"class", "style", "type", "role", "tabindex", "disabled", "checked", "selected", "hidden",
"open", "dir", "lang", "rel", "target", "colspan", "rowspan", "width", "height",
"viewbox", "xmlns", "d", "fill", "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin",
"x", "y", "x1", "x2", "y1", "y2", "cx", "cy", "r", "rx", "ry", "points", "transform", "opacity",
"aria-hidden", "aria-expanded", "aria-selected", "aria-checked", "aria-current", "aria-disabled",
"aria-orientation", "aria-haspopup", "aria-modal", "aria-pressed", "aria-invalid", "aria-live", "aria-busy",
"data-slot", "data-state", "data-side", "data-align", "data-orientation", "data-variant",
"data-size", "data-disabled", "data-highlighted", "data-placeholder", ANALYTICS_UNMASK_ATTRIBUTE,
]);
/** Fixed IDs that page CSS targets (`#root`, `#main-content`); never customer data. */
const LAYOUT_IDS = new Set(["root", "main-content", "properties-pane-header-slot"]);
/**
* Session replay `maskAttributeFn`. Deny by default: only layout attributes,
* rrweb's own metadata, stylesheets and links outside customer content keep
* their values. Free-text attributes stay masked even on opted-in chrome,
* because labels such as `aria-label` often name customer data (for example
* the organization switcher's "Open <name> switcher").
*/
export function maskReplayAttribute(name: string, value: string, element?: Element | null): string {
const key = name.toLowerCase();
// rrweb's own serialized metadata (`rr_width`, `_cssText`, ...).
if (key.startsWith("rr_") || key.startsWith("_")) return value;
if (LAYOUT_ATTRIBUTES.has(key)) return value;
if (key === "id" && LAYOUT_IDS.has(value)) return value;
// Stylesheets render the page. Every other `href` (download links carry
// file paths, markdown links carry customer URLs) stays masked.
if (key === "href" && element?.tagName?.toLowerCase() === "link") return redactAnalyticsUrl(value);
return value.replace(/\S/g, "*");
}
/** Routes whose next path segment is a one-time secret (claim and invite links). */
const SECRET_PATH_SEGMENT = /(\/(?:board-claim|invite)\/)[^/?#\s"']+/gi;
const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
/**
* Prepares a URL or path for analytics. Deny by default: a URL keeps only its
* origin and path, because query and hash values can hold credentials
* (`token`, `code`, `state`), file paths or search text. The token segment of
* claim and invite links is redacted. Any other string only has secret
* `key=value` pairs redacted.
*/
export function redactAnalyticsUrl(value: string): string {
if (!value.includes("/") && !value.includes("?") && !value.includes("#")) return value;
const trimmed = value.trim();
let result: string;
if (ABSOLUTE_URL.test(trimmed)) {
try {
const url = new URL(trimmed);
result = `${url.origin === "null" ? `${url.protocol}//` : url.origin}${url.pathname}`;
} catch {
result = redactUrlSecrets(value);
}
} else if (trimmed.startsWith("/")) {
result = trimmed.replace(/[?#].*$/, "");
} else {
result = redactUrlSecrets(value);
}
return result.replace(SECRET_PATH_SEGMENT, "$1REDACTED");
}
@@ -0,0 +1,48 @@
import { readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { PAPERCLIP_EVENTS } from "@paperclipai/shared/telemetry/generated/paperclip-telemetry";
// Each event name has exactly one sender. The server sends every
// `PAPERCLIP_EVENTS` event, so browser code must never capture one too, or
// PostHog would count it twice.
const UI_SRC = fileURLToPath(new URL("../..", import.meta.url));
function sourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name);
if (entry.isDirectory()) return entry.name === "node_modules" ? [] : sourceFiles(path);
return /\.(ts|tsx)$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name) ? [path] : [];
});
}
/** `x.capture("name"` with a literal name, or `x.capture(PAPERCLIP_EVENTS...`. */
function findServerEventCaptures(source: string, serverEvents: ReadonlySet<string>): string[] {
const found: string[] = [];
for (const match of source.matchAll(/\.capture\(\s*(?:(["'`])([^"'`]+)\1|(PAPERCLIP_EVENTS\b[^,)]*))/g)) {
if (match[3]) found.push(match[3].trim());
else if (match[2] && serverEvents.has(match[2])) found.push(match[2]);
}
return found;
}
describe("browser analytics event ownership", () => {
const serverEvents = new Set<string>(Object.values(PAPERCLIP_EVENTS));
it("detects a server-owned event name passed to capture()", () => {
expect(findServerEventCaptures(`posthog.capture("agent.created", {})`, serverEvents)).toEqual(["agent.created"]);
expect(findServerEventCaptures(`client.capture(PAPERCLIP_EVENTS["goal.created"])`, serverEvents))
.toEqual(['PAPERCLIP_EVENTS["goal.created"]']);
expect(findServerEventCaptures(`posthog.capture("ui_button_clicked")`, serverEvents)).toEqual([]);
});
it("never captures a PAPERCLIP_EVENTS event from UI code", () => {
const offenders = sourceFiles(UI_SRC).flatMap((file) =>
findServerEventCaptures(readFileSync(file, "utf8"), serverEvents)
.map((name) => `${relative(UI_SRC, file)}: ${name}`),
);
expect(offenders).toEqual([]);
});
});
@@ -0,0 +1,197 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BrowserAnalyticsConfig } from "@paperclipai/shared";
import {
buildPostHogInitOptions,
cancelPendingProductAnalytics,
resetProductAnalyticsForTest,
scrubCapturedEvent,
setProductAnalyticsUser,
startProductAnalytics,
type ProductAnalyticsClient,
} from "./product-analytics";
const config: BrowserAnalyticsConfig = {
token: "phc_test",
apiHost: "/_ph",
uiHost: "https://us.posthog.com",
environment: "staging",
stackId: "stack-1",
replayEnabled: true,
};
function mockClient() {
return {
init: vi.fn(),
register: vi.fn(),
identify: vi.fn(),
group: vi.fn(),
reset: vi.fn(),
} satisfies { [K in keyof ProductAnalyticsClient]: ReturnType<typeof vi.fn> };
}
async function flush() {
await Promise.resolve();
await Promise.resolve();
}
describe("product analytics", () => {
let client: ReturnType<typeof mockClient>;
let load: ReturnType<typeof vi.fn<() => Promise<ProductAnalyticsClient>>>;
let scheduled: (() => void) | null;
const schedule = (start: () => void) => {
scheduled = start;
return () => { scheduled = null; };
};
beforeEach(() => {
client = mockClient();
load = vi.fn(async () => client as unknown as ProductAnalyticsClient);
scheduled = null;
});
afterEach(() => resetProductAnalyticsForTest());
it("does not load posthog-js until the page settles", async () => {
startProductAnalytics(config, { load, schedule });
await flush();
expect(load).not.toHaveBeenCalled();
scheduled!();
await flush();
expect(load).toHaveBeenCalledTimes(1);
expect(client.init).toHaveBeenCalledWith("phc_test", expect.objectContaining({ api_host: "/_ph" }));
expect(client.register).toHaveBeenCalledWith({ deployment_source: "cloud", environment: "staging" });
});
it("loads once when the scheduler calls back twice (settled page and deadline)", async () => {
let starts: Array<() => void> = [];
startProductAnalytics(config, { load, schedule: (start) => { starts = [start, start]; return () => {}; } });
starts[0]!();
starts[1]!();
await flush();
expect(load).toHaveBeenCalledTimes(1);
});
it("never loads when cancelled before the page settles", async () => {
startProductAnalytics(config, { load, schedule });
cancelPendingProductAnalytics();
expect(scheduled).toBeNull();
await flush();
expect(load).not.toHaveBeenCalled();
});
it("identifies the signed-in user with email and name as person properties, then joins the workspace group", async () => {
setProductAnalyticsUser({ id: "user-1", email: "jane@example.com", name: "Jane" });
startProductAnalytics(config, { load, schedule });
scheduled!();
await flush();
expect(client.identify).toHaveBeenCalledWith("user-1", { email: "jane@example.com", name: "Jane" });
expect(client.group).toHaveBeenCalledWith("workspace", "stack-1");
// Email and name never become super (event) properties.
for (const [props] of client.register.mock.calls) {
expect(props).not.toHaveProperty("email");
expect(props).not.toHaveProperty("name");
}
});
it("identifies a user who signs in after posthog-js loaded, once", async () => {
startProductAnalytics(config, { load, schedule });
scheduled!();
await flush();
expect(client.identify).not.toHaveBeenCalled();
setProductAnalyticsUser({ id: "user-1", email: null, name: null });
setProductAnalyticsUser({ id: "user-1", email: null, name: null });
expect(client.identify).toHaveBeenCalledTimes(1);
expect(client.identify).toHaveBeenCalledWith("user-1", {});
});
it("resets identity on sign-out and keeps the deployment super properties", async () => {
setProductAnalyticsUser({ id: "user-1", email: "jane@example.com", name: "Jane" });
startProductAnalytics(config, { load, schedule });
scheduled!();
await flush();
client.register.mockClear();
setProductAnalyticsUser(null);
expect(client.reset).toHaveBeenCalledTimes(1);
expect(client.register).toHaveBeenCalledWith({ deployment_source: "cloud", environment: "staging" });
setProductAnalyticsUser({ id: "user-2", email: null, name: null });
expect(client.identify).toHaveBeenLastCalledWith("user-2", {});
});
it("does not reset an anonymous visitor", async () => {
startProductAnalytics(config, { load, schedule });
scheduled!();
await flush();
setProductAnalyticsUser(null);
expect(client.reset).not.toHaveBeenCalled();
});
it("builds privacy-safe init options", () => {
const options = buildPostHogInitOptions(config, "acme.paperclip.app");
expect(options).toMatchObject({
api_host: "/_ph",
ui_host: "https://us.posthog.com",
person_profiles: "identified_only",
capture_pageview: "history_change",
capture_pageleave: true,
autocapture: true,
mask_all_text: true,
mask_all_element_attributes: true,
capture_performance: { web_vitals: true },
enable_heatmaps: true,
disable_session_recording: false,
tracing_headers: ["acme.paperclip.app"],
session_recording: { maskAllInputs: true, blockClass: "ph-no-capture" },
});
// Replay masks every text node; maskTextFn reveals only opted-in chrome.
expect(options.session_recording?.maskTextSelector).toBe("*");
expect(options.session_recording?.maskTextFn).toBeTypeOf("function");
expect(options.session_recording?.maskAttributeFn).toBeTypeOf("function");
expect(options).toMatchObject({ disable_surveys: true, disable_product_tours: true, disable_web_experiments: true, disable_conversations: true });
expect(buildPostHogInitOptions({ ...config, replayEnabled: false }, "x").disable_session_recording).toBe(true);
});
it("drops the page title, which names tasks and organizations, from every event", () => {
const event = {
uuid: "u",
event: "$pageview",
properties: { title: "Customer task title · Verify Co", $title: "x", $current_url: "https://acme.paperclip.app/VER/issues/VER-1" },
} as unknown as Parameters<typeof scrubCapturedEvent>[0];
expect(scrubCapturedEvent(event)?.properties).toEqual({ $current_url: "https://acme.paperclip.app/VER/issues/VER-1" });
expect(buildPostHogInitOptions(config, "x").before_send).toBe(scrubCapturedEvent);
expect(scrubCapturedEvent(null)).toBeNull();
});
it("redacts one-time tokens from URLs in events and replay meta, and keeps compressed replay data intact", () => {
const gz = "\x1f\x8b\x08binary/board-claim/zzz";
const event = {
uuid: "u",
event: "$snapshot",
properties: {
$current_url: "https://acme.paperclip.app/board-claim/claim-secret-123",
$referrer: "https://acme.paperclip.app/cli-auth/abc?token=cli-secret-456",
$set_once: { $initial_current_url: "https://acme.paperclip.app/invite/invite-secret-789" },
$snapshot_data: [{ type: 4, data: { href: "https://acme.paperclip.app/oauth-handoff?code=c1&state=s1" } }, { type: 2, data: gz }],
$pathname: "/VER/issues/VER-1",
},
} as unknown as Parameters<typeof scrubCapturedEvent>[0];
const out = JSON.stringify(scrubCapturedEvent(event));
for (const secret of ["claim-secret-123", "cli-secret-456", "invite-secret-789", "code=c1", "state=s1"]) {
expect(out).not.toContain(secret);
}
expect(out).toContain("/board-claim/REDACTED");
expect(out).toContain("/VER/issues/VER-1");
const data = (scrubCapturedEvent(event)!.properties.$snapshot_data as Array<{ data: unknown }>)[1]!.data;
expect(data).toBe(gz);
});
it("keeps the event timestamp a Date", () => {
const timestamp = new Date("2026-11-17T12:00:00Z");
const event = { uuid: "u", event: "$pageview", timestamp, properties: { $current_url: "https://a.paperclip.app/x?y=1" } } as unknown as Parameters<typeof scrubCapturedEvent>[0];
const out = scrubCapturedEvent(event)!;
expect(out.timestamp).toBeInstanceOf(Date);
expect(out.timestamp).toBe(timestamp);
expect(out.properties.$current_url).toBe("https://a.paperclip.app/x");
});
});
+302
View File
@@ -0,0 +1,302 @@
// Browser product analytics (PostHog) for hosted Paperclip Cloud.
//
// This is the only module that talks to posthog-js. It runs only when the
// signed-in session carries a `browserAnalytics` config, which the server
// sends only for a cloud-managed instance with a PostHog project token and
// `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. Without a config nothing here runs
// and posthog-js is never fetched.
//
// posthog-js is not an npm dependency of the board. It loads as PostHog's
// browser script (`/static/array.js`) through the same-origin proxy, like the
// extensions it loads itself (recorder, web vitals). So it is in no bundle
// chunk, and self-hosted installs, which have no proxy, can never load it.
// See `ProductAnalyticsGate.tsx` and `server/src/services/cloud-posthog-browser.ts`.
//
// To keep cold loads fast, posthog-js loads only after the page settles
// (first paint, page reads finished, browser idle), or at a deadline.
//
// Identity: after sign-in the user's ID becomes the PostHog person, with email
// and name set as person properties only (never event properties), and the
// browser joins the `workspace` group for this stack. Sign-out resets both.
//
// Product events that the server already sends (`PAPERCLIP_EVENTS`) must never
// be captured here; `product-analytics-events.test.ts` enforces that.
import type { BrowserAnalyticsConfig } from "@paperclipai/shared";
import {
ANALYTICS_MASK_TEXT_SELECTOR,
ANALYTICS_NO_CAPTURE_CLASS,
maskReplayAttribute,
maskReplayText,
redactAnalyticsUrl,
} from "./privacy";
/** The posthog-js calls this module makes. */
export interface ProductAnalyticsClient {
init(token: string, config: PostHogInitOptions): unknown;
register(properties: Record<string, unknown>): void;
identify(distinctId: string, personProperties?: Record<string, unknown>): void;
group(groupType: string, groupKey: string): void;
reset(): void;
}
/** An event as posthog-js hands it to `before_send`. */
export type CapturedEvent = {
event: string;
properties: Record<string, unknown>;
timestamp?: Date;
[key: string]: unknown;
};
/** The posthog-js `init` options this module sets (posthog-js `PostHogConfig`). */
export type PostHogInitOptions = {
api_host: string;
ui_host?: string;
person_profiles: "identified_only";
capture_pageview: "history_change";
capture_pageleave: boolean;
autocapture: boolean;
mask_all_text: boolean;
mask_all_element_attributes: boolean;
capture_performance: { web_vitals: boolean };
enable_heatmaps: boolean;
disable_session_recording: boolean;
session_recording: {
maskAllInputs: boolean;
maskTextSelector: string;
maskTextFn: (text: string, element?: HTMLElement | null) => string;
maskAttributeFn: (name: string, value: string, element?: Element | null) => string;
blockClass: string;
};
tracing_headers: string[];
mask_personal_data_properties: boolean;
before_send: (event: CapturedEvent | null) => CapturedEvent | null;
disable_surveys: boolean;
disable_product_tours: boolean;
disable_web_experiments: boolean;
disable_conversations: boolean;
};
export type ProductAnalyticsUser = {
id: string;
email: string | null;
name: string | null;
};
export type ProductAnalyticsOptions = {
/** Overridable for tests. Defaults to loading PostHog's script through the proxy. */
load?: (config: BrowserAnalyticsConfig) => Promise<ProductAnalyticsClient>;
/** Calls `start` when posthog-js may load; returns a cancel function. */
schedule: (start: () => void) => () => void;
};
/** Load posthog-js no later than this after the session arrives. */
export const PRODUCT_ANALYTICS_LOAD_DEADLINE_MS = 15_000;
const WORKSPACE_GROUP_TYPE = "workspace";
/** PostHog's browser build, served by the assets host through the proxy. */
export const POSTHOG_SCRIPT_PATH = "/static/array.js";
type WindowWithPostHog = Window & { posthog?: Partial<ProductAnalyticsClient> };
function loadPostHog(config: BrowserAnalyticsConfig): Promise<ProductAnalyticsClient> {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = `${config.apiHost}${POSTHOG_SCRIPT_PATH}`;
script.async = true;
script.onload = () => {
const client = (window as WindowWithPostHog).posthog;
if (client && typeof client.init === "function") resolve(client as ProductAnalyticsClient);
else reject(new Error("posthog_script_did_not_load"));
};
script.onerror = () => reject(new Error("posthog_script_did_not_load"));
document.head.appendChild(script);
});
}
const GZIP_MAGIC = "\x1f\x8b";
/** Redacts URL secrets in every string, including replay meta events (their `href`). */
function redactStrings(value: unknown): unknown {
if (typeof value === "string") {
// Compressed replay data is binary in a string; its attributes were
// already masked by `maskReplayAttribute` before compression.
return value.startsWith(GZIP_MAGIC) ? value : redactAnalyticsUrl(value);
}
if (Array.isArray(value)) return value.map(redactStrings);
// Plain objects only: a `Date` (the event timestamp) and other class
// instances pass through unchanged.
if (value && typeof value === "object") {
const proto = Object.getPrototypeOf(value);
if (proto !== Object.prototype && proto !== null) return value;
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactStrings(entry)]));
}
return value;
}
/**
* Last step before an event leaves the browser.
* - Drops the page title: posthog-js copies `document.title` into page views,
* and Paperclip titles name the task and the organization.
* - Redacts secrets in URLs (`$current_url`, `$referrer`, replay meta `href`,
* ...): one-time claim and invite tokens and secret query values.
*/
export function scrubCapturedEvent(event: CapturedEvent | null): CapturedEvent | null {
if (!event) return event;
const scrubbed = redactStrings(event) as CapturedEvent;
if (scrubbed.properties) {
delete scrubbed.properties.title;
delete scrubbed.properties.$title;
}
return scrubbed;
}
export function buildPostHogInitOptions(
config: BrowserAnalyticsConfig,
apiHostname: string,
): PostHogInitOptions {
return {
api_host: config.apiHost,
...(config.uiHost ? { ui_host: config.uiHost } : {}),
person_profiles: "identified_only",
capture_pageview: "history_change",
capture_pageleave: true,
// Clicks and their element tree only: never element text or attribute
// values, so no customer content reaches autocapture events.
autocapture: true,
mask_all_text: true,
mask_all_element_attributes: true,
capture_performance: { web_vitals: true },
enable_heatmaps: true,
disable_session_recording: !config.replayEnabled,
session_recording: {
// Mask everything; only opted-in UI chrome shows its text (privacy.ts).
maskAllInputs: true,
maskTextSelector: ANALYTICS_MASK_TEXT_SELECTOR,
maskTextFn: maskReplayText,
// Attributes too (title, aria-label, alt, src, ...): deny by default.
maskAttributeFn: maskReplayAttribute,
blockClass: ANALYTICS_NO_CAPTURE_CLASS,
},
// Links browser sessions to server events (X-POSTHOG-SESSION-ID and
// friends). Our own origin only; no third-party request gets them.
tracing_headers: [apiHostname],
// Advertising click IDs in URLs are personal data.
mask_personal_data_properties: true,
before_send: scrubCapturedEvent,
// Features we do not use. Off, so posthog-js only calls the endpoints the
// server proxy allows (server/src/routes/posthog-proxy.ts).
disable_surveys: true,
disable_product_tours: true,
disable_web_experiments: true,
disable_conversations: true,
};
}
function superProperties(config: BrowserAnalyticsConfig) {
return {
deployment_source: "cloud",
environment: config.environment,
};
}
type State = {
config: BrowserAnalyticsConfig;
client: ProductAnalyticsClient | null;
cancelSchedule: (() => void) | null;
loading: boolean;
};
let state: State | null = null;
let wantedUser: ProductAnalyticsUser | null = null;
let identifiedUserId: string | null = null;
function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) {
const user = wantedUser;
if (user) {
if (identifiedUserId === user.id) return;
const personProperties: Record<string, string> = {};
if (user.email) personProperties.email = user.email;
if (user.name) personProperties.name = user.name;
client.identify(user.id, personProperties);
client.group(WORKSPACE_GROUP_TYPE, config.stackId);
identifiedUserId = user.id;
return;
}
if (identifiedUserId !== null) {
// `reset` also clears super properties; keep the deployment ones.
client.reset();
client.register(superProperties(config));
identifiedUserId = null;
}
}
/**
* Start browser analytics for this page session. Idempotent: posthog-js is a
* page-wide singleton, so later calls (session refetches) keep the first
* config.
*/
export function startProductAnalytics(
config: BrowserAnalyticsConfig,
options: ProductAnalyticsOptions,
): void {
if (state) return;
const current: State = { config, client: null, cancelSchedule: null, loading: false };
state = current;
const load = options.load ?? loadPostHog;
current.cancelSchedule = options.schedule(() => {
// The scheduler may call back more than once (settled page, deadline).
const cancel = current.cancelSchedule;
current.cancelSchedule = null;
cancel?.();
if (state !== current || current.loading) return;
current.loading = true;
load(config)
.then((client) => {
if (state !== current) return;
client.init(config.token, buildPostHogInitOptions(config, window.location.hostname));
client.register(superProperties(config));
current.client = client;
applyIdentity(client, config);
})
.catch(() => {
// Analytics must never break the board. A failed script load leaves it
// off for this page session.
if (state === current) current.loading = false;
});
});
}
/** Set (or clear, on sign-out) the signed-in user. Safe to call before posthog-js loads. */
export function setProductAnalyticsUser(user: ProductAnalyticsUser | null): void {
wantedUser = user;
if (state?.client) applyIdentity(state.client, state.config);
}
/**
* Forget the signed-in person now. Sign-out calls this before it leaves the
* page (Cloud sign-out navigates away while the session query is still
* populated), so the next person in this browser never inherits the identity.
*/
export function resetProductAnalyticsIdentity(): void {
setProductAnalyticsUser(null);
}
/**
* Cancel a load that has not started yet. posthog-js cannot be unloaded once
* it runs, so a running client keeps running; sign-out resets its identity
* through `setProductAnalyticsUser(null)`.
*/
export function cancelPendingProductAnalytics(): void {
if (!state || state.client || state.loading) return;
state.cancelSchedule?.();
state = null;
}
export function resetProductAnalyticsForTest(): void {
state?.cancelSchedule?.();
state = null;
wantedUser = null;
identifiedUserId = null;
}
@@ -0,0 +1,59 @@
// @vitest-environment jsdom
import { renderToStaticMarkup } from "react-dom/server";
import { Bot } from "lucide-react";
import { afterEach, describe, expect, it } from "vitest";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { EmptyState } from "@/components/EmptyState";
import { ANALYTICS_UNMASK_ATTRIBUTE, maskReplayText } from "./privacy";
// Shared components render customer text too (agent names, document titles),
// so none of them reveals replay text unless its caller opts in.
function textOf(html: string, text: string): string {
document.body.innerHTML = html;
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
if (walker.currentNode.textContent === text) return maskReplayText(text, walker.currentNode.parentElement);
}
throw new Error(`text not rendered: ${text}`);
}
describe("shared components and session replay", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("masks customer text in shared components by default", () => {
const html = renderToStaticMarkup(
<div>
<Button>Open Acme Plan</Button>
<Label>Ada Agent</Label>
<Tabs><TabsList><TabsTrigger value="a">Q3 Board Deck</TabsTrigger></TabsList></Tabs>
<EmptyState icon={Bot} message="No costs for Ada Agent yet." />
</div>,
);
expect(html).not.toContain(ANALYTICS_UNMASK_ATTRIBUTE);
expect(textOf(html, "Open Acme Plan")).toBe("**** **** ****");
expect(textOf(html, "Ada Agent")).toBe("*** *****");
expect(textOf(html, "Q3 Board Deck")).toBe("** ***** ****");
expect(textOf(html, "No costs for Ada Agent yet.")).toBe("** ***** *** *** ***** ****");
});
it("shows fixed product copy when the caller opts in", () => {
const html = renderToStaticMarkup(
<div>
<Button analyticsChrome>New task</Button>
<Label analyticsChrome>Agent name</Label>
<Tabs><TabsList><TabsTrigger analyticsChrome value="a">Activity</TabsTrigger></TabsList></Tabs>
<EmptyState analyticsChrome icon={Bot} message="Inbox zero." />
</div>,
);
expect(textOf(html, "New task")).toBe("New task");
expect(textOf(html, "Agent name")).toBe("Agent name");
expect(textOf(html, "Activity")).toBe("Activity");
expect(textOf(html, "Inbox zero.")).toBe("Inbox zero.");
});
});
@@ -0,0 +1,102 @@
// @vitest-environment jsdom
import { readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { buildPostHogInitOptions } from "./product-analytics";
import { maskReplayText } from "./privacy";
// Session replay masks all text by default. Text shows only inside the
// unmask allowlist, so this file is the review point for that allowlist.
//
// Connected-account content (Gmail bodies, Calendar events, Slack messages in
// tasks, chat, tool results and previews) is Google user data / Slack data:
// no human may read it in a replay (Google API Limited Use). It must never sit
// inside an unmasked element. Before adding any entry below, confirm the
// element renders fixed product copy only, never connected-account or other
// customer content.
const UI_SRC = join(import.meta.dirname, "../..");
/** Files that may spread the unmask attribute: shared components, behind an opt-in prop. */
const UNMASK_PROPS_FILES = [
"components/EmptyState.tsx",
"components/SidebarNavItem.production.tsx",
"components/SidebarNavItem.tsx",
"components/ui/button.tsx",
"components/ui/label.tsx",
"components/ui/tabs.tsx",
"lib/analytics/privacy.ts",
];
/**
* Reviewed `analyticsChrome` opt-ins on Button, Label, TabsTrigger or
* EmptyState, as "file: component". Empty today: none opts in.
*/
const REVIEWED_CHROME_OPT_INS: string[] = [];
function sourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name);
if (entry.isDirectory()) return entry.name === "node_modules" ? [] : sourceFiles(path);
return /\.(ts|tsx)$/.test(entry.name) && !/\.(test|stories)\.tsx?$/.test(entry.name) ? [path] : [];
});
}
const files = sourceFiles(UI_SRC).map((path) => ({ name: relative(UI_SRC, path), source: readFileSync(path, "utf8") }));
describe("session replay unmask allowlist", () => {
it("spreads the unmask attribute only in the reviewed shared components", () => {
const users = files
.filter((file) => /ANALYTICS_UNMASK_PROPS|data-analytics-unmask/.test(file.source))
.map((file) => file.name)
.sort();
expect(users).toEqual(UNMASK_PROPS_FILES);
});
it("opts in sidebar items only when the label is a fixed string", () => {
const offenders: string[] = [];
for (const file of files) {
for (const match of file.source.matchAll(/<SidebarNavItem\b[^>]*?\banalyticsChrome\b[\s\S]*?\/>/g)) {
if (!/\slabel="[^"]+"/.test(match[0])) offenders.push(`${file.name}: ${match[0].slice(0, 80)}`);
}
}
expect(offenders).toEqual([]);
});
it("has no unreviewed analyticsChrome opt-in on other shared components", () => {
const optIns: string[] = [];
for (const file of files) {
for (const match of file.source.matchAll(/<(Button|Label|TabsTrigger|EmptyState)\b[^>]*?\banalyticsChrome\b/g)) {
optIns.push(`${file.name}: ${match[1]}`);
}
}
expect(optIns.sort()).toEqual(REVIEWED_CHROME_OPT_INS);
});
it("masks connected-account content in replays and keeps it out of autocapture", () => {
document.body.innerHTML = `
<nav data-analytics-unmask><span id="nav">Tasks</span></nav>
<div class="task-chat">
<div class="tool-result"><p id="gmail">Re: Q3 contract — please sign by Friday</p></div>
<div class="tool-result"><p id="calendar">Board meeting with Acme, 3pm</p></div>
<div class="slack-preview"><p id="slack">#deals: we lost the Globex renewal</p></div>
</div>`;
const text = (id: string) => {
const element = document.getElementById(id)!;
return maskReplayText(element.textContent!, element);
};
expect(text("nav")).toBe("Tasks");
expect(text("gmail")).not.toMatch(/[A-Za-z0-9]/);
expect(text("calendar")).not.toMatch(/[A-Za-z0-9]/);
expect(text("slack")).not.toMatch(/[A-Za-z0-9]/);
// Autocapture never records element text or attribute values anywhere.
const options = buildPostHogInitOptions(
{ token: "t", apiHost: "/_ph", uiHost: null, environment: "production", stackId: "s", replayEnabled: true },
"acme.paperclip.app",
);
expect(options.mask_all_text).toBe(true);
expect(options.mask_all_element_attributes).toBe(true);
document.body.innerHTML = "";
});
});
+2
View File
@@ -8,6 +8,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { App } from "./App";
import { AppErrorBoundary } from "./components/AppErrorBoundary";
import { SentryGate } from "./components/SentryGate";
import { ProductAnalyticsGate } from "./components/ProductAnalyticsGate";
import { CompanyProvider, useCompany } from "./context/CompanyContext";
import { LinkPreviewProvider } from "./context/LinkPreviewContext";
import { LiveUpdatesProvider } from "./context/LiveUpdatesProvider";
@@ -128,6 +129,7 @@ getOrCreatePaperclipReactRoot(window, rootElement).render(
<AppErrorBoundary>
<QueryClientProvider client={queryClient}>
<SentryGate />
<ProductAnalyticsGate />
<ThemeProvider>
<BrowserRouter>
<CompanyProvider>