flare-redact 0.8.0 → 1.0.0

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/MIGRATION.md +58 -0
  3. package/README.md +238 -59
  4. package/SECURITY.md +32 -0
  5. package/bench/adversarial-runtime.mjs +23 -0
  6. package/bench/performance.mjs +36 -0
  7. package/bin/flare-redact.mjs +1 -1
  8. package/dist/cli.d.ts +1 -1
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +122 -32
  11. package/dist/cli.js.map +1 -1
  12. package/dist/crypto.d.ts +6 -0
  13. package/dist/crypto.d.ts.map +1 -0
  14. package/dist/crypto.js +128 -0
  15. package/dist/crypto.js.map +1 -0
  16. package/dist/csv.d.ts +3 -3
  17. package/dist/csv.js +3 -3
  18. package/dist/detectors.d.ts +17 -7
  19. package/dist/detectors.d.ts.map +1 -1
  20. package/dist/detectors.js +59 -35
  21. package/dist/detectors.js.map +1 -1
  22. package/dist/engine.d.ts +46 -4
  23. package/dist/engine.d.ts.map +1 -1
  24. package/dist/engine.js +179 -25
  25. package/dist/engine.js.map +1 -1
  26. package/dist/graph.d.ts +9 -0
  27. package/dist/graph.d.ts.map +1 -0
  28. package/dist/graph.js +94 -0
  29. package/dist/graph.js.map +1 -0
  30. package/dist/http.d.ts +5 -0
  31. package/dist/http.d.ts.map +1 -1
  32. package/dist/http.js +54 -1
  33. package/dist/http.js.map +1 -1
  34. package/dist/index.d.ts +20 -5
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +306 -54
  37. package/dist/index.js.map +1 -1
  38. package/dist/llm.d.ts.map +1 -1
  39. package/dist/llm.js +92 -54
  40. package/dist/llm.js.map +1 -1
  41. package/dist/secure-vault.d.ts +26 -0
  42. package/dist/secure-vault.d.ts.map +1 -0
  43. package/dist/secure-vault.js +137 -0
  44. package/dist/secure-vault.js.map +1 -0
  45. package/dist/session.d.ts.map +1 -1
  46. package/dist/session.js +3 -29
  47. package/dist/session.js.map +1 -1
  48. package/dist/stream.d.ts +5 -1
  49. package/dist/stream.d.ts.map +1 -1
  50. package/dist/stream.js +68 -8
  51. package/dist/stream.js.map +1 -1
  52. package/dist/tool.d.ts +30 -0
  53. package/dist/tool.d.ts.map +1 -0
  54. package/dist/tool.js +37 -0
  55. package/dist/tool.js.map +1 -0
  56. package/dist/transforms.d.ts +12 -0
  57. package/dist/transforms.d.ts.map +1 -0
  58. package/dist/transforms.js +91 -0
  59. package/dist/transforms.js.map +1 -0
  60. package/dist/vault.d.ts +14 -3
  61. package/dist/vault.d.ts.map +1 -1
  62. package/dist/vault.js +72 -38
  63. package/dist/vault.js.map +1 -1
  64. package/package.json +17 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,87 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 — 2026-07-23
