flare-redact 1.9.0 → 1.10.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 (70) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +122 -1225
  3. package/bench/adversarial-runtime.mjs +27 -6
  4. package/dist/ai-sdk.d.ts +62 -0
  5. package/dist/ai-sdk.d.ts.map +1 -0
  6. package/dist/ai-sdk.js +263 -0
  7. package/dist/ai-sdk.js.map +1 -0
  8. package/dist/checksums.d.ts +43 -0
  9. package/dist/checksums.d.ts.map +1 -1
  10. package/dist/checksums.js +184 -0
  11. package/dist/checksums.js.map +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +5 -2
  14. package/dist/cli.js.map +1 -1
  15. package/dist/detectors.d.ts.map +1 -1
  16. package/dist/detectors.js +7 -4
  17. package/dist/detectors.js.map +1 -1
  18. package/dist/extra.d.ts.map +1 -1
  19. package/dist/extra.js +229 -1
  20. package/dist/extra.js.map +1 -1
  21. package/dist/file-discovery.d.ts +5 -0
  22. package/dist/file-discovery.d.ts.map +1 -1
  23. package/dist/file-discovery.js +5 -1
  24. package/dist/file-discovery.js.map +1 -1
  25. package/dist/gateway/body.d.ts.map +1 -1
  26. package/dist/gateway/body.js +2 -1
  27. package/dist/gateway/body.js.map +1 -1
  28. package/dist/gateway/config.d.ts +5 -3
  29. package/dist/gateway/config.d.ts.map +1 -1
  30. package/dist/gateway/config.js.map +1 -1
  31. package/dist/gateway/index.d.ts +1 -0
  32. package/dist/gateway/index.d.ts.map +1 -1
  33. package/dist/gateway/index.js +1 -0
  34. package/dist/gateway/index.js.map +1 -1
  35. package/dist/gateway/server.d.ts.map +1 -1
  36. package/dist/gateway/server.js +17 -1
  37. package/dist/gateway/server.js.map +1 -1
  38. package/dist/gateway/sse.d.ts +35 -0
  39. package/dist/gateway/sse.d.ts.map +1 -0
  40. package/dist/gateway/sse.js +217 -0
  41. package/dist/gateway/sse.js.map +1 -0
  42. package/dist/help.d.ts.map +1 -1
  43. package/dist/help.js +11 -5
  44. package/dist/help.js.map +1 -1
  45. package/dist/init.d.ts.map +1 -1
  46. package/dist/init.js +12 -3
  47. package/dist/init.js.map +1 -1
  48. package/dist/llm.d.ts.map +1 -1
  49. package/dist/llm.js +20 -9
  50. package/dist/llm.js.map +1 -1
  51. package/dist/locales.d.ts +3 -2
  52. package/dist/locales.d.ts.map +1 -1
  53. package/dist/locales.js +152 -3
  54. package/dist/locales.js.map +1 -1
  55. package/dist/pack.d.ts.map +1 -1
  56. package/dist/pack.js +14 -1
  57. package/dist/pack.js.map +1 -1
  58. package/dist/vault.d.ts +26 -1
  59. package/dist/vault.d.ts.map +1 -1
  60. package/dist/vault.js +61 -3
  61. package/dist/vault.js.map +1 -1
  62. package/docker/README.md +8 -5
  63. package/docs/guide.md +1416 -0
  64. package/package.json +10 -3
  65. package/spec/SPEC.md +40 -3
  66. package/spec/conformance/README.md +8 -1
  67. package/spec/conformance/cases.json +60 -1
  68. package/spec/conformance/expected.json +815 -7
  69. package/spec/detectors.json +1118 -222
  70. package/spec/detectors.schema.json +3 -1
package/README.md CHANGED
@@ -1,11 +1,12 @@
1
1
  <p align="center">
2
- <img src="assets/flare-redact.svg" alt="flare-redact" width="200">
2
+ <img src="assets/flare-redact.svg" alt="flare-redact" width="160">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">flare-redact</h1>
6
6
 
7
7
  <p align="center">
8
- <b>Hide secrets & PII in logs, prompts, and text, before they leak.</b>
8
+ <b>Keep secrets and personal data out of your logs, Sentry, LLM prompts and commits.</b><br>
9
+ It reads the values, not the field names. Zero dependencies.
9
10
  </p>
10
11
 
11
12
  <p align="center">
@@ -14,402 +15,106 @@
14
15
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License"></a>
15
16
  <img src="https://img.shields.io/npm/types/flare-redact.svg" alt="TypeScript">
16
17
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
18
+ <img src="https://img.shields.io/badge/detectors-129-4f46e5" alt="129 detectors">
17
19
  <img src="https://img.shields.io/badge/languages-24-4f46e5" alt="24 languages">
18
- <img src="https://img.shields.io/badge/detectors-90-4f46e5" alt="90 detectors">
19
- <img src="https://img.shields.io/badge/runtime-node%20%7C%20browser%20%7C%20edge-blue" alt="Runtimes">
20
20
  </p>
21
21
 
22
22
  <p align="center">
23
- 🌐 <b>International by default: 24 languages</b><br>
24
- 🇬🇧 🇨🇳 🇮🇳 🇪🇸 🇸🇦 🇫🇷 🇵🇹 🇷🇺 🇯🇵 🇩🇪 🇰🇷 🇹🇷 🇮🇹 🇮🇷 🇵🇱 🇺🇦 🇳🇱 🇻🇳 🇮🇩 🇹🇭 🇬🇷 🇮🇱 🇦🇿 🇷🇴
23
+ <a href="https://flare-collection.github.io/flare-redact/">Playground</a>
24
+ · <a href="docs/guide.md">Guide</a>
25
+ · <a href="docs/guide.md#api">API</a>
26
+ · <a href="https://flare-collection.github.io/flare-redact/guides/">Recipes</a>
27
+ · <a href="https://flare-collection.github.io/flare-redact/llms-full.txt">Docs for AI assistants</a>
25
28
  </p>
26
29
 
27
30
  <p align="center">
28
- <a href="https://flare-collection.github.io/flare-redact/">Live playground</a>
29
- · <a href="https://flare-collection.github.io/flare-redact/guides/">Practical redaction guides</a>
30
- · <a href="https://flare-collection.github.io/flare-redact/llms-full.txt">LLM-friendly API reference</a>
31
+ <img src="assets/demo.svg" alt="Before and after: secrets and PII masked in a log line, across languages" width="820">
31
32
  </p>
32
33
 
33
- ---
34
-
35
- Every leaked secret has the same origin story: someone logged an object, and a
36
- password, token, or API key was sitting inside it. The code looked innocent
37
- (`logger.info({ user })`), but `user` carried a session token, and now it's in
38
- your log aggregator, your error tracker, and three vendors' systems forever.
39
-
40
- **flare-redact** is one function you wrap around that data. It reads the *content*,
41
- not just the field names, so it catches the AWS key someone pasted into a free-text
42
- `note`, the JWT in an `Authorization` header, the card number in a stack trace, and
43
- masks them, keeping just enough of a hint to stay debuggable.
34
+ Someone logs an object, a session token was inside it, and now that token sits
35
+ in your log aggregator, your error tracker and an LLM provider's servers.
36
+ Redaction by field name only hides the fields you remembered to list.
37
+ **flare-redact** looks at the values themselves, so the AWS key pasted into a
38
+ `note` field and the card number inside a stack trace are masked too.
44
39
 
45
40
  ```js
46
41
  import { redact } from 'flare-redact';
47
42
 
48
43
  redact('User alice@corp.com paid with 4242 4242 4242 4242, token ghp_' + 'a'.repeat(36));
49
44
  // → 'User a***@*** paid with **** **** **** 4242, token ghp_***'
50
- ```
51
-
52
- Nothing to configure. No list of field paths to maintain. No native build step.
53
45
 
