flare-redact 1.3.0 → 1.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,64 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.1 — 2026-08-04
4
+
5
+ ### Search discovery and documentation
6
+
7
+ - Add an indexable developer-guide hub plus focused, original guides for
8
+ JavaScript PII redaction, Node.js log secret redaction, LLM prompt privacy,
9
+ and scoped MCP/tool restoration. Each page includes tested code, explicit
10
+ security boundaries, authorship, a canonical URL, social metadata, and
11
+ structured article data.
12
+ - Link the guides from the live playground and package README, point package
13
+ metadata at the documentation site, and expand the XML sitemap from one HTML
14
+ page to six purpose-specific search pages.
15
+ - Refresh the landing page title, description, software metadata, navigation,
16
+ and playground release label for the universal middleware and scoped tool
17
+ boundary introduced in 1.4.0.
18
+
19
+ ### Verification
20
+
21
+ - Add automated documentation tests for unique titles and canonicals, required
22
+ metadata, valid JSON-LD, local-link integrity, sitemap coverage, and the live
23
+ release label. The complete suite grows from 194 to 198 tests. Runtime APIs
24
+ and redaction behavior are unchanged.
25
+
26
+ ## 1.4.0 — 2026-08-04
27
+
28
+ ### Universal integration
29
+
30
+ - Add `flare-redact/middleware`, a zero-dependency boundary for any SDK method,
31
+ route handler, queue consumer, webhook, RPC function, telemetry exporter, or
32
+ persistence call. `process()` / `processAsync()` handle individual values;
33
+ `wrap()` preserves method `this`, supports synchronous and promised results,
34
+ and can protect all inputs, selected plain-data argument indexes, outputs, or
35
+ both; `wrapAsync()` supports asynchronous local semantic providers.
36
+ - Support `redact`, `observe`, and fail-closed `block` actions. Finding callbacks
37
+ and `RedactionBlockedError` always contain value-free metadata even when the
38
+ underlying policy opts into raw scan values.
39
+ - Add a runnable `universal-boundaries` example and smoke-test it in CI.
40
+
41
+ ### Agent and MCP security
42
+
43
+ - Add `createScopedToolBoundary()`, with an independent reversible vault per
44
+ runtime-owned tool or trust domain. A placeholder transplanted by a model into
45
+ another tool's arguments remains opaque, while same-scope restoration and a
46
+ final trusted `restoreForApp()` continue to work.
47
+ - Bound active scopes, reject invalid scope names and cross-scope custom
48
+ placeholder collisions, support narrow or complete reset, and preserve the
49
+ existing `createToolBoundary()` API for backward compatibility.
50
+ - Document the legacy shared-vault threat explicitly: one unscoped boundary
51
+ must not be shared across mutually untrusted tools.
52
+
53
+ ### Verification
54
+
55
+ - Add adversarial coverage for cross-tool placeholder exfiltration, same-tool
56
+ JSON arguments, unknown placeholders, trusted final-app restoration, reset,
57
+ scope limits, and custom collisions. Add middleware coverage for every action,
58
+ value-free events/errors, sync and promised outputs, method binding, and async
59
+ semantic providers. Extend the graph/vault benchmark with wrapped middleware
60
+ and scoped tool round trips. The suite grows from 181 to 194 tests.
61
+
3
62
  ## 1.3.0 — 2026-07-27
4
63
 
5
64
  ### CLI
package/MIGRATION.md CHANGED
@@ -1,16 +1,42 @@
1
- # Migrating to flare-redact 1.0
2
-
3
- Version 1.0 makes the public API safe by default and establishes the compatibility
4
- contract for the `1.x` line.
1
+ # Migrating flare-redact
5
2
 
6
3
  ## Upgrade
7
4
 
8
5
  ```bash
9
- npm install flare-redact@^1.0.0
6
+ npm install flare-redact@^1.4.0
10
7
  ```
11
8
 
12
- Projects pinned to `0.9.0`, `^0.9.0`, or a lockfile stay on their current version
13
- until this command is run.
9
+ Version 1.4 is backward compatible with the `1.x` line. Projects pinned to an
10
+ older exact version or lockfile stay there until explicitly upgraded.
11
+
12
+ ## 1.4 agent-boundary security upgrade
13
+
14
+ Version 1.4 is backward compatible, but multi-tool agent applications should
15
+ replace a shared `createToolBoundary()` with `createScopedToolBoundary()`.
16
+ The legacy boundary restores every placeholder in one conversation vault. A
17
+ prompt-injected model can copy a placeholder from one tool result into another
18
+ tool's arguments, causing the second tool call to receive the original value.
19
+
20
+ ```js
21
+ import { createScopedToolBoundary } from 'flare-redact/tool';
22
+
23
+ const boundary = createScopedToolBoundary();
24
+ const safe = boundary.redactForModel('database', databaseResult);
25
+ const call = await model.generateToolCall(safe);
26
+
27
+ // Map an accepted tool to a runtime-owned scope; never trust arbitrary model
28
+ // text as the authorization scope.
29
+ const localCall = boundary.restoreForTool(acceptedTool.scope, call);
30
+ ```
31
+
32
+ Use one stable scope per tool or trust domain. Same-scope calls restore normally;
33
+ cross-scope and unknown placeholders stay opaque. Single-tool applications can
34
+ keep `createToolBoundary()` unchanged.
35
+
36
+ ## 1.0 safe-by-default changes
37
+
38
+ Version 1.0 established the compatibility contract for the `1.x` line. Projects
39
+ upgrading directly from `0.9.x` must account for the changes below.
14
40
 
