flare-redact 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.0 — 2026-08-04
4
+
5
+ ### Universal integration
6
+
7
+ - Add `flare-redact/middleware`, a zero-dependency boundary for any SDK method,
8
+ route handler, queue consumer, webhook, RPC function, telemetry exporter, or
9
+ persistence call. `process()` / `processAsync()` handle individual values;
10
+ `wrap()` preserves method `this`, supports synchronous and promised results,
11
+ and can protect all inputs, selected plain-data argument indexes, outputs, or
12
+ both; `wrapAsync()` supports asynchronous local semantic providers.
13
+ - Support `redact`, `observe`, and fail-closed `block` actions. Finding callbacks
14
+ and `RedactionBlockedError` always contain value-free metadata even when the
15
+ underlying policy opts into raw scan values.
16
+ - Add a runnable `universal-boundaries` example and smoke-test it in CI.
17
+
18
+ ### Agent and MCP security
19
+
20
+ - Add `createScopedToolBoundary()`, with an independent reversible vault per
21
+ runtime-owned tool or trust domain. A placeholder transplanted by a model into
22
+ another tool's arguments remains opaque, while same-scope restoration and a
23
+ final trusted `restoreForApp()` continue to work.
24
+ - Bound active scopes, reject invalid scope names and cross-scope custom
25
+ placeholder collisions, support narrow or complete reset, and preserve the
26
+ existing `createToolBoundary()` API for backward compatibility.
27
+ - Document the legacy shared-vault threat explicitly: one unscoped boundary
28
+ must not be shared across mutually untrusted tools.
29
+
30
+ ### Verification
31
+
32
+ - Add adversarial coverage for cross-tool placeholder exfiltration, same-tool
33
+ JSON arguments, unknown placeholders, trusted final-app restoration, reset,
34
+ scope limits, and custom collisions. Add middleware coverage for every action,
35
+ value-free events/errors, sync and promised outputs, method binding, and async
36
+ semantic providers. Extend the graph/vault benchmark with wrapped middleware
37
+ and scoped tool round trips. The suite grows from 181 to 194 tests.
38
+
3
39
  ## 1.3.0 — 2026-07-27
4
40
 
5
41
  ### 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
@@ -57,13 +57,14 @@ Nothing to configure. No list of field paths to maintain. No native build step.
57
57
  | | | |
58
58
  |---|---|---|
59
59
  | 🔍 **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 |
60
+ | 🤖 **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
61
 
62
62
  ## Contents
63
63
 
