flare-redact 1.8.0 โ†’ 1.9.1

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