15
41
  ## Breaking change: scan values are opt-in
16
42
 
package/README.md CHANGED
@@ -24,6 +24,12 @@
24
24
  🇬🇧 🇨🇳 🇮🇳 🇪🇸 🇸🇦 🇫🇷 🇵🇹 🇷🇺 🇯🇵 🇩🇪 🇰🇷 🇹🇷 🇮🇹 🇮🇷 🇵🇱 🇺🇦 🇳🇱 🇻🇳 🇮🇩 🇹🇭 🇬🇷 🇮🇱 🇦🇿 🇷🇴
25
25
  </p>
26
26
 
27
+ <p align="center">
28
+ <a href="https://flare-collection.github.io/flare-redact/">Live playground</a>
29
+ · <a href="https://flare-collection.github.io/flare-redact/guides/">Practical redaction guides</a>
30
+ · <a href="https://flare-collection.github.io/flare-redact/llms-full.txt">LLM-friendly API reference</a>
31
+ </p>
32
+
27
33
  ---
28
34
 
29
35
  Every leaked secret has the same origin story: someone logged an object, and a
@@ -57,13 +63,15 @@ Nothing to configure. No list of field paths to maintain. No native build step.
57
63
  | | | |
58
64
  |---|---|---|
59
65
  | 🔍 **Context-aware** — spans carry risk and confidence | 🔐 **Secure vaults** — opaque tokens, optional AES-GCM persistence | 🎭 **Useful test data** — keyed pseudonyms and typed surrogates |
60
- | 🤖 **LLM + tool boundary** — protects prompts, tool calls, and MCP payloads | 🌍 **24-language secret vocabulary** — plus checksum-validated IDs | 🪶 **Zero runtime dependencies** — Node, browser, and edge |
66
+ | 🤖 **Scoped LLM + tool boundaries** — stops cross-tool placeholder restore | 🔌 **Universal middleware** — wrap any SDK, handler, queue, or RPC function | 🪶 **Zero runtime dependencies** — Node, browser, and edge |
61
67
 
62
68
  ## Contents
63
69
 