4
+
5
+ ### Production boundaries
6
+
7
+ - Sanitize credentials, path segments, query values, and fragments inside HTTP
8
+ URL strings; export `redactUrl()` for standalone use.
9
+ - Redact complete OpenAI and Anthropic message structures, including tool-call
10
+ arguments, and restore streamed OpenAI tool arguments and Anthropic partial
11
+ JSON across arbitrary chunk boundaries.
12
+ - Add `flare-redact/tool` with one-way tool/MCP helpers and a reversible,
13
+ conversation-scoped `createToolBoundary()` for agent loops.
14
+ - Make stream redaction record-aware for multiline PEM private keys, fail closed
15
+ on unterminated keys, and bound buffered record size.
16
+
17
+ ### Safe and stable core
18
+
19
+ - Omit raw secret values from `scan()` and `scanAsync()` findings by default.
20
+ Trusted diagnostics can opt in with `includeValues: true`.
21
+ - Preserve cycles and shared references during redaction; traverse `Map`, `Set`,
22
+ enumerable symbols, `Error`, `URL`, and `URLSearchParams`.
23
+ - Make global/sticky allow-list and sensitive-key regular expressions
24
+ deterministic across repeated values.
25
+ - Add stable `FlareRedactError` codes; resource and stream limits use
26
+ `ERR_REDACTION_LIMIT`.
27
+ - Add `compilePolicy()` and make `createRedactor()` / `definePolicy()` reuse
28
+ resolved detectors and matchers, including async operations.
29
+ - Replace bracket-specific streamed vault restoration with matching based on the
30
+ actual placeholder set, including custom placeholder formats.
31
+
32
+ ### Verification
33
+
34
+ - Expand the test suite from 112 to 129 production-focused tests covering HTTP
35
+ URL leakage, tool/MCP boundaries, streamed tool arguments, circular graphs,
36
+ complex built-ins, multiline keys, custom placeholders, and safe findings.
37
+ - Add package export and tarball validation to CI.
38
+ - Add a dedicated `0.9.x` to `1.0.0` migration guide.
39
+
40
+ See [MIGRATION.md](MIGRATION.md) before upgrading.
41
+
42
+ ## 0.9.0 — 2026-07-23
43
+
44
+ ### Security
45
+
46
+ - Replace 32-bit FNV correlation tokens with keyed HMAC-SHA-256.
47
+ - Rename non-reversible shape preservation to `pseudonym`; retain `fpe` only as
48
+ a deprecated compatibility alias and stop describing it as encryption.
49
+ - Add deterministic type-consistent `surrogate` mode.
50
+ - Require `transformSecret` for hash, pseudonym, and surrogate modes.
51
+ - Use opaque 96-bit random vault placeholders by default.
52
+ - Add PBKDF2-SHA-256 + AES-256-GCM authenticated vault persistence.
53
+ - Make CLI vault files encrypted by default and reject plaintext maps unless
54
+ `--allow-plaintext-vault` is explicit.
55
+ - Add per-string input/finding limits and hostile-input benchmarks.
56
+
57
+ ### Detection and resilience
58
+
59
+ - Add risk and confidence to findings and SARIF output.
60
+ - Add weighted risk-aware overlap resolution.
61
+ - Add opt-in contextual person-name, street-address, and birth-date detectors.
62
+ - Add sync and async semantic-provider hooks for local NER models.
63
+ - Detect bracket-obfuscated email addresses, spaced AWS keys, and tokens split
64
+ with zero-width characters while preserving original character spans.
65
+ - Add reproducible latency and hostile-input scaling benchmarks.
66
+ - Change scan JSON to schema version 2.
67
+ - Make line/column calculation linear in input plus findings instead of rescanning
68
+ the prefix for every finding.
69
+ - Add runnable OpenAI-compatible, Express + Pino, and copy-ready GitHub Actions
70
+ CLI scan examples.
71
+
72
+ ### Migration
73
+
74
+ - Upgrade Node.js to version 20 or newer. Opaque vault placeholders and encrypted
75
+ vault persistence rely on the stable Web Crypto API.
76
+ - Set `transformSecret` in code, or `FLARE_REDACT_SECRET` for the CLI, when using
77
+ deterministic protected modes.
78
+ - Set `FLARE_REDACT_VAULT_PASSWORD` before CLI `--vault` or `--restore`.
79
+ - Use `createVault({ placeholderStyle: 'readable' })` only if legacy predictable
80
+ placeholders are required in a trusted local flow.
81
+ - Update scan-report consumers for schema version 2 and the `risk` and
82
+ `confidence` fields.
83
+
84
+ ## 0.8.0
85
+
86
+ - Add file-aware scan reports with line/column locations, safe JSON, and SARIF
87
+ output for CI and code-scanning integrations.
package/MIGRATION.md ADDED
@@ -0,0 +1,58 @@
1
+ # Migrating to flare-redact 1.0
2
+
3
+ Version 1.0 makes the public API safe by default and establishes the compatibility
4
+ contract for the `1.x` line.
5
+
6
+ ## Upgrade
7
+
8
+ ```bash
9
+ npm install flare-redact@^1.0.0
10
+ ```
11
+
12
+ Projects pinned to `0.9.0`, `^0.9.0`, or a lockfile stay on their current version
13
+ until this command is run.
14
+
15
+ ## Breaking change: scan values are opt-in
16
+
17
+ `scan()` and `scanAsync()` no longer return the raw matched secret by default.
18
+ Locations, detector metadata, risk, and confidence are unchanged.
19
+
20
+ ```js
21
+ scan(input); // value is omitted
22
+ scan(input, { includeValues: true }); // value is present
23
+ ```
24
+
25
+ Only enable `includeValues` in trusted, in-process diagnostics. Do not send those
26
+ findings to logs, CI reports, analytics, or error trackers.
27
+
28
+ ## Object graph behavior
29
+
30
+ Redaction now terminates safely on circular input and preserves shared
31
+ references. It also traverses `Map`, `Set`, enumerable symbol values, `Error`
32
+ messages, `URL`, and `URLSearchParams`. If code previously depended on these
33
+ values being passed through without inspection, review the new masked output.
34
+
35
+ ## HTTP snapshots
36
+
37
+ `redactHttp()` now sanitizes the URL string in addition to `query`, `params`,
38
+ headers, and body. Use `redactUrl()` directly when logging a URL outside an HTTP
39
+ request snapshot.
40
+
41
+ ## LLM and tool calls
42
+
43
+ OpenAI and Anthropic wrappers now redact the complete message structure,
44
+ including tool-call argument strings, and restore streamed tool arguments across
45
+ chunk boundaries. For model-agnostic agent loops and MCP, use
46
+ `createToolBoundary()` from `flare-redact/tool`.
47
+
48
+ ## Streams
49
+
50
+ `redactStream()` now buffers bounded multiline private-key records. Complete and
51
+ unterminated PEM private keys are masked; an oversized buffered record raises
52
+ `RedactionLimitError` with code `ERR_REDACTION_LIMIT`.
53
+
54
+ ## Reusable policies
55
+
56
+ `createRedactor()` and `definePolicy()` now precompile detector selection and
57
+ matchers. `compilePolicy()` is the explicit name for the same API and also
58
+ exposes async scan/redaction methods.
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <img src="https://img.shields.io/npm/types/flare-redact.svg" alt="TypeScript">
16
16
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
17
17
  <img src="https://img.shields.io/badge/languages-24-4f46e5" alt="24 languages">
