flare-redact 1.9.1 → 1.10.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +16 -7
  3. package/bench/adversarial-runtime.mjs +27 -6
  4. package/dist/ai-sdk.d.ts +62 -0
  5. package/dist/ai-sdk.d.ts.map +1 -0
  6. package/dist/ai-sdk.js +263 -0
  7. package/dist/ai-sdk.js.map +1 -0
  8. package/dist/checksums.d.ts +43 -0
  9. package/dist/checksums.d.ts.map +1 -1
  10. package/dist/checksums.js +184 -0
  11. package/dist/checksums.js.map +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +5 -2
  14. package/dist/cli.js.map +1 -1
  15. package/dist/detectors.d.ts.map +1 -1
  16. package/dist/detectors.js +7 -4
  17. package/dist/detectors.js.map +1 -1
  18. package/dist/extra.d.ts.map +1 -1
  19. package/dist/extra.js +229 -1
  20. package/dist/extra.js.map +1 -1
  21. package/dist/file-discovery.d.ts +5 -0
  22. package/dist/file-discovery.d.ts.map +1 -1
  23. package/dist/file-discovery.js +5 -1
  24. package/dist/file-discovery.js.map +1 -1
  25. package/dist/gateway/body.d.ts.map +1 -1
  26. package/dist/gateway/body.js +2 -1
  27. package/dist/gateway/body.js.map +1 -1
  28. package/dist/gateway/config.d.ts +5 -3
  29. package/dist/gateway/config.d.ts.map +1 -1
  30. package/dist/gateway/config.js.map +1 -1
  31. package/dist/gateway/index.d.ts +1 -0
  32. package/dist/gateway/index.d.ts.map +1 -1
  33. package/dist/gateway/index.js +1 -0
  34. package/dist/gateway/index.js.map +1 -1
  35. package/dist/gateway/server.d.ts.map +1 -1
  36. package/dist/gateway/server.js +17 -1
  37. package/dist/gateway/server.js.map +1 -1
  38. package/dist/gateway/sse.d.ts +35 -0
  39. package/dist/gateway/sse.d.ts.map +1 -0
  40. package/dist/gateway/sse.js +217 -0
  41. package/dist/gateway/sse.js.map +1 -0
  42. package/dist/help.d.ts.map +1 -1
  43. package/dist/help.js +11 -5
  44. package/dist/help.js.map +1 -1
  45. package/dist/init.d.ts.map +1 -1
  46. package/dist/init.js +12 -3
  47. package/dist/init.js.map +1 -1
  48. package/dist/llm.d.ts.map +1 -1
  49. package/dist/llm.js +20 -9
  50. package/dist/llm.js.map +1 -1
  51. package/dist/locales.d.ts +3 -2
  52. package/dist/locales.d.ts.map +1 -1
  53. package/dist/locales.js +152 -3
  54. package/dist/locales.js.map +1 -1
  55. package/dist/pack.d.ts.map +1 -1
  56. package/dist/pack.js +14 -1
  57. package/dist/pack.js.map +1 -1
  58. package/dist/vault.d.ts +26 -1
  59. package/dist/vault.d.ts.map +1 -1
  60. package/dist/vault.js +61 -3
  61. package/dist/vault.js.map +1 -1
  62. package/docker/README.md +8 -5
  63. package/docs/guide.md +165 -16
  64. package/package.json +8 -2
  65. package/spec/SPEC.md +40 -3
  66. package/spec/conformance/README.md +8 -1
  67. package/spec/conformance/cases.json +60 -1
  68. package/spec/conformance/expected.json +815 -7
  69. package/spec/detectors.json +1118 -222
  70. package/spec/detectors.schema.json +3 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,103 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.0 (2026-11-18)
