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