64
70
  - [Install](#install)
71
+ - [Practical guides](https://flare-collection.github.io/flare-redact/guides/)
65
72
  - [Runnable examples](#runnable-examples)
66
73
  - [Redact anything](#redact-anything)
74
+ - [Integrate any SDK or framework](#integrate-any-sdk-or-framework)
67
75
  - [Redact prompts before they reach an LLM](#redact-prompts-before-they-reach-an-llm)
68
76
  - [Ways to hide a value](#ways-to-hide-a-value)
69
77
  - [Reversible redaction](#reversible-redaction)
@@ -142,6 +150,7 @@ Clone the repository and run these small applications locally:
142
150
  |---|---|---|
143
151
  | [`openai-privacy`](examples/openai-privacy) | The model sees an opaque placeholder while the app receives the restored value | `npm --prefix examples/openai-privacy start` |
144
152
  | [`express-pino`](examples/express-pino) | Express keeps the original request while Pino receives a safe snapshot | `npm --prefix examples/express-pino run smoke` |
153
+ | [`universal-boundaries`](examples/universal-boundaries) | Any SDK method is sanitized and cross-tool placeholder exfiltration is blocked | `npm --prefix examples/universal-boundaries start` |
145
154
  | [`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 |
146
155
 
147
156
  Run `npm run build` and install an example's dependencies before its first run.
@@ -169,6 +178,52 @@ redact({
169
178
  // }
170
179
  ```
171
180
 
181
+ ## Integrate any SDK or framework
182
+
183
+ `flare-redact/middleware` puts one compiled policy around plain-data function
184
+ boundaries. It works without framework dependencies: analytics SDK methods,
185
+ server-action payloads, queue consumers, webhook clients, RPC functions,
186
+ database writes, and telemetry exporters all use the same boundary shape.
187
+
188
+ ```js
189
+ import { createRedactionMiddleware } from 'flare-redact/middleware';
190
+
191
+ const boundary = createRedactionMiddleware({
192
+ policy: {
193
+ enable: ['high_entropy'],
194
+ refineConfidence: true,
195
+ minConfidence: 0.65,
196
+ },
197
+ onFindings(event) {
198
+ audit.info({
199
+ boundary: event.name,
200
+ count: event.findings.length,
201
+ detectors: event.findings.map((finding) => finding.detector),
202
+ }); // finding metadata is always value-free
203
+ },
204
+ });
205
+
206
+ analytics.track = boundary.wrap(analytics.track, { name: 'analytics.track' });
207
+ await analytics.track('checkout', { email, authorization });
208
+ // analytics receives a redacted copy; the caller's object stays unchanged
209
+ ```
210
+
211
+ The same boundary supports three deployment modes:
212
+
213
+ ```js
214
+ createRedactionMiddleware({ action: 'redact' }); // default: sanitize and continue
215
+ createRedactionMiddleware({ action: 'observe' }); // report only, change nothing
216
+ createRedactionMiddleware({ action: 'block' }); // throw RedactionBlockedError
217
+ ```
218
+
219
+ Use `process(value)` directly inside framework hooks. `wrap()` handles sync and
220
+ promise-returning functions while preserving method `this`; `wrapAsync()` adds
221
+ async local `semanticProvider` support. Inputs are protected by default, and
222
+ `{ output: true }` also protects returned values. For signatures containing
223
+ framework-native request/response objects or callbacks, protect only plain-data
224
+ arguments (`{ input: [1] }`) or call `process(request.body)` explicitly; do not
225
+ clone a native `Request`/`Response` object.
226
+
172
227
  ## Redact prompts before they reach an LLM
173
228
 
174
229
  Your app sends user data to OpenAI or Anthropic. Somewhere in that prompt is a
@@ -397,22 +452,36 @@ Detected original values stay local while your app keeps a reversible reference.
397
452
 
398
453
  An agent loop has two directions: model-produced arguments need their local
399
454
  values restored before a tool executes, while tool results need new secrets
400
- masked before they enter model context. One conversation-scoped boundary handles
401
- both without sending its vault anywhere:
455
+ masked before they enter model context. Use a separate vault for each tool or
456
+ trust domain so a prompt-injected model cannot move one tool's placeholder into
457
+ another tool's arguments and recover the original:
402
458
 
403
459
  ```js
404
- import { createToolBoundary } from 'flare-redact/tool';
460
+ import { createScopedToolBoundary } from 'flare-redact/tool';
405
461
 
406
- const boundary = createToolBoundary();
462
+ const boundary = createScopedToolBoundary();
407
463
 
408
- const safePrompt = boundary.redactForModel(userMessage);
409
- const modelCall = await model.generateToolCall(safePrompt);
410
- const localCall = boundary.restoreForTool(modelCall);
464
+ const result = await database.query('select connection_uri from services');
465
+ const safeResult = boundary.redactForModel('database', result);
466
+ const modelCall = await model.generateToolCall(safeResult);
411
467
 
412
- const result = await executeTool(localCall);
413
- const safeResult = boundary.redactForModel(result);
468
+ // Use a runtime-owned tool/trust-domain name, never a model-supplied scope.
469
+ const acceptedTool = toolRegistry.resolve(modelCall.name);
470
+ const localCall = boundary.restoreForTool(acceptedTool.scope, modelCall);
471
+ await executeTool(localCall);
414
472
  ```
415
473
 
474
+ Only placeholders minted inside `acceptedTool.scope` are restored. Unknown and
475
+ cross-scope placeholders stay opaque. `restoreForApp()` can restore every scope
476
+ only at the final trusted application boundary, and `reset(scope?)` clears one
477
+ scope or the whole conversation. Scope count is bounded by default.
478
+
479
+ > **Legacy warning:** `createToolBoundary()` remains backward compatible for a
480
+ > single tool or single trust domain, but `restoreForTool()` restores *any*
481
+ > placeholder known to that boundary. Do not share one legacy boundary across
482
+ > mutually untrusted tools. Prefer `createScopedToolBoundary()` for new agent
483
+ > and MCP integrations.
484
+
416
485
  For safe logging without reversibility, use `redactToolCall()`,
417
486
  `redactToolResult()`, or `redactMcpMessage()` from the same entry point.
418
487
 
@@ -603,7 +672,7 @@ machine-readable JSON and SARIF reports never echo the matched secret value:
603
672
  with:
604
673
  node-version: 24
605
674
  - name: Scan project text files
606
- run: npx --yes --package flare-redact@1.3.0 flare-redact --scan . --exclude package-lock.json
675
+ run: npx --yes --package flare-redact@1.4.1 flare-redact --scan . --exclude package-lock.json
607
676
  ```
608
677
 
609
678
  The scan runs on the GitHub runner, reports safe file and source locations, and
@@ -787,6 +856,7 @@ redactUrl(url, opts?) // 'flare-redact/http' → sanitized absolute/relati
787
856
  httpRedactor(opts?) // 'flare-redact/http' → Express/Connect middleware
788
857
  redactCsv(text, opts?) // 'flare-redact/csv' → anonymize a CSV dataset
789
858
  wrapFetch(fetch, opts?) // 'flare-redact/fetch' → redact egress to named hosts
859
+ createRedactionMiddleware(opts?) // 'flare-redact/middleware' → any function/handler
790
860
 
791
861
  // from 'flare-redact/ml'
792
862
  secretProbability(value, context?): number // learned secret-vs-look-alike score, 0..1
@@ -798,7 +868,8 @@ wrapAnthropic(client, opts?) // same for messages.create + sy
798
868
  redactPrompt(text, opts?): { text, vault }
799
869
 
800
870
  // from 'flare-redact/tool'
801
- createToolBoundary(opts?) // reversible model ↔ tool/MCP boundary
871
+ createScopedToolBoundary(opts?) // scope-safe model ↔ tool/MCP boundary
872
+ createToolBoundary(opts?) // legacy single-trust-domain boundary
802
873
  redactToolCall / redactToolResult / redactMcpMessage
803
874
 
804
875
  // from 'flare-redact/stream'
@@ -845,6 +916,11 @@ npm run benchmark:adversarial
845
916
  - A vault map is sensitive; persist only the authenticated encrypted envelope.
846
917
  - Restoring a placeholder intentionally reveals its original locally. Do not
847
918
  forward restored model output to another untrusted sink automatically.
919
+ - A model-produced tool name is untrusted input. Resolve it to a runtime-owned
920
+ tool/trust-domain scope before calling `restoreForTool()`.
921
+ - The legacy `createToolBoundary()` restores every placeholder in its shared
922
+ vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
923
+ domain can receive model-produced arguments.
848
924
  - The 24-language badge describes secret-key vocabulary, not general multilingual
849
925
  named-entity recognition. Use a local `semanticProvider` for that task.
850
926
 
@@ -4,6 +4,8 @@
4
4
  // performance.mjs; hostile input in adversarial-runtime.mjs.
5
5
  import { performance } from 'node:perf_hooks';
6
6
  import { redact, createVault, scan } from '../dist/index.js';
7
+ import { createRedactionMiddleware } from '../dist/middleware.js';
8
+ import { createScopedToolBoundary } from '../dist/tool.js';
7
9
 
8
10
  const runs = Number(process.env.FLARE_BENCH_RUNS ?? 10);
9
11
  const warmups = Number(process.env.FLARE_BENCH_WARMUPS ?? 3);
@@ -70,6 +72,24 @@ for (const count of [100, 1_000]) {
70
72
  results.push(bench('scan:findings-per-line', { bytes: Buffer.byteLength(input) }, () => scan(input)));
71
73
  }
72
74
 
75
+ {
76
+ const events = Array.from({ length: 100 }, (_, i) => makeEvent(i));
77
+ const middleware = createRedactionMiddleware();
78
+ const sink = middleware.wrap((payload) => payload, { name: 'benchmark.sink' });
79
+ results.push(bench('middleware:wrapped-input', { objects: 100 }, () => sink(events)));
80
+ }
81
+
82
+ {
83
+ const value = 'database password=hunter2 owner=alice@example.com';
84
+ results.push(bench('tool:scoped-round-trip', { scopes: 4 }, () => {
85
+ const boundary = createScopedToolBoundary();
86
+ for (const scope of ['database', 'email', 'storage', 'payments']) {
87
+ const safe = boundary.redactForModel(scope, value);
88
+ boundary.restoreForTool(scope, safe);
89
+ }
90
+ }));
91
+ }
92
+
73
93
  process.stdout.write(JSON.stringify({
74
94
  schemaVersion: 1,
75
95
  node: process.version,
@@ -0,0 +1,56 @@
1
+ import { type Finding, type RedactOptions } from './index.js';
2
+ export type RedactionAction = 'redact' | 'observe' | 'block';
3
+ export type SafeFinding = Omit<Finding, 'value'>;
4
+ export interface RedactionContext {
5
+ /** Stable name for the boundary, route, queue, SDK method, or sink. */
6
+ name?: string;
7
+ phase?: 'input' | 'output' | 'value';
8
+ /** Caller-owned, non-sensitive correlation metadata. */
9
+ metadata?: Readonly<Record<string, unknown>>;
10
+ }
11
+ export interface RedactionEvent extends RedactionContext {
12
+ action: RedactionAction;
13
+ /** Findings are always value-free, even if the underlying policy opts in. */
14
+ findings: readonly SafeFinding[];
15
+ }
16
+ export interface RedactionMiddlewareOptions {
17
+ policy?: RedactOptions;
18
+ /** Redact (default), observe without changing data, or reject on a finding. */
19
+ action?: RedactionAction;
20
+ /** Called only when findings exist. Raw matched values are never exposed. */
21
+ onFindings?: (event: RedactionEvent) => void;
22
+ }
23
+ export interface WrapOptions {
24
+ /**
25
+ * Sanitize/reject the complete argument array (true, default), no arguments
26
+ * (false), or only the named zero-based argument indexes.
27
+ */
28
+ input?: boolean | readonly number[];
29
+ /** Sanitize/reject the return value, including resolved promises. Default: false. */
30
+ output?: boolean;
31
+ /** Boundary name included in finding events and block errors. */
32
+ name?: string;
33
+ /** Caller-owned, non-sensitive correlation metadata. */
34
+ metadata?: Readonly<Record<string, unknown>>;
35
+ }
36
+ export interface RedactionMiddleware {
37
+ inspect(value: unknown): readonly SafeFinding[];
38
+ inspectAsync(value: unknown): Promise<readonly SafeFinding[]>;
39
+ process<T>(value: T, context?: RedactionContext): T;
40
+ processAsync<T>(value: T, context?: RedactionContext): Promise<T>;
41
+ wrap<T extends (...args: any[]) => any>(handler: T, opts?: WrapOptions): T;
42
+ wrapAsync<T extends (...args: any[]) => any>(handler: T, opts?: WrapOptions): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>;
43
+ }
44
+ export declare class RedactionBlockedError extends Error {
45
+ readonly code = "ERR_REDACTION_BLOCKED";
46
+ readonly findings: readonly SafeFinding[];
47
+ readonly context: Readonly<RedactionContext>;
48
+ constructor(findings: readonly SafeFinding[], context?: RedactionContext);
49
+ }
50
+ /**
51
+ * Framework-neutral data boundary for SDK methods, route handlers, queues,
52
+ * webhooks, RPC calls, analytics clients, and persistence functions.
53
+ * Detector state is compiled once and reused across every invocation.
54
+ */
55
+ export declare function createRedactionMiddleware(opts?: RedactionMiddlewareOptions): RedactionMiddleware;
56
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,OAAO,EACZ,KAAK,aAAa,EACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,CAAC;AAC7D,MAAM,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAEjD,MAAM,WAAW,gBAAgB;IAC/B,uEAAuE;IACvE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC;IACrC,wDAAwD;IACxD,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,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C,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EACzC,OAAO,EAAE,CAAC,EACV,IAAI,CAAC,EAAE,WAAW,GACjB,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAChE;AAED,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,2BAA2B;IACxC,QAAQ,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,CAAC;IAC1C,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;gBAEjC,QAAQ,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,GAAE,gBAAqB;CAO7E;AAgCD;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,GAAE,0BAA+B,GACpC,mBAAmB,CAkGrB"}
@@ -0,0 +1,128 @@
1
+ import { compilePolicy, } from './index.js';
2
+ export class RedactionBlockedError extends Error {
3
+ constructor(findings, context = {}) {
4
+ const suffix = context.name ? ` at "${context.name}"` : '';
5
+ super(`Sensitive data blocked${suffix}: ${findings.length} finding(s).`);
6
+ this.code = 'ERR_REDACTION_BLOCKED';
7
+ this.name = 'RedactionBlockedError';
8
+ this.findings = findings;
9
+ this.context = Object.freeze({ ...context });
10
+ }
11
+ }
12
+ function safeFindings(findings) {
13
+ return Object.freeze(findings.map(({ value: _value, ...finding }) => Object.freeze(finding)));
14
+ }
15
+ function isPromiseLike(value) {
16
+ return ((typeof value === 'object' || typeof value === 'function') &&
17
+ value !== null &&
18
+ typeof value.then === 'function');
19
+ }
20
+ function wrapContext(opts, phase) {
21
+ return { name: opts.name, metadata: opts.metadata, phase };
22
+ }
23
+ function inputIndexes(input) {
24
+ if (!Array.isArray(input))
25
+ return undefined;
26
+ const unique = new Set();
27
+ for (const index of input) {
28
+ if (!Number.isInteger(index) || index < 0) {
29
+ throw new RangeError('wrap() input indexes must be non-negative integers.');
30
+ }
31
+ unique.add(index);
32
+ }
33
+ return Object.freeze([...unique]);
34
+ }
35
+ /**
36
+ * Framework-neutral data boundary for SDK methods, route handlers, queues,
37
+ * webhooks, RPC calls, analytics clients, and persistence functions.
38
+ * Detector state is compiled once and reused across every invocation.
39
+ */
40
+ export function createRedactionMiddleware(opts = {}) {
41
+ const action = opts.action ?? 'redact';
42
+ if (action !== 'redact' && action !== 'observe' && action !== 'block') {
43
+ throw new TypeError('Redaction middleware action must be redact, observe, or block.');
44
+ }
45
+ const policy = compilePolicy(opts.policy ?? {});
46
+ const inspect = (value) => safeFindings(policy.scan(value));
47
+ const inspectAsync = async (value) => safeFindings(await policy.scanAsync(value));
48
+ const decide = (value, findings, context) => {
49
+ if (findings.length) {
50
+ opts.onFindings?.(Object.freeze({ ...context, action, findings }));
51
+ if (action === 'block')
52
+ throw new RedactionBlockedError(findings, context);
53
+ }
54
+ return value;
55
+ };
56
+ const process = (value, context = {}) => {
57
+ if (action === 'redact' && !opts.onFindings)
58
+ return policy.redact(value);
59
+ const resolvedContext = { phase: 'value', ...context };
60
+ const findings = inspect(value);
61
+ decide(value, findings, resolvedContext);
62
+ return action === 'redact' ? policy.redact(value) : value;
63
+ };
64
+ const processAsync = async (value, context = {}) => {
65
+ if (action === 'redact' && !opts.onFindings)
66
+ return policy.redactAsync(value);
67
+ const resolvedContext = { phase: 'value', ...context };
68
+ const findings = await inspectAsync(value);
69
+ decide(value, findings, resolvedContext);
70
+ return action === 'redact' ? policy.redactAsync(value) : value;
71
+ };
72
+ const wrap = (handler, wrapOpts = {}) => {
73
+ if (typeof handler !== 'function')
74
+ throw new TypeError('wrap() expects a function.');
75
+ const input = wrapOpts.input ?? true;
76
+ const indexes = inputIndexes(input);
77
+ const output = wrapOpts.output ?? false;
78
+ const wrapped = function (...args) {
79
+ let safeArgs = args;
80
+ if (indexes) {
81
+ safeArgs = [...args];
82
+ for (const index of indexes) {
83
+ if (index < safeArgs.length) {
84
+ safeArgs[index] = process(safeArgs[index], wrapContext(wrapOpts, 'input'));
85
+ }
86
+ }
87
+ }
88
+ else if (input) {
89
+ safeArgs = process(args, wrapContext(wrapOpts, 'input'));
90
+ }
91
+ const result = Reflect.apply(handler, this, safeArgs);
92
+ if (!output)
93
+ return result;
94
+ if (isPromiseLike(result)) {
95
+ return Promise.resolve(result).then((value) => process(value, wrapContext(wrapOpts, 'output')));
96
+ }
97
+ return process(result, wrapContext(wrapOpts, 'output'));
98
+ };
99
+ return wrapped;
100
+ };
101
+ const wrapAsync = (handler, wrapOpts = {}) => {
102
+ if (typeof handler !== 'function')
103
+ throw new TypeError('wrapAsync() expects a function.');
104
+ const input = wrapOpts.input ?? true;
105
+ const indexes = inputIndexes(input);
106
+ const output = wrapOpts.output ?? false;
107
+ return async function (...args) {
108
+ let safeArgs = args;
109
+ if (indexes) {
110
+ safeArgs = [...args];
111
+ for (const index of indexes) {
112
+ if (index < safeArgs.length) {
113
+ safeArgs[index] = await processAsync(safeArgs[index], wrapContext(wrapOpts, 'input'));
114
+ }
115
+ }
116
+ }
117
+ else if (input) {
118
+ safeArgs = await processAsync(args, wrapContext(wrapOpts, 'input'));
119
+ }
120
+ const result = await Reflect.apply(handler, this, safeArgs);
121
+ return output
122
+ ? await processAsync(result, wrapContext(wrapOpts, 'output'))
123
+ : result;
124
+ };
125
+ };
126
+ return { inspect, inspectAsync, process, processAsync, wrap, wrapAsync };
127
+ }
128
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,GAGd,MAAM,YAAY,CAAC;AAqDpB,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAK9C,YAAY,QAAgC,EAAE,UAA4B,EAAE;QAC1E,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,OAAO,CAAC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AAY,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AAC3E,CAAC"}
package/dist/tool.d.ts CHANGED
@@ -15,6 +15,26 @@ export interface ToolBoundary {
15
15
  readonly size: number;
16
16
  reset(): void;
17
17
  }
18
+ export interface ScopedToolBoundaryOptions extends Omit<VaultOptions, 'placeholder' | 'placeholderStyle'> {
19
+ /** Maximum number of distinct tool/trust-domain scopes kept at once. Default: 128. */
20
+ maxScopes?: number;
21
+ /** Optional globally unique placeholder formatter. Opaque random placeholders are safer. */
22
+ placeholder?: (scope: string, detectorId: string, index: number) => string;
23
+ }
24
+ export interface ScopedToolBoundary {
25
+ /** Mask values for model context and bind new placeholders to one restore scope. */
26
+ redactForModel<T>(scope: string, result: T): T;
27
+ /** Restore only placeholders minted inside this exact scope. */
28
+ restoreForTool<T>(scope: string, call: T): T;
29
+ /** Restore every scope for the trusted final application boundary. */
30
+ restoreForApp<T>(output: T): T;
31
+ /** Number of placeholder mappings across all scopes. */
32
+ readonly size: number;
33
+ /** Currently allocated scopes, in insertion order. */
34
+ readonly scopes: readonly string[];
35
+ /** Reset one scope, or every scope when omitted. */
36
+ reset(scope?: string): void;
37
+ }
18
38
  /** One-way redaction for logging or persisting a tool call safely. */
19
39
  export declare function redactToolCall<T>(call: T, opts?: RedactOptions): T;
20
40
  /** One-way redaction for logging or persisting a tool/MCP result safely. */
@@ -25,6 +45,20 @@ export declare function redactMcpMessage<T>(message: T, opts?: RedactOptions): T
25
45
  * Reversible boundary for agent loops:
26
46
  *
27
47
  * model tool call -> restoreForTool -> execute -> redactForModel -> model
48
+ *
49
+ * Security: this shared vault is intended for one tool or trust domain. For
50
+ * multi-tool agents, use createScopedToolBoundary() so a model cannot move a
51
+ * placeholder into a different tool call and have it restored there.
28
52
  */
29
53
  export declare function createToolBoundary(opts?: VaultOptions): ToolBoundary;
54
+ /**
55
+ * Reversible agent boundary with a separate vault per tool or trust domain.
56
+ * A placeholder minted for one scope remains opaque when a model transplants
57
+ * it into another scope's arguments.
58
+ *
59
+ * boundary.redactForModel('database', result)
60
+ * boundary.restoreForTool('database', call) // allowed
61
+ * boundary.restoreForTool('http', call) // placeholder stays opaque
62
+ */
63
+ export declare function createScopedToolBoundary(opts?: ScopedToolBoundaryOptions): ScopedToolBoundary;
30
64
  //# sourceMappingURL=tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAe,KAAK,KAAK,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAExE,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,cAAc,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC;IAChC,2EAA2E;IAC3E,cAAc,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;IAC9B,6EAA6E;IAC7E,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC;IAC/B,mDAAmD;IACnD,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,KAAK,IAAI,IAAI,CAAC;CACf;AAED,sEAAsE;AACtE,wBAAgB,cAAc,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAEtE;AAED,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAE1E;AAED,+DAA+D;AAC/D,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAE3E;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IA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AC/B,wDAAwD;IACxD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,oDAAoD;IACpD,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,sEAAsE;AACtE,wBAAgB,cAAc,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAEtE;AAED,4EAA4E;AAC5E,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAE1E;AAED,+DAA+D;AAC/D,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,GAAE,aAAkB,GAAG,CAAC,CAE3E;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE,YAAiB,GAAG,YAAY,CAgBxE;AASD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,GAAE,yBAA8B,GACnC,kBAAkB,CAwFpB"}
package/dist/tool.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { redact } from './index.js';
2
- import { createVault } from './vault.js';
2
+ import { createVault, restore } from './vault.js';
3
3
  /** One-way redaction for logging or persisting a tool call safely. */
4
4
  export function redactToolCall(call, opts = {}) {
5
5
  return redact(call, opts);
@@ -16,6 +16,10 @@ export function redactMcpMessage(message, opts = {}) {
16
16
  * Reversible boundary for agent loops:
17
17
  *
18
18
  * model tool call -> restoreForTool -> execute -> redactForModel -> model
19
+ *
20
+ * Security: this shared vault is intended for one tool or trust domain. For
21
+ * multi-tool agents, use createScopedToolBoundary() so a model cannot move a
22
+ * placeholder into a different tool call and have it restored there.
19
23
  */
20
24
  export function createToolBoundary(opts = {}) {
21
25
  let vault = createVault(opts);
@@ -34,4 +38,109 @@ export function createToolBoundary(opts = {}) {
34
38
  },
35
39
  };
36
40
  }
41
+ function validateScope(scope) {
42
+ if (typeof scope !== 'string' || scope.length === 0 || scope.length > 256) {
43
+ throw new TypeError('Tool scope must be a non-empty string no longer than 256 characters.');
44
+ }
45
+ return scope;
46
+ }
47
+ /**
48
+ * Reversible agent boundary with a separate vault per tool or trust domain.
49
+ * A placeholder minted for one scope remains opaque when a model transplants
50
+ * it into another scope's arguments.
51
+ *
52
+ * boundary.redactForModel('database', result)
53
+ * boundary.restoreForTool('database', call) // allowed
54
+ * boundary.restoreForTool('http', call) // placeholder stays opaque
55
+ */
56
+ export function createScopedToolBoundary(opts = {}) {
57
+ const { maxScopes = 128, placeholder, ...redactOptions } = opts;
58
+ if (!Number.isInteger(maxScopes) || maxScopes < 1 || maxScopes > 10_000) {
59
+ throw new RangeError('maxScopes must be an integer from 1 to 10,000.');
60
+ }
61
+ const vaults = new Map();
62
+ const placeholderOwners = new Map();
63
+ const dropScope = (scope) => {
64
+ const vault = vaults.get(scope);
65
+ if (!vault)
66
+ return;
67
+ for (const [token] of vault.entries()) {
68
+ if (placeholderOwners.get(token) === scope)
69
+ placeholderOwners.delete(token);
70
+ }
71
+ vaults.delete(scope);
72
+ };
73
+ const vaultFor = (rawScope) => {
74
+ const scope = validateScope(rawScope);
75
+ const existing = vaults.get(scope);
76
+ if (existing)
77
+ return existing;
78
+ if (vaults.size >= maxScopes) {
79
+ throw new Error(`Scoped tool boundary exceeded its ${maxScopes} scope limit.`);
80
+ }
81
+ const vault = createVault({
82
+ ...redactOptions,
83
+ placeholderStyle: 'opaque',
84
+ ...(placeholder
85
+ ? { placeholder: (detectorId, index) => placeholder(scope, detectorId, index) }
86
+ : {}),
87
+ });
88
+ vaults.set(scope, vault);
89
+ return vault;
90
+ };
91
+ const registerPlaceholders = (scope, vault) => {
92
+ for (const [token] of vault.entries()) {
93
+ const owner = placeholderOwners.get(token);
94
+ if (owner !== undefined && owner !== scope) {
95
+ throw new Error(`Placeholder generator produced a cross-scope collision for "${token}".`);
96
+ }
97
+ placeholderOwners.set(token, scope);
98
+ }
99
+ };
100
+ return {
101
+ redactForModel(rawScope, result) {
102
+ const scope = validateScope(rawScope);
103
+ const vault = vaultFor(scope);
104
+ const redacted = vault.redact(result);
105
+ try {
106
+ registerPlaceholders(scope, vault);
107
+ }
108
+ catch (error) {
109
+ dropScope(scope);
110
+ throw error;
111
+ }
112
+ return redacted;
113
+ },
114
+ restoreForTool(scope, call) {
115
+ const validScope = validateScope(scope);
116
+ return vaults.get(validScope)?.restore(call) ?? call;
117
+ },
118
+ restoreForApp(output) {
119
+ const entries = new Map();
120
+ for (const vault of vaults.values()) {
121
+ for (const [token, value] of vault.entries())
122
+ entries.set(token, value);
123
+ }
124
+ return restore(output, entries);
125
+ },
126
+ get size() {
127
+ let total = 0;
128
+ for (const vault of vaults.values())
129
+ total += vault.size;
130
+ return total;
131
+ },
132
+ get scopes() {
133
+ return Object.freeze([...vaults.keys()]);
134
+ },
135
+ reset(scope) {
136
+ if (scope === undefined) {
137
+ vaults.clear();
138
+ placeholderOwners.clear();
139
+ return;
140
+ }
141
+ const validScope = validateScope(scope);
142
+ dropScope(validScope);
143
+ },
144
+ };
145
+ }
37
146
  //# sourceMappingURL=tool.js.map
package/dist/tool.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../src/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAsB,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,WAAW,EAAiC,MAAM,YAAY,CAAC;AAkBxE,sEAAsE;AACtE,MAAM,UAAU,cAAc,CAAI,IAAO,EAAE,OAAsB,EAAE;IACjE,OAAO,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AAC5B,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,gBAAgB,CAAI,MAAS,EAAE,OAAsB,EAAE;IACrE,OAAO,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,C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kB,CAAC;YAC1C,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;gBACpC,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE;oBAAE,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAClC,CAAC;QACD,IAAI,IAAI;YACN,IAAI,KAAK,GAAG,CAAC,CAAC;YACd,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE;gBAAE,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC;YACzD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,MAAM;YACR,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QAC3C,CAAC;QACD,KAAK,CAAC,KAAc;YAClB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,iBAAiB,CAAC,KAAK,EAAE,CAAC;gBAC1B,OAAO;YACT,CAAC;YACD,MAAM,UAAU,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;YACxC,SAAS,CAAC,UAAU,CAAC,CAAC;QACxB,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "flare-redact",
3
- "version": "1.3.0",
4
- "description": "Local, zero-dependency secret and PII redaction with contextual findings, secure reversible vaults, and LLM adapters.",
3
+ "version": "1.4.1",
4
+ "description": "Zero-dependency TypeScript secret and PII redaction for any SDK, logs, HTTP, LLM prompts, and scoped MCP tool boundaries.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "./dist/index.js",
@@ -50,6 +50,10 @@
50
50
  "./fetch": {
51
51
  "types": "./dist/fetch.d.ts",
52
52
  "default": "./dist/fetch.js"
53
+ },
54
+ "./middleware": {
55
+ "types": "./dist/middleware.d.ts",
56
+ "default": "./dist/middleware.js"
53
57
  }
54
58
  },
55
59
  "bin": {
@@ -138,12 +142,14 @@
138
142
  "multi-language",
139
143
  "national-id",
140
144
  "iban",
141
- "gdpr-compliance"
145
+ "gdpr-compliance",
146
+ "middleware",
147
+ "mcp",
148
+ "ai-agents",
149
+ "data-loss-prevention",
150
+ "sdk"
142
151
  ],
143
- "author": {
144
- "name": "Umud Hasanli",
145
- "url": "https://github.com/umudhasanli"
146
- },
152
+ "author": "Umud Hasanli (https://github.com/umudhasanli)",
147
153
  "license": "MIT",
148
154
  "publishConfig": {
149
155
  "access": "public"
@@ -152,7 +158,7 @@
152
158
  "type": "git",
153
159
  "url": "git+https://github.com/flare-collection/flare-redact.git"
154
160
  },
155
- "homepage": "https://github.com/flare-collection/flare-redact#readme",
161
+ "homepage": "https://flare-collection.github.io/flare-redact/",
156
162
  "bugs": {
157
163
  "url": "https://github.com/flare-collection/flare-redact/issues"
158
164
  },
@@ -162,5 +168,13 @@
162
168
  "devDependencies": {
163
169
  "@types/node": "^20.0.0",
164
170
  "typescript": "^5.6.0"
171
+ },
172
+ "directories": {
173
+ "doc": "docs",
174
+ "example": "examples",
175
+ "test": "test"
176
+ },
177
+ "dependencies": {
178
+ "undici-types": "^6.21.0"
165
179
  }
166
180
  }