4
+
5
+ ### Security: restored values keep the structure of JSON (GHSA-4c5j-9f3p-p7mh)
6
+
7
+ - An original put back into a string that is JSON is now JSON-escaped: tool-call
8
+ `arguments`, Anthropic `partial_json`, JSON-mode output, and any string that
9
+ is a JSON object or array passed to `vault.restore()` or `restore()`. Before,
10
+ a value containing `"` broke the JSON, and a value containing `","key":` could
11
+ add a field to tool-call arguments or replace an earlier one, since JSON
12
+ parsers keep the last duplicate key. Text that is not JSON is restored exactly
13
+ as before.
14
+ - Covered: `wrapOpenAI` and `wrapAnthropic` (buffered and streamed), the tool
15
+ boundaries, `authorizeForSink`, the CLI's `--restore`, and the gateway. The
16
+ gateway now restores streamed responses event by event and field by field, so
17
+ a placeholder split across two events is put back and tool arguments that are
18
+ JSON inside a JSON event are escaped at both levels. `response.streamEscape:
19
+ 'none'` keeps the old byte-level behaviour.
20
+ - OpenAI `json_object`/`json_schema` and Anthropic `output_config.format`
21
+ requests have their streamed text restored escaped too.
22
+ - The Python, Go and Rust engines follow the same rule, described in FRS-1
23
+ section 11 and checked by new conformance cases. Python's `wrap_openai` and
24
+ `wrap_anthropic` now restore streamed tool arguments (they were left as
25
+ placeholders) and no longer drop text held back at the end of a field. Go and
26
+ Rust add a JSON stream restorer (`StreamJSON`, `stream_json`) for callers that
27
+ restore tool arguments themselves.
28
+ - Known limits: JSON carried as a string inside tool arguments gets one level of
29
+ escaping, and the deprecated streaming `function_call` is not restored.
30
+
31
+ ### Security: url_credentials in linear time (GHSA-x2x8-c4pf-r947)
32
+
33
+ - The URL scheme in `url_credentials` is limited to 64 characters. Unbounded, a
34
+ long run of scheme characters such as `a-b.a-b.…` made matching take time
35
+ quadratic in its length: about 7 s for 80 kB through the default `redact()`,
36
+ and the same in the Python engine. 1 MB now takes about 130 ms.
37
+ - The scheme may contain `_`, so passwords in SQLAlchemy URLs such as
38
+ `oracle+cx_oracle://scott:tiger@db` and `redshift+redshift_connector://…`
39
+ are masked. They were not masked before.
40
+ - Ships in the FRS-1 pack, which moves to version 1.10.0, with new conformance
41
+ cases and a new case in `npm run benchmark:adversarial`.
42
+
43
+ ### Vercel AI SDK
44
+
45
+ - Add `flare-redact/ai-sdk`. `wrapLanguageModel({ model, middleware:
46
+ flareRedactMiddleware() })` keeps secrets and personal data out of prompts for
47
+ every provider the AI SDK supports (OpenAI, Anthropic, Google, Bedrock,
48
+ Mistral, Groq and the rest). System, user and assistant text, reasoning,
49
+ tool-call inputs and tool results become placeholders before the call; text,
50
+ reasoning, tool calls and structured output are restored after it, streamed or
51
+ not, including placeholders split across chunks. Files and images pass through
52
+ unchanged.
53
+ - It takes the same options as `wrapOpenAI`, plus `session` to keep placeholders
54
+ stable across calls, and works with AI SDK 5, 6 and 7 without depending on
55
+ `ai`. `flare-redact init` recognises the `ai` package and prints the line.
56
+
57
+ ### 39 more detectors (90 to 129)
58
+
59
+ - 25 service tokens, on by default: `aws_bedrock_key`, `langsmith_key`,
60
+ `pinecone_key`, `tavily_key`, `pypi_token`, `rubygems_key`,
61
+ `dockerhub_token`, `jfrog_token`, `google_oauth_secret`,
62
+ `alibaba_access_key`, `heroku_api_key`, `flyio_token`,
63
+ `terraform_cloud_token`, `pulumi_token`, `planetscale_token`,
64
+ `onepassword_token`, `age_secret_key`, `sentry_auth_token`, `grafana_token`,
65
+ `dynatrace_token`, `atlassian_token`, `slack_webhook`, `mailchimp_key`,
66
+ `brevo_key` and `resend_key`.
67
+ - `gitlab_token` catches GitLab 17's longer personal access tokens and the
68
+ deploy, runner, trigger, CI job and other GitLab token types.
69
+ `digitalocean_token` catches OAuth (`doo_v1_`) and refresh (`dor_v1_`) tokens.
70
+ - 14 national IDs, off by default and reached through `enable` or the `llm`,
71
+ `gdpr` and `strict` presets, each validated by its check digit and, where the
72
+ number carries one, its birth date: `ro_cnp`, `se_personnummer`, `fi_hetu`,
73
+ `no_fodselsnummer`, `be_national_number`, `pt_nif`, `za_id`, `mx_curp`,
74
+ `cl_rut`, `ar_cuit`, `sg_nric`, `il_teudat_zehut`, `gr_amka` and `uk_nino`
75
+ (prefix and suffix rules; it has no check digit). With `za` or `ro` enabled, a
76
+ South African ID or Romanian CNP is masked whole instead of as a card number.
77
+ - Every detector ships in all four engines through the FRS-1 pack, with match
78
+ and near-miss tests and hostile-input cases in the adversarial benchmark.
79
+
80
+ ### Where people already look
81
+
82
+ - Add `.pre-commit-hooks.yaml`: `id: flare-redact` stops a commit for the lines
83
+ it adds, and `id: flare-redact-files` scans whole files for
84
+ `pre-commit run --all-files` and pre-commit.ci. The package now builds in
85
+ `prepack`, so installing it from a git checkout works.
86
+ - Add a GitHub Action: `uses: flare-collection/flare-redact@v1` scans the
87
+ checkout, annotates each finding on the pull request, writes a job summary,
88
+ can upload SARIF to code scanning, and never prints a value. Each release
89
+ moves the `v1` tag.
90
+ - The Python and Rust engines are published to PyPI and crates.io from this
91
+ release on, and the Go module gets `sdk/go/vX.Y.Z` tags so `go get` sees real
92
+ versions. Both packages now include the licence file.
93
+
94
+ ### Platforms
95
+
96
+ - CI runs the whole suite on Windows and macOS. `--scan` reports file paths with
97
+ forward slashes on every platform; on Windows they used backslashes, which also
98
+ made SARIF URIs invalid there.
99
+ - The Python engine requires 3.9 or newer, the oldest version CI tests.
100
+
3
101
  ## 1.9.1 (2026-11-17)
