feat(analytics): make replay work content a deployment opt-in (#22820)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Hosts can enable PostHog browser analytics and session replay
through deployment configuration.
> - Replay masks work content, which makes task and artifact flows hard
to understand.
> - Hosts must decide whether their deployment may show this content.
> - This pull request adds an explicit deployment opt-in, with work
content masked by default.
> - Eligible companies can show work content after that opt-in, while
connected-account checks and secret masking still apply.

## Linked Issues or Issue Description

No public issue exists. This change follows the enhancement template.

**What existing behavior does this improve?**

Session replay masks task descriptions, document bodies and artifact
previews. A host cannot choose to show eligible work content
independently of enabling replay.

**Subsystem affected**

Browser session replay, deployment analytics configuration, and the
authenticated session contract.

**Current behavior**

Work content stays masked in every company. Task and artifact titles
already show. PostHog project masking settings cannot override the
options supplied by the board UI.

**Proposed behavior**

Keep work content masked by default. Set
`PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1` in deployment
configuration to allow it for eligible companies. Unset, `0`, and other
values keep it masked. Browser analytics and replay must also be
enabled. A host can keep replay enabled while work content stays masked.

**Reason and benefit**

Hosts control their recording policy without editing Core source. An
eligible company's replay can show the task flow after the host opts in.

**Breaking changes**

None relative to the base branch. Self-hosted analytics remain disabled
by the existing analytics gate. Existing deployments retain work-content
masking unless they explicitly opt in. The session gains an optional
boolean and the tool connection list gains an optional `hiddenCount`
field. Missing fields fail closed.

## What Changed

- Add `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED`, default off.
Resolve it in the existing server analytics configuration and send the
effective boolean as `browserAnalytics.replayWorkContentEnabled`. The
shared session schema preserves the field and accepts older servers that
omit it.
- Require both replay and the work-content opt-in before the UI queries
company sources or permits visibility. Removing the opt-in from a
refreshed session masks content even when eligible source answers remain
cached.
- Preserve the original company checks: complete tool connection and
chat endpoint lists, no Google or Slack source, no known aggregator or
router, and the selected company's route. Unknown, failed, invalidated,
or hidden source data keeps content masked. Live source changes reset
the check.
- Mark task descriptions, document bodies, attachment and artifact
previews, and file viewers as work content. Customer content, editors,
comments, chat, run output and connected-account surfaces remain masked.
Secrets remain blocked or redacted. Input and attribute values remain
masked.
- Preserve credential punctuation in task previews by reusing the shared
Markdown plain-text helper. Bound conversion to the first 2,048 source
characters, and always mask source-capped previews to protect incomplete
credentials. Scan complete command-line flag names once before
classifying secrets and reading their values. A 512 KiB hyphen input and
long flag names have regression coverage.
- Mask surfaces that show cut or rewritten work content, where the
redaction cannot work. A cut task preview masks when the text before its
180-character limit holds a credential. The document card preview (first
4,000 characters) masks when the cut changes what the redaction masks
before it. The text preview on an artifact card always masks, because
the server strips hyphens and underscores from it and cuts it at 280
characters. Quoted flag values run past escaped quotes, and flag names
can hold an underscore. An unquoted token that starts with `--` is read
as the next flag, not as a value, so `--auth
--tlsCertificateKeyFilePassword hunter2` masks `hunter2`.
- Refresh the recording once when a company's work content first becomes
visible. Keep the existing autocapture text and attribute masking.
- Add tests for deployment switches, session parsing and exposure,
disabled source requests, older servers, and withdrawal with cached
data. Retain the original masking, company, secret, and source-change
tests.
- Document configuration, rollback, restart and tab-reload steps,
residual recording risks, and the board-only `hiddenCount` API field
with absent-on-older-server semantics. Refresh the shared-source pins
with the maintained generator; runtime and compiler pins stay unchanged.

The original implementation and commits are preserved from @nguyenm7.
The deployment configuration follow-up adds the host opt-in.

When squash-merging, preserve the follow-up author's credit in the
squash commit body:

```text
Co-Authored-By: Devin Foley <devinfoley@users.noreply.github.com>
```

## Verification

Current head `2ce967f1e1`: CI has 43 checks passed and four skipped,
with none failed or pending. The Greptile review on this head is 5/5,
and both findings from its previous review are fixed. No person has
approved the pull request yet. The evidence below was recorded on
earlier heads and is kept as the record of how the change was verified.

Greptile apex review: 5/5 on `45023e6`, with no unresolved review
threads. CI on that head is green: 76 checks passed and four skipped,
with no failed or pending checks. The branch has no merge conflicts with
master.

On the final source change, locally:

- `cd ui && pnpm exec vitest run src/lib/analytics
src/context/LiveUpdatesProvider.test.ts
src/lib/markdown-plain-text.test.ts`: 10 files, 520 tests pass. The
secret-redaction cases are in `replay-secret-redaction.test.tsx`, so
`replay-masking.test.tsx` stays under 1,000 lines (701).
- `cd server && pnpm exec vitest run
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/auth-routes.test.ts
src/__tests__/posthog-direct-transport.test.ts`: 4 files, 124 tests
pass.
- `cd packages/shared && pnpm exec vitest run
src/validators/access.test.ts`: 22 tests pass.
- `pnpm exec vitest run -c tests/runner-e2e/vitest.config.ts
source-sdk-public-inputs`: 13 tests pass.
- Shared, server and UI package typechecks pass. Server and UI builds
pass.
- Token gates, module boundaries, the test budget check for changed
suites, and `git diff --check` pass.
- Long-preview regression proof: four rendered tests initially fail on
`9f2039d` because it passes 128,005 characters to conversion. They now
verify a 2,048-character input bound while calling the real helper, a
maximum 180-character summary, and complete replay masking for capped
sources. Inputs include backticks, stars, underscores and brackets. The
earlier short-preview credential tests still pass.
- Review regression proof: three rendered task-preview tests expose
GitLab, GitHub and OpenAI fixture credentials on `7533fbe`; they pass
after preserving token punctuation. An 80,000-hyphen input took about
3.25 seconds on that head and failed the 500 ms bound. The single-pass
flag scan passes the guard with a 512 KiB prefix followed by a real
password flag.
- Regression proof: the added tests first failed on the prior
implementation, including work content visible with a missing or false
opt-in and after withdrawal. They pass with the new gate.
- `pnpm verify`: exit 2, broader verification required because the
analytics document is a global CI input. Required CI supplies
repository-wide coverage. An earlier exit 1 identified stale
shared-source pins; the maintained generator refreshed them and the 13
pin tests pass.
- Direct UI `tsc --noEmit` initially lacked generated Storybook catalogs
in the fresh checkout. The maintained UI typecheck generates those files
and passes. A preliminary Vitest `--project ui` invocation matched no
named project; the commands above use the package configuration.
- Secret scan reviewed the commit diff. Gitleaks reports two generic-key
matches in the generated source-pin registry; both equal the
corresponding Git blob hashes. The remaining commit content scans clean.
No run artifacts or private deployment data are committed.

CI follow-up on `45023e6`: [server shard
10/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948661)
timed out twice at the existing 15-second limit in
`issue-document-batch.integration.test.ts`, test "rejects many large
documents using a size-only query before loading any bodies". The test
prepares 200 half-MiB documents and later rewrites them. The same test
and server code are unchanged from `9f2039d`, where [the same shard
passed](https://github.com/paperclipai/paperclip/actions/runs/45558505382/job/139016469065)
and this test took 8.39 seconds. The intervening commit changes UI and
documentation only.

The exact failing case passes locally on the current head with `cd
server && pnpm exec vitest run
src/services/native-runtime/issue-document-batch.integration.test.ts -t
'rejects many large documents using a size-only query before loading any
bodies'` (one passed, 15 skipped). This shows local recovery; it does
not establish the cause of the CI timeout. A targeted shard rerun was
requested, but GitHub refused because the workflow is still running. No
test limits or product code have been changed to hide the failure. This
initial failure is retained here as evidence; the successful
second-attempt outcome is recorded below.

CI follow-up, second shard: [server shard
13/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948654)
failed `ai-connections.test.ts`, test "requires sign-in after the
receiver process dies with an exchanged but unsaved token". The first
attempt failed its wait for one token exchange and an advisory-lock
waiter within 25 seconds. The automatic retry failed earlier because the
first attempt had already inserted the fixed membership fixture. The
suite, receiver helper and AI connection service are unchanged by this
work. The [original PR head passed this
shard](https://github.com/paperclipai/paperclip/actions/runs/45544519067/job/138970880217),
with the same test taking 21.06 seconds.

The exact case passes locally on `45023e6` with `cd server && pnpm exec
vitest run src/__tests__/ai-connections.test.ts -t 'requires sign-in
after the receiver process dies with an exchanged but unsaved token'`
(one passed, 164 skipped). The cause of the missed CI wait remains
unconfirmed. This local pass does not clear the failed CI result.
Targeted reruns were initially blocked by GitHub while the workflow was
running. See the successful second-attempt outcome below.

CI recovery: [workflow attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45560174673/attempts/2)
completed successfully on unchanged head `45023e6`. Both previously
failed shards now pass. No source edits, timeout increases, or test
removals were needed. The original timeout and missed-wait causes remain
unconfirmed; the earlier failures and comparison evidence above are
preserved. Final acceptance uses the green current-head CI result
together with the local checks and 5/5 review.

Not run locally: repository-wide tests/builds or a live PostHog
recording. The tests exercise the masking callback and UI state, not the
externally loaded recorder.

After deployment, compare a masked replay with the work-content flag
unset against an opted-in eligible company. Then verify that
Google/Slack or a hidden source keeps the same surfaces masked. Restart
the server and reload open tabs after changing deployment environment
values.

## Risks

- The opt-in belongs to the host, not to the people who use the
deployment. Nothing in this pull request asks or tells a user. A host
that sets the flag must tell its users first. The plan for the hosted
service is in #23338.
- Enabling the new flag allows eligible work content to leave the
instance in replay data. Leave it unset or set it to `0` to keep work
content masked. No deployment or fleet policy is changed by this PR.
- The flag does not bypass company eligibility checks or secret masking.
Changing it affects future recording after the configuration reaches the
browser; it does not remove previously recorded content.
- Connection detection is a best effort. A custom MCP server with an
unrelated name and URL, or credentials used directly by an agent, can
carry Google or Slack data without appearing as a known source.
- Secret redaction is a best effort. Unknown or unlabeled secrets,
non-English labels, values on a later line or under a table header, and
values outside bounded line context can be missed. Some ordinary values
are over-masked.
- Source changes can race with recording until the live update arrives.
A missed update can extend that window to the five-minute refresh.
Connection count and list queries can disagree briefly and then mask
conservatively.
- Hidden drafts and aggregators can keep harmless content masked. Text
rendered during a source recheck stays masked until it renders again.
The first visible state adds a full recording snapshot.
- Task previews now inspect at most 2,048 source characters before
conversion. Very long markup can produce an incomplete summary.
Source-capped previews stay fully masked; opening the full task keeps
the normal work-content policy.
- Artifact card text previews stay masked in every company. Document
card previews and cut task previews mask when a credential sits at or
before the cut, so some replays show stars there while the full document
shows.
- Task titles, names and other previously visible surfaces remain
visible and can contain copied customer text. New work-content surfaces
must preserve company scoping.

## Model Used

- Original implementation: Anthropic Claude Opus 5.5 (`claude-opus-5-5`)
and Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with
shell, edits, tests and the original read-only exploration subagent.
- Deployment configuration follow-up: OpenAI `gpt-6.1-sol` through the
Codex, xhigh reasoning, shell, file edits and test tools. Context window
size is not exposed by the runtime. No additional subagents.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Dotta <bippadotta@protonmail.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 18:53:11 +00:00
1 parent 0abb7834f7
commit 5a9c06b315
45 files changed
+2329 -89

No files matched your search

+136 -4
View File
@@ -31,6 +31,7 @@ extensions posthog-js loads at run time (recorder, web vitals).
| `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. |
| `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED` | off | `1` allows task descriptions, document bodies and artifact contents in replays for eligible companies. Browser analytics and replay must also be on. Unset, `0` and all other values keep work content masked. |
| `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT` | `1024` | Proxy requests in flight for the whole server. See [Proxy limits](#proxy-limits). |
| `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT_PER_CLIENT` | `128` | Proxy requests in flight from one public client address. See [Proxy limits](#proxy-limits). |
@@ -41,6 +42,29 @@ For a customer whose contract forbids recording, set
analytics for a stack, unset `PAPERCLIP_POSTHOG_BROWSER_ENABLED`. Both take
effect on the next server restart.
### Work content opt-in
Work content stays masked by default, even when session replay is on. Hosts
can opt in through the deployment environment:
```sh
PAPERCLIP_POSTHOG_BROWSER_ENABLED=1
PAPERCLIP_POSTHOG_REPLAY_ENABLED=1
PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1
```
The existing Cloud instance and project-token requirements still apply. The
server sends the effective setting as
`browserAnalytics.replayWorkContentEnabled` in the authenticated session.
An older server that omits this field keeps work content masked. The UI makes
no work-content source requests unless both replay and this setting are on.
The opt-in allows the company checks below to run; it does not bypass them or
secret masking. To keep replay on with work content masked, remove
`PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED` or set it to `0`. Restart the
server and reload open board tabs to pick up deployment changes. Previously
recorded content is not changed by this setting.
## Consent
The per-browser EU/UK/Swiss consent banner and Profile opt-out switch are
@@ -198,8 +222,9 @@ organization-naming steps have no `step` value. No event carries free text.
## Privacy
Session replay shows text by default, the way PostHog normally works. Text is
masked only inside marked customer content. Input values and attribute values
are always masked.
masked only inside marked customer content, and inside work content unless the
deployment opts in and the company holds no Google or Slack data. Input values
and attribute values are always masked.
- Session replay masks every input value (`maskAllInputs`).
- Replay masks text only inside these markers (`ANALYTICS_MASK_TEXT_SELECTOR`
@@ -209,6 +234,9 @@ are always masked.
these elements entirely.
- `contenteditable` editors (not `contenteditable="false"`).
- `ANALYTICS_WORK_CONTENT_CLASS` (`ph-work-content`): work content, see
below.
rrweb masks a text node only when its parent matches the selector or has an
ancestor that matches it. All other text, for example navigation, headings,
buttons, task titles, agent names, project names and company names, is
@@ -220,10 +248,113 @@ are always masked.
element references (`id`, `for`, `aria-labelledby`) are always masked, so
images record as empty boxes and link targets (for example download links
with file paths) never leave.
- Work content shows in replays only when the deployment sets
`PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1` and the company holds no
Google or Slack data. Work content is the task description (task page and the
first bubble of the task chat), the task preview description, document bodies,
attachment and artifact previews (text, tables, patches, markdown) and the
file viewer. Task titles, artifact titles and file names were already
recorded as they are. Comments, chat messages, run output and every
connected-account surface stay customer content and always mask.
- `ReplayWorkContentVisibility`
(`ui/src/lib/analytics/replay-work-content.tsx`) sets
`data-replay-work-content="visible"` on `<html>` only when the company's
tool connections and chat endpoints both hold a confirmed answer and none
of them, in any status, is Google (Gmail, Drive, Calendar, Docs and the
other Workspace services), Slack, an aggregator (Composio, Arcade,
Executor) or an app that reaches Google or Slack through another service
(Zapier, Make, GSC Wizard, Windsor.ai). Aggregators and these apps are
found by catalog slug, by server host and by name, because "Connect your
own MCP server" saves a URL and a free name with no slug. Slack chat
channels are found by `config.provider`, because a removed channel's
endpoint is archived (and leaves the endpoint list) while its connection
row stays with a custom name.
- The connection list must be complete. `GET
/api/companies/:companyId/tools/connections` leaves some rows out of a
board reader's list: another person's draft connection (a Google or Slack
connection returns to draft when its sign-in expires) and a connector
whose plugin is unavailable. The response reports how many as
`hiddenCount`. A hidden row can be Google or Slack, so the check counts
only a list with `hiddenCount: 0`. An older server sends no count, which
also keeps work content masked.
- The flag is the selected company's answer, so it applies only to that
company's content. The selection follows the URL in an effect after the
page renders, and a manual switch delays it, so the check also needs the
URL's company prefix to be the selected company's (`routeShowsCompany`).
A task preview loads a task by id and can show another company's task:
`IssueQuicklookCard` uses the work content marker only when the task's
`companyId` is the selected company (`workContentClassForCompany`), and
masks any other. Task previews convert at most 2,048 source characters to
plain text, then limit the summary to 180 characters. When the source cap
applies, the preview always masks: a cut source can contain incomplete
credential text. When only the 180-character limit applies, the preview
masks if the text before the cut holds anything the replay redaction
masks, because a credential that crosses the cut is too short to match
its format. Opening the full task still uses the normal work-content
rule.
- A surface that shows cut or rewritten work content cannot rely on the
redaction, because a cut credential is too short to match its format and
a rewrite can remove the separator the format needs. The document card
preview shows the first 4,000 characters and masks when that cut changes
what the redaction masks before it (`cutKeepsRedaction`). The text
preview on an artifact card always masks: the server strips hyphens and
underscores from it and cuts it at 280 characters
(`normalizePreviewText`), and the board never sees the source.
- A missing or disabled deployment opt-in, loading, a failed latest fetch
(even with an older answer cached), a list that waits on a refresh, no
company and replay off all keep work content masked. The check keeps its
own query keys (`replayWorkContentQueryKeys`)
and drops an answer when the company changes.
- `LiveUpdatesProvider` resets the check on every activity in a connection
family (`tool_connection.*`, `tool_app.*`, `tool_example.*`,
`tool_application.*`, `connection_installs.*`, `ai_connection.*`,
`chat_endpoint.*`, `chat_github.*`, `email_endpoint.*`) and on
`company.imported`, so work content masks at once and stays masked until
the lists reload. Several routes add a connection row and some build the
action name at run time, so a new action in these families re-checks
without a code change. A new family needs an entry in
`SOURCE_CHANGE_FAMILIES`. Six frequent actions that cannot add a source
are left out (`NOT_A_SOURCE_CHANGE`: health and catalog checks,
credential reads and refreshes, incoming webhooks). The live socket
closes while the tab is hidden, so the provider invalidates active
queries when the tab returns or the socket reopens, and an invalidated
list does not count until it reloads. A five-minute refetch covers a
missed live update.
- `maskReplayText` (the rrweb `maskTextFn`) shows work content text only
when the nearest marker around it is the work content marker, so customer
content, secrets and editors inside work content stay masked.
- Shown work content still passes through `redactReplaySecrets`. It masks
known key and token formats (OpenAI, Anthropic, GitHub, Slack, AWS,
Google, JWTs, private key blocks), the value of a `label: value` or
`name=value` assignment whose label says secret (`API_KEY`, `API key`,
`password`, `DB_PASS`, a name that ends in `key`), secret command-line
flags (`--password value`; a token that starts with `--` is the next
flag, not a value), auth header credentials, URL passwords and
long mixed-case random tokens. rrweb records one text node at a time, so
the function also reads the text before the node on its line: a bold
label, a value in inline code, a value with bold or italic text inside it
and a value split across syntax-highlight spans are masked. A private key
that the file viewer or a highlighter renders line by line is masked on
every line up to its closing marker. A value runs to its closing quote or
the end of its line inside the element it starts in, so the sentence
after an inline `KEY=value` still shows. It is a best
effort. Labels are matched in English. It does not catch a secret with no
label and no known format (a short password in a sentence, a lowercase
hex key), a value on a different line from its label, or a value in a
table cell under a header.
- rrweb decides masking when it records a node, so the page calls
`refreshSessionReplay` (a new full snapshot) the first time work content
becomes visible for a company. Text that renders while a later re-check
runs stays masked until it renders again.
- The task chat container carries no mask of its own. Each header, row, live
tail, notice and the composer carry `ANALYTICS_MASK_CLASS`, and the
description row carries `ANALYTICS_WORK_CONTENT_CLASS`
(`TaskChatThreadView` `replayMask`).
- The masking options in `posthog.init` take precedence over the PostHog
project's "Privacy and masking" settings (posthog-js 1.450). posthog-js
ignores the project setting and logs a warning when the two differ. Keep the
project masking settings empty, and change masking only in `privacy.ts`. The
project masking settings empty. Use deployment configuration for work
content visibility and `privacy.ts` for the masking rules. The
`ph-mask` class is also the posthog-js default `maskTextClass`.
- `ANALYTICS_NO_CAPTURE_CLASS` replaces secrets with a blank box in replays:
every password-type `Input`, environment variable values, new secret
@@ -247,7 +378,8 @@ are always masked.
surfaces below, and other free-form text that agents or customers write,
carry `ANALYTICS_MASK_CLASS` on their content element (not on the chrome
around it):
- Rendered markdown (task bodies, comments, chat messages, documents), the
- Rendered markdown (comments, chat messages; task descriptions and
documents are work content, above), the
rich editor, task and issue chat threads (messages, tool calls, tool
results, interaction cards), the comment timeline and the file viewer.
- Link preview cards, task quicklook descriptions, external object pills and
+21
View File
@@ -5,6 +5,27 @@ summary: Remove a connection or one of its grants, cancel a first sign-in, read
Removing a connection or a grant always completes in Paperclip. The response says what happened at the provider when Paperclip can ask the provider to end access.
## List Connections
```
GET /api/companies/{companyId}/tools/connections
```
The caller needs company access and `connections:read`. The `200` response has
a `connections` array containing the connections visible to the caller.
For board users, the response also has `hiddenCount`, a nonnegative integer
that counts company connections omitted from the array. This includes another
user's draft connection and connections whose plugin is unavailable. A zero
count means the response did not omit any connection at the time of the check.
Agent responses do not include this field.
Older servers can omit `hiddenCount`. An absent count means completeness is
unknown; callers must not treat it as zero. In particular, the session replay
source check keeps work content masked when the count is missing or positive.
The count and the connection list are separate queries, so concurrent changes
can temporarily make them differ.
## Remove a Connection
```
@@ -102,6 +102,24 @@ describe("currentUserProfileSchema", () => {
});
describe("authSessionSchema", () => {
it.each([undefined, false, true])("preserves the replay work content setting across session parsing: %s", (enabled) => {
const result = authSessionSchema.parse({
session: { id: "s1", userId: "u1" },
user: { id: "u1", email: "a@b.com", name: "Jane", image: null },
sentryDsn: null,
browserAnalytics: {
token: "phc_test",
apiHost: "/_ph",
uiHost: null,
environment: "test",
stackId: "stack-1",
replayEnabled: true,
...(enabled === undefined ? {} : { replayWorkContentEnabled: enabled }),
},
});
expect(result.browserAnalytics?.replayWorkContentEnabled).toBe(enabled);
});
it("parses a session where user name is empty string (identity provider without a name)", () => {
const result = authSessionSchema.safeParse({
session: { id: "s1", userId: "u1" },
+1
View File
@@ -234,6 +234,7 @@ export const browserAnalyticsConfigSchema = z.object({
environment: z.string().min(1),
stackId: z.string().min(1),
replayEnabled: z.boolean(),
replayWorkContentEnabled: z.boolean().optional(),
consentRequired: z.boolean().nullable().optional(),
cloudTrialInferenceEnabled: z.boolean().optional(),
});
+7
View File
@@ -115,6 +115,7 @@ describe("auth routes", () => {
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "stack-1");
vi.stubEnv("PAPERCLIP_POSTHOG_PROJECT_TOKEN", "phc_test");
vi.stubEnv("PAPERCLIP_POSTHOG_BROWSER_ENABLED", undefined);
vi.stubEnv("PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED", undefined);
const off = await request(createApp(actor, baseUser)).get("/api/auth/get-session");
expect(off.status).toBe(200);
@@ -131,10 +132,16 @@ describe("auth routes", () => {
environment: "staging",
stackId: "stack-1",
replayEnabled: true,
replayWorkContentEnabled: false,
consentRequired: false,
cloudTrialInferenceEnabled: false,
});
vi.stubEnv("PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED", "1");
const workContentOn = await request(createApp(actor, baseUser)).get("/api/auth/get-session");
expect(workContentOn.status).toBe(200);
expect(workContentOn.body.browserAnalytics.replayWorkContentEnabled).toBe(true);
vi.stubEnv("PAPERCLIP_POSTHOG_COUNTRY_HEADER", "cf-ipcountry");
const eu = await request(createApp(actor, baseUser)).get("/api/auth/get-session").set("CF-IPCountry", "FR");
expect(eu.body.browserAnalytics.consentRequired).toBe(false);
@@ -49,11 +49,18 @@ describe("browser analytics config exposure", () => {
environment: "production",
stackId: "stack-1",
replayEnabled,
replayWorkContentEnabled: false,
consentRequired: false,
cloudTrialInferenceEnabled: false,
});
});
it("exposes the deployment's work content opt-in only while replay is on", () => {
const env = { ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED: "1" };
expect(resolveBrowserAnalyticsConfig(env)?.replayWorkContentEnabled).toBe(true);
expect(resolveBrowserAnalyticsConfig({ ...env, PAPERCLIP_POSTHOG_REPLAY_ENABLED: "0" })?.replayWorkContentEnabled).toBe(false);
});
it("never requires consent regardless of edge country headers", () => {
const on = { ...CLOUD, ...TOKEN, ...BROWSER };
const withHeader = { ...on, PAPERCLIP_POSTHOG_COUNTRY_HEADER: "CF-IPCountry" };
@@ -30,6 +30,7 @@ describe("resolveCloudPostHogConfig", () => {
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
});
});
@@ -100,4 +101,27 @@ describe("resolveCloudPostHogConfig", () => {
),
).toBe(false);
});
it.each([undefined, "", "0", "true", "invalid", "1", " 1 "])(
"requires an explicit work content opt-in: %s",
(value) => {
const config = resolveCloudPostHogConfig({
...CLOUD,
PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1",
PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED: value,
});
expect(config?.replayEnabled).toBe(true);
expect(config?.replayWorkContentEnabled).toBe(value?.trim() === "1");
},
);
it("cannot enable work content without browser analytics and replay", () => {
const env = { ...CLOUD, PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED: "1" };
expect(resolveCloudPostHogConfig(env)?.replayWorkContentEnabled).toBe(false);
expect(resolveCloudPostHogConfig({
...env,
PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1",
PAPERCLIP_POSTHOG_REPLAY_ENABLED: "0",
})?.replayWorkContentEnabled).toBe(false);
});
});
@@ -183,6 +183,7 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{ factory: async () => fakeClient },
@@ -259,6 +260,7 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{ factory: () => factoryPromise },
@@ -359,6 +359,7 @@ describe("cloud-trial-inference", () => {
directEnabled: true,
browserEnabled: true,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
},
{
@@ -10,6 +10,7 @@ const config: CloudPostHogConfig = {
directEnabled: true,
browserEnabled: false,
replayEnabled: false,
replayWorkContentEnabled: false,
cloudTrialInferenceEnabled: false,
};
@@ -19597,6 +19597,8 @@ describeEmbeddedPostgres("tool access service", () => {
expect(memberRes.body.connections).not.toEqual(
expect.arrayContaining([expect.objectContaining({ id: otherDraft.id })]),
);
// The member's list is incomplete, and the response says so.
expect(memberRes.body.hiddenCount).toBe(1);
const ownerApp = createRouteApp(
db,
@@ -19612,6 +19614,7 @@ describeEmbeddedPostgres("tool access service", () => {
expect.objectContaining({ id: activeConnection.id }),
]),
);
expect(ownerRes.body.hiddenCount).toBe(0);
});
it("keeps direct profile and policy mutation routes viewer-safe", async () => {
+10 -1
View File
@@ -1975,7 +1975,16 @@ function connectorEnrollmentPrincipal(req: Request): string {
}, { mutation: false, readContext: connectionRequestContext(req) })));
visible = visible.filter((_, index) => allowed[index].allowed);
}
res.json({ connections: visible });
if (req.actor.type !== "board") {
res.json({ connections: visible });
return;
}
// How many of the company's connections this response leaves out: another
// person's draft, or a connector whose plugin is unavailable. A board
// reader that must know every source (the session replay privacy check)
// treats any hidden row as unknown.
const total = await svc.countConnections(companyId);
res.json({ connections: visible, hiddenCount: Math.max(0, total - visible.length) });
});
router.post("/companies/:companyId/tools/connections", managementGuard("connections:configure", "POST /companies/:companyId/tools/connections", { personal: true }), validate(createToolConnectionSchema), async (req, res) => {
@@ -67,6 +67,7 @@ export function resolveBrowserAnalyticsConfig(
environment: config.environment ?? (isCloudStagingInstance(env) ? "staging" : "production"),
stackId: config.stackId,
replayEnabled: config.replayEnabled,
replayWorkContentEnabled: config.replayWorkContentEnabled,
// Consent banner is disabled during private beta; sending false also keeps
// any cached older UI bundle from prompting during rollout.
consentRequired: false,
+4 -1
View File
@@ -47,6 +47,7 @@ export type CloudPostHogConfig = {
directEnabled: boolean; // PAPERCLIP_POSTHOG_DIRECT !== "0"
browserEnabled: boolean; // PAPERCLIP_POSTHOG_BROWSER_ENABLED === "1"
replayEnabled: boolean; // browserEnabled && PAPERCLIP_POSTHOG_REPLAY_ENABLED !== "0"
replayWorkContentEnabled: boolean;
cloudTrialInferenceEnabled: boolean; // PAPERCLIP_MANAGED_CONFIG.features.enableCloudTrialInference
};
@@ -66,6 +67,7 @@ export function resolveCloudPostHogConfig(
if (!token || !stackId) return null;
const browserEnabled = readEnv(env, "PAPERCLIP_POSTHOG_BROWSER_ENABLED") === "1";
const replayEnabled = browserEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_ENABLED") !== "0";
return {
token,
host: (readEnv(env, "PAPERCLIP_POSTHOG_HOST") ?? DEFAULT_CLOUD_POSTHOG_HOST).replace(/\/+$/, ""),
@@ -73,7 +75,8 @@ export function resolveCloudPostHogConfig(
stackId,
directEnabled: readEnv(env, "PAPERCLIP_POSTHOG_DIRECT") !== "0",
browserEnabled,
replayEnabled: browserEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_ENABLED") !== "0",
replayEnabled,
replayWorkContentEnabled: replayEnabled && readEnv(env, "PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED") === "1",
cloudTrialInferenceEnabled: resolveCloudTrialInferenceEnabled(env),
};
}
+14
View File
@@ -4882,6 +4882,20 @@ export function toolAccessService(
return connections;
},
/**
* Every tool connection row of the company, including the rows
* `listConnections` leaves out (a connector whose plugin is unavailable).
* The list route reports the difference, so a reader can tell a complete
* list from a filtered one.
*/
countConnections: async (companyId: string): Promise<number> => {
const [row] = await db
.select({ total: sql<number>`count(*)::int` })
.from(toolConnections)
.where(eq(toolConnections.companyId, companyId));
return row?.total ?? 0;
},
createConnection: async (
companyId: string,
input: CreateToolConnection,
@@ -495,8 +495,8 @@
"packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d",
"packages/shared/src/upstream-failure-codes.test.ts": "b4a12899b8daa13b4a015945f21ead45a1f36a2a",
"packages/shared/src/upstream-failure-codes.ts": "da13407180aa18d5bb20c8dfc1d3b48538bd71d0",
"packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1",
"packages/shared/src/validators/access.ts": "efd12471a885dcdcae575dc73445f8bbbd06b889",
"packages/shared/src/validators/access.test.ts": "121d9f1e0bd1715ba3c5d1ff1016d38898d06afa",
"packages/shared/src/validators/access.ts": "85c63826b522027847cd22531ead9efc40008950",
"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",
+9 -1
View File
@@ -86,7 +86,15 @@ import { api, detachInflightGet, type RequestOptions } from "./client";
*/
export type ToolApplicationsResponse = { applications: ToolApplication[] };
export type ToolConnectionsResponse = { connections: ToolConnection[] };
export type ToolConnectionsResponse = {
connections: ToolConnection[];
/**
* How many of the company's connections the server left out of
* `connections` for this board reader: another person's draft, or a
* connector whose plugin is unavailable. Absent from an older server.
*/
hiddenCount?: number;
};
export type ToolCatalogResponse = { catalog: ToolCatalogEntry[] };
export type ToolRuntimeSlotsResponse = { runtimeSlots: ToolRuntimeSlot[] };
export type ToolRuntimeHealthResponse = ToolRuntimeHealthSummary;
+1 -1
View File
@@ -65,7 +65,7 @@ export function DocumentMarkdownBody({ documentKey, revisionId, documentIssueId,
return (
<div ref={containerRef}>
<MarkdownBody {...props} documentIssueId={documentIssueId} onImageClick={openImage} />
<MarkdownBody replayContent="work" {...props} documentIssueId={documentIssueId} onImageClick={openImage} />
<ImageGalleryModal
items={items}
initialIndex={(image ?? 1) - 1}
+5 -5
View File
@@ -40,7 +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 { ANALYTICS_WORK_CONTENT_CLASS } from "@/lib/analytics/privacy";
import { fileResourcesApi } from "@/api/file-resources";
import { ApiError } from "@/api/client";
import { queryViewKind } from "@/components/QueryView";
@@ -354,9 +354,9 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM
role="region"
aria-label={`${resource.title} source`}
tabIndex={0}
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)}
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_WORK_CONTENT_CLASS)}
>
<pre className={cn("m-0 font-mono text-xs leading-5", ANALYTICS_MASK_CLASS)}>
<pre className={cn("m-0 font-mono text-xs leading-5", ANALYTICS_WORK_CONTENT_CLASS)}>
{lines.map((lineText, index) => {
const lineNumber = index + 1;
const isHighlighted = lineNumber === highlightedLine;
@@ -406,7 +406,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM
}
return (
<div className={cn("relative flex min-h-0 flex-1 flex-col", ANALYTICS_MASK_CLASS)}>
<div className={cn("relative flex min-h-0 flex-1 flex-col", ANALYTICS_WORK_CONTENT_CLASS)}>
{previewMode === undefined && <div className="absolute right-3 top-3 z-20">
<div
role="group"
@@ -455,7 +455,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM
tabIndex={0}
className="flex-1 overflow-auto bg-background p-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
>
<WorkspaceFileMarkdownBody softBreaks={false}>
<WorkspaceFileMarkdownBody softBreaks={false} replayContent="work">
{content.content.data}
</WorkspaceFileMarkdownBody>
</div>
+5
View File
@@ -12,6 +12,8 @@ import { FoldCurtain } from "./FoldCurtain";
interface InlineEditorProps {
value: string;
/** Session replay treatment of the rendered markdown (see `MarkdownBody`). Editing always masks. */
replayContent?: "customer" | "work";
onSave: (value: string) => void | Promise<unknown>;
as?: "h1" | "h2" | "p" | "span";
className?: string;
@@ -96,6 +98,7 @@ function OwnedInlineEditor({
draftKey,
readCurrentValue,
draftOwner,
replayContent,
}: InlineEditorProps & { draftOwner: string | undefined }) {
const [editing, setEditing] = useState(false);
const editingChangeCallback = useRef(onEditingChange);
@@ -433,6 +436,7 @@ function OwnedInlineEditor({
<MarkdownBody
className={cn("paperclip-edit-in-place-content", className)}
externalReferences={externalReferences}
replayContent={replayContent}
>
{previewValue}
</MarkdownBody>
@@ -441,6 +445,7 @@ function OwnedInlineEditor({
<MarkdownBody
className={cn("paperclip-edit-in-place-content", className)}
externalReferences={externalReferences}
replayContent={replayContent}
>
{previewValue}
</MarkdownBody>
@@ -148,7 +148,7 @@ function MarkdownAttachmentCard({
<p className="px-1 py-2 text-xs text-destructive">Could not load markdown preview.</p>
) : (
<FoldCurtain>
<MarkdownBody className="paperclip-edit-in-place-content min-h-(--sz-220px) text-sm leading-7" softBreaks={false}>
<MarkdownBody replayContent="work" className="paperclip-edit-in-place-content min-h-(--sz-220px) text-sm leading-7" softBreaks={false}>
{data ?? ""}
</MarkdownBody>
</FoldCurtain>
+30 -11
View File
@@ -16,7 +16,9 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { StatusGlyph } from "@/components/StatusGlyph";
import { ProjectTile } from "@/components/ProjectTile";
import { useFlyoutAppearance } from "@/components/ui/flyout-appearance";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { ANALYTICS_MASK_CLASS, redactReplaySecrets, workContentClassForCompany } from "@/lib/analytics/privacy";
import { useOptionalCompany } from "@/context/CompanyContext";
import { markdownToPlainText } from "@/lib/markdown-plain-text";
/* ------------------------------------------------------------------ */
/* Single-flight quicklook store */
@@ -96,6 +98,8 @@ export function quicklookAlignOffset(align: "start" | "center" | "end" = "start"
}
export type IssueQuicklookIssue = Pick<Issue, "id" | "title" | "updatedAt"> & {
/** The task's company. Session replay shows the description only for the selected company's own task. */
companyId?: string | null;
identifier?: string | null;
status: string;
priority: string;
@@ -107,17 +111,23 @@ export type IssueQuicklookIssue = Pick<Issue, "id" | "title" | "updatedAt"> & {
originId?: string | null;
};
const SUMMARY_SOURCE_LIMIT = 2_048;
function summarizeIssueDescription(description: string | null | undefined) {
if (!description) return null;
const summary = description
.replace(/!\[[^\]]*]\([^)]+\)/g, " ")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/[#>*_`~-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
const plain = markdownToPlainText(description.slice(0, SUMMARY_SOURCE_LIMIT));
if (!summary) return null;
return summary.length > 180 ? `${summary.slice(0, 177).trimEnd()}...` : summary;
if (!plain) return null;
const sourceCut = description.length > SUMMARY_SOURCE_LIMIT;
const cut = sourceCut || plain.length > 180;
return {
text: cut ? `${plain.slice(0, 177).trimEnd()}...` : plain,
// A cut can leave the start of a credential, too short to match its
// format. So a cut preview masks in session replay when its source was
// capped, or when the text before the cut holds anything the replay
// redaction masks.
maskInReplay: sourceCut || (cut && redactReplaySecrets(plain) !== plain),
};
}
/** "·" between facts in the quicklook's meta and status lines. */
@@ -172,7 +182,9 @@ export function IssueQuicklookCard({
compact?: boolean;
}) {
const appearance = useFlyoutAppearance();
const description = useMemo(() => summarizeIssueDescription(issue.description), [issue.description]);
const selectedCompanyId = useOptionalCompany()?.selectedCompanyId;
const summary = useMemo(() => summarizeIssueDescription(issue.description), [issue.description]);
const description = summary?.text;
const projectName = issue.project?.name;
return (
@@ -212,7 +224,14 @@ export function IssueQuicklookCard({
</RouterDom.Link>
{description ? (
<p data-slot="task-preview-description" className={cn("text-xs leading-5 text-muted-foreground [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:4] overflow-hidden", ANALYTICS_MASK_CLASS)}>
<p data-slot="task-preview-description" className={cn("text-xs leading-5 text-muted-foreground [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:4] overflow-hidden",
// A preview loads a task by id, so it can show another company's task
// than the selected one. Only the selected company's own task is work
// content in session replay; any other always masks.
summary?.maskInReplay
? ANALYTICS_MASK_CLASS
: workContentClassForCompany(issue.companyId, selectedCompanyId),
)}>
{description}
</p>
) : null}
+12 -3
View File
@@ -16,7 +16,7 @@ import { buildDocumentAnnotationHash, parseDocumentAnnotationHash } from "@/lib/
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 { ANALYTICS_MASK_CLASS, ANALYTICS_WORK_CONTENT_CLASS } from "@/lib/analytics/privacy";
import { MarkdownUrlLink } from "./MarkdownUrlLink";
import { recognizeLinkPreview, type LinkPreviewState } from "@paperclipai/shared";
import { Link, useCaseHref } from "@/lib/router";
@@ -151,6 +151,13 @@ interface MarkdownBodyProps {
* openable, so the markdown re-parses with the new answers.
*/
resolveWorkspaceFileRef?: WorkspaceFileRefResolver;
/**
* How session replay treats this text. `customer` (default) always masks.
* `work` is for task descriptions, document bodies and artifact contents:
* it shows only when the company holds no Google or Slack data
* (`ANALYTICS_WORK_CONTENT_CLASS`).
*/
replayContent?: "customer" | "work";
}
let mermaidLoaderPromise: Promise<typeof import("mermaid").default> | null = null;
@@ -841,6 +848,7 @@ function MarkdownBodyImpl({
onImageClick,
mediaMode = "render",
resolveWorkspaceFileRef,
replayContent = "customer",
}: MarkdownBodyProps) {
const { theme } = useTheme();
const coordinator = useCoordinatorPresentation();
@@ -1111,8 +1119,9 @@ 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,
// Customer content always masks in session replay; work content masks
// unless the company holds no Google or Slack data. Autocapture skips both.
replayContent === "work" ? ANALYTICS_WORK_CONTENT_CLASS : ANALYTICS_MASK_CLASS,
className,
)}
style={mergeWrapStyle(style)}
+7 -6
View File
@@ -3399,15 +3399,15 @@ 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,
// No replay mask here: every child below carries its own, so the
// task description (work content) can show when allowed.
isMobile && !historyRevealed && "task-chat-history-pending",
)}
data-testid="task-chat-thread"
ref={historyShellRef}
>
{!historyRevealed ? (
<div className="absolute inset-0 z-10 overflow-hidden bg-background" data-testid="task-chat-history-loading">
<div className={cn("absolute inset-0 z-10 overflow-hidden bg-background", ANALYTICS_MASK_CLASS)} data-testid="task-chat-history-loading">
<TaskChatLoadingShell mobile={isMobile} streamlined={streamlinedUiEnabled} coordinator={coordinatorEnabled} />
</div>
) : null}
@@ -3420,7 +3420,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
{historyError || (historyPending && historyWaitExpired) ? (
<div
role="status"
className="absolute inset-x-0 top-0 z-20 mx-auto flex w-full max-w-(--tc-shell-max-w) items-center gap-2 border border-border bg-background px-4 py-2 text-sm text-muted-foreground"
className={cn("absolute inset-x-0 top-0 z-20 mx-auto flex w-full max-w-(--tc-shell-max-w) items-center gap-2 border border-border bg-background px-4 py-2 text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}
>
{historyError ? "Some task history could not be loaded." : "Some task history is still loading."}
{historyError ? (
@@ -3442,7 +3442,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
<>
{items.length === 0 && !tailRunId && !optimisticRunnerStartup && !scrollingHistory?.hasMore ? (
<div
className="min-h-0 flex-1 overflow-y-auto"
className={cn("min-h-0 flex-1 overflow-y-auto", ANALYTICS_MASK_CLASS)}
>
{threadHeaderWithBlockers || pendingQuestions.isError || decisionReceipts.isError || decisionReceipts.hasNextPage || taskHandoffs.isError || taskHandoffs.hasNextPage ? (
<div
@@ -3483,6 +3483,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
header={<>{threadHeaderWithBlockers}{!issueBrief ? historyControl : null}<CoordinatorChatQuestionStatus query={pendingQuestions} /><CoordinatorChatReceiptStatus query={decisionReceipts} scroll={!!scrollingHistory} /><CoordinatorChatHandoffStatus query={taskHandoffs} scroll={!!scrollingHistory} /></>}
renderInteraction={renderInteraction}
renderBrief={renderBrief}
replayMask
renderMessageActions={renderMessageActions}
renderQueuedAction={renderQueuedAction}
onTryAgainNoLiveExecutionPath={
@@ -3613,7 +3614,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
</div>
</div>
{assignedAgentForNotice?.status === "paused" && !isTerminalIssueStatus(issueStatus) ? (
<div className="mx-auto w-full max-w-(--tc-shell-max-w) px-4 pt-2">
<div className={cn("mx-auto w-full max-w-(--tc-shell-max-w) px-4 pt-2", ANALYTICS_MASK_CLASS)}>
<IssueAssigneePausedNotice
agent={assignedAgentForNotice}
issueStatus={issueStatus}
@@ -142,6 +142,10 @@ function TextPreview({ artifact }: { artifact: PreviewArtifact }) {
return (
<PreviewFrame className="bg-card">
<div className="absolute inset-0 overflow-hidden p-3">
{/* Always masked in session replay, even for a company whose work
content shows: the server strips hyphens and underscores from this
text and cuts it at 280 characters (`normalizePreviewText`), so a
credential in it no longer matches any format the redaction knows. */}
<p className={cn("max-h-full overflow-hidden whitespace-pre-wrap break-words text-base leading-6 text-muted-foreground/75", ANALYTICS_MASK_CLASS)}>
{preview}
</p>
@@ -1,6 +1,6 @@
import { isPatchFile } from "@/lib/patch";
import { PatchLines } from "@/components/PatchLines";
import { useState, type ReactNode } from "react";
import { useMemo, useState, type ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import {
ArrowRight,
@@ -31,7 +31,7 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { ANALYTICS_MASK_CLASS, ANALYTICS_WORK_CONTENT_CLASS, cutKeepsRedaction } from "@/lib/analytics/privacy";
import { cn } from "@/lib/utils";
// Renderers contain UI labels only. All artifact-specific content is passed in.
@@ -307,9 +307,9 @@ export function CommitCard(props: CommitCardProps) {
);
}
function Markdown({ body, preview = false }: { body: string; preview?: boolean }) {
function Markdown({ body, preview = false, replayMask = false }: { body: string; preview?: boolean; replayMask?: boolean }) {
return (
<div className={cn("flex flex-col gap-3 text-sm leading-relaxed", ANALYTICS_MASK_CLASS)}>
<div className={cn("flex flex-col gap-3 text-sm leading-relaxed", replayMask ? ANALYTICS_MASK_CLASS : ANALYTICS_WORK_CONTENT_CLASS)}>
<ReactMarkdown
components={{
pre: ({ children }) => <pre className={preview
@@ -386,13 +386,20 @@ export interface DocumentCardProps extends ArtifactIdentity {
expanded?: boolean;
actions?: ReactNode;
}
/** How much of a document the card preview renders. */
const DOCUMENT_PREVIEW_LENGTH = 4000;
export function DocumentCard(props: DocumentCardProps) {
const patch = props.patch ?? isPatchFile(props.filename);
const content = (body: string, preview = false) => patch
? <pre className={cn(ANALYTICS_MASK_CLASS, preview
// The preview cuts the body, and a cut can leave the start of a credential,
// too short to match its format. Session replay masks the preview when the
// cut changes what the redaction masks before it.
const maskPreview = useMemo(() => !cutKeepsRedaction(props.body, DOCUMENT_PREVIEW_LENGTH), [props.body]);
const content = (body: string, preview = false, replayMask = false) => patch
? <pre className={cn(preview
? "paperclip-patch-preview m-0 min-w-0 overflow-hidden whitespace-pre font-mono text-xs leading-5"
: "m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-xs leading-5", ANALYTICS_MASK_CLASS)}><code><PatchLines text={body} /></code></pre>
: <Markdown body={body} preview={preview} />;
: "m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-xs leading-5", replayMask ? ANALYTICS_MASK_CLASS : ANALYTICS_WORK_CONTENT_CLASS)}><code><PatchLines text={body} /></code></pre>
: <Markdown body={body} preview={preview} replayMask={replayMask} />;
return (
<Card>
{props.body && (
@@ -400,7 +407,7 @@ export function DocumentCard(props: DocumentCardProps) {
className="max-h-52 overflow-hidden border-b border-border bg-muted/20 p-5"
inert
>
{content(props.body.slice(0, 4000), true)}
{content(props.body.slice(0, DOCUMENT_PREVIEW_LENGTH), true, maskPreview)}
</div>
)}
<div className="flex flex-col gap-3 p-5">
@@ -454,7 +461,7 @@ export interface DataCardProps extends ArtifactIdentity {
function DataTable({ columns, rows }: Pick<DataCardProps, "columns" | "rows">) {
return (
<div className="overflow-x-auto">
<table className={cn("w-full text-left text-xs", ANALYTICS_MASK_CLASS)}>
<table className={cn("w-full text-left text-xs", ANALYTICS_WORK_CONTENT_CLASS)}>
<thead>
<tr>
{columns.map((column, i) => (
@@ -227,7 +227,7 @@ function MarkdownWorkProductRow({
onPanelOpenChange={setAnnotationPanelOpen}
panelPlacement="popover"
>
<MarkdownBody>{reviewDoc.body}</MarkdownBody>
<MarkdownBody replayContent="work">{reviewDoc.body}</MarkdownBody>
</IssueDocumentAnnotations>
) : (
<p className="text-sm text-muted-foreground">Document is empty.</p>
@@ -409,7 +409,7 @@ function DocumentRow({
onPanelOpenChange={setAnnotationPanelOpen}
panelPlacement="popover"
>
<MarkdownBody>{doc.body}</MarkdownBody>
<MarkdownBody replayContent="work">{doc.body}</MarkdownBody>
</IssueDocumentAnnotations>
) : (
<p className="text-sm text-muted-foreground">Document is empty.</p>
@@ -1,5 +1,6 @@
import { useLayoutEffect, useRef, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
interface TaskChatComposerDockProps {
children: ReactNode;
@@ -53,6 +54,9 @@ export function TaskChatComposerDock({ children, mobile, streamlined, concealed
aria-hidden={concealed || placeholder || undefined}
className={cn(
"task-chat-composer-dock flex max-w-(--tc-shell-max-w) shrink-0 flex-col gap-2",
// Customer content (queued messages, turn status, drafts): masked in
// session replay. The task chat container itself carries no mask.
ANALYTICS_MASK_CLASS,
concealed && "invisible",
mobile
? cn("w-auto px-1 pb-1", streamlined ? "-mx-2" : "mx-2")
@@ -156,6 +156,7 @@ export function TaskChatDescriptionBubble({ brief }: TaskChatDescriptionBubblePr
softBreaks
linkIssueReferences
externalReferences={brief.externalReferences}
replayContent="work"
>
{brief.description}
</MarkdownBody>
@@ -0,0 +1,50 @@
// @vitest-environment jsdom
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it } from "vitest";
import { REPLAY_WORK_CONTENT_ATTRIBUTE } from "@/lib/analytics/privacy";
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
import { TaskChatThreadView } from "./TaskChatThreadView";
import type { TaskChatItem } from "./task-chat-model";
const items: TaskChatItem[] = [
{ id: "brief", kind: "brief" },
{ id: "failed", kind: "marker", variant: "interrupted", label: "Pulled the Globex inbox thread" },
];
function render(replayMask: boolean) {
document.body.innerHTML = renderToStaticMarkup(
<TaskChatThreadView
items={items}
scroll={false}
replayMask={replayMask}
header={<p>Header from Slack</p>}
renderBrief={() => <p>Ship the Q3 launch plan</p>}
tail={<p>Live tail output</p>}
/>,
);
}
describe("TaskChatThreadView session replay", () => {
afterEach(() => {
document.body.innerHTML = "";
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
});
it("masks every row, the header and the tail, and masks the description by default", () => {
render(true);
expect(replayLeaks("Ship the Q3 launch plan")).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Pulled the Globex inbox thread")).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Header from Slack")).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Live tail output")).toEqual({ rendered: true, recorded: false });
});
it("shows only the description when the company holds no Google or Slack data", () => {
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
render(true);
expect(replayLeaks("Ship the Q3 launch plan")).toEqual({ rendered: true, recorded: true });
expect(replayLeaks("Pulled the Globex inbox thread")).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Header from Slack")).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Live tail output")).toEqual({ rendered: true, recorded: false });
});
});
@@ -10,6 +10,7 @@ import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion";
import { afterVisibleConversationPaint, useVisibleWelcomeEntry, type WelcomeAnimation } from "@/lib/onboarding-chat";
import type { IssueAttachment } from "@paperclipai/shared";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS, ANALYTICS_WORK_CONTENT_CLASS } from "@/lib/analytics/privacy";
import { useStreamlinedTaskChatPresentation } from "./presentation-mode";
import type {
TaskChatInteractionItem,
@@ -67,6 +68,13 @@ interface TaskChatThreadViewProps {
* nothing without it.
*/
renderBrief?: () => ReactNode;
/**
* Session replay: mask every header, item and tail row, except the brief
* (the task description), which is work content and shows only when the
* company holds no Google or Slack data. The live thread sets it because
* its own container carries no mask.
*/
replayMask?: boolean;
/**
* Renders the copy/👍/👎 action cluster prepended to an agent bubble's footer
* line (PAP-413). The live thread binds it to the feedback-vote API; harness
@@ -370,6 +378,7 @@ export function TaskChatThreadView({
onRuntimeRequestDecision,
renderInteraction,
renderBrief,
replayMask = false,
renderMessageActions,
renderQueuedAction,
onTryAgainNoLiveExecutionPath,
@@ -418,6 +427,9 @@ export function TaskChatThreadView({
retryableMarkerId, onRetryFailedRun, retryFailedRunId, attachments, onOpenSkill, onOpenBrowser,
);
};
const replayClass = (item: TaskChatItem) => replayMask
? (item.kind === "brief" ? ANALYTICS_WORK_CONTENT_CLASS : ANALYTICS_MASK_CLASS)
: undefined;
const renderedItems = streamlined
? visibleItems.map((item) => ({ item, content: renderVisibleItem(item) }))
.filter((entry) => entry.content !== null)
@@ -435,9 +447,12 @@ export function TaskChatThreadView({
item.kind === "message" ? (item.renderKey ?? item.id) : item.id
}
id={item.kind === "message" ? `comment-${item.id}` : undefined}
className={taskChatItemSpacingClass(
item,
renderedItems[index - 1]?.item ?? null,
className={cn(
taskChatItemSpacingClass(
item,
renderedItems[index - 1]?.item ?? null,
),
replayClass(item),
)}
data-thread-item-kind={
item.kind === "message" ? item.author : item.kind
@@ -461,6 +476,7 @@ export function TaskChatThreadView({
item.kind === "interaction" &&
item.interaction.status !== "pending" &&
"-mt-3",
replayClass(item),
)}
>
{renderVisibleItem(item)}
@@ -473,6 +489,7 @@ export function TaskChatThreadView({
renderInteraction, renderBrief, renderMessageActions, renderQueuedAction, onboardingWelcomeAnimation, historyVisible,
onTryAgainNoLiveExecutionPath, tryAgainNoLiveExecutionPathPending,
retryableMarkerId, onRetryFailedRun, retryFailedRunId, attachments, onOpenSkill, onOpenBrowser,
replayMask,
]);
const body = (
<div
@@ -484,14 +501,14 @@ export function TaskChatThreadView({
>
{header ? (
<div
className={cn("flex flex-col gap-6", streamlined ? "pb-4" : "pb-2")}
className={cn("flex flex-col gap-6", streamlined ? "pb-4" : "pb-2", replayMask && ANALYTICS_MASK_CLASS)}
data-testid="task-chat-thread-header"
>
{header}
</div>
) : null}
{history}
{tail ? <div data-conversation-typography="" className={streamlined ? "mt-4" : undefined}>{tail}</div> : null}
{tail ? <div data-conversation-typography="" className={cn(streamlined && "mt-4", replayMask && ANALYTICS_MASK_CLASS)}>{tail}</div> : null}
</div>
);
@@ -16,7 +16,7 @@ import { attachmentDownloadPath, isMarkdownAttachment, isTextAttachment } from "
import { queryKeys } from "@/lib/queryKeys";
import { readTextPreview, TEXT_PREVIEW_MAX_BYTES } from "@/lib/text-preview";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { ANALYTICS_WORK_CONTENT_CLASS } from "@/lib/analytics/privacy";
import { cn } from "@/lib/utils";
export { readTextPreview, TEXT_PREVIEW_MAX_BYTES } from "@/lib/text-preview";
@@ -42,13 +42,13 @@ export function TextAttachmentPreview({ title, text, markdown, html = false, csv
<a href={downloadUrl} download aria-label={`Download ${title}`} title={`Download ${title}`}><Download aria-hidden /></a>
</Button>
</header>
<div className={cn(renderHtml || renderCsv ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 min-w-0 flex-1 overflow-auto p-4", ANALYTICS_MASK_CLASS)}>
<div className={cn(renderHtml || renderCsv ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 min-w-0 flex-1 overflow-auto p-4", ANALYTICS_WORK_CONTENT_CLASS)}>
{text.length === 0 ? <p className="text-sm text-muted-foreground">File is empty.</p>
: renderCsv ? <CsvPreview text={text} title={title} />
: renderHtml ? <HtmlArtifactPreview html={text} title={title} />
: markdown && mode === "rendered" ? <MarkdownBody mediaMode="reference">{text}</MarkdownBody>
: patch ? <pre className={cn("paperclip-patch-source m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_MASK_CLASS)} aria-label={`${title} patch`}><code><PatchLines text={text} /></code></pre>
: <pre className={cn("whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_MASK_CLASS)} aria-label={`${title} raw text`}>{text}</pre>}
: markdown && mode === "rendered" ? <MarkdownBody mediaMode="reference" replayContent="work">{text}</MarkdownBody>
: patch ? <pre className={cn("paperclip-patch-source m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_WORK_CONTENT_CLASS)} aria-label={`${title} patch`}><code><PatchLines text={text} /></code></pre>
: <pre className={cn("whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_WORK_CONTENT_CLASS)} aria-label={`${title} raw text`}>{text}</pre>}
</div>
</div>
);
+25 -1
View File
@@ -14,6 +14,7 @@ import { describe, expect, it, vi } from "vitest";
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { __liveUpdatesTestUtils } from "./LiveUpdatesProvider";
import { queryKeys } from "../lib/queryKeys";
import { replayWorkContentQueryKeys } from "../lib/analytics/replay-work-content";
describe("LiveUpdatesProvider issue invalidation", () => {
it("discovers first proactive deliveries without invalidating another human's chat list", () => {
@@ -46,6 +47,28 @@ describe("LiveUpdatesProvider issue invalidation", () => {
}
client.clear();
});
it.each([
["tool_connection.created", true],
["tool_app.oauth_connected", true],
["tool_connection.machine_sign_in_created", true],
["ai_connection.connected", true],
["chat_endpoint.created", true],
["tool_connection.health_check", false],
] as const)("masks session replay work content until sources reload after %s", (action, resets) => {
const client = new QueryClient();
const connections = replayWorkContentQueryKeys.connections("company-1");
const endpoints = replayWorkContentQueryKeys.chatEndpoints("company-1");
client.setQueryData(connections, { connections: [] });
client.setQueryData(endpoints, []);
__liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", {
entityType: "tool_connection", entityId: "connection-1", action,
}, { userId: "user-1", agentId: null });
// A reset drops the cached "no Google or Slack" answer, so the check
// reads as unknown (masked) until the lists load again.
expect(client.getQueryData(connections) === undefined).toBe(resets);
expect(client.getQueryData(endpoints) === undefined).toBe(resets);
client.clear();
});
it("refreshes cached tasks whose relation summaries embed a changed blocker", () => {
const client = new QueryClient();
const blocker = { id: "blocker-uuid", identifier: "PAP-3808", title: "Blocker", status: "blocked" };
@@ -281,7 +304,8 @@ describe("LiveUpdatesProvider issue invalidation", () => {
"refreshes company AI account previews after %s", (action) => {
const invalidateQueries = vi.fn();
__liveUpdatesTestUtils.invalidateActivityQueries(
{ invalidateQueries, getQueryData: () => undefined, getQueryCache: () => ({ findAll: () => [] }) } as never,
// `ai_connection.*` also resets the session replay source check.
{ invalidateQueries, resetQueries: vi.fn(), getQueryData: () => undefined, getQueryCache: () => ({ findAll: () => [] }) } as never,
"company-1", { entityType: "connection_grant", entityId: "grant-1", action },
{ userId: "owner", agentId: null },
);
+8
View File
@@ -60,6 +60,7 @@ import {
} from "../lib/optimistic-issue-runs";
import { useConnectivityStore } from "../lib/connectivity";
import { queryKeys } from "../lib/queryKeys";
import { isReplayWorkContentSourceChange, replayWorkContentQueryKeys } from "../lib/analytics/replay-work-content";
import { extractCompanyPrefixFromPath, toCompanyRelativePath } from "../lib/company-routes";
import { useLocation } from "../lib/router";
import { agentRouteRef } from "../lib/utils";
@@ -1656,6 +1657,13 @@ function invalidateActivityQueries(
queryClient.invalidateQueries({ queryKey: ["ai-connections", companyId] });
}
if (isReplayWorkContentSourceChange(action)) {
// A new Google or Slack source must mask session replay at once: the reset
// drops the cached lists, so work content stays masked until they reload.
void queryClient.resetQueries({ queryKey: replayWorkContentQueryKeys.connections(companyId) });
void queryClient.resetQueries({ queryKey: replayWorkContentQueryKeys.chatEndpoints(companyId) });
}
if (action?.startsWith("primary_agent.") || action?.startsWith("agent.") || action?.startsWith("resource_membership.")) {
queryClient.invalidateQueries({ queryKey: ["primary-agent", companyId] });
}
+595 -6
View File
@@ -2,8 +2,10 @@
//
// Session replay shows text by default and masks ALL input values. Text is
// masked only inside customer content marked with `ANALYTICS_MASK_CLASS`,
// inside secrets marked with `ANALYTICS_NO_CAPTURE_CLASS` (blocked entirely)
// and inside editable content. Autocapture never records element text or
// inside secrets marked with `ANALYTICS_NO_CAPTURE_CLASS` (blocked entirely),
// inside editable content, and inside work content marked with
// `ANALYTICS_WORK_CONTENT_CLASS` unless the company holds no Google or Slack
// data. 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`
@@ -13,8 +15,9 @@
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
/**
* Customer content: task and issue bodies, comments, chat messages, documents,
* artifacts and connected-account data. Session replay masks its text, and
* Customer content: comments, chat messages, run output, connected-account
* data and anything else that is not work content (see
* `ANALYTICS_WORK_CONTENT_CLASS`). Session replay always masks its text, and
* autocapture records nothing from inside it.
*/
export const ANALYTICS_MASK_CLASS = "ph-mask ph-sensitive";
@@ -26,12 +29,598 @@ export const ANALYTICS_MASK_CLASS = "ph-mask ph-sensitive";
*/
export const ANALYTICS_NO_CAPTURE_CLASS = "ph-no-capture";
/** Session replay masks text only inside these markers. */
export const ANALYTICS_MASK_TEXT_SELECTOR = [
/**
* Work content: task descriptions, document bodies and artifact contents.
* Secrets inside it stay masked (`redactReplaySecrets`). Session replay masks
* all of it unless the page says the active company holds no Google or Slack
* data (`REPLAY_WORK_CONTENT_ATTRIBUTE` on `<html>`, set by
* `ReplayWorkContentVisibility`). Agents copy connected-account content into
* these surfaces, and our privacy policy and the Google API Limited Use rules
* say no person may read that content in a replay.
*
* A strict marker inside work content still wins: `ANALYTICS_MASK_CLASS`,
* `ANALYTICS_NO_CAPTURE_CLASS` and editors stay masked (see `maskReplayText`).
*/
export const ANALYTICS_WORK_CONTENT_CLASS = "ph-work-content";
/** `<html>` attribute that shows work content in replays when set to `"visible"`. */
export const REPLAY_WORK_CONTENT_ATTRIBUTE = "data-replay-work-content";
/**
* The marker for work content that is loaded by id and so may belong to
* another company than the selected one (a task preview on a link). The
* page's visible flag is the selected company's answer, so only that
* company's content may use the work content marker. Content of another
* company, or of an unknown one, is customer content and always masks.
*/
export function workContentClassForCompany(
contentCompanyId: string | null | undefined,
selectedCompanyId: string | null | undefined,
): string {
return contentCompanyId && contentCompanyId === selectedCompanyId ? ANALYTICS_WORK_CONTENT_CLASS : ANALYTICS_MASK_CLASS;
}
/** Markers that always mask, wherever they sit. */
const STRICT_MASK_SELECTOR = [
...ANALYTICS_MASK_CLASS.split(" "),
ANALYTICS_NO_CAPTURE_CLASS,
].map((name) => `.${name}`).concat("[contenteditable]:not([contenteditable=\"false\"])").join(", ");
/**
* Session replay masks text only inside these markers. Work content is in the
* selector too, so it fails closed: `maskReplayText` decides whether it shows.
*/
export const ANALYTICS_MASK_TEXT_SELECTOR = `${STRICT_MASK_SELECTOR}, .${ANALYTICS_WORK_CONTENT_CLASS}`;
/** True when the page has confirmed that work content may show in replays. */
export function replayWorkContentVisible(doc: Document | null | undefined = globalThis.document): boolean {
return doc?.documentElement?.getAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE) === "visible";
}
function maskCharacters(text: string): string {
return text.replace(/\S/g, "*");
}
/**
* Words that say a label names a secret, anywhere in the label (`API_KEY`,
* `dbPassword`, `Client secret`).
*/
const SECRET_NAME_WORD = /api[-_ ]?key|access[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|token|secret|passw(?:or)?d|passwd|passphrase|pwd|credentials?|private[-_ ]?key|client[-_ ]?secret|session[-_ ]?id|cookie|connection[-_ ]?string|dsn|jwt|bearer/i;
/**
* Words that say secret only as the last word of a label: `ENCRYPTION_KEY`,
* `signingKey`, `Key`, `DB_PASS`, `auth`, `PIN`. Elsewhere they are ordinary
* words ("Key findings: ...", "Pass rate: 98%").
*/
const SECRET_NAME_END = /keys?$|(?:^|[^a-z])(?:pass|auth|pin|otp)$/i;
function labelNamesSecret(label: string): boolean {
return SECRET_NAME_WORD.test(label) || SECRET_NAME_END.test(label);
}
/**
* A label and its assignment operator: `NAME=`, `name: `, `"name": `,
* `name := `, `name => `, `API key: `, `**Password**: `. The label is the
* last one to four words before the operator. It starts only at the start of
* a word and each word is one character class, so it stays linear on long
* input.
*/
const ASSIGNMENT_START = /(?<![A-Za-z0-9_.-])((?:[A-Za-z0-9_.-]+[ \t]){0,3}[A-Za-z0-9_.-]+)["'`*]{0,3}[ \t]*(?::=|=>|[:=])[ \t]*/g;
const QUOTES = new Set(['"', "'", "`"]);
function isLineBreak(char: string | undefined): boolean {
return char === "\n" || char === "\r";
}
/**
* The value that starts at `index`, as the range to mask and the index after
* it. A quoted value runs to its closing quote (escaped quotes included) or
* the end of the line; an unquoted value runs to the end of the line, as in
* YAML. There is no length limit, so a long secret leaves no readable tail.
*/
function secretValueRange(text: string, index: number): { from: number; to: number; end: number } {
const quote = text[index];
if (quote !== undefined && QUOTES.has(quote)) {
let cursor = index + 1;
while (cursor < text.length && !isLineBreak(text[cursor])) {
if (text[cursor] === "\\") {
cursor += 2;
continue;
}
if (text[cursor] === quote) return { from: index + 1, to: cursor, end: cursor + 1 };
cursor += 1;
}
const to = Math.min(cursor, text.length);
return { from: index + 1, to, end: to };
}
let cursor = index;
while (cursor < text.length && !isLineBreak(text[cursor])) cursor += 1;
return { from: index, to: cursor, end: cursor };
}
/**
* Masks the whole value of every `name: value` / `name=value` /
* `"name": "value"` assignment whose label says secret, so
* `password="correct horse battery staple"` masks in full while the next JSON
* field and a preceding `user=bob` still show.
*
* `nodeStart` and `continues` are for text that follows other text on its
* line (see `redactReplaySecrets`). A value that began before `nodeStart`
* masks on through this node in two cases: it is quoted and still open (up to
* its closing quote, so `Password: "correct **horse** battery"` masks every
* word while the text after the closing quote shows), or `continues` says an
* unquoted value runs into this node. Otherwise the value is left to the
* node it began in. The scan then goes on from the text after its operator,
* so a later label in the earlier text (`KEY=abc and password: `) still
* masks this node.
*/
function redactSecretAssignments(text: string, nodeStart: number, continues: (offset: number) => boolean): string {
const pattern = new RegExp(ASSIGNMENT_START.source, "g");
let result = "";
let copied = 0;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
if (!labelNamesSecret(match[1] ?? "")) continue;
const valueStart = match.index + match[0].length;
const range = secretValueRange(text, valueStart);
if (range.from < nodeStart) {
const quoted = range.from === valueStart + 1;
const runsOn = range.to > nodeStart && (quoted || continues(range.from));
if (!runsOn) {
// A closed quoted value has a known end. An unquoted one does not, so
// read on inside it: that can only find more to mask.
if (quoted) pattern.lastIndex = Math.max(pattern.lastIndex, range.end);
continue;
}
}
if (range.to > range.from) {
result += text.slice(copied, range.from) + maskCharacters(text.slice(range.from, range.to));
copied = range.to;
}
pattern.lastIndex = Math.max(range.end, pattern.lastIndex);
}
return copied === 0 ? text : result + text.slice(copied);
}
/**
* A command-line flag whose name says secret, with its value after a space:
* `--password hunter2`, `--api-key "a b"`, `--db_password x`.
* (`--password=hunter2` is an assignment.) A flag name says secret by the
* same words as an assignment label (`labelNamesSecret`), so `--api_key`,
* `--access_key`, `--private-key`, `--key` and `--auth` count too. A quoted
* value runs to its closing quote, past escaped quotes
* (`"correct \"horse\" battery"`), or to the end of the line. An unquoted
* token that starts with `--` is the next flag, never a value: a flag such as
* `--auth` can stand alone, and the flag after it may be the secret one.
*/
function redactSecretFlags(text: string): string {
const names = /--[A-Za-z0-9_-]*/g;
const values = /"(?:\\[^\n\r]?|[^"\\\n\r])*"?|'(?:\\[^\n\r]?|[^'\\\n\r])*'?|\S+/y;
let result = "";
let copied = 0;
let match: RegExpExecArray | null;
while ((match = names.exec(text)) !== null) {
if (!labelNamesSecret(match[0].slice(2))) continue;
let valueStart = names.lastIndex;
while (text[valueStart] === " " || text[valueStart] === "\t") valueStart += 1;
if (valueStart === names.lastIndex) continue;
values.lastIndex = valueStart;
const value = values.exec(text);
if (!value) continue;
// The next flag is not this flag's value: `--auth --password hunter2`
// must still reach `--password`. The scan goes on from the end of this
// name, so that flag is judged next.
if (value[0].startsWith("--")) continue;
result += text.slice(copied, valueStart) + maskCharacters(value[0]);
copied = values.lastIndex;
names.lastIndex = copied;
}
return copied === 0 ? text : result + text.slice(copied);
}
/** `Authorization: Bearer x`, `Basic x`, `Token x`: the credential is masked. */
const AUTH_SCHEME = /(\b(?:Bearer|Basic|Token)\s+)([A-Za-z0-9._~+/=-]{8,})/g;
/** Credentials inside a URL (`scheme://user:password@host`). */
const URL_USERINFO = /([a-z][a-z0-9+.-]{0,31}:\/\/)([^\s/@:]+:[^\s/@]+)(@)/gi;
/** Well-known credential formats, masked wherever they appear. */
const KNOWN_TOKEN = new RegExp(
[
String.raw`\b(?:sk|rk|pk)[-_](?:live|test|ant|proj|or)?[-_]?[A-Za-z0-9_-]{16,}`,
String.raw`\bgh[pousr]_[A-Za-z0-9]{20,}`,
String.raw`\bgithub_pat_[A-Za-z0-9_]{20,}`,
String.raw`\bglpat-[A-Za-z0-9_-]{16,}`,
String.raw`\bxox[abposr]-[A-Za-z0-9-]{10,}`,
String.raw`\b(?:AKIA|ASIA)[0-9A-Z]{16}\b`,
String.raw`\bAIza[0-9A-Za-z_-]{30,}`,
String.raw`\bya29\.[0-9A-Za-z_-]{20,}`,
String.raw`\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`,
String.raw`-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----|$)`,
].join("|"),
"g",
);
/**
* A long run of mixed-case letters and digits, such as a pasted API key in an
* unknown format. Hex hashes and UUIDs have no uppercase letters, so they show.
*/
const RANDOM_TOKEN = /[A-Za-z0-9+/_=-]{32,}/g;
function looksRandom(token: string): boolean {
return /[a-z]/.test(token) && /[A-Z]/.test(token) && /[0-9]/.test(token);
}
/** Two redactions of `text` as one: a character is masked when either masks it. */
function mergeMasks(text: string, first: string, second: string): string {
if (first === second) return first;
let merged = "";
for (let index = 0; index < text.length; index += 1) {
merged += first[index] === text[index] ? second[index] : first[index];
}
return merged;
}
/** Every redaction keeps the text length, so a slice of the result lines up with the input. */
function redactSecretsInLine(text: string, nodeStart: number, continues: (offset: number) => boolean): string {
return redactSecretFlags(redactSecretAssignments(text.replace(KNOWN_TOKEN, maskCharacters), nodeStart, continues))
.replace(AUTH_SCHEME, (_match, scheme: string, value: string) => `${scheme}${maskCharacters(value)}`)
.replace(URL_USERINFO, (_match, scheme: string, userinfo: string, at: string) => `${scheme}${maskCharacters(userinfo)}${at}`)
.replace(RANDOM_TOKEN, (token) => (looksRandom(token) ? maskCharacters(token) : token));
}
/** Text around a text node on its line, for `redactReplaySecrets`. */
export type ReplayLineContext = {
/** The text before the node on the same line. */
before: string;
/** The rest of the current non-whitespace token after the node on the same line. */
after?: string;
/**
* Whether a secret value that starts at this offset of `before` runs on
* into the node. A value runs to the end of its line (or its closing quote)
* inside the element it starts in: `Password: "correct **horse** battery"`
* masks all three nodes, while the sentence after an inline
* `KEY=value` still shows.
*/
continues: (offset: number) => boolean;
};
const never = () => false;
/**
* Masks secrets inside text that is otherwise shown in replays: known key and
* token formats, `name=value` assignments whose label says secret, secret
* command-line flags, auth header credentials, URL passwords, private key
* blocks and long random-looking tokens. Work content can hold a pasted key
* (a config file, a task description), and the board's no-capture marker only
* covers fields it renders as secrets.
*
* rrweb records one text node at a time, and Markdown and syntax highlighting
* split a line into several nodes (`**Password:** hunter2`, a value in inline
* code, a value with bold text inside, `postgres://admin:**pa55word**@host`).
* `context` carries the text before the node on its line and the rest of its
* token after it, so a label, an unfinished value, or a URL credential split
* across nodes still masks this one. Context only adds masking: whatever the
* text masks by itself stays masked.
*/
export function redactReplaySecrets(text: string, context?: ReplayLineContext): string {
const alone = redactSecretsInLine(text, 0, never);
const before = context?.before ?? "";
const after = context?.after ?? "";
if (!before && !after) return alone;
const inLine = redactSecretsInLine(
before + text + after,
before.length,
context?.continues ?? never,
).slice(before.length, before.length + text.length);
return mergeMasks(text, alone, inLine);
}
/** How much text before a node is read for its label, and how many nodes back. */
const LINE_CONTEXT_MAX_LENGTH = 256;
const LINE_CONTEXT_MAX_NODES = 64;
const MAX_CONTEXT_CANDIDATES = 16;
/** Elements that start a new line, so text before them is not on this line. */
const LINE_BREAK_TAGS = new Set([
"ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "BR", "DD", "DETAILS", "DIV", "DL", "DT", "FIGURE", "FOOTER",
"FORM", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HR", "LI", "MAIN", "NAV", "OL", "P", "PRE", "SECTION",
"SUMMARY", "TABLE", "TBODY", "TD", "TFOOT", "TH", "THEAD", "TR", "UL",
]);
const ELEMENT_NODE = 1;
const TEXT_NODE = 3;
function startsNewLine(node: Node): boolean {
return node.nodeType === ELEMENT_NODE && LINE_BREAK_TAGS.has(node.nodeName.toUpperCase());
}
/** Decoration that is not part of the line's text, such as a line-number gutter. */
function isHiddenFromText(node: Node): boolean {
return node.nodeType === ELEMENT_NODE && (node as Element).getAttribute("aria-hidden") === "true";
}
/** The first child that counts as text of the line, skipping decoration. */
function firstTextChild(node: Node): Node | null {
let child = node.firstChild;
while (child && isHiddenFromText(child)) child = child.nextSibling;
return child;
}
/** The last child that counts as text of the line, skipping decoration. */
function lastTextChild(node: Node): Node | null {
let child = node.lastChild;
while (child && isHiddenFromText(child)) child = child.previousSibling;
return child;
}
/** The text before a node on its line, and the text node each part came from. */
type LineBefore = { text: string; parts: Array<{ end: number; node: Text }> };
/**
* The text before `node` on its line inside `root`: earlier text nodes, back
* to a line break, a block element or `root`. Bounded, so recording a long
* line stays linear.
*/
function lineBefore(node: Text, root: Element): LineBefore {
const found: Array<{ data: string; node: Text }> = [];
let length = 0;
let current: Node = node;
for (let visited = 0; visited < LINE_CONTEXT_MAX_NODES && length < LINE_CONTEXT_MAX_LENGTH; visited += 1) {
let previous: Node | null = current.previousSibling;
if (!previous) {
const parent = current.parentNode;
if (!parent || parent === root || startsNewLine(parent)) break;
current = parent;
continue;
}
current = previous;
if (isHiddenFromText(previous)) continue;
if (startsNewLine(previous)) break;
let reachedBlock = false;
for (let child = lastTextChild(previous); child; child = lastTextChild(previous)) {
previous = child;
if (startsNewLine(previous)) {
reachedBlock = true;
break;
}
}
if (reachedBlock) break;
current = previous;
if (previous.nodeType !== TEXT_NODE) continue;
const data = (previous as Text).data;
const lineBreak = Math.max(data.lastIndexOf("\n"), data.lastIndexOf("\r"));
const onLine = lineBreak >= 0 ? data.slice(lineBreak + 1) : data;
found.unshift({ data: onLine, node: previous as Text });
length += onLine.length;
if (lineBreak >= 0) break;
}
// Keep the end of the line when it is longer than the limit.
const dropped = Math.max(0, length - LINE_CONTEXT_MAX_LENGTH);
let end = -dropped;
const parts = found.map((part) => {
end += part.data.length;
return { end, node: part.node };
});
return { text: found.map((part) => part.data).join("").slice(dropped), parts };
}
/**
* The rest of the current non-whitespace token after `node` on its line inside
* `root`: later text nodes up to whitespace, a block element, or `root`.
* Bounded, so recording a long line stays linear while split URL credentials
* (such as `postgres://admin:**pa55word**@db.internal`) still see `@`.
*/
function lineAfter(node: Text, root: Element): string {
const found: string[] = [];
let length = 0;
let current: Node = node;
for (let visited = 0; visited < LINE_CONTEXT_MAX_NODES && length < LINE_CONTEXT_MAX_LENGTH; visited += 1) {
let next: Node | null = current.nextSibling;
if (!next) {
const parent = current.parentNode;
if (!parent || parent === root || startsNewLine(parent)) break;
current = parent;
continue;
}
current = next;
if (isHiddenFromText(next)) continue;
if (startsNewLine(next)) break;
let reachedBlock = false;
for (let child = firstTextChild(next); child; child = firstTextChild(next)) {
next = child;
if (startsNewLine(next)) {
reachedBlock = true;
break;
}
}
if (reachedBlock) break;
current = next;
if (next.nodeType !== TEXT_NODE) continue;
const data = (next as Text).data;
const space = data.search(/\s/);
const onToken = space >= 0 ? data.slice(0, space) : data;
found.push(onToken);
length += onToken.length;
if (space >= 0) break;
}
return found.join("").slice(0, LINE_CONTEXT_MAX_LENGTH);
}
/**
* Lookups that hold for one synchronous run of the recorder (a full snapshot,
* or one batch of mutations). The DOM cannot change inside such a run, so
* each parent's text children are indexed once and each key-block answer is
* reused by the next line. A microtask drops them before the page can change.
*/
type RecordingPass = {
textChildren: WeakMap<Element, Map<string, Text[]>>;
inPrivateKey: WeakMap<Text, boolean>;
};
let recordingPass: RecordingPass | null = null;
function currentRecordingPass(): RecordingPass {
if (!recordingPass) {
recordingPass = { textChildren: new WeakMap(), inPrivateKey: new WeakMap() };
queueMicrotask(() => {
recordingPass = null;
});
}
return recordingPass;
}
/**
* The child text nodes of `parent` that hold exactly `text`. rrweb passes the
* text and its parent element, not the node. The index is built once per
* parent and pass, so a paragraph with thousands of text children stays
* linear.
*/
function textChildrenWith(parent: Element, text: string): Text[] {
const pass = currentRecordingPass();
let byText = pass.textChildren.get(parent);
if (!byText) {
byText = new Map();
for (let child = parent.firstChild; child; child = child.nextSibling) {
if (child.nodeType !== TEXT_NODE) continue;
const data = (child as Text).data;
const same = byText.get(data);
if (same) same.push(child as Text);
else byText.set(data, [child as Text]);
}
pass.textChildren.set(parent, byText);
}
return byText.get(text) ?? [];
}
/** The end of an opening or closing marker (`-----BEGIN RSA PRIVATE KEY-----`, PGP's `PRIVATE KEY BLOCK-----`). */
const PRIVATE_KEY_MARKER = /PRIVATE KEY(?: BLOCK)?-----/;
const PRIVATE_KEY_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
/** Text that can be part of a private key body: base64 and line breaks only. */
const KEY_BODY_TEXT = /^[A-Za-z0-9+/=\s]+$/;
/** A PEM header line between the opening marker and the body. */
const KEY_HEADER_LINE = /^[A-Za-z-]+: \S+$/;
/** A key body is at most a few dozen lines; each line is one or two nodes. */
const PRIVATE_KEY_MAX_NODES = 200;
/** Zero-width spaces stand in for empty lines in the file viewer. */
function visibleText(data: string): string {
return data.replace(/\u200b/g, "").trim();
}
/**
* The length of the start of `text` that can be the rest of a private key
* body: everything before a closing marker, or all of it, when that part is
* base64 only. Zero when the text cannot continue a key.
*/
function keyBodyPrefixLength(text: string): number {
const end = text.search(PRIVATE_KEY_END);
const body = end >= 0 ? text.slice(0, end) : text;
return visibleText(body) && KEY_BODY_TEXT.test(body) ? body.length : 0;
}
/**
* True when `node` sits inside a private key block that opened in an earlier
* node of `root`. The file viewer and syntax highlighting put each line of a
* key in its own node, so only the opening line matches the key format by
* itself. Reads back through key body text, header lines and blank lines to
* the nearest marker, and stops at anything else.
*/
function insidePrivateKeyBlock(node: Text, root: Element): boolean {
const pass = currentRecordingPass();
const walker = root.ownerDocument.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
walker.currentNode = node;
let inside = false;
for (let visited = 0; visited < PRIVATE_KEY_MAX_NODES; visited += 1) {
const previous = walker.previousNode() as Text | null;
if (!previous) break;
if (previous.parentElement && isHiddenFromText(previous.parentElement)) continue;
const data = previous.data;
if (PRIVATE_KEY_MARKER.test(data)) {
inside = data.lastIndexOf("-----BEGIN ") > data.lastIndexOf("-----END ");
break;
}
const line = visibleText(data);
if (!line) continue;
// The line before was answered in this pass: the same answer holds here.
const known = pass.inPrivateKey.get(previous);
if (known !== undefined) {
inside = known;
break;
}
if (!KEY_BODY_TEXT.test(line) && !KEY_HEADER_LINE.test(line)) break;
}
pass.inPrivateKey.set(node, inside);
return inside;
}
/**
* Redacts the text of a shown work content node with its line context.
* rrweb passes the text and its parent element, not the node, so every child
* text node with this text is a candidate and a character is masked when any
* candidate masks it.
*/
function redactWorkContentText(text: string, parent: HTMLElement, root: Element): string {
if (!/\S/.test(text)) return text;
// Preformatted text: a line is one statement, so a value runs to its end.
const preformatted = parent.closest("pre") !== null;
const keyBodyLength = keyBodyPrefixLength(text);
let result = redactReplaySecrets(text);
const candidates = textChildrenWith(parent, text);
// Many identical siblings: do not read context for each, mask the text.
if (candidates.length > MAX_CONTEXT_CANDIDATES) return maskCharacters(text);
for (const child of candidates) {
if (keyBodyLength > 0 && insidePrivateKeyBlock(child, root)) {
result = mergeMasks(text, result, maskCharacters(text.slice(0, keyBodyLength)) + text.slice(keyBodyLength));
}
const line = lineBefore(child, root);
const after = /\s$/.test(text) ? "" : lineAfter(child, root);
if (!line.text && !after) continue;
// Elsewhere a value runs on only inside the element it starts in.
const continues = (offset: number) => preformatted
|| (line.parts.find((part) => offset < part.end)?.node.parentNode?.contains(child) ?? false);
result = mergeMasks(text, result, redactReplaySecrets(text, { before: line.text, after, continues }));
}
return result;
}
/**
* True when showing only the first `shown` characters of `text` leaves the
* redaction of that part unchanged. A surface that cuts work content (a
* preview of the first 4,000 characters) can cut a credential in two, and the
* part left is too short to match its format. When the cut changes what is
* masked before it, the surface must use `ANALYTICS_MASK_CLASS`.
*/
export function cutKeepsRedaction(text: string, shown: number): boolean {
if (text.length <= shown) return true;
return redactReplaySecrets(text).slice(0, shown) === redactReplaySecrets(text.slice(0, shown));
}
/**
* Session replay `maskTextFn`. rrweb calls it only for text inside
* `ANALYTICS_MASK_TEXT_SELECTOR`. The nearest marker decides: work content
* shows when the page allows it, with secrets inside it still masked
* (`redactReplaySecrets`), and every other marker masks. Whitespace stays, so
* the layout stays readable.
*/
export function maskReplayText(text: string, element?: HTMLElement | null): string {
const nearest = element?.closest?.(ANALYTICS_MASK_TEXT_SELECTOR);
if (
element
&& nearest
&& nearest.classList.contains(ANALYTICS_WORK_CONTENT_CLASS)
&& !nearest.matches(STRICT_MASK_SELECTOR)
&& replayWorkContentVisible(nearest.ownerDocument)
) {
return redactWorkContentText(text, element, nearest);
}
return maskCharacters(text);
}
/**
* Attributes that only describe layout, state or structure. Every other
* attribute (title, alt, aria-label, placeholder, value, src, href, data-*,
@@ -144,9 +144,10 @@ describe("product analytics", () => {
tracing_headers: ["acme.paperclip.app"],
session_recording: { maskAllInputs: true, blockClass: "ph-no-capture" },
});
// Replay masks text only inside customer content, secrets and editable content.
expect(options.session_recording?.maskTextSelector).toBe(".ph-mask, .ph-sensitive, .ph-no-capture, [contenteditable]:not([contenteditable=\"false\"])");
expect(options.session_recording).not.toHaveProperty("maskTextFn");
// Replay masks text only inside customer content, secrets, editable content
// and work content; maskTextFn shows work content when the page allows it.
expect(options.session_recording?.maskTextSelector).toBe(".ph-mask, .ph-sensitive, .ph-no-capture, [contenteditable]:not([contenteditable=\"false\"]), .ph-work-content");
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);
+17
View File
@@ -27,6 +27,7 @@ import {
ANALYTICS_MASK_TEXT_SELECTOR,
ANALYTICS_NO_CAPTURE_CLASS,
maskReplayAttribute,
maskReplayText,
redactAnalyticsUrl,
} from "./privacy";
@@ -73,6 +74,7 @@ export type PostHogInitOptions = {
session_recording: {
maskAllInputs: boolean;
maskTextSelector: string;
maskTextFn: (text: string, element?: HTMLElement | null) => string;
maskAttributeFn: (name: string, value: string, element?: Element | null) => string;
blockClass: string;
};
@@ -182,6 +184,8 @@ export function buildPostHogInitOptions(
// Text shows; only marked customer content and secrets mask (privacy.ts).
maskAllInputs: true,
maskTextSelector: ANALYTICS_MASK_TEXT_SELECTOR,
// Shows work content only when the company holds no Google or Slack data.
maskTextFn: maskReplayText,
// Attributes too (title, aria-label, alt, src, ...): deny by default.
maskAttributeFn: maskReplayAttribute,
blockClass: ANALYTICS_NO_CAPTURE_CLASS,
@@ -339,6 +343,19 @@ export function startProductAnalytics(
});
}
/**
* Record the page again from a fresh snapshot. rrweb decides masking when it
* records a node, so text recorded masked stays masked until it re-renders.
* `ReplayWorkContentVisibility` calls this when work content becomes visible.
* It does nothing when replay is off or not loaded yet.
*/
export function refreshSessionReplay(): void {
const current = state;
if (!current?.client || !current.config.replayEnabled) return;
current.client.stopSessionRecording?.();
current.client.startSessionRecording?.();
}
/** Set (or clear, on sign-out) the signed-in user. Safe to call before posthog-js loads. */
export function setProductAnalyticsUser(user: ProductAnalyticsUser | null): void {
if (wantedUser && wantedUser.id !== user?.id && state) state.queued = [];
+222 -19
View File
@@ -6,6 +6,7 @@ import { act } from "react";
import { createRoot } from "react-dom/client";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
import type { ConnectionGrant, DocumentRevision } from "@paperclipai/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AccountQuotaPanels } from "@/components/AccountQuotaPanels";
@@ -20,9 +21,22 @@ import { RunInvocationCard } from "@/components/run-log/RunDetails";
import { ChatConversationList } from "@/pages/apps/chat/ChatConversationList";
import { VoiceTranscript } from "@/components/voice/VoiceTranscript";
import { RunTranscriptView } from "@/components/transcript/RunTranscriptView";
import { IssueQuicklookCard } from "@/components/IssueLinkQuicklook";
import { ArtifactPreview } from "@/components/artifacts/ArtifactCard";
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
import * as CompanyContext from "@/context/CompanyContext";
import * as MarkdownPlainText from "@/lib/markdown-plain-text";
import { buildPostHogInitOptions } from "./product-analytics";
import { ANALYTICS_MASK_CLASS, ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS } from "./privacy";
import { isBlockedFromReplay, replayLeaks } from "./replay-recording.test-utils";
import {
ANALYTICS_MASK_CLASS,
ANALYTICS_MASK_TEXT_SELECTOR,
ANALYTICS_NO_CAPTURE_CLASS,
ANALYTICS_WORK_CONTENT_CLASS,
REPLAY_WORK_CONTENT_ATTRIBUTE,
maskReplayText,
workContentClassForCompany,
} from "./privacy";
import { isBlockedFromReplay, recordedTextOf as recordedTextOfWith, replayLeaks, stars } from "./replay-recording.test-utils";
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
@@ -36,23 +50,47 @@ const options = buildPostHogInitOptions(
function recordedText(node: Text): string {
const parent = node.parentElement;
const masked = parent?.closest(options.session_recording.maskTextSelector) != null;
return masked ? node.data.replace(/\S/g, "*") : node.data;
// Like rrweb: text inside the selector goes through `maskTextFn`.
return masked ? options.session_recording.maskTextFn(node.data, parent) : node.data;
}
function recordedTextOf(html: string, text: string): string {
document.body.innerHTML = html;
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode as Text;
if (node.data.includes(text)) return recordedText(node);
}
throw new Error(`text not rendered: ${text}`);
// Through the options PostHog gets, so these cases also cover that wiring.
const recordedTextOf = (html: string, text: string) => recordedTextOfWith(html, text, recordedText);
function renderTaskPreview(description: string): string {
return renderToStaticMarkup(
<MemoryRouter>
<IssueQuicklookCard
issue={{
id: "task-1", companyId: "co-1", title: "Review access", status: "todo",
priority: "medium", updatedAt: new Date(0), description,
}}
linkTo="/ACME/issues/ACME-1"
/>
</MemoryRouter>,
);
}
/**
* Work content: masked unless the company holds no Google or Slack data
* (`ANALYTICS_WORK_CONTENT_CLASS`). Task descriptions, document bodies and
* artifact contents.
*/
const WORK_CONTENT_SURFACES: Array<{ file: string; content: string }> = [
{ file: "components/IssueLinkQuicklook.tsx", content: "data-slot=\"task-preview-description\"" },
{ file: "components/task-side-panel/TaskAttachmentPanel.tsx", content: "File is empty." },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "<PatchLines text={body} />" },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "<ReactMarkdown" },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "{columns.map(" },
{ file: "components/FileViewerSheet.tsx", content: "{lines.map(" },
];
const MASKED_SURFACES: Array<{ file: string; content: string }> = [
// The server strips hyphens and underscores from this text and cuts it at
// 280 characters, so the board cannot find a credential in it.
{ file: "components/artifacts/ArtifactCard.tsx", content: "{preview}" },
{ file: "components/LinkPreview.tsx", content: "{preview.title}" },
{ file: "components/LinkPreview.tsx", content: "{target.canonicalUrl}" },
{ file: "components/IssueLinkQuicklook.tsx", content: "data-slot=\"task-preview-description\"" },
{ file: "components/ExternalObjectPill.tsx", content: "{valueLabel}" },
{ file: "components/ExternalObjectPill.tsx", content: "{labelText}" },
{ file: "components/issue-properties/external-object-rows.tsx", content: "{displayKey}</span>" },
@@ -147,11 +185,6 @@ const MASKED_SURFACES: Array<{ file: string; content: string }> = [
{ file: "pages/CaseDetail.tsx", content: "{caseData.summary}" },
{ file: "pages/CaseDetail.tsx", content: "{files.map(" },
{ file: "components/CaseFieldsPanel.tsx", content: "aria-label=\"Case fields\"" },
{ file: "components/task-side-panel/TaskAttachmentPanel.tsx", content: "File is empty." },
{ file: "components/artifacts/ArtifactCard.tsx", content: "{preview}" },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "<PatchLines text={body} />" },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "<ReactMarkdown" },
{ file: "components/artifacts/RichArtifactCards.tsx", content: "{columns.map(" },
{ file: "components/AttentionQueueRow.tsx", content: "{detailLine}" },
{ file: "components/AttentionObligationEvidence.tsx", content: "{attentionEvidenceLabel(item, entry)}" },
{ file: "components/coordinator/NeedsYouCardKit.tsx", content: "{children}</p>" },
@@ -272,9 +305,158 @@ describe("session replay text masking", () => {
expect(recordedTextOf(`<div contenteditable="false"><p>Read only</p></div>`, "Read only")).toBe("Read only");
});
it("sends only the marker selector to session replay", () => {
it("masks work content unless the page allows it", () => {
const html = `<div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Ship the Q3 plan</p></div>`;
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("**** *** ** ****");
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("Ship the Q3 plan");
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "pending");
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("**** *** ** ****");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("keeps strict markers inside visible work content masked", () => {
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const work = (inner: string) => `<div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Plan <span>${inner}</span></p></div>`;
expect(recordedTextOf(work(`</span><span class="${ANALYTICS_MASK_CLASS}">ana@acme.com`), "ana@acme.com")).toBe("************");
expect(recordedTextOf(work(`</span><span contenteditable="true">Draft`), "Draft")).toBe("*****");
expect(recordedTextOf(`<div class="${ANALYTICS_WORK_CONTENT_CLASS} ${ANALYTICS_MASK_CLASS}"><p>Both markers</p></div>`, "Both markers")).toBe("**** *******");
// A work row inside a masked container shows (the task chat description).
expect(recordedTextOf(`<div class="${ANALYTICS_MASK_CLASS}"><div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Brief</p></div><p>Reply</p></div>`, "Brief")).toBe("Brief");
expect(recordedTextOf(`<div class="${ANALYTICS_MASK_CLASS}"><div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Brief</p></div><p>Reply</p></div>`, "Reply")).toBe("*****");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("shows a task preview as work content only for the selected company's own task", () => {
// A preview loads a task by id, so it can belong to another company than
// the one whose source check set the page's visible flag.
expect(workContentClassForCompany("co-1", "co-1")).toBe(ANALYTICS_WORK_CONTENT_CLASS);
expect(workContentClassForCompany("co-2", "co-1")).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany(undefined, "co-1")).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany("co-1", null)).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany(null, null)).toBe(ANALYTICS_MASK_CLASS);
const quicklook = readFileSync(join(UI_SRC, "components/IssueLinkQuicklook.tsx"), "utf8");
expect(quicklook).toContain("workContentClassForCompany(issue.companyId, selectedCompanyId)");
});
it.each([
["glpat", "-", "AbCdEfGhIjKlMnOpQr12"],
["ghp", "_", "AbCdEfGhIjKlMnOpQr12"],
["sk-proj", "-", "AbCdEfGhIjKlMnOpQr12"],
])("masks a %s credential in the rendered task preview", (prefix, separator, value) => {
const token = [prefix, value].join(separator);
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const html = renderTaskPreview(`Use **${token}** for the review.`);
expect(recordedTextOf(html, value)).toBe(`Use ${stars(token)} for the review.`);
expect(document.querySelector('[data-slot="task-preview-description"]')?.textContent)
.toBe(`Use ${token} for the review.`);
} finally {
company.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("always masks the text preview on an artifact card", () => {
// `normalizePreviewText` on the server turns `glpat-AbC...` into
// `glpat AbC...` and cuts the text, so no token format matches it.
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
for (const previewText of ["Use glpat AbCdEfGhIjKlMnOpQr12 for the review.", "Ship the Q3 launch plan by Friday"]) {
const html = renderToStaticMarkup(
<ArtifactPreview artifact={{ mediaKind: "document", contentPath: null, title: "Notes", source: "document", previewText }} />,
);
expect(recordedTextOf(html, previewText.slice(0, 8))).toBe(stars(previewText));
}
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("masks a document card preview when its 4,000-character cut crosses a credential", () => {
const card = (body: string) => renderToStaticMarkup(
<DocumentCard title="Runbook" summary="Deploy steps" author="Ana" updatedAt="2026-11-30" filename="runbook.md" body={body} />,
);
const prose = "Deploy the staging cluster step by step. ";
const lead = prose.repeat(97).slice(0, 3_990);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
// The preview ends inside the token: `ghp_abcdef` would record in clear.
expect(recordedTextOf(card(`${lead}ghp_abcdefghijklmnopqrstuvwxyz0123 and confirm.`), "Deploy the staging"))
.not.toMatch(/[A-Za-z]/);
// A long document with no credential at the cut still shows.
expect(recordedTextOf(card(prose.repeat(200)), "Deploy the staging")).toContain("Deploy the staging cluster");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("masks a cut task preview whose text holds a credential", () => {
// The preview shows 177 characters. A credential that crosses that cut is
// too short to match its format, so its first characters would record.
const lead = "Please rotate the deploy credential for the staging cluster before the Friday release and tell the team in the channel when it is done so nobody is blocked on it. ";
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
for (const token of ["ghp_abcdefghijklmnopqrstuvwxyz0123", "sk-proj-AbCdEfGhIjKlMnOpQrStUvWx1234", "Xk9pQ2mZ7rT4vB8nL3wY6sD1fH5jK0aCXk9pQ2mZ7rT4"]) {
const html = renderTaskPreview(`${lead}${token} and confirm.`);
const rendered = document.createElement("div");
rendered.innerHTML = html;
const shown = rendered.querySelector('[data-slot="task-preview-description"]')?.textContent ?? "";
// The person sees the cut text, with the start of the credential.
expect(shown.endsWith("...")).toBe(true);
expect(shown).toContain(token.slice(0, 8));
// The replay records none of it.
expect(recordedTextOf(html, "Please rotate")).toBe(stars(shown));
}
// A cut preview with no credential still shows.
const plain = renderTaskPreview(`${lead}${lead}`);
expect(recordedTextOf(plain, "Please rotate")).toContain("Please rotate the deploy credential");
} finally {
company.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it.each(["`", "*", "_", "["])("bounds %s runs before converting a task preview", (marker) => {
const convert = MarkdownPlainText.markdownToPlainText;
const conversion = vi.spyOn(MarkdownPlainText, "markdownToPlainText").mockImplementation((markdown) => {
expect(markdown.length).toBeLessThanOrEqual(2_048);
return convert(markdown);
});
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const html = renderTaskPreview(`Use ${marker.repeat(128_000)}x`);
const recorded = recordedTextOf(html, "Use");
const rendered = document.querySelector('[data-slot="task-preview-description"]')?.textContent ?? "";
expect(conversion).toHaveBeenCalledTimes(1);
expect(rendered.length).toBeLessThanOrEqual(180);
expect(rendered).toContain("Use");
expect(recorded).toBe(stars(rendered));
} finally {
company.mockRestore();
conversion.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("sends the marker selector and the work content mask function to session replay", () => {
expect(options.session_recording.maskTextSelector).toBe(ANALYTICS_MASK_TEXT_SELECTOR);
expect(options.session_recording).not.toHaveProperty("maskTextFn");
expect(options.session_recording.maskTextFn).toBe(maskReplayText);
expect(options.session_recording.maskAllInputs).toBe(true);
expect(options.session_recording.blockClass).toBe(ANALYTICS_NO_CAPTURE_CLASS);
});
@@ -385,6 +567,27 @@ describe("session replay text masking", () => {
expect(elements.some((tag) => tag.includes("ANALYTICS_MASK_CLASS"))).toBe(true);
});
it.each([
{ file: "components/FileViewerSheet.tsx", content: "<WorkspaceFileMarkdownBody" },
])("renders Markdown work content with the work marker at $content in $file", ({ file, content }) => {
// An inner MarkdownBody without replayContent="work" carries the strict
// mask, which wins over a work marker on its wrapper.
const source = readFileSync(join(UI_SRC, file), "utf8");
const index = source.indexOf(content);
expect(index, `content not found in ${file}`).toBeGreaterThanOrEqual(0);
expect(source.slice(index, tagEnd(source, index + 1) + 1)).toContain("replayContent=\"work\"");
});
it.each(WORK_CONTENT_SURFACES)("keeps the work content mask on $content in $file", ({ file, content }) => {
const source = readFileSync(join(UI_SRC, file), "utf8");
const index = source.indexOf(content);
expect(index, `content not found in ${file}`).toBeGreaterThanOrEqual(0);
const contentTag = source.startsWith("<", index) ? source.slice(index, tagEnd(source, index + 1) + 1) : "";
const elements = [...openElementsAt(source, index), contentTag];
// `workContentClassForCompany` picks the work marker for the selected company's own content.
expect(elements.some((tag) => tag.includes("ANALYTICS_WORK_CONTENT_CLASS") || tag.includes("workContentClassForCompany("))).toBe(true);
});
it("finds the portaled content of connection and account surfaces", () => {
expect(CONNECTION_PORTALS.length).toBeGreaterThan(40);
});
@@ -1,14 +1,29 @@
import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS } from "./privacy";
import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS, maskReplayText } from "./privacy";
const BLOCK_SELECTOR = `.${ANALYTICS_NO_CAPTURE_CLASS}`;
export function recordedTextNode(node: Text): string {
const parent = node.parentElement;
if (parent?.closest(BLOCK_SELECTOR)) return "";
if (parent?.closest(ANALYTICS_MASK_TEXT_SELECTOR)) return node.data.replace(/\S/g, "*");
// Like rrweb: text inside the selector goes through `maskTextFn`.
if (parent?.closest(ANALYTICS_MASK_TEXT_SELECTOR)) return maskReplayText(node.data, parent);
return node.data;
}
/** One mask character for each character that is not white space, like the recorder. */
export const stars = (text: string) => text.replace(/\S/g, "*");
/** Renders `html` and returns what a replay records for the text node that holds `text`. */
export function recordedTextOf(html: string, text: string, record: (node: Text) => string = recordedTextNode): string {
document.body.innerHTML = html;
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode as Text;
if (node.data.includes(text)) return record(node);
}
throw new Error(`text not rendered: ${text}`);
}
export function recordedText(root: Node = document.body): string {
const doc = root.ownerDocument ?? (root as Document);
const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
@@ -0,0 +1,345 @@
// @vitest-environment jsdom
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MarkdownBody } from "@/components/MarkdownBody";
import { ThemeProvider } from "@/context/ThemeContext";
import {
ANALYTICS_WORK_CONTENT_CLASS,
REPLAY_WORK_CONTENT_ATTRIBUTE,
cutKeepsRedaction,
redactReplaySecrets,
} from "./privacy";
import { recordedTextNode as recordedText, recordedTextOf, stars } from "./replay-recording.test-utils";
// What `redactReplaySecrets` masks inside text that replays otherwise show.
// Which elements are masked or shown at all is in `replay-masking.test.tsx`.
describe("secret redaction in session replay text", () => {
afterEach(() => {
document.body.innerHTML = "";
});
it("masks secrets inside visible work content", () => {
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const work = (text: string) => `<div class="${ANALYTICS_WORK_CONTENT_CLASS}"><pre>${text}</pre></div>`;
expect(recordedTextOf(work("OPENAI_API_KEY=sk-proj-abcdefghijklmnop1234"), "OPENAI_API_KEY="))
.toBe(`OPENAI_API_KEY=${stars("sk-proj-abcdefghijklmnop1234")}`);
expect(recordedTextOf(work("Deploy the Q3 plan"), "Deploy the Q3 plan")).toBe("Deploy the Q3 plan");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it.each([
["an OpenAI key", "key sk-proj-abcdefghijklmnop1234 here", "sk-proj-abcdefghijklmnop1234"],
["an Anthropic key", "sk-ant-api03-AbCdEfGhIjKlMnOpQr", "sk-ant-api03-AbCdEfGhIjKlMnOpQr"],
["a GitHub token", "ghp_abcdefghijklmnopqrstuvwxyz0123", "ghp_abcdefghijklmnopqrstuvwxyz0123"],
["a Slack token", "xoxb-123456789012-abcdefABCDEF", "xoxb-123456789012-abcdefABCDEF"],
["an AWS key id", "id AKIAABCDEFGHIJKLMNOP", "AKIAABCDEFGHIJKLMNOP"],
["a Google API key", "AIzaSyA1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q", "AIzaSyA1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q"],
["a JWT", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefgh1234", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefgh1234"],
["an env assignment", "DATABASE_PASSWORD=hunter2", "hunter2"],
["a JSON field", "\"apiKey\": \"abc123secret\"", "abc123secret"],
["a YAML field", "client_secret: s3cr3t-value", "s3cr3t-value"],
["a quoted password with spaces", "password=\"correct horse battery staple\"", "correct horse battery staple"],
["a single-quoted secret with punctuation", "secret: 'p@ss, word; 42!'", "p@ss, word; 42!"],
["an unquoted YAML password with spaces", "password: correct horse battery staple", "correct horse battery staple"],
["a quoted value with an escaped quote", "\"token\": \"ab\\\"cd ef\"", "ab\\\"cd ef"],
["a bearer header", "Authorization: Bearer abcdef123456", "abcdef123456"],
["URL credentials", "postgres://admin:pa55word@db.internal:5432/app", "admin:pa55word"],
["a random token", "value Xk9pQ2mZ7rT4vB8nL3wY6sD1fH5jK0aC", "Xk9pQ2mZ7rT4vB8nL3wY6sD1fH5jK0aC"],
["a private key", "-----BEGIN RSA PRIVATE KEY-----\nMIIBOg\n-----END RSA PRIVATE KEY-----", "-----BEGIN RSA PRIVATE KEY-----\nMIIBOg\n-----END RSA PRIVATE KEY-----"],
])("redactReplaySecrets masks %s", (_label, input, secret) => {
expect(redactReplaySecrets(input)).toBe(input.replace(secret, stars(secret)));
});
it("masks only the secret value in JSON, leaving the next field", () => {
expect(redactReplaySecrets("{\"password\": \"correct horse\", \"title\": \"Q3 plan\"}"))
.toBe("{\"password\": \"******* *****\", \"title\": \"Q3 plan\"}");
});
it("masks an unclosed quoted secret to the end of its line", () => {
expect(redactReplaySecrets("password=\"correct horse\nnext line")).toBe("password=\"******* *****\nnext line");
});
it("masks a secret value longer than any length limit in full", () => {
const hex = "0123456789abcdef".repeat(400);
expect(redactReplaySecrets(`COOKIE=${hex}`)).toBe(`COOKIE=${stars(hex)}`);
expect(redactReplaySecrets(`"cookie": "${hex}", "title": "Q3"`)).toBe(`"cookie": "${stars(hex)}", "title": "Q3"`);
});
it("masks secrets behind long names, after other assignments, and long URL passwords", () => {
const longName = `${"SERVICE_".repeat(12)}PASSWORD`;
expect(redactReplaySecrets(`${longName}=hunter2`)).toBe(`${longName}=*******`);
expect(redactReplaySecrets("user=bob password=hunter2")).toBe("user=bob password=*******");
const longPassword = "p".repeat(400);
expect(redactReplaySecrets(`postgres://admin:${longPassword}@db:5432/app`))
.toBe(`postgres://${stars(`admin:${longPassword}`)}@db:5432/app`);
const longFlag = `--${"service-".repeat(500)}password`;
expect(redactReplaySecrets(`${longFlag} hunter2 --region us`)).toBe(`${longFlag} ******* --region us`);
});
it.each([
["a spaced label", "API key: 8f3a9c2e41b7d605", "8f3a9c2e41b7d605"],
["a spaced label after other words", "The staging private key: 8f3a9c2e41b7d605", "8f3a9c2e41b7d605"],
["a session id label", "Session ID: 9f8e7d6c5b4a", "9f8e7d6c5b4a"],
["a name that ends in key", "ENCRYPTION_KEY=0f1e2d3c4b5a", "0f1e2d3c4b5a"],
["a camel-case key name", "signingKey: 'left right'", "left right"],
["a short password name", "DB_PASS=hunter2", "hunter2"],
["a PIN", "PIN: 4821", "4821"],
["a passphrase", "passphrase: correct horse", "correct horse"],
["a bold Markdown label in a raw file", "**Password**: hunter2", "hunter2"],
["a command-line flag", "mysql --password hunter2 --host db", "hunter2"],
["a quoted command-line flag", "deploy --api-key \"left right\" --region us", "\"left right\""],
["a quoted flag value with escaped quotes", "mysql --password \"correct \\\"horse\\\" battery staple\" --host db", "\"correct \\\"horse\\\" battery staple\""],
["a single-quoted flag value with an escaped quote", "run --token 'it\\'s a secret' --dry-run", "'it\\'s a secret'"],
["a flag name with an underscore", "run --verbose --db_password hunter2 --host db", "hunter2"],
["an api_key flag", "deploy --api_key hunter2 --region us", "hunter2"],
["an access key flag", "sync --access_key hunter2 --bucket logs", "hunter2"],
["a private key flag", "sign --private-key hunter2 --out file", "hunter2"],
["a bare key flag", "decrypt --key hunter2 --in file", "hunter2"],
["an auth flag", "call --auth hunter2 --json", "hunter2"],
["a password flag after a flag that takes no value", "mongod --auth --tlsCertificateKeyFilePassword hunter2", "hunter2"],
["a password flag after two flags that take no value", "run --token --auth --db-password hunter2 --host db", "hunter2"],
["a quoted value that starts with two hyphens", "run --password \"--hunter2\" --host db", "\"--hunter2\""],
])("redactReplaySecrets masks %s", (_label, input, secret) => {
expect(redactReplaySecrets(input)).toBe(input.replace(secret, stars(secret)));
});
describe("a secret split across the nodes of one line", () => {
// rrweb records one text node at a time. Markdown and syntax highlighting
// put a label and its value in different nodes of the same line.
const work = (inner: string) => `<div class="${ANALYTICS_WORK_CONTENT_CLASS}">${inner}</div>`;
function withVisibleWorkContent(run: () => void) {
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
run();
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
}
it("masks a value after a bold label", () => withVisibleWorkContent(() => {
expect(recordedTextOf(work("<p><strong>Password:</strong> hunter2</p>"), "hunter2")).toBe(" *******");
expect(recordedTextOf(work("<p><strong>Password:</strong> hunter2</p>"), "Password")).toBe("Password:");
}));
it("masks a value in inline code after its label", () => withVisibleWorkContent(() => {
expect(recordedTextOf(work("<p>Password: <code>hunter2</code></p>"), "hunter2")).toBe("*******");
expect(recordedTextOf(work("<p><strong>API key</strong>: <code>8f3a9c2e41b7d605</code></p>"), "8f3a")).toBe("****************");
expect(recordedTextOf(work("<ul><li>Staging token: <code>blue-green-42</code></li><li>Owner: <code>ana</code></li></ul>"), "blue-green")).toBe("*************");
expect(recordedTextOf(work("<ul><li>Staging token: <code>blue-green-42</code></li><li>Owner: <code>ana</code></li></ul>"), "ana")).toBe("ana");
}));
it("masks a quoted value with formatting inside it, and shows the text after its closing quote", () => withVisibleWorkContent(() => {
const html = work('<p>Password: "correct <strong>horse</strong> battery <em>staple</em>" and then sign in</p>');
expect(recordedTextOf(html, "Password")).toBe('Password: "******* ');
expect(recordedTextOf(html, "horse")).toBe("*****");
expect(recordedTextOf(html, "battery")).toBe(" ******* ");
expect(recordedTextOf(html, "staple")).toBe("******");
expect(recordedTextOf(html, "and then sign in")).toBe('" and then sign in');
}));
it("shows the sentence after an inline assignment, and masks a later secret in it", () => withVisibleWorkContent(() => {
const html = work("<p>Set <code>API_KEY=abc123</code> in the env file, then use password: hunter2</p>");
expect(recordedTextOf(html, "API_KEY")).toBe("API_KEY=******");
expect(recordedTextOf(html, "in the env file")).toBe(" in the env file, then use password: *******");
}));
it("masks a value whose label follows an inline assignment in an earlier node", () => withVisibleWorkContent(() => {
// The first value ends with its inline code, so the scan reads on and
// finds the label that sits between the two code elements.
const html = work("<p>Set <code>API_KEY=abc123</code> and password: <code>hunter2</code> today</p>");
expect(recordedTextOf(html, "hunter2")).toBe("*******");
expect(recordedTextOf(html, "today")).toBe(" today");
const quoted = work("<p>Use <code>token=\"abc123\"</code> with pin: <code>4821</code></p>");
expect(recordedTextOf(quoted, "4821")).toBe("****");
}));
it("masks an unquoted value with formatting inside it, to the end of its line", () => withVisibleWorkContent(() => {
const html = work("<p><strong>Password:</strong> correct <em>horse</em> battery<br>Next line</p>");
expect(recordedTextOf(html, "correct")).toBe(" ******* ");
expect(recordedTextOf(html, "horse")).toBe("*****");
expect(recordedTextOf(html, "battery")).toBe(" *******");
expect(recordedTextOf(html, "Next line")).toBe("Next line");
}));
it("masks URL credentials split by Markdown bold formatting", () => withVisibleWorkContent(() => {
const html = renderToStaticMarkup(
<ThemeProvider>
<MarkdownBody replayContent="work">
{"Connect with postgres://admin:**pa55word**@db.internal today"}
</MarkdownBody>
</ThemeProvider>,
);
expect(html).toContain("<strong>pa55word</strong>");
expect(recordedTextOf(html, "pa55word")).toBe("********");
expect(recordedTextOf(html, "postgres://")).toBe("Connect with postgres://******");
expect(recordedTextOf(html, "@db.internal")).toBe("@db.internal today");
}));
it("masks a value split across syntax highlight spans", () => withVisibleWorkContent(() => {
const env = work("<pre><code><span>PASSWORD</span>=abc<span>$def</span>\n<span>REGION</span>=us</code></pre>");
expect(recordedTextOf(env, "=abc")).toBe("=***");
expect(recordedTextOf(env, "$def")).toBe("****");
expect(recordedTextOf(env, "=us")).toBe("=us");
const json = work("<pre><code>{<span>\"password\"</span><span>:</span> <span>\"correct horse\"</span>, <span>\"title\"</span>: <span>\"Q3 plan\"</span>}</code></pre>");
expect(recordedTextOf(json, "correct horse")).toBe("\"******* *****\"");
expect(recordedTextOf(json, "Q3 plan")).toBe("\"Q3 plan\"");
}));
it("reads the label through the file viewer's line-number gutter", () => withVisibleWorkContent(() => {
const line = work("<pre><div><span aria-hidden=\"true\">12</span><code><span>db_password</span>: <span>hunter2</span></code></div><div><span aria-hidden=\"true\">13</span><code>region: us</code></div></pre>");
expect(recordedTextOf(line, "hunter2")).toBe("*******");
expect(recordedTextOf(line, "region")).toBe("region: us");
}));
it("keeps a label on its own line or block", () => withVisibleWorkContent(() => {
expect(recordedTextOf(work("<p>Reset the password:</p><p>Open the settings page</p>"), "Open")).toBe("Open the settings page");
expect(recordedTextOf(work("<p>Reset the password:<br>Open the settings page</p>"), "Open")).toBe("Open the settings page");
expect(recordedTextOf(work("<table><tr><td>Password</td><td>rotated weekly</td></tr></table>"), "rotated")).toBe("rotated weekly");
}));
it("masks every candidate when sibling nodes hold the same text", () => withVisibleWorkContent(() => {
// rrweb passes the text and its parent, not the node, so the two
// " abc " nodes cannot be told apart: one follows a secret label.
const html = work("<p><b>Token:</b> abc <b>Owner:</b> abc </p>");
document.body.innerHTML = html;
const texts = Array.from(document.querySelector("p")!.childNodes).filter((node) => node.nodeType === Node.TEXT_NODE) as Text[];
expect(texts.map(recordedText)).toEqual([" *** ", " *** "]);
}));
it("never shows more with line context than without it", () => {
// A gutter number glued to a key breaks the word boundary of the known
// formats. The text is still redacted by itself.
expect(redactReplaySecrets("sk-proj-abcdefghijklmnop1234", { before: "12", continues: () => true }))
.toBe(stars("sk-proj-abcdefghijklmnop1234"));
expect(redactReplaySecrets("password: hunter2", { before: "note: ", continues: () => false })).toBe("password: *******");
expect(redactReplaySecrets("plain words", { before: "note: ", continues: () => false })).toBe("plain words");
});
it("masks every line of a private key that the file viewer renders line by line", () => withVisibleWorkContent(() => {
// `FileContentViewer`: one <div> per line, a gutter number and a <code>.
const lines = [
"notes for the deploy", "-----BEGIN RSA PRIVATE KEY-----", "Proc-Type: 4,ENCRYPTED", "\u200b",
"abcdefghijklmnop", "QRSTUVWX", "tail12==", "-----END RSA PRIVATE KEY-----", "done", "abcdefghijklmnop",
];
document.body.innerHTML = work(`<pre>${lines.map((line, index) => `<div><span aria-hidden="true">${index + 1}</span><code>${line}</code></div>`).join("")}</pre>`);
const recorded = Array.from(document.querySelectorAll("code")).map((code) => recordedText(code.firstChild as Text));
expect(recorded).toEqual([
"notes for the deploy", stars("-----BEGIN RSA PRIVATE KEY-----"), "Proc-Type: 4,ENCRYPTED", "\u200b",
"****************", "********", "********", "-----END RSA PRIVATE KEY-----", "done", "abcdefghijklmnop",
]);
}));
it("masks a PGP private key block line by line", () => withVisibleWorkContent(() => {
const lines = ["-----BEGIN PGP PRIVATE KEY BLOCK-----", "Version: 2", "\u200b", "abcdefghijkl", "=AbCd", "-----END PGP PRIVATE KEY BLOCK-----", "after"];
document.body.innerHTML = work(`<pre>${lines.map((line) => `<div><code>${line}</code></div>`).join("")}</pre>`);
const recorded = Array.from(document.querySelectorAll("code")).map((code) => recordedText(code.firstChild as Text));
expect(recorded).toEqual([stars(lines[0]!), "Version: 2", "\u200b", "************", "*****", lines[5], "after"]);
}));
it("masks the rest of a private key that ends inside a later node", () => withVisibleWorkContent(() => {
const html = work("<pre><code><span>-----BEGIN PRIVATE KEY-----\n</span><span>abcdefgh\n</span><span>ijkl==\n-----END PRIVATE KEY-----\nsafe words</span></code></pre>");
expect(recordedTextOf(html, "abcdefgh")).toBe("********\n");
expect(recordedTextOf(html, "ijkl")).toBe("******\n-----END PRIVATE KEY-----\nsafe words");
}));
// rrweb calls the mask function for every text node, so its work per node
// must not grow with the page. A wall-clock bound depends on the machine,
// so these count how often the function reads the text of a node: to scan
// siblings again for every node it would have to read each of them again.
function textReadsWhileRecording(html: string): { reads: number; nodes: number } {
document.body.innerHTML = html;
const texts: Text[] = [];
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) texts.push(walker.currentNode as Text);
const readData = Object.getOwnPropertyDescriptor(CharacterData.prototype, "data")!.get!;
let reads = 0;
const spy = vi.spyOn(CharacterData.prototype, "data", "get").mockImplementation(function (this: CharacterData) {
reads += 1;
return readData.call(this);
});
try {
for (const node of texts) recordedText(node);
} finally {
spy.mockRestore();
}
return { reads, nodes: texts.length };
}
// The line context reads at most 64 earlier nodes for one node.
const MAX_TEXT_READS_PER_NODE = 100;
it("does linear work on a long paragraph of prose between inline elements", () => withVisibleWorkContent(() => {
// Every text child of the <p> differs, so each one is its own candidate.
const parts = Array.from({ length: 1_500 }, (_unused, index) => `prose number ${index} goes on <b>bold ${index}</b> `).join("");
const { reads, nodes } = textReadsWhileRecording(work(`<p>${parts}</p>`));
// 1,500 prose nodes, 1,500 bold nodes and the space after the last one.
expect(nodes).toBe(3_001);
expect(reads).toBeLessThan(nodes * MAX_TEXT_READS_PER_NODE);
}));
it("does linear work on a long highlighted line", () => withVisibleWorkContent(() => {
const spans = Array.from({ length: 1_000 }, (_unused, index) => `<span>part${index}</span> `).join("");
const { reads, nodes } = textReadsWhileRecording(work(`<pre><code>${spans}</code></pre>`));
expect(nodes).toBe(2_000);
expect(reads).toBeLessThan(nodes * MAX_TEXT_READS_PER_NODE);
}));
});
it("redacts a large text node quickly", () => {
// rrweb calls this for every recorded text node, so it must stay linear.
const inputs = [
"tokentoken".repeat(20_000),
"a".repeat(200_000),
"password_".repeat(20_000) + "=x",
"https://" + "a:".repeat(50_000),
("const value = computeTotal(lineItems); // TODO token budget\n").repeat(3_000),
"password=\"" + "\\a".repeat(100_000),
"secret: " + "x".repeat(200_000),
];
const started = performance.now();
for (const input of inputs) redactReplaySecrets(input);
expect(performance.now() - started).toBeLessThan(500);
});
it.each([
"Ship the Q3 launch plan by Friday",
"commit 3f786850e387550fdab836ed7e6dc881de23001b",
"id 123e4567-e89b-12d3-a456-426614174000",
"The token budget was 4k per run.",
"See https://github.com/paperclipai/paperclip/pull/22820",
"Key findings: revenue grew 12% in Q3",
"Pass rate: 98% across the suite",
"Keyboard shortcut: Ctrl+K",
"OAuth: enabled for every workspace",
"Next step: run pnpm verify --full",
"Run it with --keyboard us --verbose --region eu",
"git log --author ana --oneline",
"mongod --auth --port 27017",
])("redactReplaySecrets leaves ordinary text alone: %s", (input) => {
expect(redactReplaySecrets(input)).toBe(input);
});
it("says when a cut changes what the redaction masks before it", () => {
const lead = "Rotate the deploy credential before Friday. ";
const token = "ghp_abcdefghijklmnopqrstuvwxyz0123";
// The cut leaves `ghp_abcdef`, too short to match the GitHub format.
expect(cutKeepsRedaction(`${lead}${token} done`, lead.length + 10)).toBe(false);
// A credential that ends before the cut is masked either way.
expect(cutKeepsRedaction(`${lead}${token} and then tell the team`, lead.length + token.length + 8)).toBe(true);
expect(cutKeepsRedaction(`${lead}No credential in this text at all.`, lead.length + 5)).toBe(true);
expect(cutKeepsRedaction("short", 4_000)).toBe(true);
});
it("redacts an adversarial run of hyphens without stalling the recorder", () => {
const prefix = "-".repeat(512 * 1024);
const input = `${prefix}\nmysql --password hunter2 --host db`;
const started = performance.now();
expect(redactReplaySecrets(input)).toBe(`${prefix}\nmysql --password ******* --host db`);
expect(performance.now() - started).toBeLessThan(500);
});
});
@@ -0,0 +1,387 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
companyId: "co-1" as string | null,
companyPrefix: "ACME" as string | null,
pathname: "/ACME/issues/ACME-1",
session: { browserAnalytics: { replayEnabled: true, replayWorkContentEnabled: true } } as unknown,
connections: vi.fn(),
chatEndpoints: vi.fn(),
refresh: vi.fn(),
}));
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({
selectedCompanyId: mocks.companyId,
selectedCompany: mocks.companyId && mocks.companyPrefix ? { id: mocks.companyId, issuePrefix: mocks.companyPrefix } : null,
}),
}));
vi.mock("@/lib/router", () => ({ useLocation: () => ({ pathname: mocks.pathname }) }));
vi.mock("@/api/auth", () => ({ authApi: { getSession: async () => mocks.session } }));
vi.mock("@/api/tools", () => ({ toolsApi: { listConnections: (id: string) => mocks.connections(id) } }));
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: (id: string) => mocks.chatEndpoints(id) } }));
vi.mock("./product-analytics", () => ({ refreshSessionReplay: () => mocks.refresh() }));
import { REPLAY_WORK_CONTENT_ATTRIBUTE } from "./privacy";
import { queryKeys } from "@/lib/queryKeys";
import {
ReplayWorkContentVisibility,
companyAllowsReplayWorkContent,
connectionCarriesConnectedAccountData,
isReplayWorkContentSourceChange,
replayWorkContentQueryKeys,
routeShowsCompany,
} from "./replay-work-content";
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
/** A complete connection list, as the server sends it to a board reader. */
function connectionList(connections: ReturnType<typeof connection>[] = [], hiddenCount = 0) {
return { connections, hiddenCount };
}
function connection(overrides: { name?: string; config?: Record<string, unknown>; transportConfig?: Record<string, unknown> } = {}) {
return { name: "Linear", config: {}, transportConfig: {}, ...overrides };
}
describe("connectionCarriesConnectedAccountData", () => {
it("flags Google, Slack and aggregator connections", () => {
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: "google-workspace" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: "gmail" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ transportConfig: { sourceTemplateKey: "google-drive" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: "slack" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: "composio" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ name: "Team Slack" }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ transportConfig: { url: "https://gmail.mcp.example.com/mcp" } }))).toBe(true);
});
it("flags a custom-named Slack chat channel by its provider", () => {
// Removing a Slack channel archives its endpoint (gone from the endpoint
// list) but keeps this connection row, named however the person chose.
expect(connectionCarriesConnectedAccountData(connection({ name: "Support", config: { provider: "slack" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ name: "Support", config: { provider: "telegram" } }))).toBe(false);
});
it("flags apps that reach Google or Slack through another service", () => {
for (const slug of ["zapier", "make", "gsc-wizard", "windsor-ai"]) {
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: slug } }))).toBe(true);
}
// The same apps added by hand, under any name.
expect(connectionCarriesConnectedAccountData(connection({ name: "Automations", transportConfig: { url: "https://mcp.zapier.com/api/mcp/s/abc/mcp" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ name: "Scenarios", transportConfig: { serverUrl: "https://eu1.make.com/mcp" } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ name: "Beauty", transportConfig: { url: "https://mcp.makeup.example.com/mcp" } }))).toBe(false);
expect(connectionCarriesConnectedAccountData(connection({ name: "Notes", transportConfig: { url: "not a url" } }))).toBe(false);
});
it("flags a known gateway added through the generic setup, with no catalog slug", () => {
// "Connect your own MCP server" saves the URL and a free name, no slug.
for (const url of [
"https://mcp.composio.dev/partner/mcp", "https://connect.composio.dev/mcp", "https://backend.composio.dev/v3/mcp/abc",
"https://api.arcade.dev/mcp/gateway", "https://executor.sh/mcp",
]) {
expect(connectionCarriesConnectedAccountData(connection({ name: "Team tools", transportConfig: { url } }))).toBe(true);
expect(connectionCarriesConnectedAccountData(connection({ name: "Team tools", transportConfig: { serverUrl: url } }))).toBe(true);
}
for (const name of ["Composio", "Arcade gateway", "Executor", "Zapier", "Make", "Windsor.ai", "GSC Wizard"]) {
expect(connectionCarriesConnectedAccountData(connection({ name, transportConfig: { url: "https://mcp.internal.example/mcp" } }))).toBe(true);
}
expect(connectionCarriesConnectedAccountData(connection({ name: "Maker space", transportConfig: { url: "https://decomposio.example/mcp" } }))).toBe(false);
});
it("leaves other connections alone", () => {
expect(connectionCarriesConnectedAccountData(connection({ config: { sourceTemplateKey: "linear" } }))).toBe(false);
expect(connectionCarriesConnectedAccountData(connection({ name: "GitHub", transportConfig: { url: "https://api.githubcopilot.com/mcp" } }))).toBe(false);
});
});
describe("companyAllowsReplayWorkContent", () => {
it("needs both lists loaded and no Google or Slack source", () => {
expect(companyAllowsReplayWorkContent(undefined, [])).toBe(false);
expect(companyAllowsReplayWorkContent(connectionList(), undefined)).toBe(false);
expect(companyAllowsReplayWorkContent(connectionList(), [])).toBe(true);
expect(companyAllowsReplayWorkContent(connectionList([connection()]), [{ provider: "github" } as never])).toBe(true);
expect(companyAllowsReplayWorkContent(connectionList([connection({ config: { sourceTemplateKey: "gmail" } })]), [])).toBe(false);
expect(companyAllowsReplayWorkContent(connectionList(), [{ provider: "slack" } as never])).toBe(false);
});
it("needs a connection list the server did not filter", () => {
// Another person's draft (an expired Google sign-in returns to draft) or
// a connector whose plugin is unavailable: the hidden row can be Google.
expect(companyAllowsReplayWorkContent(connectionList([], 1), [])).toBe(false);
expect(companyAllowsReplayWorkContent(connectionList([connection()], 2), [])).toBe(false);
// An older server sends no count.
expect(companyAllowsReplayWorkContent({ connections: [] }, [])).toBe(false);
});
});
describe("routeShowsCompany", () => {
it("accepts the selected company's own pages and pages with no company", () => {
expect(routeShowsCompany("/ACME/issues/ACME-1", "ACME")).toBe(true);
expect(routeShowsCompany("/acme/dashboard", "ACME")).toBe(true);
expect(routeShowsCompany("/", "ACME")).toBe(true);
expect(routeShowsCompany("/instance/settings", "ACME")).toBe(true);
});
it("rejects a page of another company, or any company page with no selected company", () => {
expect(routeShowsCompany("/OTHER/issues/OTHER-1", "ACME")).toBe(false);
expect(routeShowsCompany("/OTHER/issues/OTHER-1", null)).toBe(false);
expect(routeShowsCompany("/OTHER/issues/OTHER-1", undefined)).toBe(false);
});
});
describe("isReplayWorkContentSourceChange", () => {
it("matches the activity the server logs when a source is added", () => {
// The actions `server/src/routes/tool-access.ts` and the chat channel
// services log. A connect from the Apps catalog logs `tool_app.*`.
for (const action of [
"tool_app.connected", "tool_app.oauth_connected", "tool_app.reconnected", "tool_example.installed",
"tool_connection.created", "tool_connection.updated", "connection_installs.changed",
"chat_endpoint.created", "chat_endpoint.updated", "chat_endpoint.reconnected", "company.imported",
]) {
expect(isReplayWorkContentSourceChange(action)).toBe(true);
}
});
it("matches every other action of a connection family, named or not", () => {
// Other routes add a connection row too (a machine sign-in, a model
// connection, an email channel, a GitHub chat app), and some build the
// action name at run time. A new action in these families must re-check.
for (const action of [
"tool_connection.machine_sign_in_created", "tool_connection.archived", "tool_connection.some_future_action",
"ai_connection.connected", "ai_connection.reconnected", "ai_connection.pool_saved",
"email_endpoint.connected", "chat_github.app_connected", "tool_application.created",
]) {
expect(isReplayWorkContentSourceChange(action)).toBe(true);
}
});
it("ignores frequent activity that adds no source", () => {
for (const action of [
"tool_connection.health_check", "tool_connection.catalog_refresh", "tool_connection.credential_resolution",
"tool_connection.webhook_processed", "ai_connection.credential_refreshed", "chat_endpoint.webhook_verified",
"tool_gateway.call_completed", "issue.updated", "company.updated", null, undefined,
]) {
expect(isReplayWorkContentSourceChange(action)).toBe(false);
}
});
});
describe("ReplayWorkContentVisibility", () => {
let host: HTMLDivElement;
let root: Root;
let queryClient: QueryClient;
async function render() {
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<ReplayWorkContentVisibility />
</QueryClientProvider>,
);
});
await settle();
}
// Let the queries settle and React render the result.
async function settle() {
for (let i = 0; i < 10; i += 1) {
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
}
const visible = () => document.documentElement.getAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
beforeEach(() => {
mocks.companyId = "co-1";
mocks.companyPrefix = "ACME";
mocks.pathname = "/ACME/issues/ACME-1";
mocks.session = { browserAnalytics: { replayEnabled: true, replayWorkContentEnabled: true } };
mocks.connections.mockReset().mockResolvedValue(connectionList());
mocks.chatEndpoints.mockReset().mockResolvedValue([]);
mocks.refresh.mockReset();
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
});
it("shows work content for a company without Google or Slack, and refreshes the replay once", async () => {
await render();
expect(visible()).toBe("visible");
expect(mocks.refresh).toHaveBeenCalledTimes(1);
});
it("keeps work content masked when the company has a Google connection", async () => {
mocks.connections.mockResolvedValue(connectionList([connection({ config: { sourceTemplateKey: "google-workspace" } })]));
await render();
expect(visible()).toBeNull();
expect(mocks.refresh).not.toHaveBeenCalled();
});
it("keeps work content masked when Slack is a chat endpoint", async () => {
mocks.chatEndpoints.mockResolvedValue([{ provider: "slack" }]);
await render();
expect(visible()).toBeNull();
});
it("keeps work content masked when the connection list fails (for example no permission)", async () => {
mocks.connections.mockRejectedValue(new Error("403"));
await render();
expect(visible()).toBeNull();
});
it("keeps work content masked when the server hid a connection from this viewer", async () => {
// A Google connection returns to draft when its sign-in expires, and the
// list hides another person's draft from a member, so the visible part
// of the list proves nothing.
mocks.connections.mockResolvedValue(connectionList([], 1));
await render();
expect(visible()).toBeNull();
expect(mocks.refresh).not.toHaveBeenCalled();
});
it("keeps work content masked when the server does not say whether the list is complete", async () => {
mocks.connections.mockResolvedValue({ connections: [] });
await render();
expect(visible()).toBeNull();
});
it("makes no requests and stays masked when session replay is off", async () => {
mocks.session = { browserAnalytics: null };
await render();
expect(visible()).toBeNull();
expect(mocks.connections).not.toHaveBeenCalled();
expect(mocks.chatEndpoints).not.toHaveBeenCalled();
});
it.each([
null,
{ browserAnalytics: null },
{ browserAnalytics: { replayEnabled: false, replayWorkContentEnabled: true } },
{ browserAnalytics: { replayEnabled: true } },
{ browserAnalytics: { replayEnabled: true, replayWorkContentEnabled: false } },
])("makes no source requests and stays masked without both deployment switches: %j", async (session) => {
mocks.session = session;
await render();
expect(visible()).toBeNull();
expect(mocks.connections).not.toHaveBeenCalled();
expect(mocks.chatEndpoints).not.toHaveBeenCalled();
expect(mocks.refresh).not.toHaveBeenCalled();
});
it("masks cached eligible content when the deployment opt-in is withdrawn", async () => {
await render();
expect(visible()).toBe("visible");
await act(async () => {
queryClient.setQueryData(queryKeys.auth.session, {
browserAnalytics: { replayEnabled: true, replayWorkContentEnabled: false },
});
});
await settle();
expect(visible()).toBeNull();
expect(mocks.connections).toHaveBeenCalledTimes(1);
expect(mocks.chatEndpoints).toHaveBeenCalledTimes(1);
expect(mocks.refresh).toHaveBeenCalledTimes(1);
});
it("masks again as soon as a source change resets the check, and stays masked for a new Google connection", async () => {
await render();
expect(visible()).toBe("visible");
let finishReload: (value: unknown) => void = () => {};
mocks.connections.mockImplementation(() => new Promise((resolve) => { finishReload = resolve; }));
await act(async () => {
void queryClient.resetQueries({ queryKey: replayWorkContentQueryKeys.connections("co-1") });
});
await settle();
expect(visible()).toBeNull();
finishReload(connectionList([connection({ config: { sourceTemplateKey: "gmail" } })]));
await settle();
expect(visible()).toBeNull();
expect(mocks.connections).toHaveBeenCalledTimes(2);
});
it("masks while the page shows another company than the selected one", async () => {
// The selection follows the URL in an effect after the page renders, and
// a manual switch delays it, so another company's task can render first.
await render();
expect(visible()).toBe("visible");
mocks.pathname = "/OTHER/issues/OTHER-7";
await render();
expect(visible()).toBeNull();
mocks.pathname = "/ACME/issues/ACME-1";
await render();
expect(visible()).toBe("visible");
expect(mocks.refresh).toHaveBeenCalledTimes(1);
});
it("masks while an invalidated list refreshes, and shows again without another snapshot", async () => {
// `LiveUpdatesProvider` invalidates every active query when the tab
// returns or the socket reopens, because it missed events meanwhile.
await render();
expect(visible()).toBe("visible");
let finishReload: (value: unknown) => void = () => {};
mocks.chatEndpoints.mockImplementation(() => new Promise((resolve) => { finishReload = resolve; }));
await act(async () => {
void queryClient.invalidateQueries({ queryKey: replayWorkContentQueryKeys.chatEndpoints("co-1") });
});
await settle();
expect(visible()).toBeNull();
finishReload([]);
await settle();
expect(visible()).toBe("visible");
expect(mocks.refresh).toHaveBeenCalledTimes(1);
});
it("starts from unknown on a return to a company, and takes a new snapshot when it shows", async () => {
await render();
expect(visible()).toBe("visible");
mocks.companyId = "co-2";
mocks.companyPrefix = "OTHER";
mocks.pathname = "/OTHER/dashboard";
mocks.connections.mockResolvedValue(connectionList([connection({ config: { sourceTemplateKey: "gmail" } })]));
await render();
expect(visible()).toBeNull();
mocks.companyId = "co-1";
mocks.companyPrefix = "ACME";
mocks.pathname = "/ACME/dashboard";
let finishReload: (value: unknown) => void = () => {};
mocks.connections.mockImplementation(() => new Promise((resolve) => { finishReload = resolve; }));
await render();
// The first answer for co-1 is gone: nothing shows until a new one loads.
expect(visible()).toBeNull();
finishReload(connectionList());
await settle();
expect(visible()).toBe("visible");
expect(mocks.refresh).toHaveBeenCalledTimes(2);
});
it("masks when a refresh fails, even with an earlier answer cached", async () => {
await render();
expect(visible()).toBe("visible");
mocks.connections.mockRejectedValue(new Error("403"));
await act(async () => {
await queryClient.refetchQueries({ queryKey: replayWorkContentQueryKeys.connections("co-1") });
});
await settle();
expect(visible()).toBeNull();
});
it("clears the attribute on unmount", async () => {
await render();
expect(visible()).toBe("visible");
act(() => root.unmount());
expect(visible()).toBeNull();
root = createRoot(host);
});
});
@@ -0,0 +1,277 @@
// Decides whether session replay may show work content (task descriptions,
// document bodies, artifact contents) for the active company.
//
// Work content stays masked unless the company holds no Google or Slack data:
// agents copy connected-account content into tasks and artifacts, and our
// privacy policy and the Google API Limited Use rules say no person may read
// that content in a replay. Every unknown state (analytics off, no company,
// a query loading, failing or waiting on a refresh, a connection list the
// server filtered) keeps it masked, and a new connection or chat channel masks
// it again until the check reruns.
import { useLayoutEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { connectionSourceSlug, isAppAggregator, type ToolConnection } from "@paperclipai/shared";
import { authApi } from "@/api/auth";
import { chatEndpointsApi, type ChatEndpoint } from "@/api/chatEndpoints";
import { toolsApi } from "@/api/tools";
import { useCompany } from "@/context/CompanyContext";
import { extractCompanyPrefixFromPath } from "@/lib/company-routes";
import { queryKeys } from "@/lib/queryKeys";
import { useLocation } from "@/lib/router";
import { REPLAY_WORK_CONTENT_ATTRIBUTE } from "./privacy";
import { refreshSessionReplay } from "./product-analytics";
/** Google (Gmail, Drive, Calendar, Docs, ...) and Slack, by slug, name or server URL. */
const CONNECTED_ACCOUNT_PATTERN = /google|gmail|slack/i;
/**
* Catalog apps that reach Google or Slack data through another service:
* automation routers (Zapier, Make) and Google Search Console or Google Ads
* readers (GSC Wizard, Windsor.ai). They count like an aggregator.
*/
const ROUTER_SOURCE_SLUGS = new Set(["zapier", "make", "gsc-wizard", "windsor-ai"]);
/**
* The server hosts of the aggregators and router apps. "Connect your own MCP
* server" saves a URL and a free name with no catalog slug, so a gateway
* added that way is found by its host.
*/
const GATEWAY_SOURCE_HOSTS = [
"composio.dev", "arcade.dev", "executor.sh",
"zapier.com", "make.com", "gscwizard.com", "windsor.ai",
];
/** The same services by the name a person is likely to give the connection. */
const GATEWAY_SOURCE_NAME = /\b(?:composio|arcade|executor|zapier|make|windsor(?:\.ai)?|gsc wizard)\b/i;
function isGatewaySourceUrl(value: string): boolean {
let host: string;
try {
host = new URL(value).hostname.toLowerCase();
} catch {
return false;
}
return GATEWAY_SOURCE_HOSTS.some((gatewayHost) => host === gatewayHost || host.endsWith(`.${gatewayHost}`));
}
function stringValue(value: unknown): string {
return typeof value === "string" ? value : "";
}
/**
* True when a tool connection can bring Google or Slack data into the company.
* Any status counts (draft, disabled and archived too), because content an
* agent copied while it was active stays in tasks and artifacts. Aggregators
* (Composio, Arcade, Executor) and the router apps above count too: they can
* route Google or Slack.
*/
export function connectionCarriesConnectedAccountData(
connection: Pick<ToolConnection, "name" | "config" | "transportConfig"> & { metadata?: Record<string, unknown> | null },
): boolean {
const slug = connectionSourceSlug(connection);
if (slug && (isAppAggregator(slug) || ROUTER_SOURCE_SLUGS.has(slug))) return true;
const transport = connection.transportConfig ?? {};
if (isGatewaySourceUrl(stringValue(transport.url)) || isGatewaySourceUrl(stringValue(transport.serverUrl))) return true;
if (GATEWAY_SOURCE_NAME.test(connection.name)) return true;
const haystack = [
slug ?? "",
connection.name,
stringValue(transport.url),
stringValue(transport.serverUrl),
stringValue(transport.sourceTemplateKey),
stringValue(connection.config?.sourceTemplateKey),
// Chat channel connections (Slack and others) store their provider here,
// with no template key or URL, and keep a custom name.
stringValue(connection.config?.provider),
].join(" ");
return CONNECTED_ACCOUNT_PATTERN.test(haystack);
}
/**
* True when work content may show in replays: both lists loaded, the
* connection list is complete, and no tool connection or chat endpoint (any
* status) is Google, Slack, an aggregator or a router app.
*
* The server leaves some connections out of a reader's list: another person's
* draft (a Google or Slack connection returns to draft when its sign-in
* expires) and a connector whose plugin is unavailable. It reports how many
* as `hiddenCount`. A hidden row can be Google or Slack, so only a list with
* `hiddenCount: 0` counts. An older server sends no count, which also masks.
*/
export function companyAllowsReplayWorkContent(
connectionList: {
connections: ReadonlyArray<Parameters<typeof connectionCarriesConnectedAccountData>[0]>;
hiddenCount?: number;
} | undefined,
chatEndpoints: ReadonlyArray<Pick<ChatEndpoint, "provider">> | undefined,
): boolean {
if (!connectionList || !chatEndpoints) return false;
if (connectionList.hiddenCount !== 0) return false;
if (connectionList.connections.some(connectionCarriesConnectedAccountData)) return false;
if (chatEndpoints.some((endpoint) => endpoint.provider === "slack")) return false;
return true;
}
/**
* True when the page at `pathname` belongs to the company with this issue
* prefix, or to no company. The visible flag is the selected company's
* answer, but the selection follows the URL in an effect after the page
* renders, and a manual switch delays it. In between, the page can show
* another company's task under the selected company's flag, so a company
* page counts only when its prefix is the selected company's.
*/
export function routeShowsCompany(pathname: string, issuePrefix: string | null | undefined): boolean {
const routePrefix = extractCompanyPrefixFromPath(pathname);
if (!routePrefix) return true;
return !!issuePrefix && routePrefix.toUpperCase() === issuePrefix.toUpperCase();
}
function setReplayWorkContent(visible: boolean) {
const root = document.documentElement;
if (visible) root.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
else root.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
/**
* Query keys for this check, kept apart from the Apps page's keys so a reset
* masks replays without touching other screens.
*/
export const replayWorkContentQueryKeys = {
all: ["replay-work-content"] as const,
connections: (companyId: string) => ["replay-work-content", companyId, "connections"] as const,
chatEndpoints: (companyId: string) => ["replay-work-content", companyId, "chat-endpoints"] as const,
};
/**
* Activity that can add a Google or Slack source, by the family of the action
* the server logs: a tool connection or app (`tool_connection.*`,
* `tool_app.*`, `tool_example.*`, `tool_application.*`,
* `connection_installs.*`), a model connection (`ai_connection.*`), a chat or
* email channel (`chat_endpoint.*`, `chat_github.*`, `email_endpoint.*`), or
* an imported company. Several routes add a connection row and some build the
* action name at run time, so the check matches the whole family: a new
* action re-checks without a change here. `LiveUpdatesProvider` resets the
* check on these, so work content stays masked until the source lists load.
*/
const SOURCE_CHANGE_FAMILIES = [
"tool_connection.",
"tool_app.",
"tool_example.",
"tool_application.",
"connection_installs.",
"ai_connection.",
"chat_endpoint.",
"chat_github.",
"email_endpoint.",
];
const SOURCE_CHANGE_ACTIONS = new Set(["company.imported"]);
/**
* Frequent actions in those families that cannot add a source: health and
* catalog checks, credential reads and refreshes, and incoming webhooks. A
* re-check on each of them would mask work content over and over.
*/
const NOT_A_SOURCE_CHANGE = new Set([
"tool_connection.health_check",
"tool_connection.catalog_refresh",
"tool_connection.credential_resolution",
"tool_connection.webhook_processed",
"ai_connection.credential_refreshed",
"chat_endpoint.webhook_verified",
]);
export function isReplayWorkContentSourceChange(action: string | null | undefined): boolean {
if (!action || NOT_A_SOURCE_CHANGE.has(action)) return false;
return SOURCE_CHANGE_ACTIONS.has(action) || SOURCE_CHANGE_FAMILIES.some((family) => action.startsWith(family));
}
/** Backstop refresh, in case a live update is missed (a dropped socket). */
const RECHECK_INTERVAL_MS = 5 * 60 * 1000;
/**
* Shared options of the two source lists. `staleTime: Infinity` makes a list
* stale only when something invalidates it, so `isCurrentAnswer` can tell a
* confirmed answer from one that is waiting on a refresh. `gcTime: 0` drops
* the answer as soon as the company changes, so a return to that company
* starts from unknown instead of an old answer.
*/
const SOURCE_LIST_OPTIONS = {
refetchInterval: RECHECK_INTERVAL_MS,
staleTime: Infinity,
gcTime: 0,
} as const;
/**
* True when a source list holds a confirmed answer: its latest fetch
* succeeded and nothing has invalidated it since. The live socket closes
* while the tab is hidden and does not replay events, so
* `LiveUpdatesProvider` invalidates every active query when the tab returns
* or the socket reopens. Until that refresh lands, an earlier "no Google or
* Slack" answer may have missed a new source, so it does not count.
*/
function isCurrentAnswer(query: { status: string; isStale: boolean }): boolean {
return query.status === "success" && !query.isStale;
}
/**
* Sets `REPLAY_WORK_CONTENT_ATTRIBUTE` on `<html>` for the active company.
* Renders nothing. Mount it under `CompanyProvider`. It runs its queries only
* when session replay is on (hosted Cloud), so self-hosted installs make no
* extra requests.
*/
export function ReplayWorkContentVisibility() {
const { selectedCompanyId, selectedCompany } = useCompany();
const { pathname } = useLocation();
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
const workContentEnabled = session?.browserAnalytics?.replayEnabled === true
&& session.browserAnalytics.replayWorkContentEnabled === true;
const companyId = workContentEnabled ? selectedCompanyId : null;
const connections = useQuery({
...SOURCE_LIST_OPTIONS,
queryKey: replayWorkContentQueryKeys.connections(companyId ?? ""),
queryFn: () => toolsApi.listConnections(companyId!),
enabled: !!companyId,
});
const chatEndpoints = useQuery({
...SOURCE_LIST_OPTIONS,
queryKey: replayWorkContentQueryKeys.chatEndpoints(companyId ?? ""),
queryFn: () => chatEndpointsApi.list(companyId!),
enabled: !!companyId,
});
// Only a confirmed answer counts: while loading, after a reset, while a
// refresh is pending, when the latest fetch failed (even with older data
// cached) and while the page shows another company, work content stays
// masked.
const visible = !!companyId
&& routeShowsCompany(pathname, selectedCompany?.issuePrefix)
&& isCurrentAnswer(connections)
&& isCurrentAnswer(chatEndpoints)
&& companyAllowsReplayWorkContent(connections.data, chatEndpoints.data);
// The company whose work content this recording already shows.
const snapshotCompanyId = useRef<string | null>(null);
// Layout effect: it runs before rrweb's mutation observer reads a company
// switch, so the next company's content is never recorded with the last
// company's setting.
useLayoutEffect(() => {
setReplayWorkContent(visible);
if (!visible) {
if (snapshotCompanyId.current !== companyId) snapshotCompanyId.current = null;
return;
}
// Text recorded before the first answer for this company is masked, so
// record the page again once. A later re-check masks only what renders
// while it runs, which is not worth another full snapshot.
if (snapshotCompanyId.current !== companyId) {
snapshotCompanyId.current = companyId;
refreshSessionReplay();
}
}, [visible, companyId]);
useLayoutEffect(() => () => setReplayWorkContent(false), []);
return null;
}
+2
View File
@@ -3,6 +3,8 @@ import type { ExecutionWorkspace, Issue, Project } from "@paperclipai/shared";
type ProjectWorkspaceLike = Pick<Project, "workspaces" | "primaryWorkspace">;
export type ProjectWorkspaceLinkedIssue = Pick<Issue, "id" | "identifier" | "title" | "updatedAt"> & {
/** Read by the task preview's session replay rule (`IssueQuicklookCard`). */
companyId?: string | null;
status: string;
priority: string;
description?: string | null;
+2
View File
@@ -9,6 +9,7 @@ import { App } from "./App";
import { AppErrorBoundary } from "./components/AppErrorBoundary";
import { SentryGate } from "./components/SentryGate";
import { ProductAnalyticsGate } from "./components/ProductAnalyticsGate";
import { ReplayWorkContentVisibility } from "./lib/analytics/replay-work-content";
import { CompanyProvider, useCompany } from "./context/CompanyContext";
import { LinkPreviewProvider } from "./context/LinkPreviewContext";
import { LiveUpdatesProvider } from "./context/LiveUpdatesProvider";
@@ -137,6 +138,7 @@ getOrCreatePaperclipReactRoot(window, rootElement).render(
<ThemeProvider>
<BrowserRouter>
<CompanyProvider>
<ReplayWorkContentVisibility />
<EditorAutocompleteProvider>
<ToastProvider>
<MutationErrorToastBridge />
+1
View File
@@ -8321,6 +8321,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
placeholder="Add a description..."
multiline
foldable
replayContent="work"
mentions={mentionOptions}
externalReferences={
externalObjectsState.isEnabled