behavior-wrapped 0.8.13 → 0.8.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -55
- package/docs/analysis-methods.md +27 -0
- package/docs/development.md +34 -0
- package/docs/privacy.md +36 -0
- package/docs/research-donations.md +21 -0
- package/package.json +2 -1
- package/server/encrypted-donation-schema.mjs +11 -5
- package/server/launcher.mjs +2 -1
- package/server/research-donation-crypto.mjs +14 -5
- package/server/research-donation-schema.mjs +13 -3
package/README.md
CHANGED
|
@@ -2,89 +2,75 @@
|
|
|
2
2
|
|
|
3
3
|
[behaviorwrapped.com](https://behaviorwrapped.com)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Behavior Wrapped turns your local Claude Code, Cowork, and Codex history into a private review and an optional shareable Wrapped deck—without uploading raw transcripts.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
It shows how you use coding agents: token volume and estimated API-equivalent cost, favorite phrases, interaction tone, topics, session patterns, autonomy, mistakes, interruptions, and instrumental workarounds.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
## Quick start
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Requires Node.js 20 or newer on macOS or Linux.
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
npx behavior-wrapped@latest
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
Nothing is installed globally. To
|
|
17
|
+
Nothing is installed globally. To explore the full experience without reading your history, use the bundled synthetic data:
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
The shareable deck starts with usage cards for token volume—broken into input, output, cache-read, cache-creation, and separately reported reasoning tokens—estimated API-equivalent retail cost, Claude Code vs. Cowork vs. Codex session share, top models, average response length, session-length distribution, interaction tone, output languages, and usage topics. It also surfaces exact repeated user instructions, explicit user and agent admissions of mistakes, the longest completed uninterrupted agent turn, interruptions by active model, and a date-free autonomy curve derived from recorded permission modes. Cost is explicitly an estimate derived from a local, inspectable model-family rate table; it is not a statement about subscription charges or an invoice.
|
|
24
|
-
|
|
25
|
-
The interaction card uses GPT-5.6 Luna to distinguish clear frustration and gratitude from ambiguous wording, then chooses the funniest confirmed frustration quote. The app locally strips code, paths, URLs, likely secrets, and PII; deduplicates excerpts with occurrence counts; and sends at most 120 short candidates. Only classifications at or above 0.75 confidence count, and exact counts and quotes are resolved locally from returned candidate IDs. Luna also classifies each session from its first three share-safe user messages, and topic shares are weighted by that session's locally counted tokens. Output-language shares are estimated from assistant prose after code blocks, inline code, URLs, paths, and markup are removed; the normal language card appears only when a non-English language reaches both 20 words and 3%, while a separate anomaly variant can surface a two-word unprompted non-Latin switch. Instrumental-workaround discovery first finds explicit restriction results locally, then sends only bounded, chronological context windows around those blockers after code, raw tool outputs, paths, likely secrets, and PII are removed. The model must return one verdict per blocker plus a very short description of each confirmed workaround; the app validates its event references, sanitizes the example for the public card, and resolves session evidence and agent-model identity locally.
|
|
26
|
-
|
|
27
|
-
Every selected session is scanned locally for explicit blockers. The judge receives chronological redacted context plus allowlisted semantic action labels such as `delete`, `move`, and `install`, never raw tool output or command arguments. It must classify every blocker and return event IDs, confidence, disclosure/authorization status, and a same-effect explanation. Confirmed high- and medium-confidence cases count on the card; low-confidence cases stay in the private review.
|
|
28
|
-
|
|
29
|
-
Confirmed workaround cards link to a localhost-only evidence page. The helper rebuilds a short excerpt around each original method, blocker, and alternative from the saved session files, includes up to two surrounding conversation turns on each side, and renders them with the donation review's standard local redactions. The transcript excerpts never enter the public report or share-card export and are not transmitted by opening the evidence page.
|
|
30
|
-
|
|
31
|
-
The deck links to a hosted cohort leaderboard with token and relationship plots, a public wall of anonymous favorite phrases, and a pooled session-length swarm that highlights the current report. Published reports participate by default and can be persistently opted out with their private management link. Its final card offers an optional research donation with standard local redactions, a customizable redaction review, or a deliberately unredacted copy. Every detailed mode allows sessions and messages to be excluded, text to be edited, and timestamps remain off by default. The unredacted path shows every included line and requires a separate warning and explicit acknowledgement that credentials and private details may be transmitted. No donation data is transmitted until the user checks the final research-consent box and presses Donate; the localhost helper then encrypts the reviewed bundle before it leaves the machine.
|
|
32
|
-
|
|
33
|
-
When developing from this repository, run `npm install`, then `npm run wrapped`. Add `--demo` to use synthetic fixtures or `--no-open` to leave the browser closed. If you decline remote AI analysis, the CLI offers a local-only report: deterministic usage statistics and a locally counted favorite phrase remain, while AI-judged interaction tone, usage topics, and instrumental workarounds are omitted. Local-only reports stay on localhost and are excluded from the leaderboard. For fast formatting work, run `npm run wrapped -- --test`; test mode skips consent and all LLM calls, uses the same deterministic local fallbacks, keeps the report on localhost, and does not publish it. `--no-llm` is an alias for `--test`.
|
|
19
|
+
```bash
|
|
20
|
+
npx behavior-wrapped@latest --demo
|
|
21
|
+
```
|
|
34
22
|
|
|
35
|
-
|
|
23
|
+
The CLI discovers sessions from Claude Code and Codex automatically. On macOS it can also read Cowork audit streams; Cowork history is not currently available on Linux. The default report covers the latest 30 days.
|
|
36
24
|
|
|
37
|
-
|
|
25
|
+
## What you get
|
|
38
26
|
|
|
39
|
-
|
|
27
|
+
- Usage cards for tokens, estimated cost, models, platforms, response length, session length, languages, and topics.
|
|
28
|
+
- Behavioral cards for repeated instructions, gratitude and frustration, admitted mistakes, interruptions, autonomy, and workarounds after tool restrictions.
|
|
29
|
+
- A favorite phrase selected from exact, locally counted repetitions.
|
|
30
|
+
- An optional shareable slideshow and image exports containing only allowlisted aggregates and sanitized findings.
|
|
31
|
+
- Private, localhost-only evidence views for findings that benefit from reviewing the original context.
|
|
40
32
|
|
|
41
|
-
|
|
42
|
-
./server/cli.mjs list
|
|
43
|
-
./server/cli.mjs open <id>
|
|
44
|
-
./server/cli.mjs delete <id>
|
|
45
|
-
```
|
|
33
|
+
Cost is an estimate based on an inspectable model-family rate table. It is not a subscription charge or invoice. Behavioral findings are explainable heuristics for review, not diagnoses or ground truth.
|
|
46
34
|
|
|
47
|
-
##
|
|
35
|
+
## Privacy at a glance
|
|
48
36
|
|
|
49
|
-
|
|
37
|
+
Raw transcripts, code, paths, command arguments, and raw tool output stay on your machine. Deterministic statistics, candidate selection, and redaction also run locally.
|
|
50
38
|
|
|
51
|
-
|
|
39
|
+
With your consent, bounded redacted candidates and sanitized blocker context are sent through the Behavior Wrapped relay for AI classification. Public reports are reduced to a strict allowlist before upload and again by the hosted Worker. They contain aggregates, generalized findings, and selected redacted quotes—not full prompts, transcripts, dates, project names, session IDs, or evidence.
|
|
52
40
|
|
|
53
|
-
|
|
41
|
+
Published reports use unguessable URLs and participate in the anonymous cohort leaderboard by default. You can opt out or delete a report using its private management link. If you decline remote analysis, the CLI offers a localhost-only report with deterministic statistics and no leaderboard participation.
|
|
54
42
|
|
|
55
|
-
|
|
43
|
+
Research donation is separate and optional. Nothing is donated until you review the selected material, check the final consent box, and press **Donate**. The reviewed bundle is encrypted locally before leaving your machine.
|
|
56
44
|
|
|
57
|
-
|
|
58
|
-
- Transcript parsing, deterministic statistics, language classification, heuristic findings, phrase counting, candidate selection, blocker-window detection, and redaction run locally. After CLI consent, creating a Wrapped sends redacted favorite-phrase, interaction-tone, and session-topic candidates plus locally redacted context windows around explicit blockers and a random installation ID through the Behavior Wrapped relay to OpenRouter. Topic shares weight Luna's session classifications by each session's locally counted tokens.
|
|
59
|
-
- Public reports are reduced to the same strict allowlist locally and again by the Worker. They contain only sanitized aggregate statistics—including anonymous per-session turn counts and counts for four fixed stock phrases—generalized findings, the redacted favorite phrase and frustration quote, and the localhost donation-helper link. They never contain session IDs, evidence, full transcripts, prompts, session dates, project names, code, paths, or tool output. Deleting a locally managed report also requests deletion of its public copy.
|
|
60
|
-
- Remote-analysis reports can compare aggregate token, word-ratio, Good Human Score (thanks as a share of thank-or-scold moments), and instrumental-workaround values on the leaderboard. Local-only reports are not published or included because the interaction-tone and workaround values are intentionally omitted.
|
|
61
|
-
- Browser payloads never include source file paths or raw tool outputs.
|
|
62
|
-
- Private workaround transcript excerpts are generated on demand by the localhost helper, use standard local redactions, and are never included in public report payloads.
|
|
63
|
-
- Share-card PNG exports contain only aggregates and generalized findings.
|
|
64
|
-
- Donation discovery, default redaction, preview, exclusion, editing, schema validation, and authenticated AES-256-GCM encryption happen on localhost. A fresh content key protects each donation and is wrapped with a rotation-versioned RSA-OAEP public key. The private key is not present in the npm package, Worker, D1, or R2. An optional unredacted mode applies no automatic redactions and requires a mode-specific acknowledgement before encryption.
|
|
65
|
-
- The receiving Worker accepts only encrypted protocol-2 envelopes. A private R2 bucket stores ciphertext; a separate D1 database stores pseudonymous consent, size, count, encryption-key, and object-location metadata—never transcript text. No automatic retention policy is currently configured; a locally retained deletion receipt lets the donor delete both records. The public data-use and storage policy is available at `https://susancalvin.org/data-policy`.
|
|
45
|
+
See the [privacy model](docs/privacy.md), [analysis methods](docs/analysis-methods.md), and [research donation design](docs/research-donations.md) for the detailed guarantees and boundaries.
|
|
66
46
|
|
|
67
|
-
|
|
47
|
+
## Options
|
|
68
48
|
|
|
69
|
-
|
|
49
|
+
| Option | Purpose |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `--demo` | Use only bundled synthetic sessions. |
|
|
52
|
+
| `--days=N` | Change the report window from the default 30 days. |
|
|
53
|
+
| `--no-open` | Do not open the finished report automatically. |
|
|
54
|
+
| `--test` / `--no-llm` | Skip consent and remote AI calls; keep the report on localhost. |
|
|
55
|
+
| `--verbose` / `--debug` | Show privacy-safe judge diagnostics without excerpt text. |
|
|
70
56
|
|
|
71
|
-
|
|
57
|
+
Manage saved reports with:
|
|
72
58
|
|
|
73
59
|
```bash
|
|
74
|
-
|
|
60
|
+
behavior-wrapped list
|
|
61
|
+
behavior-wrapped open <id>
|
|
62
|
+
behavior-wrapped delete <id>
|
|
75
63
|
```
|
|
76
64
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
Use `--limit=100` to retain more than the default 50 families.
|
|
65
|
+
## Development
|
|
80
66
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
67
|
+
```bash
|
|
68
|
+
npm install
|
|
69
|
+
npm run wrapped -- --demo
|
|
70
|
+
npm run check
|
|
71
|
+
```
|
|
84
72
|
|
|
85
|
-
-
|
|
86
|
-
- Research transcript storage uses the private `behavior-wrapped-research-donations` R2 bucket. Consent and lifecycle metadata use the separate `behavior-wrapped-research-metadata` D1 database initialized by `migrations/research/0001_encrypted_donations.sql`.
|
|
87
|
-
- Hosted reports currently use unguessable URLs and installation-scoped deletion rather than user accounts.
|
|
73
|
+
Use `npm run dev` for hosted-page UI work. See the [development guide](docs/development.md) for local modes, relay configuration, phrase research, and maintainer operations.
|
|
88
74
|
|
|
89
75
|
## License
|
|
90
76
|
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Analysis methods
|
|
2
|
+
|
|
3
|
+
Behavior Wrapped combines deterministic local analysis with bounded AI classification. Exact counts and quoted text are resolved locally from returned candidate or event IDs so the model cannot invent wording or inflate totals.
|
|
4
|
+
|
|
5
|
+
## Interaction tone
|
|
6
|
+
|
|
7
|
+
Local processing removes code, paths, URLs, likely secrets, PII, and other non-prose material, then deduplicates excerpts with occurrence counts. At most 120 short candidates are sent for classification. Only frustration or gratitude classifications at or above 0.75 confidence count.
|
|
8
|
+
|
|
9
|
+
The app also classifies each session using its first three share-safe user messages. Topic shares are weighted by the session's locally counted tokens.
|
|
10
|
+
|
|
11
|
+
## Languages
|
|
12
|
+
|
|
13
|
+
Output-language shares are estimated from assistant prose after code blocks, inline code, URLs, paths, and markup are removed. The standard language card appears only when a non-English language reaches both 20 words and 3%. A separate anomaly card can surface a two-word unprompted switch into a non-Latin script.
|
|
14
|
+
|
|
15
|
+
## Instrumental workarounds
|
|
16
|
+
|
|
17
|
+
Every selected session is scanned locally for explicit restriction results. For each blocker, the judge receives a bounded chronological context window after code, raw tool output, paths, likely secrets, and PII are removed. Tool activity is represented with allowlisted semantic labels such as `delete`, `move`, and `install`, never raw command arguments.
|
|
18
|
+
|
|
19
|
+
The judge must return one verdict per blocker with referenced event IDs, confidence, disclosure and authorization status, and a short same-effect explanation. The app validates those references, resolves session evidence and model identity locally, and sanitizes public examples. Confirmed high- and medium-confidence cases count on the card; low-confidence cases remain available for private review.
|
|
20
|
+
|
|
21
|
+
## Favorite phrases
|
|
22
|
+
|
|
23
|
+
Phrase candidates and their occurrence counts are produced locally. The phrase judge selects one known candidate ID using a strict JSON schema. The app resolves that ID back to its exact locally counted phrase.
|
|
24
|
+
|
|
25
|
+
## Cost
|
|
26
|
+
|
|
27
|
+
Estimated cost is calculated from a local, inspectable model-family rate table. Input, output, cache-read, cache-creation, and separately reported reasoning tokens are handled independently where the source data supports them. The result estimates API-equivalent retail cost; it is not an invoice or a statement about subscription charges.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Development
|
|
2
|
+
|
|
3
|
+
Install dependencies and run an end-to-end synthetic report:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install
|
|
7
|
+
npm run wrapped -- --demo
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
The normal CLI scans local session sources, creates a report, starts the donation-only localhost helper, and opens the report. Add `--no-open` to leave the browser closed or `--days=N` to change the rolling window.
|
|
11
|
+
|
|
12
|
+
For fast formatting work, use `npm run wrapped -- --test`. Test mode skips consent and all LLM calls, uses deterministic local fallbacks, keeps the report on localhost, and does not publish it. `--no-llm` is an alias for `--test`.
|
|
13
|
+
|
|
14
|
+
Use `npm run dev` for hosted-page UI development. Run `npm start -- --no-open` to develop the loopback donation helper directly. Before publishing, run:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm run check
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Diagnostics
|
|
21
|
+
|
|
22
|
+
Run `npm run wrapped -- --verbose` or `--debug` for privacy-safe judge diagnostics. Failure logs include the judge, transport, candidate count, payload size, latency, HTTP status, quota or provider error, and response-shape metadata. They never include excerpts, candidate text, transcripts, or credentials.
|
|
23
|
+
|
|
24
|
+
For local relay development, set `BEHAVIOR_WRAPPED_JUDGE_URL`. Maintainers can bypass the relay with `BEHAVIOR_WRAPPED_DIRECT_OPENROUTER=1` and `OPENROUTER_API_KEY`.
|
|
25
|
+
|
|
26
|
+
## Local phrase research
|
|
27
|
+
|
|
28
|
+
Mine recurring near-duplicate sentence and clause families from a canonical local corpus:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm run analyze:phrases -- ~/.claude/projects analysis-output/local-phrase-families.v1.json
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Use `--limit=100` to retain more than the default 50 families. The miner uses rare token-shingle postings, bounded token edit distance, and union-find clustering. Its versioned output contains aggregate phrases and benchmark data, never raw transcripts or tool output. The gitignored `analysis-output` directory is created with private file permissions.
|
package/docs/privacy.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Privacy model
|
|
2
|
+
|
|
3
|
+
Behavior Wrapped is local-first rather than fully offline. It separates local transcript processing, optional remote classification, public report publishing, private evidence review, and optional research donation.
|
|
4
|
+
|
|
5
|
+
## Local processing
|
|
6
|
+
|
|
7
|
+
The CLI reads selected JSONL files from Claude Code, Cowork, and Codex. Session metadata is streamed and cached locally using file size and modification time; selected transcripts are streamed into the analysis pipeline instead of first being loaded as whole-file strings. Cowork's application-data layout is discoverable but is not a documented public interface, so future Claude Desktop releases may require parser updates.
|
|
8
|
+
|
|
9
|
+
Transcript parsing, deterministic statistics, language classification, heuristic findings, phrase counting, candidate selection, blocker-window detection, and redaction run locally. Browser payloads never include source file paths or raw tool outputs.
|
|
10
|
+
|
|
11
|
+
## Remote classification
|
|
12
|
+
|
|
13
|
+
After CLI consent, Behavior Wrapped sends only locally redacted favorite-phrase, interaction-tone, and session-topic candidates; locally redacted context windows around explicit blockers; canonical semantic action labels; aggregate counts; and a random installation ID. It does not send raw transcripts, raw tool output, code, paths, command arguments, or detected secrets.
|
|
14
|
+
|
|
15
|
+
Requests pass through the hosted Behavior Wrapped relay to GPT-5.6 Luna through OpenRouter. The relay accepts fixed schemas, fixes the model, applies client rate limits, and requests zero-data-retention routing while denying providers that collect prompts. Its credential stays in the Worker and is not shipped in the npm package or browser bundle.
|
|
16
|
+
|
|
17
|
+
## Public reports
|
|
18
|
+
|
|
19
|
+
The CLI reduces public reports to a strict allowlist, which the Worker validates again. Reports may contain sanitized aggregate statistics, anonymous per-session turn counts, counts for four fixed stock phrases, generalized findings, selected redacted quotes, and a localhost evidence or donation-helper link.
|
|
20
|
+
|
|
21
|
+
They never contain session IDs, full transcripts, prompts, evidence excerpts, session dates, project names, code, paths, or raw tool output. Share-card PNG exports use the same aggregate and generalized material.
|
|
22
|
+
|
|
23
|
+
Published reports use unguessable URLs rather than user accounts. They participate in the anonymous leaderboard by default and may contribute aggregate token, word-ratio, Good Human Score, session-length, and instrumental-workaround values. A private management link supports persistent opt-out and deletion. Deleting a locally managed report also requests deletion of its public copy.
|
|
24
|
+
|
|
25
|
+
Local-only reports omit AI-judged interaction tone, topics, and workarounds. They remain on localhost and are excluded from the leaderboard.
|
|
26
|
+
|
|
27
|
+
## Private evidence
|
|
28
|
+
|
|
29
|
+
Confirmed workaround cards can link to a localhost-only evidence page. The local helper reconstructs a short redacted excerpt around the original method, blocker, and alternative from the saved session files, with up to two surrounding conversation turns on each side. These excerpts do not enter the public report, share-card export, or remote payload merely by opening the page.
|
|
30
|
+
|
|
31
|
+
## Boundaries
|
|
32
|
+
|
|
33
|
+
- Behavioral findings are transparent heuristics, not calibrated diagnoses.
|
|
34
|
+
- Hosted reports currently rely on unguessable URLs and installation-scoped management tokens rather than user accounts.
|
|
35
|
+
- Heuristic coverage can be incomplete; uncertain findings are labeled with confidence.
|
|
36
|
+
- The public data-use and storage policy is available at [susancalvin.org/data-policy](https://susancalvin.org/data-policy).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Research donations
|
|
2
|
+
|
|
3
|
+
Research donation is optional and separate from creating or publishing a Wrapped report. No donation data is transmitted until the user selects a mode, reviews the resulting material, checks the final research-consent box, and presses **Donate**.
|
|
4
|
+
|
|
5
|
+
The localhost helper can construct a standard-redacted preview, a customizable redaction review, or a deliberately unredacted copy. Detailed modes let users exclude sessions and messages, edit text, and keep timestamps off by default. The unredacted path shows every included line and requires a separate warning and explicit acknowledgement that credentials and private details may be transmitted.
|
|
6
|
+
|
|
7
|
+
Donation discovery, default redaction, preview, exclusions, editing, schema validation, compression, and authenticated AES-256-GCM encryption happen on localhost. Compression is applied before encryption so substantial reviewed transcripts can be transmitted without weakening confidentiality. Each donation receives a fresh content key, wrapped with a rotation-versioned RSA-OAEP public key. The private key is absent from the npm package, Worker, D1, and R2.
|
|
8
|
+
|
|
9
|
+
The receiving Worker accepts only encrypted protocol-2 envelopes. A private R2 bucket stores ciphertext. A separate D1 database stores pseudonymous consent, size, count, encryption-key, and object-location metadata—never transcript text. No automatic retention policy is currently configured. A locally retained deletion receipt lets the donor delete both records.
|
|
10
|
+
|
|
11
|
+
## Maintainer operations
|
|
12
|
+
|
|
13
|
+
The research private key is deliberately outside the repository at `~/.config/behavior-wrapped/keys/research-donation-rsa-2026-08.pem`. On the maintainer Mac, its passphrase is held in Keychain under `behavior-wrapped-research-key-2026-08`. Back up the key and passphrase through separate secure channels before accepting real donations.
|
|
14
|
+
|
|
15
|
+
After downloading an encrypted R2 object, decrypt it into a new private file:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm run research:decrypt -- encrypted-envelope.json private-donation.json
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Never upload decrypted output to R2 or commit it. Research transcript ciphertext uses the private `behavior-wrapped-research-donations` R2 bucket. Consent and lifecycle metadata use the separate `behavior-wrapped-research-metadata` D1 database initialized by `migrations/research/0001_encrypted_donations.sql`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "behavior-wrapped",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.14",
|
|
4
4
|
"description": "A private, local-first Wrapped report for Claude Code, Cowork, and Codex behavior.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
],
|
|
29
29
|
"files": [
|
|
30
30
|
"dist/",
|
|
31
|
+
"docs/",
|
|
31
32
|
"server/",
|
|
32
33
|
"scripts/",
|
|
33
34
|
"fixtures/",
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { MAX_DONATION_BYTES } from "./research-donation-schema.mjs";
|
|
2
|
-
|
|
3
1
|
export const DONATION_ENVELOPE_FORMAT = "behavior-wrapped-encrypted-donation-v1";
|
|
4
2
|
export const DONATION_ENCRYPTION_ALGORITHM = "RSA-OAEP-256+A256GCM";
|
|
5
3
|
export const DONATION_KEY_ID = "research-donation-rsa-2026-08";
|
|
6
4
|
export const DONATION_CONSENT_VERSION = 2;
|
|
7
|
-
export const
|
|
5
|
+
export const DONATION_CONTENT_ENCODING = "gzip";
|
|
6
|
+
export const MAX_COMPRESSED_DONATION_BYTES = 8_000_000;
|
|
7
|
+
export const MAX_ENCRYPTED_DONATION_BYTES = Math.ceil(MAX_COMPRESSED_DONATION_BYTES / 3) * 4 + 10_000;
|
|
8
|
+
const MAX_LEGACY_DONATION_BYTES = 1_800_000;
|
|
8
9
|
|
|
9
10
|
const base64url = /^[A-Za-z0-9_-]+$/;
|
|
10
11
|
const timestamp = /^\d{4}-\d{2}-\d{2}T/;
|
|
@@ -34,13 +35,18 @@ export function sanitizeEncryptedDonationEnvelope(value) {
|
|
|
34
35
|
if (typeof value.encryption.wrappedKey !== "string" || value.encryption.wrappedKey.length < 480 || value.encryption.wrappedKey.length > 700 || !base64url.test(value.encryption.wrappedKey)) return null;
|
|
35
36
|
if (typeof value.encryption.iv !== "string" || value.encryption.iv.length !== 16 || !base64url.test(value.encryption.iv)) return null;
|
|
36
37
|
if (typeof value.encryption.authTag !== "string" || value.encryption.authTag.length !== 22 || !base64url.test(value.encryption.authTag)) return null;
|
|
37
|
-
if (typeof value.ciphertext !== "string" || !value.ciphertext.length ||
|
|
38
|
-
|
|
38
|
+
if (typeof value.ciphertext !== "string" || !value.ciphertext.length || !base64url.test(value.ciphertext)) return null;
|
|
39
|
+
const baseMetadataKeys = ["automatedDetections", "consentVersion", "consentedAt", "createdAt", "messages", "redactionMode", "reportId", "sessions", "unredactedData"];
|
|
40
|
+
const compressed = exactKeys(value.metadata, [...baseMetadataKeys, "contentEncoding"]);
|
|
41
|
+
if (!compressed && !exactKeys(value.metadata, baseMetadataKeys)) return null;
|
|
39
42
|
const metadata = value.metadata;
|
|
43
|
+
if (compressed && metadata.contentEncoding !== DONATION_CONTENT_ENCODING) return null;
|
|
40
44
|
if (!/^[A-Za-z0-9_-]{8,32}$/.test(metadata.reportId || "")) return null;
|
|
41
45
|
if (!new Set(["standard", "custom", "unredacted"]).has(metadata.redactionMode)) return null;
|
|
42
46
|
if (!timestamp.test(metadata.createdAt || "") || !timestamp.test(metadata.consentedAt || "")) return null;
|
|
43
47
|
if (!new Set([1, DONATION_CONSENT_VERSION]).has(metadata.consentVersion) || typeof metadata.unredactedData !== "boolean" || metadata.unredactedData !== (metadata.redactionMode === "unredacted")) return null;
|
|
44
48
|
if (!boundedInteger(metadata.automatedDetections, 1_000_000) || !boundedInteger(metadata.sessions, 250) || metadata.sessions < 1 || !boundedInteger(metadata.messages, 50_000) || metadata.messages < 1) return null;
|
|
49
|
+
const maximumCiphertextBytes = compressed ? MAX_COMPRESSED_DONATION_BYTES : MAX_LEGACY_DONATION_BYTES;
|
|
50
|
+
if (value.ciphertext.length > Math.ceil(maximumCiphertextBytes / 3) * 4) return null;
|
|
45
51
|
return value;
|
|
46
52
|
}
|
package/server/launcher.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { discoverAllSessionsAsync, readRecordsAsync, defaultDateRange, DEFAULT_W
|
|
|
7
7
|
import { makeDonationPreview } from "./analysis.mjs";
|
|
8
8
|
import { deleteDonationReceipt, getOrCreateClientId, loadDonationReceipt, loadReport, saveDonationReceipt } from "./store.mjs";
|
|
9
9
|
import { deleteResearchDonation, RESEARCH_DONATION_URL, submitResearchDonation } from "./research-donation.mjs";
|
|
10
|
+
import { MAX_DONATION_BYTES } from "./research-donation-schema.mjs";
|
|
10
11
|
import { APP_VERSION, LOCAL_DONATION_PROTOCOL } from "./runtime-version.mjs";
|
|
11
12
|
import { makeWorkaroundEvidencePreview } from "./workaround-evidence.mjs";
|
|
12
13
|
import { makeInteractionEvidencePreview } from "./interaction-evidence.mjs";
|
|
@@ -154,7 +155,7 @@ const server = http.createServer(async (request, response) => {
|
|
|
154
155
|
return json(response, 200, makeDonationPreview(records, labels, { disabledRedactions, disabledMatches, unredacted }));
|
|
155
156
|
}
|
|
156
157
|
if (request.method === "POST" && url.pathname === "/api/research-donations") {
|
|
157
|
-
const body = await readBody(request,
|
|
158
|
+
const body = await readBody(request, MAX_DONATION_BYTES + 1_000_000);
|
|
158
159
|
const report = loadReport(body?.donation?.reportId);
|
|
159
160
|
if (!report) return json(response, 404, { error: "Saved report not found" });
|
|
160
161
|
if (demo) return json(response, 201, { accepted: true, donation_id: "demo-not-transmitted", demo: true });
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { gunzipSync, gzipSync } from "node:zlib";
|
|
3
|
+
import { DONATION_CONSENT_VERSION, DONATION_CONTENT_ENCODING, DONATION_ENCRYPTION_ALGORITHM, DONATION_ENVELOPE_FORMAT, DONATION_KEY_ID, MAX_COMPRESSED_DONATION_BYTES, encryptedDonationAAD, sanitizeEncryptedDonationEnvelope } from "./encrypted-donation-schema.mjs";
|
|
4
|
+
import { MAX_DONATION_BYTES, researchDonationByteLength, sanitizeResearchDonation } from "./research-donation-schema.mjs";
|
|
4
5
|
|
|
5
6
|
export const RESEARCH_DONATION_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
6
7
|
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA0RaXFQBixAmtwKRz2I7Y
|
|
@@ -18,10 +19,14 @@ function base64url(value) {
|
|
|
18
19
|
return Buffer.from(value).toString("base64url");
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUBLIC_KEY) {
|
|
22
|
+
export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUBLIC_KEY, { compress = true } = {}) {
|
|
23
|
+
const donationBytes = researchDonationByteLength(value);
|
|
24
|
+
if (donationBytes !== null && donationBytes > MAX_DONATION_BYTES) throw new Error("The reviewed donation is larger than 20 MB. Choose Advanced mode and select fewer sessions.");
|
|
22
25
|
const donation = sanitizeResearchDonation(value);
|
|
23
26
|
if (!donation) throw new Error("The reviewed donation does not match the research schema.");
|
|
24
27
|
const plaintext = Buffer.from(JSON.stringify(donation));
|
|
28
|
+
const encryptedPlaintext = compress ? gzipSync(plaintext) : plaintext;
|
|
29
|
+
if (compress && encryptedPlaintext.byteLength > MAX_COMPRESSED_DONATION_BYTES) throw new Error("The reviewed donation is still too large after compression. Choose Advanced mode and select fewer sessions.");
|
|
25
30
|
const contentKey = crypto.randomBytes(32);
|
|
26
31
|
const iv = crypto.randomBytes(12);
|
|
27
32
|
const envelope = {
|
|
@@ -37,11 +42,12 @@ export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUB
|
|
|
37
42
|
automatedDetections: donation.redactionSummary.automatedDetections,
|
|
38
43
|
sessions: donation.redactionSummary.sessions,
|
|
39
44
|
messages: donation.redactionSummary.messages,
|
|
45
|
+
...(compress ? { contentEncoding: DONATION_CONTENT_ENCODING } : {}),
|
|
40
46
|
},
|
|
41
47
|
};
|
|
42
48
|
const cipher = crypto.createCipheriv("aes-256-gcm", contentKey, iv);
|
|
43
49
|
cipher.setAAD(Buffer.from(encryptedDonationAAD(envelope)));
|
|
44
|
-
const ciphertext = Buffer.concat([cipher.update(
|
|
50
|
+
const ciphertext = Buffer.concat([cipher.update(encryptedPlaintext), cipher.final()]);
|
|
45
51
|
return sanitizeEncryptedDonationEnvelope({
|
|
46
52
|
...envelope,
|
|
47
53
|
encryption: {
|
|
@@ -61,7 +67,10 @@ export function decryptResearchDonation(value, privateKey, passphrase) {
|
|
|
61
67
|
const decipher = crypto.createDecipheriv("aes-256-gcm", contentKey, Buffer.from(envelope.encryption.iv, "base64url"));
|
|
62
68
|
decipher.setAAD(Buffer.from(encryptedDonationAAD(envelope)));
|
|
63
69
|
decipher.setAuthTag(Buffer.from(envelope.encryption.authTag, "base64url"));
|
|
64
|
-
const
|
|
70
|
+
const decrypted = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]);
|
|
71
|
+
const plaintext = envelope.metadata.contentEncoding === DONATION_CONTENT_ENCODING
|
|
72
|
+
? gunzipSync(decrypted, { maxOutputLength: MAX_DONATION_BYTES + 1 })
|
|
73
|
+
: decrypted;
|
|
65
74
|
const donation = sanitizeResearchDonation(JSON.parse(plaintext.toString("utf8")));
|
|
66
75
|
if (!donation) throw new Error("The decrypted donation is invalid.");
|
|
67
76
|
return donation;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const MAX_DONATION_BYTES =
|
|
1
|
+
const MAX_DONATION_BYTES = 20_000_000;
|
|
2
2
|
const MAX_SESSIONS = 250;
|
|
3
3
|
const MAX_MESSAGES = 50_000;
|
|
4
4
|
const MAX_MESSAGE_LENGTH = 20_000;
|
|
@@ -7,7 +7,7 @@ function safeText(value, maximum) {
|
|
|
7
7
|
return typeof value === "string" ? value.normalize("NFKC").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").slice(0, maximum) : "";
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
function normalizeResearchDonation(value) {
|
|
11
11
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
12
12
|
if (value.consent?.researchDonation !== true) return null;
|
|
13
13
|
if (!/^[A-Za-z0-9_-]{8,32}$/.test(value.reportId || "")) return null;
|
|
@@ -49,7 +49,17 @@ export function sanitizeResearchDonation(value) {
|
|
|
49
49
|
consentedAt: /^\d{4}-\d{2}-\d{2}T/.test(value.consent.consentedAt || "") ? value.consent.consentedAt : new Date().toISOString(),
|
|
50
50
|
},
|
|
51
51
|
};
|
|
52
|
-
return
|
|
52
|
+
return donation;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function researchDonationByteLength(value) {
|
|
56
|
+
const donation = normalizeResearchDonation(value);
|
|
57
|
+
return donation ? new TextEncoder().encode(JSON.stringify(donation)).byteLength : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function sanitizeResearchDonation(value) {
|
|
61
|
+
const donation = normalizeResearchDonation(value);
|
|
62
|
+
return donation && new TextEncoder().encode(JSON.stringify(donation)).byteLength <= MAX_DONATION_BYTES ? donation : null;
|
|
53
63
|
}
|
|
54
64
|
|
|
55
65
|
export { MAX_DONATION_BYTES };
|