54
- > **The same problem now has a new address: your LLM calls.** Wrap your OpenAI or
55
- > Anthropic client and detected secrets are stripped from prompts and restored in
56
- > the reply. The model never sees those original values, while references survive.
57
- > [Jump to it ↓](#redact-prompts-before-they-reach-an-llm)
46
+ redact({ user: 'bob@corp.com', password: 'hunter2', note: 'my key is AKIAIOSFODNN7EXAMPLE' });
47
+ // → { user: 'b***@***', password: '***', note: 'my key is AKIA***' }
48
+ ```
49
+
50
+ ## Highlights
51
+
52
+ - 🔍 **Reads content, not field names.** 129 detectors for API keys, tokens, JWTs,
53
+ private keys, cards, IBANs, emails and national IDs, checksum-validated
54
+ wherever a checksum exists.
55
+ - ⚡ **No code change needed.** `node --import flare-redact/register app.js`
56
+ redacts every `console.*` call.
57
+ - 🤖 **Private LLM calls.** Wrap the OpenAI or Anthropic client, or add one
58
+ middleware to the Vercel AI SDK for every provider: the model sees
59
+ placeholders, your app gets the real values back, streaming included.
60
+ - 🔌 **Fits what you already run.** pino, winston, Sentry, Express, `fetch`,
61
+ streams, and any SDK through one middleware.
62
+ - 🚫 **Stops leaks before the commit.** A pre-commit hook that scans only the
63
+ lines you add, and a CI scan with SARIF output.
64
+ - 🌍 **International by default: 24 languages** of secret vocabulary and
65
+ national ID formats.
66
+ - 🪶 **Zero dependencies.** Node 20+, browsers, edge runtimes, Bun and Deno.
67
+ - 🐍 **Python, Go and Rust** engines that run the same detector spec and pass
68
+ the same conformance suite.
58
69
 
59
70
  <p align="center">
60
- <img src="assets/demo.svg" alt="Before and after: secrets and PII masked in a log line, across languages" width="820">
71
+ 🇬🇧 🇨🇳 🇮🇳 🇪🇸 🇸🇦 🇫🇷 🇵🇹 🇷🇺 🇯🇵 🇩🇪 🇰🇷 🇹🇷 🇮🇹 🇮🇷 🇵🇱 🇺🇦 🇳🇱 🇻🇳 🇮🇩 🇹🇭 🇬🇷 🇮🇱 🇦🇿 🇷🇴
61
72
  </p>
62
73
 
63
- | | | |
64
- |---|---|---|
65
- | 🔍 **Context-aware**: spans carry risk and confidence | 🔐 **Secure vaults**: opaque tokens, optional AES-GCM persistence | 🎭 **Useful test data**: keyed pseudonyms and typed surrogates |
66
- | 🔥 **FlareFlow agent IFC**: source→sink capabilities, exact paths, cumulative budgets | 🔌 **Universal middleware**: wrap any SDK, handler, queue, or RPC function | 🪶 **Zero runtime dependencies**: Node, browser, and edge |
67
- | 🐍 **Python, Go, and Rust SDKs**: one spec, four engines, one conformance corpus | 🐳 **Sidecar gateway**: a Docker reverse proxy that needs no code change | 📜 **Detectors as data**: portable FRS-1 packs any engine can load |
68
-
69
- ## Contents
70
-
71
- - [Install](#install)
72
- - [Practical guides](https://flare-collection.github.io/flare-redact/guides/)
73
- - [Runnable examples](#runnable-examples)
74
- - [Python, Go, and Rust](#python-go-and-rust)
75
- - [The sidecar gateway](#the-sidecar-gateway)
76
- - [Redact anything](#redact-anything)
77
- - [Integrate any SDK or framework](#integrate-any-sdk-or-framework)
78
- - [Redact prompts before they reach an LLM](#redact-prompts-before-they-reach-an-llm)
79
- - [Ways to hide a value](#ways-to-hide-a-value)
80
- - [Reversible redaction](#reversible-redaction)
81
- - [Free-text PII without a model](#free-text-pii-without-a-model)
82
- - [Contextual and model-assisted PII](#contextual-and-model-assisted-pii)
83
- - [Learned confidence, fewer false positives](#learned-confidence-fewer-false-positives)
84
- - [Build a private chat app](#build-a-private-chat-app)
85
- - [Enforce information flow across agent tools](#enforce-information-flow-across-agent-tools)
86
- - [Protect tool calls and MCP loops](#protect-tool-calls-and-mcp-loops)
87
- - [Your own words](#your-own-words)
88
- - [See what leaks, and why](#see-what-leaks-and-why)
89
- - [Guard your logger in one line](#guard-your-logger-in-one-line)
90
- - [One policy, everywhere](#one-policy-everywhere)
91
- - [Anonymize a dataset for staging](#anonymize-a-dataset-for-staging)
92
- - [Guard what leaves your app](#guard-what-leaves-your-app)
93
- - [Streams](#streams)
94
- - [Fail a build when a secret sneaks in](#fail-a-build-when-a-secret-sneaks-in)
95
- - [CLI](#cli)
96
- - [What it catches](#what-it-catches)
97
- - [Multilingual secret vocabulary and IDs](#multilingual-secret-vocabulary-and-ids)
98
- - [Custom detectors & allowlists](#custom-detectors--allowlists)
99
- - [API](#api)
100
- - [Security boundaries](#security-boundaries)
101
- - [Why not a field allowlist?](#why-not-a-field-allowlist)
102
-
103
- ## Install
74
+ ## Quick start
104
75
 
105
76
  ```bash
106
77
  npm install flare-redact
107
78
  ```
108
79
 
109
- Node 20+, and it runs in the browser and edge runtimes too, with zero dependencies.
110
- Upgrading from `0.9.x`? Read the [`1.0 migration guide`](MIGRATION.md). Existing
111
- projects are not forced across the major version; upgrade explicitly with
112
- `npm install flare-redact@^1.0.0`.
113
-
114
- ### Set up in one command
115
-
116
- ```bash
117
- npx flare-redact init # the lines to paste for openai, @anthropic-ai/sdk, Sentry, pino, winston, express
118
- npx flare-redact init --hook # also stops any commit that adds a secret
119
- npx flare-redact init --ci # also writes .github/workflows/flare-redact.yml
120
- ```
121
-
122
- `init` reads `package.json`, prints one ready-to-paste step per library it
123
- recognises (console when there is no logger), and never edits source files.
124
- `--hook` writes a git pre-commit hook that scans only the lines a commit adds
125
- (with husky, it prints the line to add instead). `--ci` adds a workflow that runs
126
- `flare-redact --scan` on every pull request.
127
-
128
- ### No code change at all
80
+ Then pick the way that suits you:
129
81
 
130
82
  ```bash
83
+ # No code change: every console.* call is redacted
131
84
  node --import flare-redact/register app.js
132
- NODE_OPTIONS="--import flare-redact/register" FLARE_REDACT_PRESET=logs npm start
133
- ```
134
-
135
- Every `console.log`, `info`, `warn`, `error` and `debug` call is redacted before
136
- it is written, so you can turn redaction on in a Dockerfile or a deploy setting
137
- without opening the code. `FLARE_REDACT_PRESET` picks a [preset](#presets); an
138
- unknown name stops the process at startup rather than leaving the logs
139
- unredacted. Loggers that write to stdout themselves (pino, winston) have their
140
- own one-line integrations [below](#one-policy-everywhere).
141
-
142
- ### Presets
143
-
144
- Pick a goal instead of a list of detector tags:
145
85
 
146
- | Preset | Adds to the defaults |
147
- |---|---|
148
- | `logs` | phone numbers |
149
- | `llm` | every personal identifier (`pii`) plus names, addresses and other PII in prose (`entities`) |
150
- | `gdpr` | `llm` plus IP and MAC addresses, coordinates, VINs and wallet addresses |
151
- | `strict` | every detector, `high_entropy` included |
152
-
153
- ```js
154
- redact(text, { preset: 'llm' });
155
- const openai = wrapOpenAI(new OpenAI(), { preset: 'llm' });
156
- const log = pino(pinoRedact({ preset: 'logs' }));
86
+ # Let it read your package.json and print the lines to paste
87
+ npx flare-redact init # openai, @anthropic-ai/sdk, ai, Sentry, pino, winston, express
88
+ npx flare-redact init --hook # also stop any commit that adds a secret
89
+ npx flare-redact init --ci # also scan every pull request
157
90
  ```
158
91
 
159
- The CLI takes `--preset gdpr`, the gateway `--preset` or `FLARE_REDACT_PRESET`.
160
- `enable` and `disable` apply on top of a preset and `only` ignores it. An unknown
161
- name throws `ERR_UNKNOWN_PRESET` instead of quietly redacting less. Presets belong
162
- to the Node package, the CLI and the gateway; the Python, Go and Rust clients
163
- reach them through the gateway.
164
-
165
- ### React and the browser
166
-
167
- The core is plain ESM with no Node built-ins, is tree-shakeable
168
- (only `flare-redact/register` has side effects), and uses the standard Web
169
- Crypto API, so `redact`,
170
- `scan`, vaults, and the LLM helpers work unchanged in React, Vue, and edge
171
- functions. CI smoke-tests the core on Bun and Deno on every push.
172
-
173
- ```jsx
174
- import { redact } from 'flare-redact';
175
-
176
- function SupportTicket({ text }) {
177
- // Mask pasted keys and card numbers before the ticket is rendered or sent on.
178
- return <pre>{redact(text)}</pre>;
179
- }
180
- ```
181
-
182
- Only the Node-specific entry points (`flare-redact` CLI, `/stream`, `/pino`,
183
- `/winston`) need Node. One honest caveat: client-side redaction protects what
184
- you *forward* (analytics, logs, LLM calls); it is not a substitute for
185
- server-side redaction, since the original value already reached the browser.
186
-
187
- ### Using with AI coding agents
188
-
189
- The docs site serves an [`llms.txt`](https://flare-collection.github.io/flare-redact/llms.txt)
190
- and a condensed [`llms-full.txt`](https://flare-collection.github.io/flare-redact/llms-full.txt)
191
- API reference, so coding assistants that read documentation get the current
192
- API instead of guessing. If you use Claude Code, Cursor, or similar agents,
193
- one line in your project rules (`CLAUDE.md`, `.cursor/rules`, `AGENTS.md`)
194
- keeps generated code consistent:
195
-
196
- ```
197
- For masking secrets/PII in logs, prompts, or datasets, use the flare-redact
198
- package (API: https://flare-collection.github.io/flare-redact/llms-full.txt).
199
- Do not write ad-hoc redaction regexes.
200
- ```
201
-
202
- ## Runnable examples
203
-
204
- Clone the repository and run these small applications locally:
205
-
206
- | Example | What it proves | Run |
207
- |---|---|---|
208
- | [`openai-privacy`](examples/openai-privacy) | The model sees an opaque placeholder while the app receives the restored value | `npm --prefix examples/openai-privacy start` |
209
- | [`express-pino`](examples/express-pino) | Express keeps the original request while Pino receives a safe snapshot | `npm --prefix examples/express-pino run smoke` |
210
- | [`universal-boundaries`](examples/universal-boundaries) | Any SDK method is sanitized and cross-tool placeholder exfiltration is blocked | `npm --prefix examples/universal-boundaries start` |
211
- | [`flareflow-agent`](examples/flareflow-agent) | An injected model can carry an opaque secret token but cannot restore it at an unauthorized sink or path | `npm --prefix examples/flareflow-agent start` |
212
- | [`nemo-guardrails-flareflow`](examples/nemo-guardrails-flareflow) | A NeMo-validated tool call still cannot move a protected database value into an unauthorized HTTP sink | `npm --prefix examples/nemo-guardrails-flareflow start` |
213
- | [`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 |
214
-
215
- Run `npm run build` and install an example's dependencies before its first run.
216
-
217
- ## Python, Go, and Rust
92
+ Want more than the defaults? Choose a goal instead of a detector list:
93
+ `{ preset: 'logs' }`, `'llm'`, `'gdpr'` or `'strict'` ([what each adds](docs/guide.md#presets)).
218
94
 
219
- The people who most need to keep data out of a prompt are usually not writing
220
- JavaScript. There are now four engines, and they are not four ports: they all
221
- execute the same [FRS-1 detector specification](spec/SPEC.md) and are held to the
222
- same [conformance corpus](spec/conformance/), so a policy written once produces
223
- identical output in every one of them.
95
+ ## Where it plugs in
224
96
 
225
- Each engine is its own package. Installing `flare-redact` from npm gives you the
226
- JavaScript engine and nothing else: no Python, no Go, no Rust, and no
227
- dependencies of any kind.
228
-
229
- | | Install | Docs |
230
- |---|---|---|
231
- | **Go** | `go get github.com/flare-collection/flare-redact/sdk/go` | [`sdk/go`](sdk/go) |
232
- | **Python** | `pip install "flare-redact @ git+https://github.com/flare-collection/flare-redact@v1.9.0#subdirectory=sdk/python"` | [`sdk/python`](sdk/python) |
233
- | **Rust** | `flare-redact = { git = "https://github.com/flare-collection/flare-redact", tag = "v1.9.0" }` | [`sdk/rust`](sdk/rust) |
234
-
235
- The Python and Rust engines are not published to PyPI and crates.io yet, so they
236
- install from this repository. The commands above are the ones that work today.
237
-
238
- ```python
239
- from flare_redact import create_session
240
-
241
- session = create_session(enable=["pii"])
242
- safe = session.redact("Email the invoice to ada@example.com")
243
- reply = session.restore(call_your_model(safe))
244
- ```
245
-
246
- ```go
247
- policy, _ := flareredact.Compile(flareredact.Options{Enable: []string{"pii"}})
248
- slog.SetDefault(slog.New(flareredact.NewSlogHandler(handler, policy)))
249
- ```
250
-
251
- ```rust
252
- let policy = Policy::compile(Options::new().enable(["pii"]))?;
253
- let safe = policy.redact_str("contact ada@example.com")?;
254
- ```
255
-
256
- Each SDK is dependency-light on purpose (Python is standard library only, Go is
257
- standard library only, Rust is `regex` plus `serde`) because a redaction library
258
- that expands your dependency tree is a security library that widened your attack
259
- surface. Each also ships the integrations its ecosystem actually uses: a
260
- `logging` filter and formatter and OpenAI/Anthropic client wrappers in Python, an
261
- `slog.Handler` and an `http.RoundTripper` in Go.
262
-
263
- Drift is the reason this is a specification and not three ports. Detection logic
264
- maintained in four hand-written copies diverges within a release or two, and a
265
- redactor that behaves differently per language is worse than none, because the
266
- team stops being able to reason about what leaves the process. The corpus runs in
267
- all four test suites; a change that makes them disagree fails CI.
268
-
269
- Detectors themselves are data. Write an [FRS-1 pack](spec/SPEC.md) once and every
270
- engine loads the same file:
271
-
272
- ```js
273
- import { loadPack } from 'flare-redact/pack';
274
- redact(text, { detectors: loadPack(acmePack).detectors });
275
- ```
276
-
277
- A pack that uses a construct an engine cannot execute exactly (a lookahead, a
278
- `\d` whose meaning differs between languages, a checksum it does not implement)
279
- fails to load. Failing open is how a redactor leaks.
280
-
281
- ## The sidecar gateway
282
-
283
- Sometimes the right amount of integration is none. The gateway is a reverse
284
- proxy: point a vendor SDK's base URL at it, and request bodies are scrubbed on
285
- the way out and the originals restored on the way in, streaming included.
286
-
287
- ```bash
288
- docker run --rm -p 127.0.0.1:8787:8787 \
289
- -e FLARE_REDACT_ENABLE=pii \
290
- flare-redact-gateway --upstream https://api.openai.com
291
- ```
292
-
293
- ```diff
294
- - OPENAI_BASE_URL=https://api.openai.com/v1
295
- + OPENAI_BASE_URL=http://127.0.0.1:8787/v1
296
- ```
297
-
298
- That diff is the whole integration: no middleware, no wrapper, no import. It is
299
- what makes this reachable for the estate where a Python service, a PHP monolith
300
- and a Node worker all call the same vendor and none of them can grow a new
301
- dependency this quarter.
302
-
303
- Without Docker: `npx flare-redact gateway --upstream https://api.openai.com`.
304
-
305
- ```bash
306
- # several vendors, and only the parts a human typed
307
- flare-redact gateway \
308
- --route /openai=https://api.openai.com \
309
- --route /anthropic=https://api.anthropic.com \
310
- --paths 'messages[*].content,input,prompt,system'
311
- ```
312
-
313
- Redaction uses a per-request vault, so `ada@example.com` leaves as
314
- `[FR_EMAIL_9f2c…]` and comes back as itself. For a streamed reply the restorer
315
- holds back the longest suffix that could still be the start of a placeholder, so
316
- a token split across two SSE frames is restored exactly once.
317
-
318
- The header that authenticates you *to* the vendor is not the secret being hidden
319
- *from* it: `Authorization` is forwarded untouched. Bodies and matched values are
320
- never logged; the audit line carries counts. `/metrics` exposes Prometheus
321
- counters, and `/v1/redact`, `/v1/scan` and `/v1/sessions` give any language a
322
- redaction service to call.
323
-
324
- Full documentation, including the security model and what it deliberately does
325
- not do: [`docker/README.md`](docker/README.md).
326
-
327
- ## Redact anything
328
-
329
- Strings, arrays, and objects, recursively. The shape you pass in is the shape you
330
- get back.
97
+ ### Logs
331
98
 
332
99
  ```js
333
- import { redact } from 'flare-redact';
334
-
335
- redact({
336
- user: 'bob@corp.com',
337
- password: 'hunter2',
338
- tokens: ['ghp_' + 'b'.repeat(36)],
339
- note: 'my aws key is AKIAIOSFODNN7EXAMPLE',
340
- });
341
- // →
342
- // {
343
- // user: 'b***@***',
344
- // password: '***', // sensitive field name
345
- // tokens: ['ghp_***'],
346
- // note: 'my aws key is AKIA***', // found inside free text
347
- // }
348
- ```
349
-
350
- ## Integrate any SDK or framework
351
-
352
- `flare-redact/middleware` puts one compiled policy around plain-data function
353
- boundaries. It works without framework dependencies: analytics SDK methods,
354
- server-action payloads, queue consumers, webhook clients, RPC functions,
355
- database writes, and telemetry exporters all use the same boundary shape.
356
-
357
- ```js
358
- import { createRedactionMiddleware } from 'flare-redact/middleware';
359
-
360
- const boundary = createRedactionMiddleware({
361
- policy: {
362
- enable: ['high_entropy'],
363
- refineConfidence: true,
364
- minConfidence: 0.65,
365
- },
366
- onFindings(event) {
367
- audit.info({
368
- boundary: event.name,
369
- count: event.findings.length,
370
- detectors: event.findings.map((finding) => finding.detector),
371
- }); // finding metadata is always value-free
372
- },
373
- });
374
-
375
- analytics.track = boundary.wrap(analytics.track, { name: 'analytics.track' });
376
- await analytics.track('checkout', { email, authorization });
377
- // analytics receives a redacted copy; the caller's object stays unchanged
378
- ```
379
-
380
- The same boundary supports three deployment modes:
100
+ import pino from 'pino';
101
+ import { pinoRedact } from 'flare-redact/pino';
381
102
 
382
- ```js
383
- createRedactionMiddleware({ action: 'redact' }); // default: sanitize and continue
384
- createRedactionMiddleware({ action: 'observe' }); // report only, change nothing
385
- createRedactionMiddleware({ action: 'block' }); // throw RedactionBlockedError
103
+ const log = pino(pinoRedact());
104
+ log.info({ user: 'bob@corp.com', token: 'ghp_…' }, 'login');
105
+ // {"user":"b***@***","token":"***","msg":"login", …}
386
106
  ```
387
107
 
388
- Use `process(value)` directly inside framework hooks. `wrap()` handles sync and
389
- promise-returning functions while preserving method `this`; `wrapAsync()` adds
390
- async local `semanticProvider` support. Inputs are protected by default, and
391
- `{ output: true }` also protects returned values. For signatures containing
392
- framework-native request/response objects or callbacks, protect only plain-data
393
- arguments (`{ input: [1] }`) or call `process(request.body)` explicitly; do not
394
- clone a native `Request`/`Response` object.
395
-
396
- ## Redact prompts before they reach an LLM
108
+ winston has `winstonRedact()` from `flare-redact/winston`, and plain `console`
109
+ has `wrapConsole()` or the `--import` flag above.
397
110
 
398
- Your app sends user data to OpenAI or Anthropic. Somewhere in that prompt is a
399
- customer's email, an API key, or a card number, and now it's left your systems.
400
- Wrap the client once, and detected secrets are stripped from prompts and put back
401
- in the reply. The model never sees those original values; your code keeps the
402
- references it needs.
111
+ ### LLM prompts
403
112
 
404
113
  ```js
114
+ import OpenAI from 'openai';
405
115
  import { wrapOpenAI } from 'flare-redact/llm';
406
116
 
407
117
  const openai = wrapOpenAI(new OpenAI());
408
-
409
- const res = await openai.chat.completions.create({
410
- model: 'gpt-4o',
411
- messages: [{ role: 'user', content: 'Email the invoice to alice@corp.com, card 4242 4242 4242 4242' }],
412
- });
413
118
  ```
414
119
 
415
120
  ```
@@ -418,508 +123,13 @@ the model sees → Email the invoice to [FR_EMAIL_7f2a…], card [FR_CREDIT_CA
418
123
  your app gets → Sent to alice@corp.com. Card 4242 4242 4242 4242 wasn't stored.
419
124
  ```
420
125
 
421
- `wrapAnthropic` does the same for `messages.create`, including the system prompt.
422
- Both wrappers redact complete message structures, including tool-call arguments.
423
- Streaming text, OpenAI tool arguments, and Anthropic partial JSON are restored
424
- even when a placeholder is split across chunks. There's a `redactPrompt(text)`
425
- too if you'd rather hold the vault yourself.
426
-
427
- ## Ways to hide a value
428
-
429
- Pick a `mode` depending on whether you still need to *reason* about the data
430
- after it's hidden.
431
-
432
- ```js
433
- redact('bob@corp.com', { mode: 'mask' }); // 'b***@***' (default)
434
- redact('bob@corp.com', { mode: 'label' }); // '[REDACTED:email]'
435
-
436
- const protectedOptions = { transformSecret: process.env.FLARE_REDACT_SECRET };
437
- redact('bob@corp.com', { ...protectedOptions, mode: 'hash' });
438
- // 'email_3baf4d28d7c88317a…' (HMAC-SHA-256 fingerprint)
439
-
440
- redact('bob@corp.com', { ...protectedOptions, mode: 'pseudonym' });
441
- // 'kqz@rwmp.dnu' (keyed, deterministic, keeps character classes)
442
-
443
- redact('bob@corp.com', { ...protectedOptions, mode: 'surrogate' });
444
- // 'user_93a78c61e204@example.invalid' (type-consistent synthetic value)
445
- ```
446
-
447
- Protected deterministic modes require `transformSecret`; they never silently
448
- fall back to a public unsalted fingerprint. `hash` is useful for correlation,
449
- `pseudonym` retains the original character shape, and `surrogate` emits typed
450
- synthetic values such as reserved-domain emails and Luhn-valid card numbers.
451
- Use a separate secret per environment or correlation domain.
452
-
453
- `pseudonym` is deliberately **not** described as format-preserving encryption.
454
- It is non-reversible pseudonymization, not NIST FF1. The old `fpe` name remains
455
- as a compatibility alias but is deprecated.
456
-
457
- Or replace everything with one fixed string:
458
-
459
- ```js
460
- redact(payload, { mask: '█' });
461
- redact(payload, { mask: ({ detector }) => `<${detector.id}>` });
462
- ```
463
-
464
- ## Reversible redaction
465
-
466
- When you need the originals back (the LLM case above, or handing data to a
467
- system you don't trust and getting it back), use a vault. It swaps each secret
468
- for a stable placeholder and remembers the mapping.
469
-
470
- ```js
471
- import { createVault } from 'flare-redact';
472
-
473
- const vault = createVault();
474
- const safe = vault.redact('charge bob@corp.com on card 4242 4242 4242 4242');
475
- // 'charge [FR_EMAIL_7f2ad4…] on card [FR_CREDIT_CARD_19be63…]'
476
-
477
- vault.restore(safe);
478
- // 'charge bob@corp.com on card 4242 4242 4242 4242'
479
- ```
480
-
481
- The same value gets the same placeholder inside one vault, so references survive
482
- the round trip. Default placeholders include 96 random bits instead of a global
483
- sequence number. Human-readable `[EMAIL_1]` counters remain available through
484
- `createVault({ placeholderStyle: 'readable' })` for trusted local workflows.
485
-
486
- The mapping is as sensitive as the original data. Encrypt it before persistence:
487
-
488
- ```js
489
- import { sealVault, openVault, restore } from 'flare-redact';
490
-
491
- const encrypted = await sealVault(vault, process.env.FLARE_REDACT_VAULT_PASSWORD);
492
- await fs.writeFile('session.vault.json', JSON.stringify(encrypted), { mode: 0o600 });
493
-
494
- const entries = await openVault(encrypted, process.env.FLARE_REDACT_VAULT_PASSWORD);
495
- restore(safe, new Map(entries));
496
- ```
497
-
498
- Sealed vaults use PBKDF2-SHA-256 with a fresh salt and AES-256-GCM with a fresh
499
- nonce. Wrong passwords and modified files fail closed.
500
-
501
- From the CLI, `--vault` and `--restore` use encrypted files by default. Passwords
502
- come from `FLARE_REDACT_VAULT_PASSWORD` (or the variable named by
503
- `--vault-password-env`) so they do not appear in shell history:
504
-
505
- ```bash
506
- export FLARE_REDACT_VAULT_PASSWORD='use-a-secret-manager-in-production'
507
- flare-redact --vault session.vault.json < input.txt > safe.txt
508
- flare-redact --restore session.vault.json < safe.txt > restored.txt
509
- ```
510
-
511
- ## Free-text PII without a model
512
-
513
- Masking models published on Hugging Face, such as OpenAI's privacy-filter, find
514
- people, addresses and dates in prose. They also mean a model download, a runtime
515
- and a slow CPU path. `entities` gets close to what they do with no model at all:
516
- cue phrases in the 24 library languages ("my name is", "ich heiße", "меня зовут",
517
- "我叫"), name lists, address, phone and date shapes, context scoring, and later
518
- mentions of a name already found ("Alice Johnson ... Alice said").
519
-
520
- ```js
521
- import { redact, recognizeEntities } from 'flare-redact';
522
-
523
- redact(
524
- 'Hi, my name is Alice Johnson and I live at 221B Baker Street, London NW1 6XE. Call me at 415-555-0132.',
525
- { enable: ['entities'] },
526
- );
527
- // 'Hi, my name is [REDACTED PERSON] and I live at [REDACTED ADDRESS]. Call me at [REDACTED PHONE].'
528
-
529
- redact('我的名字是李华,住在北京市朝阳区建国路88号。', { enable: ['entities'] });
530
- // '我的名字是[REDACTED PERSON],住在[REDACTED ADDRESS]。'
531
-
532
- recognizeEntities('Patient: Maria García, DOB: 03/04/1985, MRN 00482913.');
533
- // private_person 'Maria García' (0.99), private_date '03/04/1985' (0.95),
534
- // account_number '00482913' (0.86)
535
- ```
536
-
537
- | Label | Finds |
538
- |---|---|
539
- | `private_person` | names after introductions, form labels, titles, greetings, sign-offs and email headers, plus known names in running text |
540
- | `private_address` | street addresses in Latin, Cyrillic, Chinese, Japanese and Korean formats, PO boxes, postcode lines |
541
- | `private_phone` | numbers after a phone cue, international numbers, North American numbers |
542
- | `private_date` | birth dates and dates tied to a person (admission, discharge, appointment) |
543
- | `account_number` | customer, policy, passport, patient, employee and other IDs that only their label identifies |
544
- | `private_handle` | `@handles` and usernames |
545
- | `private_url` | profile links, and URLs whose query carries an email, name or token |
546
- | `secret` | passwords, PINs and one-time codes written in a sentence |
547
-
548
- The labels are the privacy-filter ones, so the outputs can be compared or swapped.
549
- They are ordinary detectors: `disable: ['private_url']` drops one,
550
- `entities: { labels: ['private_person'], minConfidence: 0.7, propagate: false }`
551
- tunes the recogniser, and vaults, `surrogate` mode, streams, the CLI
552
- (`--enable entities`) and the gateway all take them. `createEntityRecognizer()`
553
- from `flare-redact/entities` returns the same recogniser as a `semanticProvider`.
554
-
555
- On the hand-labelled corpus in [`bench/entities-cases.json`](bench/entities-cases.json)
556
- (`npm run benchmark:entities`), the holdout of 57 lines was written after tuning
557
- stopped. On its first run the regex detectors alone, with every PII detector
558
- switched on, reached 35.1% F1 and left 67.4% of the PII characters visible. With
559
- `entities` it reached 84.1% F1 with 12.0% left visible and 1.4% of the clean text
560
- masked. The corpus is small and synthetic, so read it as a regression signal and
561
- not as a comparison with published model scores. A trained model still does
562
- better on names with no cue and no match in the name lists, on unusual address
563
- formats and on languages outside the 24. When you need that, plug one in through
564
- `semanticProvider`.
565
-
566
- ## Contextual and model-assisted PII
567
-
568
- Structured identifiers and credentials are best handled by deterministic rules
569
- and checksum validators. Names and addresses need context, so three conservative
570
- detectors are opt-in:
571
-
572
- ```js
573
- const findings = scan(
574
- 'Customer name: Alice Example; address: 120 Cedar Street; DOB: 1990-04-23',
575
- { enable: ['contextual'] },
576
- );
577
-
578
- // person_name, street_address, date_of_birth
579
- // each finding includes risk, confidence, and the exact sensitive span
580
- ```
581
-
582
- For broader multilingual free-text PII, connect a local model without coupling
583
- the zero-dependency core to one ML runtime:
584
-
585
- ```js
586
- const policy = {
587
- semanticProvider: {
588
- async detect(text) {
589
- return [{
590
- detector: 'person_model', label: 'Person',
591
- why: 'Local multilingual NER result.',
592
- start: 12, end: 25, confidence: 0.94, risk: 'high',
593
- }];
594
- },
595
- },
596
- minConfidence: 0.8,
597
- };
598
-
599
- const safe = await redactAsync(input, policy);
600
- ```
601
-
602
- Semantic and deterministic spans enter the same overlap arbitration. Higher-risk,
603
- higher-priority, and better-validated findings win instead of whichever regular
604
- expression happens to run first.
605
-
606
- ## Learned confidence, fewer false positives
607
-
608
- Generic, format-agnostic detectors such as `high_entropy` catch unknown-format
609
- keys, but they also fire on benign high-entropy strings: UUIDs, git SHAs, digests,
610
- object ids, and slugs. `refineConfidence` runs a small learned classifier over
611
- each match to tell real secrets from look-alikes, then nudges the confidence
612
- score. Pair it with `minConfidence` to drop the noise.
613
-
614
- ```js
615
- const noisy = 'id 9fceb02d0ae598e95dc970b74767f19372d61af8 tok Zx9Kq2Lm7Pv4Rt6Wy8Bn3Cf5Hj1Dg0As7Uv';
616
-
617
- scan(noisy, { enable: ['high_entropy'] });
618
- // git SHA and the unknown-format token both flagged at a flat 60%
619
-
620
- scan(noisy, { enable: ['high_entropy'], refineConfidence: true, minConfidence: 0.5 });
621
- // the SHA is gone; the token survives (refined up to 80%)
622
- ```
623
-
624
- The classifier is logistic regression over cheap character features (entropy,
625
- character-class mix, structure, and nearby labels like `api_key=` or `commit`).
626
- It is trained offline by [`scripts/train-confidence-model.mjs`](scripts/train-confidence-model.mjs)
627
- and shipped as fixed weights, so the runtime stays zero-dependency, synchronous,
628
- and deterministic: no model download, no native add-on, safe on edge and in the
629
- browser. Only detectors marked `refine` are touched; checksum-validated ones
630
- (cards, IBANs, national ids) are always left alone.
631
-
632
- Score a string yourself from `flare-redact` or the `flare-redact/ml` subpath:
633
-
634
- ```js
635
- import { secretProbability } from 'flare-redact/ml';
636
-
637
- secretProbability('Zx9Kq2Lm7Pv4Rt6Wy8Bn3Cf5Hj1Dg0As7Uv', 'authorization: Bearer …'); // ~1.00
638
- secretProbability('9fceb02d0ae598e95dc970b74767f19372d61af8', 'commit …'); // ~0.00
639
- ```
640
-
641
- ## Build a private chat app
642
-
643
- If you're building a chat interface (over your own local model or any API), a
644
- **session** is the drop-in layer. One session holds one vault, so a value keeps
645
- the same placeholder across every turn: mask the user's message on the way in,
646
- restore the model's reply on the way out. It's model-agnostic and synchronous.
647
- Run `npm run benchmark` on your own target runtime instead of relying on a
648
- hardware-independent latency claim.
649
-
650
- ```js
651
- import { createSession } from 'flare-redact';
652
-
653
- const session = createSession({ enable: ['pii'] });
654
-
655
- // on the way in, the model only ever sees placeholders
656
- const prompt = session.redact(userMessage);
657
- const reply = await myModel.generate(prompt);
658
-
659
- // on the way out, the user sees the real values back
660
- show(session.restore(reply));
661
- ```
662
-
663
- Streaming? Restore token by token, even when a placeholder is split across chunks:
664
-
665
- ```js
666
- const out = session.stream();
667
- for await (const chunk of modelStream) process(out.push(chunk.text));
668
- process(out.flush());
669
- ```
670
-
671
- `session.redactMessages([{ role, content }])` masks a whole chat array at once,
672
- including nested tool calls, and `session.reset()` starts a fresh conversation.
673
- Detected original values stay local while your app keeps a reversible reference.
674
-
675
- ## Enforce information flow across agent tools
126
+ `wrapAnthropic` does the same for Claude. On the Vercel AI SDK, one middleware
127
+ covers every provider: `wrapLanguageModel({ model, middleware: flareRedactMiddleware() })`
128
+ from `flare-redact/ai-sdk` ([details](docs/guide.md#every-provider-through-the-vercel-ai-sdk)).
129
+ Tool calls, MCP messages and agent tool boundaries are covered too: see
130
+ [the guide](docs/guide.md#redact-prompts-before-they-reach-an-llm).
676
131
 
677
- Tool-scoped vaults stop one class of attack, but a production agent often needs
678
- finer control: a database credential may be valid for `postgres.execute`, yet
679
- only in `args.connectionString`, only when it came from configuration, and at
680
- most once. **FlareFlow** makes that declassification policy executable outside
681
- the model.
682
-
683
- ```js
684
- import { createAgentFlow } from 'flare-redact/agent';
685
-
686
- const flow = createAgentFlow({
687
- sinks: {
688
- 'postgres.execute': {
689
- capabilities: [{
690
- id: 'database-credential',
691
- sources: ['config'],
692
- detectors: ['url_credentials'],
693
- paths: ['/args/connectionString'],
694
- maxUses: 1,
695
- }],
696
- budget: { maxUniqueValues: 1, maxBytes: 512 },
697
- },
698
- 'http.fetch': { capabilities: [] },
699
- },
700
- });
701
-
702
- const safe = flow.protectForModel('config', {
703
- connection: 'postgres://admin:password@db.internal/prod',
704
- });
705
- // The model sees [FR_FLOW_<128 random bits>]db.internal/prod, never credentials.
706
-
707
- // Resolve names through your own registry. Never trust the model's label.
708
- const tool = toolRegistry.resolve(modelCall.name);
709
- const localCall = flow.authorizeForSink(tool.id, modelCall.arguments);
710
- await tool.execute(localCall);
711
- ```
712
-
713
- Every token carries runtime provenance: source and detector. Authorization also
714
- checks the resolved sink, its exact JSON Pointer path, per-capability use count,
715
- and cumulative sink-wide use, unique-value, and UTF-8 byte budgets. One failed
716
- occurrence blocks the whole call without restoring anything or consuming a
717
- budget. Forged, expired, cross-flow, and object-key tokens fail closed.
718
-
719
- `inspectForSink()` preflights without restoring, `snapshot()` returns bounded
720
- value-free audit state, `revokeSource()` invalidates one source, and
721
- `restoreForApp()` is reserved for the trusted final application boundary. The
722
- implementation preserves cyclic/shared graphs, rejects same-flow re-entrancy
723
- during audit delivery, and never asks the model whether the flow is safe.
724
-
725
- Read the normative [FlareFlow 1 specification](spec/FLAREFLOW.md), run the
726
- [reproducible 700-attack / 300-utility benchmark](bench/agent-flow-cases.json),
727
- read the [technical preprint](paper/flareflow-preprint.md), or start the
728
- [runnable example](examples/flareflow-agent). The benchmark tests exact
729
- placeholder restoration; it is deliberately not presented as a general
730
- prompt-injection benchmark.
731
-
732
- The same operator-owned policy is available through the sidecar's `/v1/flows`
733
- API, with standard-library clients for Python and Go. That makes FlareFlow usable
734
- from any language that can send JSON over HTTP.
735
-
736
- ### NeMo Guardrails interoperability
737
-
738
- NeMo Guardrails IORails validates model-produced tool names and arguments; the
739
- application remains responsible for execution. Resolve the validated name
740
- through an application-owned registry and call `authorizeForSink()` immediately
741
- before execution. FlareFlow then adds source, detector, sink, exact JSON path,
742
- and cumulative-budget checks to the existing tool allowlist and schema checks.
743
-
744
- The [tested, no-network example](examples/nemo-guardrails-flareflow) proves both
745
- an unauthorized HTTP exfiltration denial and an approved database restoration.
746
- The [integration guide](https://flare-collection.github.io/flare-redact/guides/nemo-guardrails-flareflow/)
747
- documents the live application boundary and limitations.
748
-
749
- NVIDIA and the NVIDIA logo are trademarks and/or registered trademarks of
750
- NVIDIA Corporation. NeMo Guardrails is referenced only for interoperability.
751
- Flare Redact is independent and is not affiliated with, sponsored by, or
752
- endorsed by NVIDIA.
753
-
754
- ## Protect tool calls and MCP loops
755
-
756
- An agent loop has two directions: model-produced arguments need their local
757
- values restored before a tool executes, while tool results need new secrets
758
- masked before they enter model context. Use a separate vault for each tool or
759
- trust domain so a prompt-injected model cannot move one tool's placeholder into
760
- another tool's arguments and recover the original:
761
-
762
- ```js
763
- import { createScopedToolBoundary } from 'flare-redact/tool';
764
-
765
- const boundary = createScopedToolBoundary();
766
-
767
- const result = await database.query('select connection_uri from services');
768
- const safeResult = boundary.redactForModel('database', result);
769
- const modelCall = await model.generateToolCall(safeResult);
770
-
771
- // Use a runtime-owned tool/trust-domain name, never a model-supplied scope.
772
- const acceptedTool = toolRegistry.resolve(modelCall.name);
773
- const localCall = boundary.restoreForTool(acceptedTool.scope, modelCall);
774
- await executeTool(localCall);
775
- ```
776
-
777
- Only placeholders minted inside `acceptedTool.scope` are restored. Unknown and
778
- cross-scope placeholders stay opaque. `restoreForApp()` can restore every scope
779
- only at the final trusted application boundary, and `reset(scope?)` clears one
780
- scope or the whole conversation. Scope count is bounded by default.
781
-
782
- > **Legacy warning:** `createToolBoundary()` remains backward compatible for a
783
- > single tool or single trust domain, but `restoreForTool()` restores *any*
784
- > placeholder known to that boundary. Do not share one legacy boundary across
785
- > mutually untrusted tools. Prefer `createScopedToolBoundary()` for new agent
786
- > and MCP integrations.
787
-
788
- For safe logging without reversibility, use `redactToolCall()`,
789
- `redactToolResult()`, or `redactMcpMessage()` from the same entry point.
790
-
791
- ## Your own words
792
-
793
- Detectors can't know your product codenames, project names, or internal jargon,
794
- so hand them a list. `terms` catches exactly the words you name (any language,
795
- longest match first, word-boundary safe), one-way or reversibly.
796
-
797
- ```js
798
- // one-way, with your own replacement text
799
- redact('Launch Project Zeus with Falcon', {
800
- terms: { 'Project Zeus': '[CLASSIFIED]', 'Falcon': '[CLASSIFIED]' },
801
- });
802
- // → 'Launch [CLASSIFIED] with [CLASSIFIED]'
803
-
804
- // reversible: send to a model, get it back
805
- const vault = createVault({ terms: ['Project Zeus'] });
806
- const safe = vault.redact('ship Project Zeus'); // 'ship [FR_CUSTOM_TERM_a17c…]'
807
- vault.restore(safe); // 'ship Project Zeus'
808
- ```
809
-
810
- The same works from the CLI, including a full round-trip: mask, send the safe
811
- text anywhere, then restore what comes back:
812
-
813
- ```bash
814
- # add words inline or from a file, and write an encrypted vault
815
- export FLARE_REDACT_VAULT_PASSWORD='read-this-from-your-secret-manager'
816
- flare-redact --term "Project Zeus" --terms codenames.txt --vault map.json < in > safe
817
-
818
- # later, restore the originals from that map
819
- flare-redact --restore map.json < safe > original
820
- ```
821
-
822
- ## See what leaks, and why
823
-
824
- `scan()` finds secrets without changing the input, explains every hit in plain
825
- English, and reports one-based line/column locations, without returning the raw
826
- secret by default.
827
-
828
- ```js
829
- import { scan } from 'flare-redact';
830
-
831
- scan('deploy with password=hunter2 and AKIAIOSFODNN7EXAMPLE');
832
- // →
833
- // [
834
- // { detector: 'generic_assignment', label: 'Assigned secret',
835
- // why: 'A value assigned to a sensitive-looking field name…', start: 12, … },
836
- // { detector: 'aws_access_key', label: 'AWS access key ID',
837
- // why: 'Pairs with a secret key to control cloud resources and billing.', start: 33, … },
838
- // ]
839
- ```
840
-
841
- Trusted diagnostics can request the original span with
842
- `scan(input, { includeValues: true })`. Never enable that option for logs, CI
843
- reports, analytics, or error tracking.
844
-
845
- Need just the shape of it?
846
-
847
- ```js
848
- import { isClean, summary } from 'flare-redact';
849
-
850
- isClean(payload); // → false
851
- summary(payload); // → { total: 3, byDetector: { email: 1, github_token: 1, sensitive_key: 1 } }
852
- ```
853
-
854
- ## Guard your logger in one line
855
-
856
- `wrapConsole` patches `console.*` so every argument is redacted on the way out,
857
- and hands you a function to undo it.
858
-
859
- ```js
860
- import { wrapConsole } from 'flare-redact';
861
-
862
- const restore = wrapConsole();
863
- console.log('session', { user: 'bob@x.io', token: 'ghp_…' });
864
- // session { user: 'b***@***', token: 'ghp_***' }
865
- restore();
866
- ```
867
-
868
- Or with no code change at all: `node --import flare-redact/register app.js`
869
- (see [No code change at all](#no-code-change-at-all)).
870
-
871
- Prefer to be explicit? Bind your options once and reuse it:
872
-
873
- ```js
874
- import { createRedactor } from 'flare-redact';
875
-
876
- const safe = createRedactor({ enable: ['high_entropy'] });
877
- logger.info(safe.redact({ event: 'checkout', user }));
878
- ```
879
-
880
- ## One policy, everywhere
881
-
882
- Define what "sensitive" means once, and apply it at every layer: your app, your
883
- logger, your HTTP boundary, your LLM calls. Every adapter takes the same options
884
- object, so a secret is masked the same way across the whole system.
885
-
886
- ```js
887
- import { definePolicy } from 'flare-redact';
888
- const policy = { enable: ['high_entropy'], allow: ['status@acme.com'] };
889
- ```
890
-
891
- **pino**: reads the values, not a list of field paths you have to maintain:
892
-
893
- ```js
894
- import pino from 'pino';
895
- import { pinoRedact } from 'flare-redact/pino';
896
-
897
- const log = pino(pinoRedact(policy));
898
- log.info({ user: 'bob@corp.com' }); // → {"user":"b***@***"}
899
- ```
900
-
901
- **winston**: a format that redacts every field, symbol metadata left intact:
902
-
903
- ```js
904
- import winston from 'winston';
905
- import { winstonRedact } from 'flare-redact/winston';
906
-
907
- winston.format.combine(winston.format(winstonRedact(policy))(), winston.format.json());
908
- ```
909
-
910
- **HTTP**: a safe-to-log snapshot of a request; the live request is untouched.
911
- The URL string, query object, params, headers, and body are all sanitized:
912
-
913
- ```js
914
- import { httpRedactor } from 'flare-redact/http';
915
-
916
- app.use(httpRedactor(policy));
917
- app.use((req, _res, next) => { logger.info(req.redacted()); next(); });
918
- // Authorization and Cookie headers, and any secret in the body or query, are masked.
919
- ```
920
-
921
- **Sentry**: events, breadcrumbs, transactions, spans and Sentry Logs are
922
- redacted before they are sent:
132
+ ### Sentry
923
133
 
924
134
  ```js
925
135
  import * as Sentry from '@sentry/node';
@@ -928,404 +138,91 @@ import { sentryRedact } from 'flare-redact/sentry';
928
138
  Sentry.init({ dsn: process.env.SENTRY_DSN, ...sentryRedact({ preset: 'gdpr' }) });
929
139
  ```
930
140
 
931
- Messages, exception values, stack-frame variables and source lines, request
932
- data, user fields, span names and log messages are redacted; cookies are masked
933
- whole, whatever the options and wherever they sit. Sentry's own fields (event, trace, span and debug
934
- ids, release, timestamps, the file and function of each stack frame) are kept
935
- exactly, so events still group, link to their traces and resolve source maps
936
- even with `preset: 'strict'`. A field is kept only where Sentry puts it and only
937
- when its value looks like what belongs there, so a field of yours that happens
938
- to be called `release`, or an email in an exception type, is still redacted.
939
- Already have a `beforeSend`? Call `hooks.beforeSend(event)` from it.
940
-
941
- Sentry 11 streams spans and warns about a `beforeSendTransaction` hook it no
942
- longer calls. Leave it out there:
943
-
944
- ```js
945
- Sentry.init({ dsn, ...sentryRedact({ preset: 'gdpr' }, { traceLifecycle: 'stream' }) });
946
- ```
947
-
948
- Two things Sentry sends pass through no hook, so no hook can redact them: the
949
- release-health session (it carries the user's id and IP address when
950
- `sendDefaultPii` is on) and the trace header, which carries the name of the root
951
- span. Keep personal data out of span names, as Sentry itself advises, and leave
952
- `sendDefaultPii` off unless you need it.
953
-
954
- Same `policy` object flows into `flare-redact/llm`, `wrapConsole`, `createVault`,
955
- and `redactStream` too.
956
-
957
- ## Streams
958
-
959
- Pipe any log stream through it. Secrets may be split across chunks, and bounded
960
- multiline PEM private keys are masked as one record. Unterminated private keys
961
- fail closed instead of leaking their remaining bytes.
962
-
963
- ```js
964
- import { redactStream } from 'flare-redact/stream';
965
-
966
- process.stdin.pipe(redactStream()).pipe(process.stdout);
967
- ```
968
-
969
- ## Anonymize a dataset for staging
970
-
971
- Point it at a JSON or CSV dump with `--mode surrogate` and you get deterministic,
972
- typed synthetic values. The same input maps the same way in every row under one
973
- key, so joins survive without calling the transformation encryption or anonymity.
974
-
975
- ```bash
976
- export FLARE_REDACT_SECRET='read-this-from-your-secret-manager'
977
- flare-redact --csv --mode surrogate < customers.csv > customers.safe.csv
978
- ```
979
-
980
- ```
981
- Alice,alice@corp.com,4242 4242 4242 4242 Alice,user_93a78c61e204@example.invalid,7042 5270 7797 8927
982
- Bob,bob@corp.com,5555 5555 5555 4444 → Bob,user_441ae72c0901@example.invalid,0888 2706 6232 0274
983
- Alice,alice@corp.com,4242 4242 4242 4242 Alice,user_93a78c61e204@example.invalid,7042 5270 7797 8927
984
- ```
985
-
986
- `redactCsv(text, opts)` is available from `flare-redact/csv` for the same thing
987
- in code.
988
-
989
- ## Guard what leaves your app
990
-
991
- Stop PII from reaching an analytics, telemetry, or webhook endpoint: wrap
992
- `fetch` and name the hosts you don't trust with the real data. Every other
993
- request goes through untouched, so your real API calls are never altered.
994
-
995
- ```js
996
- import { wrapFetch } from 'flare-redact/fetch';
997
-
998
- const fetch = wrapFetch(globalThis.fetch, { hosts: ['api.segment.io', 'telemetry.vendor.com'] });
999
- // bodies sent to those hosts are redacted; everything else is left alone
1000
- ```
1001
-
1002
- ## Fail a build when a secret sneaks in
1003
-
1004
- Stop it before the commit exists:
1005
-
1006
- ```bash
1007
- npx flare-redact init --hook # writes .git/hooks/pre-commit
1008
- flare-redact --staged # what the hook runs: only the lines being added
1009
- ```
1010
-
1011
- A hook that scanned whole files would block every commit touching a file with an
1012
- old finding, and people would learn to skip it. `--staged` reads the staged diff,
1013
- so a commit is stopped only for what it introduces, and each finding points at
1014
- its line in the staged file. Skip the check once with `git commit --no-verify`.
141
+ Events, spans, logs and breadcrumbs are redacted in your process, before they
142
+ leave it. Sentry's own ids, release and stack frames stay intact, so grouping
143
+ and source maps keep working. [Details and limits](docs/guide.md#one-policy-everywhere).
1015
144
 
1016
- A scan leaves out assignments whose value is plainly code rather than a
1017
- secret: `token = process.env.TOKEN`, `password = os.getenv("DB_PASSWORD")`,
1018
- `secret = ${SECRET}`, `password: string`, `apiKey = config.apiKey`,
1019
- `token = getToken()`. It does not try to understand code. From the operator to
1020
- the end of the line there must be exactly one of those forms and nothing else
1021
- but closing punctuation or a comment. A default value, a second argument, a
1022
- string, a number, a `.env` style `DB_PASSWORD=value`: the finding stays, so
1023
- `process.env.PASSWORD || "hunter2"` and `config.get("db.password")` are both
1024
- reported. `--no-code-filter` turns it off. It applies to `--scan` and
1025
- `--staged` only: `redact()` keeps masking every such assignment, because
1026
- hiding too much in a log is safe and missing a secret is not.
145
+ ### Commits and CI
1027
146
 
1028
- In CI, `scan` from code, or `--scan` from the CLI (which exits non-zero on a
1029
- hit). File scans report `file:line:column`, while machine-readable JSON and SARIF
1030
- reports never echo the matched secret value:
1031
-
1032
- ```yaml
1033
- - uses: actions/checkout@v5
1034
- - uses: actions/setup-node@v5
1035
- with:
1036
- node-version: 24
1037
- - name: Scan project text files
1038
- run: npx --yes --package flare-redact@1.9.0 flare-redact --scan . --exclude package-lock.json
1039
- ```
1040
-
1041
- The scan runs on the GitHub runner, reports safe file and source locations, and
1042
- fails without sending repository contents to an external scanning service. A
1043
- copy-ready workflow lives in [`examples/github-secret-scan`](examples/github-secret-scan).
1044
- Recursive scans do not follow symlinks and skip binary files, files over 1 MiB,
1045
- and `.git`, `.hg`, `.svn`, `node_modules`, and `vendor` directories by default.
1046
- Use repeatable `--exclude` globs, `--max-file-size`, or
1047
- `--no-default-excludes` to change that policy.
1048
- Exclude globs support `*`, `?`, and `**`; a pattern without `/` matches that
1049
- basename at any depth.
147
+ On GitHub, `uses: flare-collection/flare-redact@v1` annotates each finding on the pull request ([inputs](docs/guide.md#fail-a-build-when-a-secret-sneaks-in)).
1050
148
 
1051
149
  ```bash
1052
- flare-redact --scan --format json .env app.log > flare-redact.json
1053
- flare-redact --sarif .env app.log > flare-redact.sarif
150
+ npx flare-redact init --hook # pre-commit: scans only the lines being added
151
+ npx flare-redact --scan . --sarif # CI: exits 1 on a finding, never prints the secret
1054
152
  ```
1055
153
 
1056
- ## CLI
154
+ Using [pre-commit](https://pre-commit.com)? Add `repo: https://github.com/flare-collection/flare-redact` with `id: flare-redact` ([setup](docs/guide.md#fail-a-build-when-a-secret-sneaks-in)).
1057
155
 
1058
- ```bash
1059
- npm install -g flare-redact
1060
- ```
156
+ ### No Node in the stack?
1061
157
 
1062
- ```bash
1063
- tail -f app.log | flare-redact # stream redacted logs
1064
- FLARE_REDACT_SECRET=… flare-redact --json --mode hash < event.json
1065
- FLARE_REDACT_SECRET=… flare-redact --csv --mode surrogate < dump.csv
1066
- flare-redact --scan config.env # list findings + why (exit 1 if any)
1067
- flare-redact --scan . # recursively scan a project
1068
- flare-redact --scan . --exclude 'test/**' --max-file-size 2mb
1069
- flare-redact --staged # only the lines the next commit adds
1070
- flare-redact --scan --format json .env app.log # safe machine-readable report
1071
- flare-redact --sarif .env > results.sarif # GitHub code-scanning report
1072
- flare-redact --summary --json < event.json # counts per detector
1073
- flare-redact --enable high_entropy < app.log # also catch unknown-format keys
1074
- flare-redact --scan --min-confidence 0.9 .env # only high-confidence findings
1075
- flare-redact --enable high_entropy --refine-confidence --min-confidence 0.5 < app.log # drop UUID/SHA noise
1076
- flare-redact --list # show every detector
1077
- flare-redact gateway --upstream https://api.openai.com # run the sidecar proxy
1078
- ```
1079
-
1080
- ### Ask it
158
+ Point any service at the [sidecar gateway](docs/guide.md#the-sidecar-gateway)
159
+ and it redacts request bodies on the way to OpenAI or Anthropic, with no code
160
+ change. Or use the [Python, Go and Rust](docs/guide.md#python-go-and-rust) engines:
1081
161
 
1082
- A flag list tells you a flag exists and nothing about when to reach for it, so
1083
- the CLI explains itself:
162
+ ```python
163
+ from flare_redact import create_session
1084
164
 
1085
- ```bash
1086
- flare-redact help # the summary
1087
- flare-redact help topics # everything it can explain
1088
- flare-redact help modes # one topic, in depth
1089
- flare-redact help email # one detector: what it finds, and why
1090
- flare-redact gateway help # the sidecar's own flags
165
+ session = create_session(enable=["pii"])
166
+ safe = session.redact("Email the invoice to ada@example.com")
1091
167
  ```
1092
168
 
1093
- The topics are `detectors`, `modes`, `vault`, `scan`, `files`, `gateway`,
1094
- `library`, `sdks`, `env` and `exit-codes`. Any detector id works as a topic too,
1095
- and a name that matches nothing suggests the nearest one rather than just
1096
- failing.
1097
-
1098
- ## What it catches
1099
-
1100
- On by default:
1101
-
1102
- | Detector | Finds |
1103
- |---|---|
1104
- | `private_key` | PEM private key blocks (RSA/EC/OpenSSH/PGP) |
1105
- | `aws_access_key` | AWS access key IDs (`AKIA…`, `ASIA…`) |
1106
- | `aws_secret_key` | AWS secret access keys in assignments (`aws_secret_access_key=…`, `"secretAccessKey": …`) |
1107
- | `github_token` | GitHub PATs and OAuth tokens (`ghp_…`, `github_pat_…`) |
1108
- | `gitlab_token` | GitLab PATs (`glpat-…`) |
1109
- | `slack_token` | Slack tokens (`xoxb-…`) |
1110
- | `stripe_key` | Stripe secret / restricted keys (`sk_live_…`, `rk_…`) |
1111
- | `anthropic_key` | Anthropic API keys (`sk-ant-…`) |
1112
- | `openai_key` | OpenAI API keys (`sk-…`) |
1113
- | `google_api_key` | Google API keys (`AIza…`) |
1114
- | `sendgrid_key` | SendGrid API keys (`SG.…`) |
1115
- | `twilio_key` | Twilio SIDs / keys (`AC…`, `SK…`) |
1116
- | `npm_token` | npm tokens (`npm_…`) |
1117
- | `jwt` | JSON Web Tokens |
1118
- | `bearer_token` | `Authorization: Bearer …` |
1119
- | `basic_auth` | `Authorization: Basic …` |
1120
- | `url_credentials` | passwords inside connection strings |
1121
- | `generic_assignment` | `password=`, `api_key: …`, `secret=…` (any language) |
1122
- | `email` | email addresses |
1123
- | `obfuscated_email` | bracket-obfuscated emails such as `name [at] host [dot] tld` |
1124
- | `credit_card` | card numbers (Luhn-validated) |
1125
- | `iban` | IBANs (mod-97 validated) |
1126
- | `openrouter_key` / `huggingface_token` / `groq_key` / `xai_key` / `perplexity_key` / `replicate_token` | more AI provider keys |
1127
- | `discord_bot_token` / `discord_webhook` / `telegram_bot_token` | chat tokens and webhook URLs |
1128
- | `shopify_token` / `square_token` / `stripe_webhook_secret` | commerce secrets |
1129
- | `digitalocean_token` / `azure_storage_key` / `vault_token` / `databricks_token` | cloud & infra secrets |
1130
- | `sentry_dsn` / `new_relic_key` | observability secrets |
1131
- | `airtable_pat` / `postman_key` / `linear_key` / `figma_token` / `notion_token` | SaaS workspace tokens |
1132
- | `doppler_token` / `supabase_key` / `netlify_token` / `mailgun_key` | platform API keys |
1133
-
1134
- Opt in with `enable`:
1135
-
1136
- | Detector / tag | Finds |
1137
- |---|---|
1138
- | `high_entropy` | long random-looking tokens of *any* format (entropy-based) |
1139
- | `crypto` | Bitcoin & Ethereum addresses, BIP39 seed phrases |
1140
- | `finance` | SWIFT/BIC, US ABA routing numbers |
1141
- | `vehicle` | VINs (checksum-validated) |
1142
- | `network` | IPs, MAC addresses, coordinates, internal URLs |
1143
- | `entities` | people, addresses, phones, personal dates, account numbers, handles, personal URLs and secrets in prose, without a model ([details](#free-text-pii-without-a-model)) |
1144
- | `phone` | E.164 and formatted national numbers (`+90 532 123 45 67`, `(555) 123-4567`, `0532 123 45 67`); digit-count validated, date-safe |
1145
-
1146
- Plus object values whose **key name** is sensitive (`password`, `token`,
1147
- `authorization`, `cookie`, `cvv`, …) are masked regardless of content.
1148
-
1149
- ## Multilingual secret vocabulary and IDs
1150
-
1151
- Secrets like API keys and card numbers don't care what language your app is in.
1152
- Neither does this, but the word-based checks do, so words like *password*,
1153
- *secret*, and *token* are recognized as assignments and as object keys in all
1154
- **24 languages** below:
169
+ ## How it compares
1155
170
 
1156
- | | | |
171
+ | Tool | What it does well | What flare-redact adds |
1157
172
  |---|---|---|
1158
- | 🇬🇧 English `password` | 🇨🇳 Chinese `密码` | 🇮🇳 Hindi `पासवर्ड` |
1159
- | 🇪🇸 Spanish `contraseña` | 🇸🇦 Arabic `كلمة المرور` | 🇫🇷 French `mot de passe` |
1160
- | 🇵🇹 Portuguese `senha` | 🇷🇺 Russian `пароль` | 🇯🇵 Japanese `パスワード` |
1161
- | 🇩🇪 German `passwort` | 🇰🇷 Korean `비밀번호` | 🇹🇷 Turkish `şifre` |
1162
- | 🇮🇹 Italian `segreto` | 🇮🇷 Persian `رمز عبور` | 🇵🇱 Polish `hasło` |
1163
- | 🇺🇦 Ukrainian `пароль` | 🇳🇱 Dutch `wachtwoord` | 🇻🇳 Vietnamese `mật khẩu` |
1164
- | 🇮🇩 Indonesian `kata sandi` | 🇹🇭 Thai `รหัสผ่าน` | 🇬🇷 Greek `κωδικός` |
1165
- | 🇮🇱 Hebrew `סיסמה` | 🇦🇿 Azerbaijani `şifrə` | 🇷🇴 Romanian `parolă` |
173
+ | Logger path redaction (pino `redact`, fast-redact) | Fast masking of the fields you list | Finds secrets in fields you never listed and inside free text |
174
+ | Sentry server-side scrubbing | Scrubs sensitive-looking fields once events reach Sentry | Redacts in your process, before the event leaves it |
175
+ | gitleaks, TruffleHog | Find secrets in git history and files | Masks secrets at runtime in logs, errors and prompts. Use both |
176
+ | Microsoft Presidio | Model-based PII detection in prose, as a Python service | Runs in-process with no model and no dependencies; plug a model in with `semanticProvider` when you need that recall |
1166
177
 
1167
- National IDs are opt-in and **checksum-validated**, so a random run of digits is
1168
- never mistaken for one. Enable a whole group or a single country by tag:
178
+ ## FAQ
1169
179
 
1170
- ```js
1171
- redact(text, { enable: ['pii'] }); // every national ID below
1172
- redact(text, { enable: ['tr', 'de'] }); // just Turkish and German
1173
- ```
1174
-
1175
- | Detector | Country | Validated by |
1176
- |---|---|---|
1177
- | `iban` | 🌐 international *(on by default)* | ISO 13616 mod-97 |
1178
- | `tr_tckn` | 🇹🇷 Turkey | TCKN checksum |
1179
- | `de_tax_id` | 🇩🇪 Germany | ISO 7064 mod-11,10 |
1180
- | `es_dni` | 🇪🇸 Spain (DNI/NIE) | control letter mod-23 |
1181
- | `it_codice_fiscale` | 🇮🇹 Italy | odd/even table |
1182
- | `br_cpf` | 🇧🇷 Brazil | two mod-11 digits |
1183
- | `nl_bsn` | 🇳🇱 Netherlands | 11-test |
1184
- | `pl_pesel` | 🇵🇱 Poland | weighted mod-10 |
1185
- | `ca_sin` | 🇨🇦 Canada | Luhn |
1186
- | `us_ssn` | 🇺🇸 United States | issued-range rules |
1187
- | `uk_nhs` | 🇬🇧 United Kingdom (NHS) | weighted mod-11 |
1188
- | `fr_nir` | 🇫🇷 France (NIR) | INSEE mod-97 key |
1189
- | `in_aadhaar` | 🇮🇳 India (Aadhaar) | Verhoeff |
1190
- | `au_tfn` | 🇦🇺 Australia (TFN) | weighted mod-11 |
1191
- | `cn_resident_id` | 🇨🇳 China | ISO 7064 mod-11,2 |
1192
- | `jp_my_number` | 🇯🇵 Japan (My Number) | weighted mod-11 |
1193
-
1194
- Every algorithm has its own tests against known-valid and known-invalid numbers,
1195
- so enabling them won't turn your logs into a wall of `[REDACTED]`.
1196
-
1197
- ## Custom detectors & allowlists
1198
-
1199
- Teach it your own secrets, and tell it what to leave alone:
1200
-
1201
- ```js
1202
- redact(text, {
1203
- custom: [{
1204
- id: 'internal_ticket',
1205
- label: 'Internal ticket',
1206
- why: 'Leaks internal issue-tracker IDs.',
1207
- pattern: /\bACME-\d{4,6}\b/g,
1208
- mask: () => '[TICKET]',
1209
- default: true,
1210
- }],
1211
- allow: ['support@acme.com'], // never redact these exact values
1212
- redactKeys: ['ssn', 'dob'], // extra sensitive object keys
1213
- });
1214
- ```
1215
-
1216
- ## API
180
+ **How do I hide API keys and passwords in Node.js logs?**
181
+ Start the app with `node --import flare-redact/register app.js`, or add
182
+ `pinoRedact()` or `winstonRedact()` to your logger. Nothing else to configure.
1217
183
 
1218
- ```ts
1219
- redact<T>(input: T, opts?): T // masked copy, same shape
1220
- redactAsync<T>(input: T, opts?): Promise<T> // supports async local NER providers
1221
- scan(input, opts?): Finding[] // findings + why, input untouched
1222
- scanAsync(input, opts?): Promise<Finding[]> // supports async local NER providers
1223
- isClean(input, opts?): boolean // any secrets at all?
1224
- isCleanAsync(input, opts?): Promise<boolean>
1225
- summary(input, opts?): { total, byDetector, byRisk }
1226
- compilePolicy(opts) // pre-resolved reusable sync + async policy
1227
- createRedactor(opts) / definePolicy(opts) // compatibility names for compilePolicy
1228
- wrapConsole(opts?, console?): () => void // patch console.*, returns restore
184
+ **How do I keep customer data out of OpenAI or Claude API calls?**
185
+ Wrap the client with `wrapOpenAI` or `wrapAnthropic`, or on the Vercel AI SDK
186
+ add `flareRedactMiddleware()` to the model. Sensitive values become
187
+ placeholders before the request is sent and are restored in the reply.
1229
188
 
1230
- createVault(opts?): Vault // reversible: redact / restore / entries
1231
- restore(input, vaultOrMap): T // put originals back
1232
- sealVault(vaultOrEntries, password): Promise<SealedVaultV1>
1233
- openVault(envelope, password): Promise<Array<[placeholder, original]>>
189
+ **Will it slow my app down?**
190
+ It runs in your process with no model and no network call, and its patterns are
191
+ bounded and tested against hostile input. `npm run benchmark` measures it on
192
+ your own runtime.
1234
193
 
1235
- // adapters, each takes the same options object
1236
- pinoRedact(opts?) // 'flare-redact/pino' → { formatters: { log } }
1237
- winstonRedact(opts?) // 'flare-redact/winston' → a format transform
1238
- sentryRedact(opts?) // 'flare-redact/sentry' → { beforeSend, beforeSendTransaction, beforeSendSpan, beforeSendLog, beforeBreadcrumb }
1239
- redactSentryEvent(e, opts?) // 'flare-redact/sentry' → one redacted error event or transaction
1240
- // node --import flare-redact/register → console.* redacted, preset from FLARE_REDACT_PRESET
1241
- redactHttp(req, opts?) // 'flare-redact/http' → safe-to-log request snapshot
1242
- redactUrl(url, opts?) // 'flare-redact/http' → sanitized absolute/relative URL
1243
- httpRedactor(opts?) // 'flare-redact/http' → Express/Connect middleware
1244
- redactCsv(text, opts?) // 'flare-redact/csv' → anonymize a CSV dataset
1245
- wrapFetch(fetch, opts?) // 'flare-redact/fetch' → redact egress to named hosts
1246
- createRedactionMiddleware(opts?) // 'flare-redact/middleware' → any function/handler
194
+ **Does it catch everything?**
195
+ No tool does. Detection is best-effort, and names in prose are found by rules,
196
+ not a trained model. Read the [security boundaries](docs/guide.md#security-boundaries)
197
+ before relying on it for compliance.
1247
198
 
1248
- // from 'flare-redact/ml'
1249
- secretProbability(value, context?): number // learned secret-vs-look-alike score, 0..1
1250
- extractFeatures(value, context?): number[] // the raw feature vector
199
+ ## For AI coding assistants
1251
200
 
1252
- // from 'flare-redact/llm'
1253
- wrapOpenAI(client, opts?) // scrub prompts, restore replies (+streaming)
1254
- wrapAnthropic(client, opts?) // same for messages.create + system
1255
- redactPrompt(text, opts?): { text, vault }
201
+ The docs site serves [`llms.txt`](https://flare-collection.github.io/flare-redact/llms.txt)
202
+ and [`llms-full.txt`](https://flare-collection.github.io/flare-redact/llms-full.txt).
203
+ Add one line to your `AGENTS.md`, `CLAUDE.md` or `.cursor/rules` so generated
204
+ code uses the library instead of ad-hoc regexes:
1256
205
 
1257
- // from 'flare-redact/tool'
1258
- createScopedToolBoundary(opts?) // scope-safe model ↔ tool/MCP boundary
1259
- createToolBoundary(opts?) // legacy single-trust-domain boundary
1260
- redactToolCall / redactToolResult / redactMcpMessage
1261
-
1262
- // from 'flare-redact/agent'
1263
- createAgentFlow({ policy?, sinks, limits? }) // provenance + path + budget enforcement
1264
- flow.protectForModel(source, value)
1265
- flow.inspectForSink(sink, call) // no restoration or budget consumption
1266
- flow.authorizeForSink(sink, call) // atomic restore or AgentFlowBlockedError
1267
- flow.restoreForApp(value) / revokeSource(source) / snapshot() / reset()
1268
-
1269
- // from 'flare-redact/stream'
1270
- redactStream(opts?): Transform // chunk-safe + bounded multiline PEM redaction
1271
-
1272
- // opts
1273
- // {
1274
- // only?, enable?, disable?, custom?, // which detectors run
1275
- // mode?: 'mask' | 'label' | 'hash' | 'pseudonym' | 'surrogate',
1276
- // transformSecret?, mask?, minConfidence?, refineConfidence?, semanticProvider?, limits?,
1277
- // includeValues?: boolean, // scan only; unsafe raw values
1278
- // redactKeys?: boolean | RegExp | string[],
1279
- // allow?: RegExp | string[],
1280
- // terms?: string[] | { term: replacement }, termsCaseSensitive?,
1281
- // }
1282
-
1283
- createSession(opts?) // chat/AI apps: redact in, restore out, streaming, reset
206
+ ```
207
+ For masking secrets or PII in logs, prompts or datasets, use the flare-redact
208
+ package (API: https://flare-collection.github.io/flare-redact/llms-full.txt).
1284
209
  ```
1285
210
 
1286
- ## Why not a field allowlist?
1287
-
1288
- Path-based redactors (like naming fields in a logger config) only hide the fields
1289
- you *remembered* to name. The leak is always the field you forgot: the free-text
1290
- message, the nested third-party payload, the string someone concatenated by hand.
1291
- flare-redact scans the actual values, so it doesn't depend on your memory.
1292
-
1293
- Built-in patterns are reviewed for bounded structure, exercised by an
1294
- adversarial runtime suite, and protected by per-string input and finding limits.
1295
- JavaScript RegExp does not provide a formal linear-time guarantee, however, and
1296
- arbitrary custom detectors are trusted code. Run the included benchmarks on your
1297
- own runtime instead of treating a badge as a security proof:
211
+ ## Documentation
1298
212
 
1299
- ```bash
1300
- npm run benchmark
1301
- npm run benchmark:adversarial
1302
- ```
213
+ - [Guide](docs/guide.md): every feature, option and integration, with examples
214
+ - [What it catches](docs/guide.md#what-it-catches): the full detector list
215
+ - [API reference](docs/guide.md#api) and [CLI](docs/guide.md#cli)
216
+ - [Recipes](https://flare-collection.github.io/flare-redact/guides/) and [runnable examples](docs/guide.md#runnable-examples)
217
+ - [Changelog](CHANGELOG.md), [migrating from 0.9](MIGRATION.md), [security policy](SECURITY.md)
1303
218
 
1304
- ## Security boundaries
219
+ ## Contributing
1305
220
 
1306
- - Detection is best-effort; a clean scan is not proof that data contains no PII.
1307
- - `scan()` omits raw values by default. `includeValues` intentionally puts those
1308
- secrets back into process memory and must stay out of external reports.
1309
- - `pseudonym` is keyed, deterministic pseudonymization, not NIST FF1 encryption.
1310
- - A vault map is sensitive; persist only the authenticated encrypted envelope.
1311
- - Restoring a placeholder intentionally reveals its original locally. Do not
1312
- forward restored model output to another untrusted sink automatically.
1313
- - A model-produced tool name is untrusted input. Resolve it to a runtime-owned
1314
- tool/trust-domain scope before calling `restoreForTool()`.
1315
- - FlareFlow policy, source ids, and sink ids are runtime-owned. A model may carry
1316
- a token but must never choose the identity or capability used to restore it.
1317
- - FlareFlow controls exact placeholder declassification. It is not a general
1318
- prompt-injection defense and cannot protect data already shown to the model.
1319
- - The legacy `createToolBoundary()` restores every placeholder in its shared
1320
- vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
1321
- domain can receive model-produced arguments.
1322
- - The 24-language badge describes secret-key vocabulary and the cue words of the
1323
- `entities` recogniser. That recogniser uses rules and name lists, not a trained
1324
- model: a name with no cue and no list match is missed. Use a local
1325
- `semanticProvider` when you need model-level recall.
221
+ Bug reports, new detectors and fixes are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
222
+ Found a leak that flare-redact missed? Please report it privately through
223
+ [SECURITY.md](SECURITY.md).
1326
224
 
1327
- Encrypted vaults do not protect a compromised host or secrets already resident
1328
- in process memory. Deterministic transforms reveal when two inputs are equal.
225
+ If flare-redact kept a secret out of your logs, a ⭐ helps other people find it.
1329
226
 
1330
227
  ## License
1331
228