@waswrongassembled/pii-shield 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/LICENSE +22 -0
- package/README.md +276 -2
- package/dist/ai-sdk/index.d.ts +19 -0
- package/dist/ai-sdk/index.js +30 -0
- package/dist/ai-sdk/middleware.d.ts +63 -0
- package/dist/ai-sdk/middleware.js +388 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +124 -0
- package/dist/detector.d.ts +28 -0
- package/dist/detector.js +3 -0
- package/dist/detectors/at-svnr.d.ts +14 -0
- package/dist/detectors/at-svnr.js +31 -0
- package/dist/detectors/authority-context.d.ts +22 -0
- package/dist/detectors/authority-context.js +278 -0
- package/dist/detectors/birth-date.d.ts +10 -0
- package/dist/detectors/birth-date.js +21 -0
- package/dist/detectors/email.d.ts +15 -0
- package/dist/detectors/email.js +29 -0
- package/dist/detectors/file-number.d.ts +16 -0
- package/dist/detectors/file-number.js +20 -0
- package/dist/detectors/iban.d.ts +10 -0
- package/dist/detectors/iban.js +41 -0
- package/dist/detectors/license-plate.d.ts +9 -0
- package/dist/detectors/license-plate.js +13 -0
- package/dist/detectors/phone.d.ts +13 -0
- package/dist/detectors/phone.js +38 -0
- package/dist/detectors/postal-address.d.ts +14 -0
- package/dist/detectors/postal-address.js +19 -0
- package/dist/detectors/salutation-person.d.ts +18 -0
- package/dist/detectors/salutation-person.js +37 -0
- package/dist/detectors/tax-number.d.ts +14 -0
- package/dist/detectors/tax-number.js +33 -0
- package/dist/entity-extractor.d.ts +47 -0
- package/dist/entity-extractor.js +245 -0
- package/dist/entity-type.d.ts +24 -0
- package/dist/entity-type.js +26 -0
- package/dist/entity.d.ts +28 -0
- package/dist/entity.js +11 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +49 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +40 -0
- package/dist/internal/pcre.d.ts +55 -0
- package/dist/internal/pcre.js +102 -0
- package/dist/internal/php-json.d.ts +15 -0
- package/dist/internal/php-json.js +48 -0
- package/dist/internal/placeholder-stream.d.ts +24 -0
- package/dist/internal/placeholder-stream.js +118 -0
- package/dist/internal/text-spans.d.ts +8 -0
- package/dist/internal/text-spans.js +15 -0
- package/dist/learning/char-set.d.ts +29 -0
- package/dist/learning/char-set.js +158 -0
- package/dist/learning/custom-entity-detector.d.ts +26 -0
- package/dist/learning/custom-entity-detector.js +70 -0
- package/dist/learning/custom-entity-type.d.ts +49 -0
- package/dist/learning/custom-entity-type.js +150 -0
- package/dist/learning/entity-learner.d.ts +50 -0
- package/dist/learning/entity-learner.js +87 -0
- package/dist/learning/json-file-store.d.ts +36 -0
- package/dist/learning/json-file-store.js +132 -0
- package/dist/learning/learned-pattern.d.ts +48 -0
- package/dist/learning/learned-pattern.js +640 -0
- package/dist/learning/pattern-grammar.d.ts +12 -0
- package/dist/learning/pattern-grammar.js +148 -0
- package/dist/learning/pattern-learner.d.ts +10 -0
- package/dist/learning/pattern-learner.js +116 -0
- package/dist/learning/store.d.ts +51 -0
- package/dist/learning/store.js +84 -0
- package/dist/masking/partial-mask.d.ts +23 -0
- package/dist/masking/partial-mask.js +43 -0
- package/dist/masking/strategy.d.ts +10 -0
- package/dist/masking/strategy.js +1 -0
- package/dist/masking/type-label-mask.d.ts +17 -0
- package/dist/masking/type-label-mask.js +28 -0
- package/dist/mcp/index.d.ts +33 -0
- package/dist/mcp/index.js +146 -0
- package/dist/mcp/tools.d.ts +63 -0
- package/dist/mcp/tools.js +183 -0
- package/dist/model/chunks.d.ts +13 -0
- package/dist/model/chunks.js +74 -0
- package/dist/model/model-detector.d.ts +110 -0
- package/dist/model/model-detector.js +420 -0
- package/dist/model/prompt.d.ts +16 -0
- package/dist/model/prompt.js +192 -0
- package/dist/pii-masker.d.ts +27 -0
- package/dist/pii-masker.js +56 -0
- package/dist/pii-shield.d.ts +40 -0
- package/dist/pii-shield.js +142 -0
- package/dist/placeholder.d.ts +48 -0
- package/dist/placeholder.js +138 -0
- package/dist/redaction.d.ts +76 -0
- package/dist/redaction.js +52 -0
- package/dist/server/config.d.ts +23 -0
- package/dist/server/config.js +187 -0
- package/dist/server/http-server.d.ts +63 -0
- package/dist/server/http-server.js +241 -0
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.js +9 -0
- package/dist/server/model-providers.d.ts +31 -0
- package/dist/server/model-providers.js +158 -0
- package/dist/service/json-body.d.ts +14 -0
- package/dist/service/json-body.js +35 -0
- package/dist/service/local-peer.d.ts +16 -0
- package/dist/service/local-peer.js +83 -0
- package/dist/service/service-api.d.ts +75 -0
- package/dist/service/service-api.js +305 -0
- package/dist/validators/at-svnr.d.ts +8 -0
- package/dist/validators/at-svnr.js +21 -0
- package/dist/validators/de-tax-id.d.ts +8 -0
- package/dist/validators/de-tax-id.js +35 -0
- package/dist/validators/iban.d.ts +5 -0
- package/dist/validators/iban.js +24 -0
- package/dist/vault/encrypted-vault.d.ts +37 -0
- package/dist/vault/encrypted-vault.js +152 -0
- package/dist/vault/in-memory-vault.d.ts +17 -0
- package/dist/vault/in-memory-vault.js +39 -0
- package/dist/vault/memory-vault-storage.d.ts +16 -0
- package/dist/vault/memory-vault-storage.js +37 -0
- package/dist/vault/vault.d.ts +38 -0
- package/dist/vault/vault.js +16 -0
- package/dist/vault-redis/index.d.ts +28 -0
- package/dist/vault-redis/index.js +33 -0
- package/docs/openapi.yaml +422 -0
- package/package.json +122 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
5
|
+
|
|
6
|
+
## [Unreleased]
|
|
7
|
+
|
|
8
|
+
## [0.1.1] - 2026-11-21
|
|
9
|
+
|
|
10
|
+
No changes to the library code. First release through the release workflow: staged on npm with Trusted Publishing and a provenance attestation, approved with 2FA (0.1.0 was published by hand without provenance).
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- Releases are staged with `npm stage publish` and need a 2FA approval on npmjs.com (`docs/RELEASING.md`).
|
|
15
|
+
|
|
16
|
+
## [0.1.0] - 2026-11-20
|
|
17
|
+
|
|
18
|
+
First release: a TypeScript port of [`clarifile/pii-shield`](https://github.com/massiveart/clarifile/tree/main/packages/pii-shield) (PHP), wire-compatible with it. Intended differences are listed in [docs/DEVIATIONS.md](docs/DEVIATIONS.md).
|
|
19
|
+
|
|
20
|
+
Privacy and crash bugs of the PHP package are fixed rather than reproduced: names with characters such as ř or Cyrillic letters are no longer dropped by the model detector (as in clarifile PR #95), SVNRs, tax IDs, phone numbers and IBANs written with non-ASCII digits are redacted, tool results of every agent step are redacted, a prompt containing the internal separator no longer fails, and long digit runs, crafted placeholders and learned patterns cannot block or crash redaction. See "PHP bugs fixed in the port" in [docs/DEVIATIONS.md](docs/DEVIATIONS.md).
|
|
21
|
+
|
|
22
|
+
### Added
|
|
23
|
+
|
|
24
|
+
- Validators with checksums: `isValidAtSvnr()`, `isValidIban()`, `isValidDeTaxId()`.
|
|
25
|
+
- Detectors for persons (salutation and letter layout), postal addresses, AT social security numbers, IBANs, tax numbers, file numbers, e-mail addresses, phone numbers, birth dates and license plates; `EntityExtractor` resolves overlaps and priorities, with an allowlist.
|
|
26
|
+
- `PiiShield`: reversible redaction with `⟦TYPE_N⟧` placeholders and `restore()` with tolerant placeholder parsing and reports of unknown and unused placeholders; `NullPiiShield`.
|
|
27
|
+
- `PiiMasker` with `TypeLabelMask` and `PartialMask` for irreversible masking.
|
|
28
|
+
- Vault: `redactToVault()`, `restoreFromVault()`, `forget()`; `EncryptedVault` (XChaCha20-Poly1305, byte-compatible with PHP), `InMemoryVault`, `MemoryVaultStorage`, and `RedisVaultStorage` in `@waswrongassembled/pii-shield/vault-redis` (peer `ioredis`).
|
|
29
|
+
- Learned entity types: `EntityLearner`, `learnPattern()`, `CustomEntityDetector`, `LearnedTypesDetector`; stores `JsonFileCustomEntityStore` (PHP's file format), `InMemoryCustomEntityStore` and `KeyValueCustomEntityStore`. Learned patterns run on a bounded backtracking matcher with PCRE semantics.
|
|
30
|
+
- `ModelDetector`: model-based detection with PHP's prompt and answer parsing, a required `location` and `acknowledgeExternalTransfer` for external providers; async APIs `redactAsync()`, `extractAsync()`, `maskAsync()`.
|
|
31
|
+
- `@waswrongassembled/pii-shield/ai-sdk` (peer `ai@^7`): `piiShieldMiddleware()` redacts every prompt and restores text, reasoning, streams, tool call inputs and structured output; `detectionModel()` adapts an AI SDK model for `ModelDetector`.
|
|
32
|
+
- `@waswrongassembled/pii-shield/server`: the HTTP service of the PHP package (`/v1`, `docs/openapi.yaml`) on `node:http` with PHP's request guard, `ServiceApi`, `startServer()`, `createRequestListener()`.
|
|
33
|
+
- `@waswrongassembled/pii-shield/mcp` (peer `@modelcontextprotocol/sdk`): the MCP tools `redact_text`, `restore_text`, `mask_text`, `learn_entity_type` and `list_entity_types` over STDIO and Streamable HTTP.
|
|
34
|
+
- `pii-shield` CLI: `pii-shield serve`, `pii-shield mcp [--http]`, configured with PHP's environment variables.
|
|
35
|
+
|
|
36
|
+
[Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.1...HEAD
|
|
37
|
+
[0.1.1]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.0...v0.1.1
|
|
38
|
+
[0.1.0]: https://github.com/waswrongassembled/pii-shield-js/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the Clarifile contributors
|
|
4
|
+
Copyright (c) 2026 waswrongassembled
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,277 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pii-shield (Node.js)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reversible PII redaction for LLM applications, with DACH recognizers (AT SVNR, IBAN, tax numbers) and checksum validation.
|
|
4
|
+
TypeScript port of [`clarifile/pii-shield`](https://github.com/massiveart/clarifile/tree/main/packages/pii-shield), wire-compatible with the PHP package.
|
|
5
|
+
|
|
6
|
+
Personal data in a text is replaced by placeholders (`⟦PERSON_1⟧`, `⟦IBAN_1⟧`) before the text goes to a language model; the answer gets the original values back. Detection runs locally (regular expressions plus checksums, optionally a model you choose), so the LLM provider only ever sees placeholders.
|
|
7
|
+
|
|
8
|
+
**Status:** 0.1.0 (release prepared, see [docs/RELEASING.md](docs/RELEASING.md)), a feature-complete port of the PHP package: detection, redaction and restore, masking, an encrypted vault (in memory or Redis), learned entity types, a model-based detector, Vercel AI SDK middleware, an HTTP service, an MCP server and a CLI. See [CHANGELOG.md](CHANGELOG.md).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @waswrongassembled/pii-shield
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Requires Node >= 22.12. The package is ESM only; `require()` works on Node >= 22.12 (require(esm)). The core depends only on `@noble/ciphers`. Optional peer dependencies, needed only for their subpath:
|
|
17
|
+
|
|
18
|
+
| Subpath | Needs |
|
|
19
|
+
| ------------------------------------------- | ---------------------------- |
|
|
20
|
+
| `@waswrongassembled/pii-shield` | - |
|
|
21
|
+
| `@waswrongassembled/pii-shield/vault-redis` | `ioredis` (5 or 6) |
|
|
22
|
+
| `@waswrongassembled/pii-shield/ai-sdk` | `ai` (7) |
|
|
23
|
+
| `@waswrongassembled/pii-shield/mcp` | `@modelcontextprotocol/sdk` |
|
|
24
|
+
| `@waswrongassembled/pii-shield/server` | - (`/mcp` needs the MCP SDK) |
|
|
25
|
+
|
|
26
|
+
All examples use synthetic data. Every `ts` block in this README is type-checked against the source by `test/readme-examples.test.ts`.
|
|
27
|
+
|
|
28
|
+
## Redact and restore
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { PiiShield } from '@waswrongassembled/pii-shield';
|
|
32
|
+
|
|
33
|
+
const shield = new PiiShield();
|
|
34
|
+
const result = shield.redact(
|
|
35
|
+
'Sehr geehrter Herr Johann Beispielmann,\nIhre SVNR 4568 150392, IBAN AT61 1904 3002 3457 3201.',
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
result.redactedText; // 'Sehr geehrter Herr ⟦PERSON_1⟧,\nIhre SVNR ⟦SVNR_1⟧, IBAN ⟦IBAN_1⟧.'
|
|
39
|
+
result.mapping; // { '⟦PERSON_1⟧': 'Johann Beispielmann', '⟦SVNR_1⟧': '4568 150392', ... }
|
|
40
|
+
|
|
41
|
+
// Send result.redactedText to the model, then restore its answer:
|
|
42
|
+
const restored = shield.restore('Antwort an ⟦PERSON_1⟧ zu ⟦SVNR_1⟧', result);
|
|
43
|
+
restored.text; // 'Antwort an Johann Beispielmann zu 4568 150392'
|
|
44
|
+
restored.unknownPlaceholders; // placeholders the model invented: []
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Detected types: `PERSON`, `EMAIL`, `PHONE`, `IBAN`, `SVNR`, `TAX_ID`, `FILE_NUMBER`, `BIRTH_DATE`, `LICENSE_PLATE`, `ADDRESS` (see `EntityType`), plus your learned types. Choose detectors with `new PiiShield({ detectors: [...] })` (default: `defaultDetectors()`).
|
|
48
|
+
|
|
49
|
+
## Masking
|
|
50
|
+
|
|
51
|
+
Irreversible replacement, for logs or analytics. IBANs and phone numbers stay partly visible by default.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { PiiMasker } from '@waswrongassembled/pii-shield';
|
|
55
|
+
|
|
56
|
+
const masker = new PiiMasker({
|
|
57
|
+
strategies: { EMAIL: (entity) => entity.value.replace(/^[^@]+/, '***') },
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
masker.mask('E-Mail j.beispielmann@example.com, IBAN AT61 1904 3002 3457 3201');
|
|
61
|
+
// 'E-Mail ***@example.com, IBAN AT61 **** **** **** 3201'
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Vault: restore in a later request
|
|
65
|
+
|
|
66
|
+
The mapping stays on your side, encrypted (XChaCha20-Poly1305) with a TTL; the client only keeps the `vaultId`. Payloads are byte-compatible with PHP's `EncryptedVault`.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { EncryptedVault, MemoryVaultStorage, parseVaultKey, PiiShield } from '@waswrongassembled/pii-shield';
|
|
70
|
+
|
|
71
|
+
const shield = new PiiShield({
|
|
72
|
+
// 32 bytes, base64; generateVaultKey() creates one
|
|
73
|
+
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: parseVaultKey(process.env.VAULT_KEY ?? '') }),
|
|
74
|
+
vaultTtl: 900,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const { redactedText, vaultId } = await shield.redactToVault('Herrn\nJohann Beispielmann\nSVNR 4568 150392');
|
|
78
|
+
// ... later, possibly in another process sharing the storage:
|
|
79
|
+
const { text } = await shield.restoreFromVault(redactedText, vaultId);
|
|
80
|
+
await shield.forget(vaultId);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
For several processes use Redis:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { Redis } from 'ioredis';
|
|
87
|
+
import { EncryptedVault, generateVaultKey } from '@waswrongassembled/pii-shield';
|
|
88
|
+
import { RedisVaultStorage } from '@waswrongassembled/pii-shield/vault-redis';
|
|
89
|
+
|
|
90
|
+
const vault = new EncryptedVault({
|
|
91
|
+
storage: new RedisVaultStorage({ client: new Redis('redis://127.0.0.1:6379') }),
|
|
92
|
+
key: generateVaultKey(), // use the same configured key in every process
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Learned entity types
|
|
97
|
+
|
|
98
|
+
Teach a type from examples; a pattern is derived and checked against the counter-examples. Stores: `JsonFileCustomEntityStore` (same file format as PHP), `InMemoryCustomEntityStore`, `KeyValueCustomEntityStore`.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { defaultDetectors, EntityLearner, JsonFileCustomEntityStore, PiiShield } from '@waswrongassembled/pii-shield';
|
|
102
|
+
|
|
103
|
+
const learner = await EntityLearner.create({ store: new JsonFileCustomEntityStore('var/learned-types.json') });
|
|
104
|
+
const { type } = await learner.learn({
|
|
105
|
+
name: 'INSURANCE_NUMBER',
|
|
106
|
+
description: 'Polizzennummer',
|
|
107
|
+
examples: ['VN-2026-000417', 'VN-2025-123456'],
|
|
108
|
+
});
|
|
109
|
+
type.pattern; // 'VN-\\d{4}-\\d{6}'
|
|
110
|
+
|
|
111
|
+
const shield = new PiiShield({ detectors: [...defaultDetectors(), learner.detector()] });
|
|
112
|
+
shield.redact('Polizze VN-2026-000999').redactedText; // 'Polizze ⟦INSURANCE_NUMBER_1⟧'
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Model-based detection
|
|
116
|
+
|
|
117
|
+
`ModelDetector` asks a language model for entities the patterns miss (names without a salutation, free-form addresses). It sends the **unredacted** text to that model, so `location` is required, and an `external` provider also needs `acknowledgeExternalTransfer: true` (data processing agreement, possibly a third-country transfer). It is async: use `redactAsync()`, `redactToVault()` or `maskAsync()`.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { defaultDetectors, ModelDetector, PiiShield } from '@waswrongassembled/pii-shield';
|
|
121
|
+
|
|
122
|
+
const model = new ModelDetector({
|
|
123
|
+
location: 'local',
|
|
124
|
+
// any function from a prompt to the model's text answer; here a local Ollama
|
|
125
|
+
model: async ({ system, user }, { signal }) => {
|
|
126
|
+
const response = await fetch('http://127.0.0.1:11434/api/chat', {
|
|
127
|
+
method: 'POST',
|
|
128
|
+
signal,
|
|
129
|
+
body: JSON.stringify({
|
|
130
|
+
model: 'qwen3:8b',
|
|
131
|
+
stream: false,
|
|
132
|
+
messages: [
|
|
133
|
+
{ role: 'system', content: system },
|
|
134
|
+
{ role: 'user', content: user },
|
|
135
|
+
],
|
|
136
|
+
}),
|
|
137
|
+
});
|
|
138
|
+
const body = (await response.json()) as { message: { content: string } };
|
|
139
|
+
|
|
140
|
+
return body.message.content;
|
|
141
|
+
},
|
|
142
|
+
timeout: 60_000,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const shield = new PiiShield({ detectors: [...defaultDetectors(), model] });
|
|
146
|
+
const result = await shield.redactAsync('Rückfragen bitte an Johann Beispielmann.');
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
With the AI SDK, `detectionModel(languageModel, settings)` from `@waswrongassembled/pii-shield/ai-sdk` adapts any AI SDK model.
|
|
150
|
+
|
|
151
|
+
## Vercel AI SDK middleware
|
|
152
|
+
|
|
153
|
+
Needs `ai@^7`. The provider only sees placeholders; answers, streams, tool call inputs and structured output come back with the original values.
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { generateText, type LanguageModel, wrapLanguageModel } from 'ai';
|
|
157
|
+
import { PiiShield } from '@waswrongassembled/pii-shield';
|
|
158
|
+
import { piiShieldMiddleware } from '@waswrongassembled/pii-shield/ai-sdk';
|
|
159
|
+
|
|
160
|
+
declare const yourModel: Exclude<LanguageModel, string>; // e.g. openai('...') from @ai-sdk/openai
|
|
161
|
+
|
|
162
|
+
const model = wrapLanguageModel({
|
|
163
|
+
model: yourModel,
|
|
164
|
+
middleware: piiShieldMiddleware(new PiiShield(), {
|
|
165
|
+
// placeholders the model invented (no personal data)
|
|
166
|
+
onRestore: ({ unknownPlaceholders }) => {
|
|
167
|
+
if (unknownPlaceholders.length > 0) console.warn('Unknown placeholders', unknownPlaceholders);
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
const { text } = await generateText({ model, prompt: 'Herrn\nJohann Beispielmann\n...' }); // streamText() too
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Every model call (every step of a tool loop) redacts the whole prompt with one mapping. Files in user or tool messages throw `UnsupportedContentError`: extract their text locally first. Differences to PHP's `PiiShieldProcessor` are listed in [docs/DEVIATIONS.md](docs/DEVIATIONS.md).
|
|
176
|
+
|
|
177
|
+
## HTTP service and CLI
|
|
178
|
+
|
|
179
|
+
The same API as the PHP service ([docs/openapi.yaml](docs/openapi.yaml), also served at `/v1/openapi.yaml`): `POST /v1/redact`, `/v1/restore`, `/v1/mask`, `/v1/learn`, `GET /v1/entities`, ...
|
|
180
|
+
|
|
181
|
+
```sh
|
|
182
|
+
npx @waswrongassembled/pii-shield serve # /v1 and /mcp on 127.0.0.1:8088
|
|
183
|
+
PII_SERVICE_TOKEN=$(openssl rand -hex 24) PII_SERVICE_VAULT_KEY=... \
|
|
184
|
+
npx @waswrongassembled/pii-shield serve --host 0.0.0.0 --port 8080
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Without a token only local peers are answered. Configuration (environment variables, Redis, model provider), programmatic use (`startServer()`, `ServiceApi`) and a Docker image: [docs/server.md](docs/server.md).
|
|
188
|
+
|
|
189
|
+
## MCP server
|
|
190
|
+
|
|
191
|
+
Tools `redact_text`, `restore_text`, `mask_text`, `learn_entity_type` and `list_entity_types` (PHP's names and schemas), over STDIO or Streamable HTTP (`/mcp` of `pii-shield serve`). Needs `@modelcontextprotocol/sdk`.
|
|
192
|
+
|
|
193
|
+
```sh
|
|
194
|
+
claude mcp add pii-shield -- npx @waswrongassembled/pii-shield mcp
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
import {
|
|
199
|
+
EncryptedVault,
|
|
200
|
+
EntityLearner,
|
|
201
|
+
generateVaultKey,
|
|
202
|
+
InMemoryCustomEntityStore,
|
|
203
|
+
MemoryVaultStorage,
|
|
204
|
+
} from '@waswrongassembled/pii-shield';
|
|
205
|
+
import { serveStdio } from '@waswrongassembled/pii-shield/mcp';
|
|
206
|
+
import { ServiceApi } from '@waswrongassembled/pii-shield/server';
|
|
207
|
+
|
|
208
|
+
const api = new ServiceApi({
|
|
209
|
+
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: generateVaultKey() }),
|
|
210
|
+
learner: await EntityLearner.create({ store: new InMemoryCustomEntityStore() }),
|
|
211
|
+
});
|
|
212
|
+
await serveStdio(api); // log to stderr only: stdout belongs to the protocol
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
`restore_text` returns the original values to the MCP client, and in an agent the client is the model: offer it only where the model may see the data.
|
|
216
|
+
|
|
217
|
+
## Interoperability with PHP
|
|
218
|
+
|
|
219
|
+
Wire-compatible with `clarifile/pii-shield`, tested against fixtures exported from the PHP package:
|
|
220
|
+
|
|
221
|
+
- the same detections and placeholders (`⟦TYPE_N⟧`) for the same text, and the same tolerant placeholder parsing on restore;
|
|
222
|
+
- vault payloads (`EncryptedVault`): PHP and Node decrypt each other's entries with the same key; the plaintext is byte-identical;
|
|
223
|
+
- learned types: `JsonFileCustomEntityStore` reads and writes PHP's JSON file; learned patterns match as in PCRE;
|
|
224
|
+
- the model detector's prompts and answer parsing, the HTTP API (status codes, messages, JSON shapes) and the MCP tools.
|
|
225
|
+
|
|
226
|
+
Not shared: `Entity.offset` is a UTF-16 index (`text.slice(offset, offset + value.length)`), PHP counts code points; they differ only after characters outside the BMP such as emoji. Offsets are not part of any wire format. `RedisVaultStorage` writes raw payloads, PHP's Symfony cache adds its own marshalling. All intended differences: [docs/DEVIATIONS.md](docs/DEVIATIONS.md).
|
|
227
|
+
|
|
228
|
+
## Limits and security
|
|
229
|
+
|
|
230
|
+
- Detection is heuristic. Patterns and checksums find structured data reliably, names and addresses only with context (salutations, letter layout) or with the model detector. Check results on your own (synthetic) data before relying on them, and never test with real personal data.
|
|
231
|
+
- A `RedactionResult` contains the original values (`mapping`, `entities`). Never log it, put it in error reports or send it to the model; send only `redactedText`. Error messages of this package never contain values.
|
|
232
|
+
- The mapping is the key to the data: keep it in your process or in the encrypted vault, keep the vault key out of code and logs, and use a short TTL.
|
|
233
|
+
- `ModelDetector` sends the unredacted text to its model. Prefer `local` or `on_premise`; an `external` provider needs `acknowledgeExternalTransfer: true` and, under the GDPR, a legal basis and a data processing agreement.
|
|
234
|
+
- The HTTP service speaks plain HTTP: in production put TLS in front and set `PII_SERVICE_TOKEN` (see [docs/server.md](docs/server.md#security)).
|
|
235
|
+
|
|
236
|
+
## Development
|
|
237
|
+
|
|
238
|
+
Requires Node >= 22.12.
|
|
239
|
+
|
|
240
|
+
```sh
|
|
241
|
+
npm ci
|
|
242
|
+
npm run check # typecheck, lint, tests, build
|
|
243
|
+
npm run check:package # publint and are-the-types-wrong on the packed package
|
|
244
|
+
npm run test:package # installs the packed tarball into a temp project and imports every subpath
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Releases: [docs/RELEASING.md](docs/RELEASING.md).
|
|
248
|
+
|
|
249
|
+
### Fixtures
|
|
250
|
+
|
|
251
|
+
`fixtures/*.json` record what the PHP package does; the TypeScript code is tested against them.
|
|
252
|
+
They are committed, so tests run without PHP. To regenerate them you need PHP >= 8.4 with `ext-sodium` and a checkout of the PHP package with `composer install` done:
|
|
253
|
+
|
|
254
|
+
```sh
|
|
255
|
+
npm run fixtures -- <path-to>/packages/pii-shield
|
|
256
|
+
# or: PII_SHIELD_PHP_DIR=<path-to>/packages/pii-shield npm run fixtures
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Re-exporting from the same PHP commit produces identical files. Intended deviations from PHP are listed in [docs/DEVIATIONS.md](docs/DEVIATIONS.md), findings for the PHP package in [docs/UPSTREAM.md](docs/UPSTREAM.md).
|
|
260
|
+
All fixture data is synthetic.
|
|
261
|
+
|
|
262
|
+
### Vault interop with PHP
|
|
263
|
+
|
|
264
|
+
The tests decrypt the PHP payloads in `fixtures/vault.json` and re-encrypt them byte for byte. The other direction (PHP reads Node payloads) needs PHP with `ext-sodium` and the PHP package with `composer install` done:
|
|
265
|
+
|
|
266
|
+
```sh
|
|
267
|
+
npm run compat:vault -- /tmp/node-payloads.json # builds, then writes payloads with random keys
|
|
268
|
+
php compat/decrypt-node-payload.php <path-to>/packages/pii-shield /tmp/node-payloads.json
|
|
269
|
+
rm /tmp/node-payloads.json # holds the keys; never commit it
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
The PHP script decrypts every case with PHP's `EncryptedVault`, compares the mapping (values and order) and checks that PHP encrypts it to the same bytes; it exits non-zero on the first mismatch.
|
|
273
|
+
`RedisVaultStorage` stores each payload raw under `prefix + sha256hex(vaultId)` (default prefix `pii_shield_vault.`). PHP's `Psr6CacheStorage` adds Symfony Cache's namespace and marshalling, so sharing one Redis between PHP and Node needs a raw adapter on the PHP side with the same key scheme.
|
|
274
|
+
|
|
275
|
+
## License and attribution
|
|
276
|
+
|
|
277
|
+
MIT, see [LICENSE](LICENSE). This is a port of [`clarifile/pii-shield`](https://github.com/massiveart/clarifile/tree/main/packages/pii-shield) (MIT, © the Clarifile contributors); the detection rules, the model prompt, the HTTP API and the MCP tool definitions come from that package.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @waswrongassembled/pii-shield/ai-sdk: Vercel AI SDK integration. Needs the `ai` package (peer dependency).
|
|
3
|
+
*/
|
|
4
|
+
import { generateText, type LanguageModel, type LanguageModelCallOptions } from 'ai';
|
|
5
|
+
import type { DetectionModel } from '../model/model-detector.js';
|
|
6
|
+
/** Settings passed to `generateText()` for every detection call, e.g. `{ temperature: 0, maxOutputTokens: 1024 }`. */
|
|
7
|
+
export type DetectionModelSettings = LanguageModelCallOptions & Pick<Parameters<typeof generateText>[0], 'maxRetries' | 'headers' | 'providerOptions'>;
|
|
8
|
+
/**
|
|
9
|
+
* An AI SDK language model as the model of a ModelDetector:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* new ModelDetector({ model: detectionModel(ollama('qwen3:8b'), { temperature: 0 }), location: 'local' })
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* The location is still yours to state: the AI SDK cannot tell where a provider runs. A plain model id
|
|
16
|
+
* string goes through the AI Gateway, an external provider.
|
|
17
|
+
*/
|
|
18
|
+
export declare function detectionModel(model: LanguageModel, settings?: DetectionModelSettings): DetectionModel;
|
|
19
|
+
export { piiShieldMiddleware, type PiiShieldMiddlewareOptions, type RedactEvent, type RestoreEvent, UnsupportedContentError, } from './middleware.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @waswrongassembled/pii-shield/ai-sdk: Vercel AI SDK integration. Needs the `ai` package (peer dependency).
|
|
3
|
+
*/
|
|
4
|
+
import { generateText } from 'ai';
|
|
5
|
+
/**
|
|
6
|
+
* An AI SDK language model as the model of a ModelDetector:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* new ModelDetector({ model: detectionModel(ollama('qwen3:8b'), { temperature: 0 }), location: 'local' })
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* The location is still yours to state: the AI SDK cannot tell where a provider runs. A plain model id
|
|
13
|
+
* string goes through the AI Gateway, an external provider.
|
|
14
|
+
*/
|
|
15
|
+
export function detectionModel(model, settings = {}) {
|
|
16
|
+
return {
|
|
17
|
+
name: typeof model === 'string' ? model : model.modelId,
|
|
18
|
+
generate: async ({ system, user }, { signal }) => {
|
|
19
|
+
const result = await generateText({
|
|
20
|
+
...settings,
|
|
21
|
+
model,
|
|
22
|
+
instructions: system,
|
|
23
|
+
prompt: user,
|
|
24
|
+
abortSignal: signal,
|
|
25
|
+
});
|
|
26
|
+
return result.text;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export { piiShieldMiddleware, UnsupportedContentError, } from './middleware.js';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { LanguageModelMiddleware } from 'ai';
|
|
2
|
+
import { PiiShieldError } from '../errors.js';
|
|
3
|
+
import type { Redactor, VaultRedactor } from '../redaction.js';
|
|
4
|
+
/**
|
|
5
|
+
* A message part that cannot be redacted (a file: image, audio, PDF, …) is in the prompt. It would reach
|
|
6
|
+
* the provider with personal data, so the call is stopped before anything is sent (PHP's
|
|
7
|
+
* UnsupportedContentException). Extract the text locally (e.g. OCR) and send text only.
|
|
8
|
+
*/
|
|
9
|
+
export declare class UnsupportedContentError extends PiiShieldError {
|
|
10
|
+
readonly code: 'UNSUPPORTED_CONTENT';
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
13
|
+
/** Reported once per model call after the prompt was redacted. Holds no personal data. */
|
|
14
|
+
export interface RedactEvent {
|
|
15
|
+
/** The placeholders the prompt was sent with, in order of assignment. */
|
|
16
|
+
readonly placeholders: readonly string[];
|
|
17
|
+
/** With `vault: true`: the id the mapping is stored under (`restoreFromVault()`, `forget()`). */
|
|
18
|
+
readonly vaultId?: string;
|
|
19
|
+
}
|
|
20
|
+
/** Reported once per model call after its answer was restored (for a stream: when it ends). */
|
|
21
|
+
export interface RestoreEvent {
|
|
22
|
+
/** Placeholders in the answer that are not in the mapping (the model invented them); they were left as they are. */
|
|
23
|
+
readonly unknownPlaceholders: readonly string[];
|
|
24
|
+
}
|
|
25
|
+
export interface PiiShieldMiddlewareOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Also store each call's mapping in the shield's vault (`redactToVault()`), e.g. to restore a stored
|
|
28
|
+
* answer in a later request. The id is reported to `onRedact`. The shield needs a vault.
|
|
29
|
+
*/
|
|
30
|
+
vault?: boolean;
|
|
31
|
+
/** Called with the placeholders (and vault id) of each call; never with the original values. */
|
|
32
|
+
onRedact?: (event: RedactEvent) => void;
|
|
33
|
+
/** Called with the placeholders the model invented (PHP: result metadata `pii_shield.unknown_placeholders`). */
|
|
34
|
+
onRestore?: (event: RestoreEvent) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Send file, reasoning-file and custom parts of assistant messages unchanged. They cannot be redacted, and
|
|
37
|
+
* the caller controls the history, so by default they are rejected (fail closed). Enable this only if such
|
|
38
|
+
* parts come from the model itself and never carry personal data the provider has not seen.
|
|
39
|
+
*/
|
|
40
|
+
allowOpaqueAssistantParts?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* AI SDK language model middleware: the provider only ever sees placeholders, the caller gets the answer
|
|
44
|
+
* with the original values (PHP's PiiShieldProcessor).
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* const model = wrapLanguageModel({ model: openai('gpt-5'), middleware: piiShieldMiddleware(new PiiShield()) });
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* - Prompt: all text of system, user, assistant and tool messages (text, reasoning, tool call inputs, tool
|
|
51
|
+
* results, approval reasons; string values of JSON, not keys) is redacted in one go, so the same value
|
|
52
|
+
* gets the same placeholder in every message. Every model call (every step of a tool loop) redacts the
|
|
53
|
+
* whole prompt again. Files in user and tool messages are rejected with `UnsupportedContentError` before
|
|
54
|
+
* anything is sent; files and custom parts of assistant messages pass unchanged.
|
|
55
|
+
* - Answer: text, reasoning, tool call inputs (JSON string values) and provider-executed tool results are
|
|
56
|
+
* restored, in `generate` and in streams (a placeholder split across chunks is held back until complete).
|
|
57
|
+
* In JSON mode (structured output) values are inserted JSON-escaped, so the JSON stays valid.
|
|
58
|
+
* `providerMetadata`, raw chunks and request/response bodies are passed unchanged.
|
|
59
|
+
*
|
|
60
|
+
* The mapping stays in this process: it is kept per call in a WeakMap, never in the call options.
|
|
61
|
+
* Async detectors (ModelDetector) work: the prompt is redacted with `redactAsync()` and the call's abort signal.
|
|
62
|
+
*/
|
|
63
|
+
export declare function piiShieldMiddleware(shield: Redactor | VaultRedactor, options?: PiiShieldMiddlewareOptions): LanguageModelMiddleware;
|