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