4
102
 
5
103
  ### Documentation
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License"></a>
16
16
  <img src="https://img.shields.io/npm/types/flare-redact.svg" alt="TypeScript">
17
17
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
18
- <img src="https://img.shields.io/badge/detectors-90-4f46e5" alt="90 detectors">
18
+ <img src="https://img.shields.io/badge/detectors-129-4f46e5" alt="129 detectors">
19
19
  <img src="https://img.shields.io/badge/languages-24-4f46e5" alt="24 languages">
20
20
  </p>
21
21
 
@@ -49,12 +49,13 @@ redact({ user: 'bob@corp.com', password: 'hunter2', note: 'my key is AKIAIOSFODN
49
49
 
50
50
  ## Highlights
51
51
 
52
- - 🔍 **Reads content, not field names.** 90 detectors for API keys, tokens, JWTs,
52
+ - 🔍 **Reads content, not field names.** 129 detectors for API keys, tokens, JWTs,
53
53
  private keys, cards, IBANs, emails and national IDs, checksum-validated
54
54
  wherever a checksum exists.
55
55
  - ⚡ **No code change needed.** `node --import flare-redact/register app.js`
56
56
  redacts every `console.*` call.
57
- - 🤖 **Private LLM calls.** Wrap the OpenAI or Anthropic client: the model sees
57
+ - 🤖 **Private LLM calls.** Wrap the OpenAI or Anthropic client, or add one
58
+ middleware to the Vercel AI SDK for every provider: the model sees
58
59
  placeholders, your app gets the real values back, streaming included.
59
60
  - 🔌 **Fits what you already run.** pino, winston, Sentry, Express, `fetch`,
60
61
  streams, and any SDK through one middleware.
@@ -83,7 +84,7 @@ Then pick the way that suits you:
83
84
  node --import flare-redact/register app.js
84
85
 
85
86
  # Let it read your package.json and print the lines to paste
86
- npx flare-redact init # openai, @anthropic-ai/sdk, Sentry, pino, winston, express
87
+ npx flare-redact init # openai, @anthropic-ai/sdk, ai, Sentry, pino, winston, express
87
88
  npx flare-redact init --hook # also stop any commit that adds a secret
88
89
  npx flare-redact init --ci # also scan every pull request
89
90
  ```
@@ -122,8 +123,11 @@ the model sees → Email the invoice to [FR_EMAIL_7f2a…], card [FR_CREDIT_CA
122
123
  your app gets → Sent to alice@corp.com. Card 4242 4242 4242 4242 wasn't stored.
123
124
  ```
124
125
 
125
- `wrapAnthropic` does the same for Claude. Tool calls, MCP messages and agent
126
- tool boundaries are covered too: see [the guide](docs/guide.md#redact-prompts-before-they-reach-an-llm).
126
+ `wrapAnthropic` does the same for Claude. On the Vercel AI SDK, one middleware
127
+ covers every provider: `wrapLanguageModel({ model, middleware: flareRedactMiddleware() })`
128
+ from `flare-redact/ai-sdk` ([details](docs/guide.md#every-provider-through-the-vercel-ai-sdk)).
129
+ Tool calls, MCP messages and agent tool boundaries are covered too: see
130
+ [the guide](docs/guide.md#redact-prompts-before-they-reach-an-llm).
127
131
 
128
132
  ### Sentry
129
133
 
@@ -140,11 +144,15 @@ and source maps keep working. [Details and limits](docs/guide.md#one-policy-ever
140
144
 
141
145
  ### Commits and CI
142
146
 
147
+ On GitHub, `uses: flare-collection/flare-redact@v1` annotates each finding on the pull request ([inputs](docs/guide.md#fail-a-build-when-a-secret-sneaks-in)).
148
+
143
149
  ```bash
144
150
  npx flare-redact init --hook # pre-commit: scans only the lines being added
145
151
  npx flare-redact --scan . --sarif # CI: exits 1 on a finding, never prints the secret
146
152
  ```
147
153
 
154
+ Using [pre-commit](https://pre-commit.com)? Add `repo: https://github.com/flare-collection/flare-redact` with `id: flare-redact` ([setup](docs/guide.md#fail-a-build-when-a-secret-sneaks-in)).
155
+
148
156
  ### No Node in the stack?
149
157
 
150
158
  Point any service at the [sidecar gateway](docs/guide.md#the-sidecar-gateway)
@@ -174,7 +182,8 @@ Start the app with `node --import flare-redact/register app.js`, or add
174
182
  `pinoRedact()` or `winstonRedact()` to your logger. Nothing else to configure.
175
183
 
176
184
  **How do I keep customer data out of OpenAI or Claude API calls?**
177
- Wrap the client with `wrapOpenAI` or `wrapAnthropic`. Sensitive values become
185
+ Wrap the client with `wrapOpenAI` or `wrapAnthropic`, or on the Vercel AI SDK
186
+ add `flareRedactMiddleware()` to the model. Sensitive values become
178
187
  placeholders before the request is sent and are restored in the reply.
179
188
 
180
189
  **Will it slow my app down?**
@@ -8,15 +8,36 @@ const cases = {
8
8
  tokenLike: (n) => 'A'.repeat(n) + '=',
9
9
  separators: (n) => '1-'.repeat(Math.floor(n / 2)),
10
10
  unicode: (n) => '密'.repeat(n),
11
+ schemeRun: (n) => 'a-b.'.repeat(Math.floor(n / 4)) + '://',
12
+ // Token prefixes followed by long runs of their body characters that never
13
+ // complete a token: each pattern must give up in time linear in the run.
14
+ tokenPrefixes: (n) => {
15
+ const prefixes = ['glpat-', 'glrt-', 'pypi-AgEIcHlwaS5vcmc', 'ABSK', 'ops_eyJ', 'sntrys_eyJ', 'glc_', 'fm2_', 'pscale_tkn_', 'ATATT3', 'HRKU-', 'dckr_pat_', 'tvly-', 'pcsk_ab1cd_'];
16
+ let out = '';
17
+ for (let i = 0; out.length < n; i++) out += prefixes[i % prefixes.length] + 'A'.repeat(1_200) + '-';
18
+ return out.slice(0, n);
19
+ },
20
+ hexRuns: (n) => ('0123456789abcdef'.repeat(4) + '-us ').repeat(Math.ceil(n / 68)).slice(0, n),
21
+ atlasRuns: (n) => ('A'.repeat(14) + '.atlasv1.' + 'A'.repeat(90) + ' ').repeat(Math.ceil(n / 114)).slice(0, n),
22
+ // Shapes the opt-in national IDs look for: printed digit groups, dotted
23
+ // groups, letter-digit runs and ID prefixes that never complete.
24
+ spacedDigits: (n) => '12 '.repeat(Math.floor(n / 3)),
25
+ dottedDigits: (n) => '12.'.repeat(Math.floor(n / 3)),
26
+ letterDigitRun: (n) => 'AB1'.repeat(Math.floor(n / 3)),
27
+ idPrefixes: (n) => 'ABCD850101H S1234567 010185-123 '.repeat(Math.floor(n / 32)),
11
28
  };
29
+ // The default policy, and every opt-in identifier through the pii tag.
30
+ const policies = { default: {}, pii: { enable: ['pii'] } };
12
31
 
13
32
  const results = [];
14
- for (const [name, build] of Object.entries(cases)) {
15
- for (const length of lengths) {
16
- const input = build(length);
17
- const start = performance.now();
18
- const findings = scan(input);
19
- results.push({ name, length: input.length, durationMs: performance.now() - start, findings: findings.length });
33
+ for (const [policy, options] of Object.entries(policies)) {
34
+ for (const [name, build] of Object.entries(cases)) {
35
+ for (const length of lengths) {
36
+ const input = build(length);
37
+ const start = performance.now();
38
+ const findings = scan(input, options);
39
+ results.push({ name, policy, length: input.length, durationMs: performance.now() - start, findings: findings.length });
40
+ }
20
41
  }
21
42
  }
22
43
 
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A language model middleware for the Vercel AI SDK (`ai`). One middleware
3
+ * covers every provider the SDK supports: prompts are redacted to opaque
4
+ * placeholders before the provider sees them, and the placeholders are put
5
+ * back in what the model returns, streamed or not.
6
+ *
7
+ * import { wrapLanguageModel } from 'ai';
8
+ * import { flareRedactMiddleware } from 'flare-redact/ai-sdk';
9
+ *
10
+ * const model = wrapLanguageModel({ model: baseModel, middleware: flareRedactMiddleware() });
11
+ *
12
+ * The types here are structural on purpose: the package does not depend on
13
+ * `ai`, and the same object works with the middleware contracts of AI SDK 5
14
+ * (`v2`), 6 (`v3`) and 7 (`v4`), whose prompt and stream shapes match for
15
+ * everything this touches.
16
+ */
17
+ import { type VaultOptions } from './vault.js';
18
+ import type { Session } from './session.js';
19
+ export interface FlareRedactMiddlewareOptions extends VaultOptions {
20
+ /**
21
+ * Keep one vault for a whole conversation instead of one per model call, so
22
+ * a value keeps the same placeholder in every step and turn. The session's
23
+ * own options apply; the other options here are ignored.
24
+ */
25
+ session?: Session;
26
+ }
27
+ /**
28
+ * The middleware object. It satisfies `LanguageModelMiddleware` from `ai` 5, 6
29
+ * and 7 without importing it.
30
+ */
31
+ export interface FlareRedactLanguageModelMiddleware {
32
+ readonly specificationVersion: 'v3';
33
+ readonly middlewareVersion: 'v2';
34
+ transformParams<P>(options: {
35
+ type: 'generate' | 'stream';
36
+ params: P;
37
+ }): Promise<P>;
38
+ wrapGenerate<R>(options: {
39
+ doGenerate: () => PromiseLike<R>;
40
+ params: unknown;
41
+ }): Promise<R>;
42
+ wrapStream<S extends {
43
+ stream: unknown;
44
+ }>(options: {
45
+ doStream: () => PromiseLike<S>;
46
+ params: unknown;
47
+ }): Promise<S>;
48
+ }
49
+ /**
50
+ * A Vercel AI SDK language model middleware that keeps secrets and personal
51
+ * data out of every prompt, for any provider:
52
+ *
53
+ * wrapLanguageModel({ model, middleware: flareRedactMiddleware({ preset: 'llm' }) })
54
+ *
55
+ * System, user and assistant text, reasoning, tool-call inputs and tool
56
+ * results are redacted to opaque placeholders before the call; text,
57
+ * reasoning, tool calls and structured output are restored in the result and
58
+ * in the stream, including placeholders split across chunks. Files and images
59
+ * are passed through unchanged. Takes the same options as `wrapOpenAI`.
60
+ */
61
+ export declare function flareRedactMiddleware(opts?: FlareRedactMiddlewareOptions): FlareRedactLanguageModelMiddleware;
62
+ //# sourceMappingURL=ai-sdk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.d.ts","sourceRoot":"","sources":["../src/ai-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAA6G,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1J,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,WAAW,4BAA6B,SAAQ,YAAY;IAChE;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,kCAAkC;IACjD,QAAQ,CAAC,oBAAoB,EAAE,IAAI,CAAC;IACpC,QAAQ,CAAC,iBAAiB,EAAE,IAAI,CAAC;IACjC,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE;QAAE,IAAI,EAAE,UAAU,GAAG,QAAQ,CAAC;QAAC,MAAM,EAAE,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACpF,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE;QAAE,UAAU,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5F,UAAU,CAAC,CAAC,SAAS;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,EAAE,OAAO,EAAE;QAAE,QAAQ,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACrH;AAsMD;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,GAAE,4BAAiC,GAAG,kCAAkC,CA0CjH"}
package/dist/ai-sdk.js ADDED
@@ -0,0 +1,263 @@
1
+ /**
2
+ * A language model middleware for the Vercel AI SDK (`ai`). One middleware
3
+ * covers every provider the SDK supports: prompts are redacted to opaque
4
+ * placeholders before the provider sees them, and the placeholders are put
5
+ * back in what the model returns, streamed or not.
6
+ *
7
+ * import { wrapLanguageModel } from 'ai';
8
+ * import { flareRedactMiddleware } from 'flare-redact/ai-sdk';
9
+ *
10
+ * const model = wrapLanguageModel({ model: baseModel, middleware: flareRedactMiddleware() });
11
+ *
12
+ * The types here are structural on purpose: the package does not depend on
13
+ * `ai`, and the same object works with the middleware contracts of AI SDK 5
14
+ * (`v2`), 6 (`v3`) and 7 (`v4`), whose prompt and stream shapes match for
15
+ * everything this touches.
16
+ */
17
+ import { buildRestore, buildStreamRestore, createVault, escapeEntriesForJson } from './vault.js';
18
+ const isObj = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ /** Keys that identify or route a part. They carry no user text and are never rewritten. */
20
+ const STRUCTURAL = new Set([
21
+ 'type', 'role', 'id', 'toolCallId', 'toolName', 'approvalId', 'approved',
22
+ 'mediaType', 'data', 'kind', 'providerOptions', 'providerExecuted',
23
+ ]);
24
+ /** Parts that pass through untouched: files and images, and provider-defined parts. */
25
+ const PASS_THROUGH = new Set(['file', 'image', 'reasoning-file', 'custom']);
26
+ const isJson = (text) => {
27
+ try {
28
+ JSON.parse(text);
29
+ return true;
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ };
35
+ function redactPrompt(prompt, vault) {
36
+ if (!Array.isArray(prompt))
37
+ return prompt;
38
+ // Every string that is not structural, one level down: the values of a tool
39
+ // result (`text`, `json`, `error-*`), a denial reason, and fields of part
40
+ // types this version does not know about yet.
41
+ const redactLoose = (part) => {
42
+ const out = {};
43
+ for (const [key, value] of Object.entries(part))
44
+ out[key] = STRUCTURAL.has(key) ? value : vault.redact(value);
45
+ return out;
46
+ };
47
+ const redactToolOutput = (output) => {
48
+ if (!isObj(output))
49
+ return vault.redact(output);
50
+ if (output.type === 'content' && Array.isArray(output.value)) {
51
+ return {
52
+ ...output,
53
+ value: output.value.map((item) => isObj(item) && item.type === 'text' && typeof item.text === 'string' ? { ...item, text: vault.redact(item.text) } : item),
54
+ };
55
+ }
56
+ return redactLoose(output);
57
+ };
58
+ const redactPart = (part) => {
59
+ if (typeof part === 'string')
60
+ return vault.redact(part);
61
+ if (!isObj(part))
62
+ return part;
63
+ const type = part.type;
64
+ if (typeof type === 'string' && PASS_THROUGH.has(type))
65
+ return part;
66
+ switch (type) {
67
+ case 'text':
68
+ case 'reasoning':
69
+ return typeof part.text === 'string' ? { ...part, text: vault.redact(part.text) } : part;
70
+ case 'tool-call':
71
+ return { ...part, input: vault.redact(part.input) };
72
+ case 'tool-result':
73
+ return 'output' in part ? { ...part, output: redactToolOutput(part.output) } : redactLoose(part);
74
+ default:
75
+ return redactLoose(part);
76
+ }
77
+ };
78
+ return prompt.map((message) => {
79
+ if (!isObj(message))
80
+ return message;
81
+ const { content } = message;
82
+ if (typeof content === 'string')
83
+ return { ...message, content: vault.redact(content) };
84
+ if (Array.isArray(content))
85
+ return { ...message, content: content.map(redactPart) };
86
+ return message;
87
+ });
88
+ }
89
+ function restorers(vault, jsonOutput) {
90
+ const entries = vault.entries();
91
+ const escaped = escapeEntriesForJson(entries);
92
+ const plain = buildRestore(entries);
93
+ const json = buildRestore(escaped);
94
+ return {
95
+ text: jsonOutput ? json : plain,
96
+ // A placeholder can only sit inside a string in valid JSON, so the
97
+ // original goes in escaped; anything that is not JSON gets it verbatim.
98
+ toolInput: (input) => (entries.length && isJson(input) ? json(input) : plain(input)),
99
+ value: (value) => vault.restore(value),
100
+ stream: (kind) => buildStreamRestore(kind === 'json' || (kind === 'text' && jsonOutput) ? escaped : entries),
101
+ };
102
+ }
103
+ function restoreContent(content, restore) {
104
+ if (!Array.isArray(content))
105
+ return content;
106
+ return content.map((part) => {
107
+ if (!isObj(part))
108
+ return typeof part === 'string' ? restore.text(part) : part;
109
+ const type = part.type;
110
+ if (typeof type === 'string' && PASS_THROUGH.has(type))
111
+ return part;
112
+ if (type === 'text' && typeof part.text === 'string')
113
+ return { ...restore.value(part), text: restore.text(part.text) };
114
+ if (type === 'tool-call' && typeof part.input === 'string')
115
+ return { ...part, input: restore.toolInput(part.input) };
116
+ return restore.value(part);
117
+ });
118
+ }
119
+ /** The stream part types whose `delta` is text the model wrote, and the part that ends each. */
120
+ const DELTAS = new Map([
121
+ ['text-delta', 'text-end'],
122
+ ['reasoning-delta', 'reasoning-end'],
123
+ ['tool-input-delta', 'tool-input-end'],
124
+ ]);
125
+ const ENDS = new Map([...DELTAS].map(([delta, end]) => [end, delta]));
126
+ function restoreStream(stream, restore) {
127
+ // One restorer per streamed block, keyed by part type and id, so a
128
+ // placeholder split across deltas is rebuilt before it is passed on.
129
+ const open = new Map();
130
+ const textTools = new Set();
131
+ const key = (type, id) => `${type}\u0000${String(id)}`;
132
+ const flushOne = (type, id, controller) => {
133
+ const block = open.get(key(type, id));
134
+ if (!block)
135
+ return;
136
+ open.delete(key(type, id));
137
+ const tail = block.restorer.flush();
138
+ if (tail)
139
+ controller.enqueue({ type, id, delta: tail });
140
+ };
141
+ const flushAll = (controller) => {
142
+ for (const { type, id } of [...open.values()])
143
+ flushOne(type, id, controller);
144
+ };
145
+ return stream.pipeThrough(new TransformStream({
146
+ transform(part, controller) {
147
+ if (!isObj(part) || typeof part.type !== 'string') {
148
+ controller.enqueue(part);
149
+ return;
150
+ }
151
+ const { type } = part;
152
+ if (DELTAS.has(type) && typeof part.delta === 'string') {
153
+ const k = key(type, part.id);
154
+ let block = open.get(k);
155
+ if (!block) {
156
+ // Reasoning is prose even when the answer is JSON; tool input is JSON
157
+ // unless its tool-input-start said otherwise.
158
+ const kind = type === 'text-delta' ? 'text' : type === 'reasoning-delta' || textTools.has(part.id) ? 'plain' : 'json';
159
+ block = { type, id: part.id, restorer: restore.stream(kind) };
160
+ open.set(k, block);
161
+ }
162
+ const delta = block.restorer.push(part.delta);
163
+ if (delta || part.providerMetadata !== undefined)
164
+ controller.enqueue({ ...part, delta });
165
+ return;
166
+ }
167
+ const deltaType = ENDS.get(type);
168
+ if (deltaType) {
169
+ flushOne(deltaType, part.id, controller);
170
+ if (type === 'tool-input-end')
171
+ textTools.delete(part.id);
172
+ // A text-end can carry citations quoting what the model was sent.
173
+ controller.enqueue(restore.value(part));
174
+ return;
175
+ }
176
+ switch (type) {
177
+ case 'tool-input-start':
178
+ if (part.inputEncoding === 'text')
179
+ textTools.add(part.id);
180
+ controller.enqueue(part);
181
+ return;
182
+ case 'tool-call':
183
+ controller.enqueue(typeof part.input === 'string' ? { ...part, input: restore.toolInput(part.input) } : part);
184
+ return;
185
+ case 'tool-result':
186
+ case 'source':
187
+ controller.enqueue(restore.value(part));
188
+ return;
189
+ case 'finish':
190
+ flushAll(controller);
191
+ controller.enqueue(part);
192
+ return;
193
+ default:
194
+ // Text and reasoning blocks are restored above; files, metadata,
195
+ // errors and raw provider chunks pass through as they arrived.
196
+ controller.enqueue(part);
197
+ }
198
+ },
199
+ flush(controller) {
200
+ flushAll(controller);
201
+ },
202
+ }));
203
+ }
204
+ const wantsJson = (params) => isObj(params) && isObj(params.responseFormat) && params.responseFormat.type === 'json';
205
+ /**
206
+ * A Vercel AI SDK language model middleware that keeps secrets and personal
207
+ * data out of every prompt, for any provider:
208
+ *
209
+ * wrapLanguageModel({ model, middleware: flareRedactMiddleware({ preset: 'llm' }) })
210
+ *
211
+ * System, user and assistant text, reasoning, tool-call inputs and tool
212
+ * results are redacted to opaque placeholders before the call; text,
213
+ * reasoning, tool calls and structured output are restored in the result and
214
+ * in the stream, including placeholders split across chunks. Files and images
215
+ * are passed through unchanged. Takes the same options as `wrapOpenAI`.
216
+ */
217
+ export function flareRedactMiddleware(opts = {}) {
218
+ const { session, ...vaultOptions } = opts;
219
+ // Fail at setup, not on the first request, when a preset or detector option is wrong.
220
+ if (!session)
221
+ createVault(vaultOptions);
222
+ // The vault lives exactly as long as one call: transformParams creates it,
223
+ // the wrap step that follows restores with it. The params object is the key.
224
+ const vaults = new WeakMap();
225
+ const vaultFor = (params) => {
226
+ const found = isObj(params) ? vaults.get(params) : undefined;
227
+ if (!found) {
228
+ throw new Error('flareRedactMiddleware: the prompt was not redacted. Pass the middleware object to wrapLanguageModel whole, without replacing transformParams.');
229
+ }
230
+ return found;
231
+ };
232
+ return {
233
+ specificationVersion: 'v3',
234
+ middlewareVersion: 'v2',
235
+ async transformParams({ params }) {
236
+ if (!isObj(params))
237
+ return params;
238
+ const vault = session ? session.vault : createVault(vaultOptions);
239
+ const redacted = { ...params, prompt: redactPrompt(params.prompt, vault) };
240
+ vaults.set(redacted, { vault, json: wantsJson(params) });
241
+ return redacted;
242
+ },
243
+ async wrapGenerate({ doGenerate, params }) {
244
+ const { vault, json } = vaultFor(params);
245
+ const result = await doGenerate();
246
+ if (!isObj(result) || !vault.size)
247
+ return result;
248
+ const restore = restorers(vault, json);
249
+ const out = { ...result, content: restoreContent(result.content, restore) };
250
+ if (typeof result.structuredOutputText === 'string')
251
+ out.structuredOutputText = restore.toolInput(result.structuredOutputText);
252
+ return out;
253
+ },
254
+ async wrapStream({ doStream, params }) {
255
+ const { vault, json } = vaultFor(params);
256
+ const result = await doStream();
257
+ if (!vault.size)
258
+ return result;
259
+ return { ...result, stream: restoreStream(result.stream, restorers(vault, json)) };
260
+ },
261
+ };
262
+ }
263
+ //# sourceMappingURL=ai-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.js","sourceRoot":"","sources":["../src/ai-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,WAAW,EAAE,oBAAoB,EAA2D,MAAM,YAAY,CAAC;AA0B1J,MAAM,KAAK,GAAG,CAAC,KAAc,EAAgB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAErH,2FAA2F;AAC3F,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU;IACxE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,kBAAkB;CACnE,CAAC,CAAC;AAEH,uFAAuF;AACvF,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,CAAC,CAAC,CAAC;AAE5E,MAAM,MAAM,GAAG,CAAC,IAAY,EAAW,EAAE;IACvC,IAAI,CAAC;QACH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AE,aAAa,CAAC,MAAM,CAAC,MAAiC,EAAE,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;QAChH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -47,4 +47,47 @@ export declare function cnResidentIdValid(value: string): boolean;
47
47
  export declare function jpMyNumberValid(value: string): boolean;
48
48
  /** Italy Codice Fiscale — 16 chars, odd/even table checksum. */
49
49
  export declare function codiceFiscaleValid(value: string): boolean;
50
+ /** Romania CNP: 13 digits, birth date, weighted mod-11 check digit (10 is written as 1). */
51
+ export declare function cnpValid(value: string): boolean;
52
+ /**
53
+ * Sweden personnummer: YYMMDD-NNNC (or `+` from age 100), or YYYYMMDDNNNC.
54
+ * Luhn over the ten-digit form; a samordningsnummer adds 60 to the day.
55
+ */
56
+ export declare function personnummerValid(value: string): boolean;
57
+ /** Finland henkilötunnus: DDMMYY, century sign, individual number, mod-31 check character. */
58
+ export declare function hetuValid(value: string): boolean;
59
+ /** Norway fødselsnummer (and D- and H-numbers): 11 digits, two mod-11 check digits. */
60
+ export declare function fodselsnummerValid(value: string): boolean;
61
+ /**
62
+ * Belgium national register number: YYMMDD, counter, check = 97 − (n mod 97),
63
+ * with a 2 prefixed for people born from 2000. BIS numbers add 20 or 40 to the
64
+ * month. The day is not checked: it is 00 when unknown and runs past 31 once a
65
+ * date's counter is used up.
66
+ */
67
+ export declare function beNationalNumberValid(value: string): boolean;
68
+ /** Portugal NIF of a person (first digit 1-3, or 45 for non-residents): weighted mod-11. */
69
+ export declare function ptNifValid(value: string): boolean;
70
+ /** South Africa ID number: YYMMDD, citizenship digit 0-2, Luhn over all 13 digits. */
71
+ export declare function zaIdValid(value: string): boolean;
72
+ /**
73
+ * Mexico CURP: 18 characters, birth date, sex, state, check digit. The check
74
+ * alphabet is 0-9, A-N, Ñ, O-Z, so O-Z count one higher than their place in A-Z.
75
+ */
76
+ export declare function curpValid(value: string): boolean;
77
+ /** Chile RUT / RUN: 7-8 digits and a mod-11 check character (10 is K, 11 is 0). */
78
+ export declare function rutValid(value: string): boolean;
79
+ /**
80
+ * Argentina CUIL / CUIT of a person (prefix 20, 23, 24 or 27): weighted mod-11.
81
+ * A check value of 10 is accepted as 9, the digit used for it in practice.
82
+ */
83
+ export declare function cuitValid(value: string): boolean;
84
+ /** Singapore NRIC / FIN (S, T, F, G series): weighted mod-11 check letter. */
85
+ export declare function nricValid(value: string): boolean;
86
+ /** Greece AMKA: DDMMYY birth date, serial, Luhn over all 11 digits. */
87
+ export declare function amkaValid(value: string): boolean;
88
+ /**
89
+ * UK National Insurance number. No checksum exists; HMRC's allocation rules
90
+ * (letters never used in the prefix, prefixes never issued, suffix A-D) are checked.
91
+ */
92
+ export declare function ninoValid(value: string): boolean;
50
93
  //# sourceMappingURL=checksums.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"checksums.d.ts","sourceRoot":"","sources":["../src/checksums.ts"],"names":[],"mappings":"AAEA,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAehD;AAED,sEAAsE;AACtE,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAYhD;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAazD,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,SAAU,GAAG,MAAM,CAW7E;AAED,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAShD;AAED,uDAAuD;AACvD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAU/C;AAGD,gEAAgE;AAChE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM/C;AAED,+DAA+D;AAC/D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAA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