64
64
  - [Install](#install)
65
65
  - [Runnable examples](#runnable-examples)
66
66
  - [Redact anything](#redact-anything)
67
+ - [Integrate any SDK or framework](#integrate-any-sdk-or-framework)
67
68
  - [Redact prompts before they reach an LLM](#redact-prompts-before-they-reach-an-llm)
68
69
  - [Ways to hide a value](#ways-to-hide-a-value)
69
70
  - [Reversible redaction](#reversible-redaction)
@@ -142,6 +143,7 @@ Clone the repository and run these small applications locally:
142
143
  |---|---|---|
143
144
  | [`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
145
  | [`express-pino`](examples/express-pino) | Express keeps the original request while Pino receives a safe snapshot | `npm --prefix examples/express-pino run smoke` |
146
+ | [`universal-boundaries`](examples/universal-boundaries) | Any SDK method is sanitized and cross-tool placeholder exfiltration is blocked | `npm --prefix examples/universal-boundaries start` |
145
147
  | [`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
148
 
147
149
  Run `npm run build` and install an example's dependencies before its first run.
@@ -169,6 +171,52 @@ redact({
169
171
  // }
170
172
  ```
171
173
 
174
+ ## Integrate any SDK or framework
175
+
176
+ `flare-redact/middleware` puts one compiled policy around plain-data function
177
+ boundaries. It works without framework dependencies: analytics SDK methods,
178
+ server-action payloads, queue consumers, webhook clients, RPC functions,
179
+ database writes, and telemetry exporters all use the same boundary shape.
180
+
181
+ ```js
182
+ import { createRedactionMiddleware } from 'flare-redact/middleware';
183
+
184
+ const boundary = createRedactionMiddleware({
185
+ policy: {
186
+ enable: ['high_entropy'],
187
+ refineConfidence: true,
188
+ minConfidence: 0.65,
189
+ },
190
+ onFindings(event) {
191
+ audit.info({
192
+ boundary: event.name,
193
+ count: event.findings.length,
194
+ detectors: event.findings.map((finding) => finding.detector),
195
+ }); // finding metadata is always value-free
196
+ },
197
+ });
198
+
199
+ analytics.track = boundary.wrap(analytics.track, { name: 'analytics.track' });
200
+ await analytics.track('checkout', { email, authorization });
201
+ // analytics receives a redacted copy; the caller's object stays unchanged
202
+ ```
203
+
204
+ The same boundary supports three deployment modes:
205
+
206
+ ```js
207
+ createRedactionMiddleware({ action: 'redact' }); // default: sanitize and continue
208
+ createRedactionMiddleware({ action: 'observe' }); // report only, change nothing
209
+ createRedactionMiddleware({ action: 'block' }); // throw RedactionBlockedError
210
+ ```
211
+
212
+ Use `process(value)` directly inside framework hooks. `wrap()` handles sync and
213
+ promise-returning functions while preserving method `this`; `wrapAsync()` adds
214
+ async local `semanticProvider` support. Inputs are protected by default, and
215
+ `{ output: true }` also protects returned values. For signatures containing
216
+ framework-native request/response objects or callbacks, protect only plain-data
217
+ arguments (`{ input: [1] }`) or call `process(request.body)` explicitly; do not
218
+ clone a native `Request`/`Response` object.
219
+
172
220
  ## Redact prompts before they reach an LLM
173
221
 
174
222
  Your app sends user data to OpenAI or Anthropic. Somewhere in that prompt is a
@@ -397,22 +445,36 @@ Detected original values stay local while your app keeps a reversible reference.
397
445
 
398
446
  An agent loop has two directions: model-produced arguments need their local
399
447
  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:
448
+ masked before they enter model context. Use a separate vault for each tool or
449
+ trust domain so a prompt-injected model cannot move one tool's placeholder into
450
+ another tool's arguments and recover the original:
402
451
 
403
452
  ```js
404
- import { createToolBoundary } from 'flare-redact/tool';
453
+ import { createScopedToolBoundary } from 'flare-redact/tool';
405
454
 
406
- const boundary = createToolBoundary();
455
+ const boundary = createScopedToolBoundary();
407
456
 
408
- const safePrompt = boundary.redactForModel(userMessage);
409
- const modelCall = await model.generateToolCall(safePrompt);
410
- const localCall = boundary.restoreForTool(modelCall);
457
+ const result = await database.query('select connection_uri from services');
458
+ const safeResult = boundary.redactForModel('database', result);
459
+ const modelCall = await model.generateToolCall(safeResult);
411
460
 
412
- const result = await executeTool(localCall);
413
- const safeResult = boundary.redactForModel(result);
461
+ // Use a runtime-owned tool/trust-domain name, never a model-supplied scope.
462
+ const acceptedTool = toolRegistry.resolve(modelCall.name);
463
+ const localCall = boundary.restoreForTool(acceptedTool.scope, modelCall);
464
+ await executeTool(localCall);
414
465
  ```
415
466
 
467
+ Only placeholders minted inside `acceptedTool.scope` are restored. Unknown and
468
+ cross-scope placeholders stay opaque. `restoreForApp()` can restore every scope
469
+ only at the final trusted application boundary, and `reset(scope?)` clears one
470
+ scope or the whole conversation. Scope count is bounded by default.
471
+
472
+ > **Legacy warning:** `createToolBoundary()` remains backward compatible for a
473
+ > single tool or single trust domain, but `restoreForTool()` restores *any*
474
+ > placeholder known to that boundary. Do not share one legacy boundary across
475
+ > mutually untrusted tools. Prefer `createScopedToolBoundary()` for new agent
476
+ > and MCP integrations.
477
+
416
478
  For safe logging without reversibility, use `redactToolCall()`,
417
479
  `redactToolResult()`, or `redactMcpMessage()` from the same entry point.
418
480
 
@@ -603,7 +665,7 @@ machine-readable JSON and SARIF reports never echo the matched secret value:
603
665
  with:
604
666
  node-version: 24
605
667
  - name: Scan project text files
606
- run: npx --yes --package flare-redact@1.3.0 flare-redact --scan . --exclude package-lock.json
668
+ run: npx --yes --package flare-redact@1.4.0 flare-redact --scan . --exclude package-lock.json
607
669
  ```
608
670
 
609
671
  The scan runs on the GitHub runner, reports safe file and source locations, and
@@ -787,6 +849,7 @@ redactUrl(url, opts?) // 'flare-redact/http' → sanitized absolute/relati
787
849
  httpRedactor(opts?) // 'flare-redact/http' → Express/Connect middleware
788
850
  redactCsv(text, opts?) // 'flare-redact/csv' → anonymize a CSV dataset
789
851
  wrapFetch(fetch, opts?) // 'flare-redact/fetch' → redact egress to named hosts
852
+ createRedactionMiddleware(opts?) // 'flare-redact/middleware' → any function/handler
790
853
 
791
854
  // from 'flare-redact/ml'
792
855
  secretProbability(value, context?): number // learned secret-vs-look-alike score, 0..1
@@ -798,7 +861,8 @@ wrapAnthropic(client, opts?) // same for messages.create + sy
798
861
  redactPrompt(text, opts?): { text, vault }
799
862
 
800
863
  // from 'flare-redact/tool'
801
- createToolBoundary(opts?) // reversible model ↔ tool/MCP boundary
864
+ createScopedToolBoundary(opts?) // scope-safe model ↔ tool/MCP boundary
865
+ createToolBoundary(opts?) // legacy single-trust-domain boundary
802
866
  redactToolCall / redactToolResult / redactMcpMessage
803
867
 
804
868
  // from 'flare-redact/stream'
@@ -845,6 +909,11 @@ npm run benchmark:adversarial
845
909
  - A vault map is sensitive; persist only the authenticated encrypted envelope.
846
910
  - Restoring a placeholder intentionally reveals its original locally. Do not
847
911
  forward restored model output to another untrusted sink automatically.
912
+ - A model-produced tool name is untrusted input. Resolve it to a runtime-owned
913
+ tool/trust-domain scope before calling `restoreForTool()`.
914
+ - The legacy `createToolBoundary()` restores every placeholder in its shared
915
+ vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
916
+ domain can receive model-produced arguments.
848
917
  - The 24-language badge describes secret-key vocabulary, not general multilingual
849
918
  named-entity recognition. Use a local `semanticProvider` for that task.
850
919
 
@@ -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,IA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ClE,IAAI,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,CAAC,CAAC;IAC3E,SAAS,CAAC,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,CA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AY,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;gBAC7D,CAAC,CAAC,MAAM,CAAC;QACb,CAAC,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,YAAY,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,CAE1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Ac,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;IAC7C,sEAAsE;IACtE,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC;IAC/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,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OAAO,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QACvD,CAAC;QACD,aAAa,CAAI,MAAS;YACxB,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,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.0",
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"
@@ -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
  }