18
- <img src="https://img.shields.io/badge/detectors-50-4f46e5" alt="50 detectors">
18
+ <img src="https://img.shields.io/badge/detectors-56-4f46e5" alt="56 detectors">
19
19
  <img src="https://img.shields.io/badge/runtime-node%20%7C%20browser%20%7C%20edge-blue" alt="Runtimes">
20
20
  </p>
21
21
 
@@ -46,8 +46,8 @@ redact('User alice@corp.com paid with 4242 4242 4242 4242, token ghp_' + 'a'.rep
46
46
  Nothing to configure. No list of field paths to maintain. No native build step.
47
47
 
48
48
  > **The same problem now has a new address: your LLM calls.** Wrap your OpenAI or
49
- > Anthropic client and secrets are stripped from every prompt and restored in the
50
- > reply — the model never sees the real data, your app still gets the right answer.
49
+ > Anthropic client and detected secrets are stripped from prompts and restored in
50
+ > the reply — the model never sees those original values, while references survive.
51
51
  > [Jump to it ↓](#redact-prompts-before-they-reach-an-llm)
52
52
 
53
53
  <p align="center">
@@ -56,17 +56,20 @@ Nothing to configure. No list of field paths to maintain. No native build step.
56
56
 
57
57
  | | | |
58
58
  |---|---|---|
59
- | 🔍 **Content-aware** — reads values, not just field names | ♻️ **Reversible** — vault: redact → use → restore | 🎭 **Format-preserving** — emails stay email-shaped |
60
- | 🤖 **LLM-safe** — strips secrets before OpenAI/Anthropic | 🌍 **24 languages** — plus checksum-validated national IDs | 🛡️ **ReDoS-safe · 0 deps** — safe on untrusted input |
59
+ | 🔍 **Context-aware** — spans carry risk and confidence | 🔐 **Secure vaults** — opaque tokens, optional AES-GCM persistence | 🎭 **Useful test data** — keyed pseudonyms and typed surrogates |
60
+ | 🤖 **LLM + tool boundary** — protects prompts, tool calls, and MCP payloads | 🌍 **24-language secret vocabulary** — plus checksum-validated IDs | 🪶 **Zero runtime dependencies** — Node, browser, and edge |
61
61
 
62
62
  ## Contents
63
63
 
64
64
  - [Install](#install)
65
+ - [Runnable examples](#runnable-examples)
65
66
  - [Redact anything](#redact-anything)
66
67
  - [Redact prompts before they reach an LLM](#redact-prompts-before-they-reach-an-llm)
67
68
  - [Ways to hide a value](#ways-to-hide-a-value)
68
69
  - [Reversible redaction](#reversible-redaction)
70
+ - [Contextual and model-assisted PII](#contextual-and-model-assisted-pii)
69
71
  - [Build a private chat app](#build-a-private-chat-app)
72
+ - [Protect tool calls and MCP loops](#protect-tool-calls-and-mcp-loops)
70
73
  - [Your own words](#your-own-words)
71
74
  - [See what leaks, and why](#see-what-leaks-and-why)
72
75
  - [Guard your logger in one line](#guard-your-logger-in-one-line)
@@ -77,9 +80,10 @@ Nothing to configure. No list of field paths to maintain. No native build step.
77
80
  - [Fail a build when a secret sneaks in](#fail-a-build-when-a-secret-sneaks-in)
78
81
  - [CLI](#cli)
79
82
  - [What it catches](#what-it-catches)
80
- - [Every language, every country](#every-language-every-country)
83
+ - [Multilingual secret vocabulary and IDs](#multilingual-secret-vocabulary-and-ids)
81
84
  - [Custom detectors & allowlists](#custom-detectors--allowlists)
82
85
  - [API](#api)
86
+ - [Security boundaries](#security-boundaries)
83
87
  - [Why not a field allowlist?](#why-not-a-field-allowlist)
84
88
 
85
89
  ## Install
@@ -88,7 +92,22 @@ Nothing to configure. No list of field paths to maintain. No native build step.
88
92
  npm install flare-redact
89
93
  ```
90
94
 
91
- Node 18+, and it runs in the browser and edge runtimes too — zero dependencies.
95
+ Node 20+, and it runs in the browser and edge runtimes too — zero dependencies.
96
+ Upgrading from `0.9.x`? Read the [`1.0 migration guide`](MIGRATION.md). Existing
97
+ projects are not forced across the major version; upgrade explicitly with
98
+ `npm install flare-redact@^1.0.0`.
99
+
100
+ ## Runnable examples
101
+
102
+ Clone the repository and run these small applications locally:
103
+
104
+ | Example | What it proves | Run |
105
+ |---|---|---|
106
+ | [`openai-privacy`](examples/openai-privacy) | The model sees an opaque placeholder while the app receives the restored value | `npm --prefix examples/openai-privacy start` |
107
+ | [`express-pino`](examples/express-pino) | Express keeps the original request while Pino receives a safe snapshot | `npm --prefix examples/express-pino run smoke` |
108
+ | [`github-secret-scan`](examples/github-secret-scan) | Pull requests fail when tracked source or configuration files contain detected secrets or PII | Copy the workflow into your repository |
109
+
110
+ Run `npm run build` and install an example's dependencies before its first run.
92
111
 
93
112
  ## Redact anything
94
113
 
@@ -117,9 +136,9 @@ redact({
117
136
 
118
137
  Your app sends user data to OpenAI or Anthropic. Somewhere in that prompt is a
119
138
  customer's email, an API key, or a card number — and now it's left your systems.
120
- Wrap the client once, and secrets are stripped from every prompt and put back in
121
- the reply. The model never sees the real values; your code still gets the right
122
- answer.
139
+ Wrap the client once, and detected secrets are stripped from prompts and put back
140
+ in the reply. The model never sees those original values; your code keeps the
141
+ references it needs.
123
142
 
124
143
  ```js
125
144
  import { wrapOpenAI } from 'flare-redact/llm';
@@ -134,14 +153,15 @@ const res = await openai.chat.completions.create({
134
153
 
135
154
  ```
136
155
  your app sends → Email the invoice to alice@corp.com, card 4242 4242 4242 4242
137
- the model sees → Email the invoice to [EMAIL_1], card [CREDIT_CARD_1]
156
+ the model sees → Email the invoice to [FR_EMAIL_7f2a…], card [FR_CREDIT_CARD_19be…]
138
157
  your app gets → Sent to alice@corp.com. Card 4242 4242 4242 4242 wasn't stored.
139
158
  ```
140
159
 
141
160
  `wrapAnthropic` does the same for `messages.create`, including the system prompt.
142
- Both handle streaming — placeholders are restored even when one is split across
143
- chunks. There's a `redactPrompt(text)` too if you'd rather hold the vault
144
- yourself.
161
+ Both wrappers redact complete message structures, including tool-call arguments.
162
+ Streaming text, OpenAI tool arguments, and Anthropic partial JSON are restored
163
+ even when a placeholder is split across chunks. There's a `redactPrompt(text)`
164
+ too if you'd rather hold the vault yourself.
145
165
 
146
166
  ## Ways to hide a value
147
167
 
@@ -151,16 +171,27 @@ after it's hidden.
151
171
  ```js
152
172
  redact('bob@corp.com', { mode: 'mask' }); // 'b***@***' (default)
153
173
  redact('bob@corp.com', { mode: 'label' }); // '[REDACTED:email]'
154
- redact('bob@corp.com', { mode: 'hash' }); // 'email_f63d8d56' (deterministic)
155
- redact('bob@corp.com', { mode: 'fpe' }); // 'kqz@rwmp.dnu' (keeps the shape)
174
+
175
+ const protectedOptions = { transformSecret: process.env.FLARE_REDACT_SECRET };
176
+ redact('bob@corp.com', { ...protectedOptions, mode: 'hash' });
177
+ // 'email_3baf4d28d7c88317a…' — HMAC-SHA-256 fingerprint
178
+
179
+ redact('bob@corp.com', { ...protectedOptions, mode: 'pseudonym' });
180
+ // 'kqz@rwmp.dnu' — keyed, deterministic, keeps character classes
181
+
182
+ redact('bob@corp.com', { ...protectedOptions, mode: 'surrogate' });
183
+ // 'user_93a78c61e204@example.invalid' — type-consistent synthetic value
156
184
  ```
157
185
 
158
- `hash` is the useful one for support work: the same input always hashes to the
159
- same token, so you can still tell that two log lines came from the same user —
160
- without ever storing who that user is. `fpe` (format-preserving) keeps the
161
- *shape* — an email stays email-shaped, a card stays card-shaped — which is what
162
- you want for realistic-but-safe test data. Both are deterministic; add `hashSalt`
163
- to make the mapping per-service.
186
+ Protected deterministic modes require `transformSecret`; they never silently
187
+ fall back to a public unsalted fingerprint. `hash` is useful for correlation,
188
+ `pseudonym` retains the original character shape, and `surrogate` emits typed
189
+ synthetic values such as reserved-domain emails and Luhn-valid card numbers.
190
+ Use a separate secret per environment or correlation domain.
191
+
192
+ `pseudonym` is deliberately **not** described as format-preserving encryption.
193
+ It is non-reversible pseudonymization, not NIST FF1. The old `fpe` name remains
194
+ as a compatibility alias but is deprecated.
164
195
 
165
196
  Or replace everything with one fixed string:
166
197
 
@@ -180,24 +211,90 @@ import { createVault } from 'flare-redact';
180
211
 
181
212
  const vault = createVault();
182
213
  const safe = vault.redact('charge bob@corp.com on card 4242 4242 4242 4242');
183
- // 'charge [EMAIL_1] on card [CREDIT_CARD_1]'
214
+ // 'charge [FR_EMAIL_7f2ad4…] on card [FR_CREDIT_CARD_19be63…]'
184
215
 
185
216
  vault.restore(safe);
186
217
  // 'charge bob@corp.com on card 4242 4242 4242 4242'
187
218
  ```
188
219
 
189
- The same value always gets the same placeholder, so references survive the round
190
- trip. Works on objects too, and `restore()` also takes a plain placeholder→value
191
- map if you persisted one.
220
+ The same value gets the same placeholder inside one vault, so references survive
221
+ the round trip. Default placeholders include 96 random bits instead of a global
222
+ sequence number. Human-readable `[EMAIL_1]` counters remain available through
223
+ `createVault({ placeholderStyle: 'readable' })` for trusted local workflows.
224
+
225
+ The mapping is as sensitive as the original data. Encrypt it before persistence:
226
+
227
+ ```js
228
+ import { sealVault, openVault, restore } from 'flare-redact';
229
+
230
+ const encrypted = await sealVault(vault, process.env.FLARE_REDACT_VAULT_PASSWORD);
231
+ await fs.writeFile('session.vault.json', JSON.stringify(encrypted), { mode: 0o600 });
232
+
233
+ const entries = await openVault(encrypted, process.env.FLARE_REDACT_VAULT_PASSWORD);
234
+ restore(safe, new Map(entries));
235
+ ```
236
+
237
+ Sealed vaults use PBKDF2-SHA-256 with a fresh salt and AES-256-GCM with a fresh
238
+ nonce. Wrong passwords and modified files fail closed.
239
+
240
+ From the CLI, `--vault` and `--restore` use encrypted files by default. Passwords
241
+ come from `FLARE_REDACT_VAULT_PASSWORD` (or the variable named by
242
+ `--vault-password-env`) so they do not appear in shell history:
243
+
244
+ ```bash
245
+ export FLARE_REDACT_VAULT_PASSWORD='use-a-secret-manager-in-production'
246
+ flare-redact --vault session.vault.json < input.txt > safe.txt
247
+ flare-redact --restore session.vault.json < safe.txt > restored.txt
248
+ ```
249
+
250
+ ## Contextual and model-assisted PII
251
+
252
+ Structured identifiers and credentials are best handled by deterministic rules
253
+ and checksum validators. Names and addresses need context, so three conservative
254
+ detectors are opt-in:
255
+
256
+ ```js
257
+ const findings = scan(
258
+ 'Customer name: Alice Example; address: 120 Cedar Street; DOB: 1990-04-23',
259
+ { enable: ['contextual'] },
260
+ );
261
+
262
+ // person_name, street_address, date_of_birth
263
+ // each finding includes risk, confidence, and the exact sensitive span
264
+ ```
265
+
266
+ For broader multilingual free-text PII, connect a local model without coupling
267
+ the zero-dependency core to one ML runtime:
268
+
269
+ ```js
270
+ const policy = {
271
+ semanticProvider: {
272
+ async detect(text) {
273
+ return [{
274
+ detector: 'person_model', label: 'Person',
275
+ why: 'Local multilingual NER result.',
276
+ start: 12, end: 25, confidence: 0.94, risk: 'high',
277
+ }];
278
+ },
279
+ },
280
+ minConfidence: 0.8,
281
+ };
282
+
283
+ const safe = await redactAsync(input, policy);
284
+ ```
285
+
286
+ Semantic and deterministic spans enter the same overlap arbitration. Higher-risk,
287
+ higher-priority, and better-validated findings win instead of whichever regular
288
+ expression happens to run first.
192
289
 
193
290
  ## Build a private chat app
194
291
 
195
292
  If you're building a chat interface — over your own local model or any API — a
196
293
  **session** is the drop-in layer. One session holds one vault, so a value keeps
197
294
  the same placeholder across every turn: mask the user's message on the way in,
198
- restore the model's reply on the way out. It's model-agnostic, synchronous, and
199
- fast enough that the cost vanishes next to inference (a 13 KB message redacts in
200
- ~0.3 ms).
295
+ restore the model's reply on the way out. It's model-agnostic and synchronous.
296
+ Run `npm run benchmark` on your own target runtime instead of relying on a
297
+ hardware-independent latency claim.
201
298
 
202
299
  ```js
203
300
  import { createSession } from 'flare-redact';
@@ -221,8 +318,31 @@ process(out.flush());
221
318
  ```
222
319
 
223
320
  `session.redactMessages([{ role, content }])` masks a whole chat array at once,
224
- and `session.reset()` starts a fresh conversation. The model never sees the real
225
- data; your app still works end to end.
321
+ including nested tool calls, and `session.reset()` starts a fresh conversation.
322
+ Detected original values stay local while your app keeps a reversible reference.
323
+
324
+ ## Protect tool calls and MCP loops
325
+
326
+ An agent loop has two directions: model-produced arguments need their local
327
+ values restored before a tool executes, while tool results need new secrets
328
+ masked before they enter model context. One conversation-scoped boundary handles
329
+ both without sending its vault anywhere:
330
+
331
+ ```js
332
+ import { createToolBoundary } from 'flare-redact/tool';
333
+
334
+ const boundary = createToolBoundary();
335
+
336
+ const safePrompt = boundary.redactForModel(userMessage);
337
+ const modelCall = await model.generateToolCall(safePrompt);
338
+ const localCall = boundary.restoreForTool(modelCall);
339
+
340
+ const result = await executeTool(localCall);
341
+ const safeResult = boundary.redactForModel(result);
342
+ ```
343
+
344
+ For safe logging without reversibility, use `redactToolCall()`,
345
+ `redactToolResult()`, or `redactMcpMessage()` from the same entry point.
226
346
 
227
347
  ## Your own words
228
348
 
@@ -239,7 +359,7 @@ redact('Launch Project Zeus with Falcon', {
239
359
 
240
360
  // reversible — send to a model, get it back
241
361
  const vault = createVault({ terms: ['Project Zeus'] });
242
- const safe = vault.redact('ship Project Zeus'); // 'ship [CUSTOM_TERM_1]'
362
+ const safe = vault.redact('ship Project Zeus'); // 'ship [FR_CUSTOM_TERM_a17c…]'
243
363
  vault.restore(safe); // 'ship Project Zeus'
244
364
  ```
245
365
 
@@ -247,7 +367,8 @@ The same works from the CLI, including a full round-trip — mask, send the safe
247
367
  text anywhere, then restore what comes back:
248
368
 
249
369
  ```bash
250
- # add words inline or from a file, and write the mapping to a vault file
370
+ # add words inline or from a file, and write an encrypted vault
371
+ export FLARE_REDACT_VAULT_PASSWORD='read-this-from-your-secret-manager'
251
372
  flare-redact --term "Project Zeus" --terms codenames.txt --vault map.json < in > safe
252
373
 
253
374
  # later, restore the originals from that map
@@ -257,8 +378,8 @@ flare-redact --restore map.json < safe > original
257
378
  ## See what leaks, and why
258
379
 
259
380
  `scan()` finds secrets without changing the input, explains every hit in plain
260
- English, and reports one-based line/column locations — handy for alerts,
261
- dashboards, and understanding *why* something matched.
381
+ English, and reports one-based line/column locations — without returning the raw
382
+ secret by default.
262
383
 
263
384
  ```js
264
385
  import { scan } from 'flare-redact';
@@ -273,6 +394,10 @@ scan('deploy with password=hunter2 and AKIAIOSFODNN7EXAMPLE');
273
394
  // ]
274
395
  ```
275
396
 
397
+ Trusted diagnostics can request the original span with
398
+ `scan(input, { includeValues: true })`. Never enable that option for logs, CI
399
+ reports, analytics, or error tracking.
400
+
276
401
  Need just the shape of it?
277
402
 
278
403
  ```js
@@ -335,7 +460,8 @@ import { winstonRedact } from 'flare-redact/winston';
335
460
  winston.format.combine(winston.format(winstonRedact(policy))(), winston.format.json());
336
461
  ```
337
462
 
338
- **HTTP** — a safe-to-log snapshot of a request; the live request is untouched:
463
+ **HTTP** — a safe-to-log snapshot of a request; the live request is untouched.
464
+ The URL string, query object, params, headers, and body are all sanitized:
339
465
 
340
466
  ```js
341
467
  import { httpRedactor } from 'flare-redact/http';
@@ -350,8 +476,9 @@ and `redactStream` too.
350
476
 
351
477
  ## Streams
352
478
 
353
- Pipe any log stream through it — secrets are masked line by line, even when one
354
- is split across chunks.
479
+ Pipe any log stream through it. Secrets may be split across chunks, and bounded
480
+ multiline PEM private keys are masked as one record. Unterminated private keys
481
+ fail closed instead of leaking their remaining bytes.
355
482
 
356
483
  ```js
357
484
  import { redactStream } from 'flare-redact/stream';
@@ -361,19 +488,19 @@ process.stdin.pipe(redactStream()).pipe(process.stdout);
361
488
 
362
489
  ## Anonymize a dataset for staging
363
490
 
364
- Point it at a JSON or CSV dump with `--mode fpe` and you get a copy that's safe
365
- to hand to staging or a test suite. Format-preserving means an email stays
366
- email-shaped and a card stays card-shaped; deterministic means the same value
367
- maps the same way in every row — so foreign keys and joins still line up.
491
+ Point it at a JSON or CSV dump with `--mode surrogate` and you get deterministic,
492
+ typed synthetic values. The same input maps the same way in every row under one
493
+ key, so joins survive without calling the transformation encryption or anonymity.
368
494
 
369
495
  ```bash
370
- flare-redact --csv --mode fpe < customers.csv > customers.safe.csv
496
+ export FLARE_REDACT_SECRET='read-this-from-your-secret-manager'
497
+ flare-redact --csv --mode surrogate < customers.csv > customers.safe.csv
371
498
  ```
372
499
 
373
500
  ```
374
- Alice,alice@corp.com,4242 4242 4242 4242 Alice,lkjjg@vfld.adz,7042 5270 7797 8929
375
- Bob,bob@corp.com,5555 5555 5555 4444 → Bob,yay@vjxl.fpe,0888 2706 6232 0279
376
- Alice,alice@corp.com,4242 4242 4242 4242 Alice,lkjjg@vfld.adz,7042 5270 7797 8929
501
+ Alice,alice@corp.com,4242 4242 4242 4242 Alice,user_93a78c61e204@example.invalid,7042 5270 7797 8927
502
+ Bob,bob@corp.com,5555 5555 5555 4444 → Bob,user_441ae72c0901@example.invalid,0888 2706 6232 0274
503
+ Alice,alice@corp.com,4242 4242 4242 4242 Alice,user_93a78c61e204@example.invalid,7042 5270 7797 8927
377
504
  ```
378
505
 
379
506
  `redactCsv(text, opts)` is available from `flare-redact/csv` for the same thing
@@ -399,8 +526,25 @@ it into CI or a pre-commit hook. File scans report `file:line:column`, while
399
526
  machine-readable JSON and SARIF reports never echo the matched secret value:
400
527
 
401
528
  ```yaml
402
- - run: git ls-files '*.env*' '*.log' '*.json' | xargs npx flare-redact --scan
403
- ```
529
+ - uses: actions/checkout@v5
530
+ - uses: actions/setup-node@v5
531
+ with:
532
+ node-version: 24
533
+ - name: Scan tracked text files
534
+ shell: bash
535
+ run: |
536
+ git ls-files -z -- \
537
+ '*.env*' '*.log' '*.json' '*.jsonl' '*.yaml' '*.yml' \
538
+ '*.toml' '*.ini' '*.conf' '*.js' '*.mjs' '*.cjs' \
539
+ '*.ts' '*.tsx' '*.jsx' \
540
+ ':(exclude)**/package-lock.json' \
541
+ | while IFS= read -r -d '' file; do printf './%s\0' "$file"; done \
542
+ | xargs -0 -r npx --yes --package flare-redact@1.0.0 flare-redact --scan
543
+ ```
544
+
545
+ The scan runs on the GitHub runner, reports safe file and source locations, and
546
+ fails without sending repository contents to an external scanning service. A
547
+ copy-ready workflow lives in [`examples/github-secret-scan`](examples/github-secret-scan).
404
548
 
405
549
  ```bash
406
550
  flare-redact --scan --format json .env app.log > flare-redact.json
@@ -415,8 +559,8 @@ npm install -g flare-redact
415
559
 
416
560
  ```bash
417
561
  tail -f app.log | flare-redact # stream redacted logs
418
- flare-redact --json --mode hash < event.json # deep-redact a JSON payload
419
- flare-redact --csv --mode fpe < dump.csv # anonymize a dataset for staging
562
+ FLARE_REDACT_SECRET=… flare-redact --json --mode hash < event.json
563
+ FLARE_REDACT_SECRET=… flare-redact --csv --mode surrogate < dump.csv
420
564
  flare-redact --scan config.env # list findings + why (exit 1 if any)
421
565
  flare-redact --scan --format json .env app.log # safe machine-readable report
422
566
  flare-redact --sarif .env > results.sarif # GitHub code-scanning report
@@ -448,6 +592,7 @@ On by default:
448
592
  | `url_credentials` | passwords inside connection strings |
449
593
  | `generic_assignment` | `password=`, `api_key: …`, `secret=…` (any language) |
450
594
  | `email` | email addresses |
595
+ | `obfuscated_email` | bracket-obfuscated emails such as `name [at] host [dot] tld` |
451
596
  | `credit_card` | card numbers (Luhn-validated) |
452
597
  | `iban` | IBANs (mod-97 validated) |
453
598
  | `discord_bot_token` / `telegram_bot_token` | chat bot tokens |
@@ -469,7 +614,7 @@ Opt in with `enable`:
469
614
  Plus object values whose **key name** is sensitive (`password`, `token`,
470
615
  `authorization`, `cookie`, `cvv`, …) are masked regardless of content.
471
616
 
472
- ## Every language, every country
617
+ ## Multilingual secret vocabulary and IDs
473
618
 
474
619
  Secrets like API keys and card numbers don't care what language your app is in.
475
620
  Neither does this — but the word-based checks do, so words like *password*,
@@ -535,19 +680,26 @@ redact(text, {
535
680
 
536
681
  ```ts
537
682
  redact<T>(input: T, opts?): T // masked copy, same shape
683
+ redactAsync<T>(input: T, opts?): Promise<T> // supports async local NER providers
538
684
  scan(input, opts?): Finding[] // findings + why, input untouched
685
+ scanAsync(input, opts?): Promise<Finding[]> // supports async local NER providers
539
686
  isClean(input, opts?): boolean // any secrets at all?
540
- summary(input, opts?): { total, byDetector } // counts per detector
541
- createRedactor(opts) / definePolicy(opts) // one policy: redact, scan, vault(), wrapConsole, options
687
+ isCleanAsync(input, opts?): Promise<boolean>
688
+ summary(input, opts?): { total, byDetector, byRisk }
689
+ compilePolicy(opts) // pre-resolved reusable sync + async policy
690
+ createRedactor(opts) / definePolicy(opts) // compatibility names for compilePolicy
542
691
  wrapConsole(opts?, console?): () => void // patch console.*, returns restore
543
692
 
544
693
  createVault(opts?): Vault // reversible: redact / restore / entries
545
694
  restore(input, vaultOrMap): T // put originals back
695
+ sealVault(vaultOrEntries, password): Promise<SealedVaultV1>
696
+ openVault(envelope, password): Promise<Array<[placeholder, original]>>
546
697
 
547
698
  // adapters — each takes the same options object
548
699
  pinoRedact(opts?) // 'flare-redact/pino' → { formatters: { log } }
549
700
  winstonRedact(opts?) // 'flare-redact/winston' → a format transform
550
701
  redactHttp(req, opts?) // 'flare-redact/http' → safe-to-log request snapshot
702
+ redactUrl(url, opts?) // 'flare-redact/http' → sanitized absolute/relative URL
551
703
  httpRedactor(opts?) // 'flare-redact/http' → Express/Connect middleware
552
704
  redactCsv(text, opts?) // 'flare-redact/csv' → anonymize a CSV dataset
553
705
  wrapFetch(fetch, opts?) // 'flare-redact/fetch' → redact egress to named hosts
@@ -557,13 +709,19 @@ wrapOpenAI(client, opts?) // scrub prompts, restore replie
557
709
  wrapAnthropic(client, opts?) // same for messages.create + system
558
710
  redactPrompt(text, opts?): { text, vault }
559
711
 
712
+ // from 'flare-redact/tool'
713
+ createToolBoundary(opts?) // reversible model ↔ tool/MCP boundary
714
+ redactToolCall / redactToolResult / redactMcpMessage
715
+
560
716
  // from 'flare-redact/stream'
561
- redactStream(opts?): Transform // line-wise stream redaction
717
+ redactStream(opts?): Transform // chunk-safe + bounded multiline PEM redaction
562
718
 
563
719
  // opts
564
720
  // {
565
721
  // only?, enable?, disable?, custom?, // which detectors run
566
- // mode?: 'mask' | 'label' | 'hash' | 'fpe', hashSalt?, mask?,
722
+ // mode?: 'mask' | 'label' | 'hash' | 'pseudonym' | 'surrogate',
723
+ // transformSecret?, mask?, minConfidence?, semanticProvider?, limits?,
724
+ // includeValues?: boolean, // scan only; unsafe raw values
567
725
  // redactKeys?: boolean | RegExp | string[],
568
726
  // allow?: RegExp | string[],
569
727
  // terms?: string[] | { term: replacement }, termsCaseSensitive?,
@@ -579,10 +737,31 @@ you *remembered* to name. The leak is always the field you forgot — the free-t
579
737
  message, the nested third-party payload, the string someone concatenated by hand.
580
738
  flare-redact scans the actual values, so it doesn't depend on your memory.
581
739
 
582
- And the patterns it scans with are **bounded and ReDoS-safe** — no nested
583
- quantifiers, no `(a+)+` blow-ups. You can point it at attacker-controlled input
584
- and it stays linear, the same principle behind its sibling
585
- [flare-regex](https://github.com/umudhasanli/flare-regex).
740
+ Built-in patterns are reviewed for bounded structure, exercised by an
741
+ adversarial runtime suite, and protected by per-string input and finding limits.
742
+ JavaScript RegExp does not provide a formal linear-time guarantee, however, and
743
+ arbitrary custom detectors are trusted code. Run the included benchmarks on your
744
+ own runtime instead of treating a badge as a security proof:
745
+
746
+ ```bash
747
+ npm run benchmark
748
+ npm run benchmark:adversarial
749
+ ```
750
+
751
+ ## Security boundaries
752
+
753
+ - Detection is best-effort; a clean scan is not proof that data contains no PII.
754
+ - `scan()` omits raw values by default. `includeValues` intentionally puts those
755
+ secrets back into process memory and must stay out of external reports.
756
+ - `pseudonym` is keyed, deterministic pseudonymization — not NIST FF1 encryption.
757
+ - A vault map is sensitive; persist only the authenticated encrypted envelope.
758
+ - Restoring a placeholder intentionally reveals its original locally. Do not
759
+ forward restored model output to another untrusted sink automatically.
760
+ - The 24-language badge describes secret-key vocabulary, not general multilingual
761
+ named-entity recognition. Use a local `semanticProvider` for that task.
762
+
763
+ Encrypted vaults do not protect a compromised host or secrets already resident
764
+ in process memory. Deterministic transforms reveal when two inputs are equal.
586
765
 
587
766
  ## License
588
767