@waswrongassembled/pii-shield 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -1
- package/README.md +127 -15
- package/dist/cli.js +30 -5
- package/dist/create-pii-shield.d.ts +91 -0
- package/dist/create-pii-shield.js +124 -0
- package/dist/detectors/known-values.d.ts +40 -0
- package/dist/detectors/known-values.js +126 -0
- package/dist/entity-extractor.d.ts +17 -1
- package/dist/entity-extractor.js +13 -2
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -3
- package/dist/internal/background.d.ts +27 -0
- package/dist/internal/background.js +47 -0
- package/dist/learning/custom-entity-type.d.ts +14 -4
- package/dist/learning/custom-entity-type.js +23 -5
- package/dist/learning/entity-learner.d.ts +33 -2
- package/dist/learning/entity-learner.js +48 -5
- package/dist/learning/store.d.ts +4 -2
- package/dist/pii-masker.js +3 -1
- package/dist/pii-shield.js +3 -1
- package/dist/postgres/index.d.ts +20 -0
- package/dist/postgres/index.js +14 -0
- package/dist/redaction.d.ts +16 -2
- package/dist/redaction.js +22 -10
- package/dist/server/config.d.ts +5 -8
- package/dist/server/config.js +77 -220
- package/dist/server/connections.d.ts +34 -0
- package/dist/server/connections.js +99 -0
- package/dist/server/doctor.d.ts +28 -0
- package/dist/server/doctor.js +438 -0
- package/dist/server/env.d.ts +62 -0
- package/dist/server/env.js +197 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/service/service-api.js +25 -0
- package/dist/testing/conformance.js +8 -3
- package/dist/vault/encrypted-vault.d.ts +39 -2
- package/dist/vault/encrypted-vault.js +96 -13
- package/dist/vault/memory-vault-storage.d.ts +8 -1
- package/dist/vault/memory-vault-storage.js +20 -8
- package/dist/vault-redis/index.d.ts +14 -0
- package/dist/vault-redis/index.js +8 -0
- package/docs/openapi.yaml +23 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,32 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.4.0] - 2026-11-23
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Known values per call: `knownValues: [{ value, type }]` for `PiiShield`, `PiiMasker` and `EntityExtractor`, and in the bodies of `POST /v1/redact` and `POST /v1/mask`. Each value is found wherever it occurs as a whole word, case-insensitively, with umlauts in either spelling (`Müller` / `Mueller` / decomposed, `ß` / `ss`) and any whitespace between its words; a short value never matches inside a longer word (`Ali` not in `Alibi`). Known values win over the allowlist and, in the service, apply regardless of `types`. Overlaps with rule findings are resolved like any other (longer span first), so placeholders never nest. The values are held only for the call: never stored, learned or logged, validation errors (`TypeError`, HTTP 400) never contain them, and the detector serializes as `{ name, count }`. Limits: 500 values, 2–200 characters each. `KnownValuesDetector` is exported. Without `knownValues` nothing changes.
|
|
13
|
+
|
|
14
|
+
## [0.3.0] - 2026-11-22
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- `createPiiShield(options)`: a `PiiShield` with safe defaults in one call. Vault entries live 900 s and expired ones are deleted at start and every 300 s on an unref'd timer (`purgeInterval`, errors to `onError`, by default name and code only); learned types are included in detection and stored without examples (`keepExamples: false`, so model-only types are refused); a vault key is never generated for a storage; the vault and the learned types are read once at start. The result also has `learner`, `notes` and `close()` / `Symbol.asyncDispose`. Without `vault` the mappings are kept in memory with a random per-process key (noted); `vault: false` turns the vault off.
|
|
19
|
+
- `postgresVault({ query, key, previousKeys?, table? })` in `/postgres` and `redisVault({ client, key, previousKeys?, prefix? })` in `/vault-redis` build the vault for `createPiiShield()`.
|
|
20
|
+
- `MemoryVaultStorage.purgeExpired()` deletes expired entries and returns their number.
|
|
21
|
+
- `pii-shield doctor [--connect] [--json] [--host <host>]` checks the service configuration from the environment with the rules of `serve` plus security recommendations (token and bind address, vault key and TTL, `sslmode` of the database URL, TLS to Redis, kept examples, external model providers) and prints findings with severity `error`, `warning`, `info` or `ok`; exit code 1 on errors. Values of secrets are never printed. `--connect` also checks that Redis and PostgreSQL answer, that the connection is encrypted, and that the tables exist, are readable and writable by the role. `checkServiceConfig(env, { connect })` and `formatFindings()` in `/server` do the same programmatically.
|
|
22
|
+
- Vault key rotation: `EncryptedVault` takes `previousKeys`, keys that only decrypt (tried in order after `key`); new entries are always written with `key`, in PHP's payload format. The service reads them from `PII_SERVICE_VAULT_PREVIOUS_KEYS` (comma-separated base64). Procedure in docs/server.md.
|
|
23
|
+
- `vaultKeyFromEnv(name = 'PII_SHIELD_VAULT_KEY', env = process.env)` and `previousVaultKeysFromEnv(name = 'PII_SHIELD_VAULT_PREVIOUS_KEYS', env)` read keys from the environment and throw a `TypeError` naming the variable, never the value, if one is missing or invalid.
|
|
24
|
+
- `pii-shield generate-key` prints a new vault key (base64). Examples now read the key with `vaultKeyFromEnv()` instead of generating one at run time.
|
|
25
|
+
- `new PiiShield({ learner })`, also for `PiiMasker` and `EntityExtractor`: adds the learned types to the default (or given) detectors, so they can no longer be left out by accident. A learner's detector is not registered twice.
|
|
26
|
+
- `EntityLearner` option `keepExamples: false`: learned types are stored with name, description and pattern only, after the pattern was checked against the examples. Model-only types (no pattern) are refused in this mode. `learner.dropExamples()` strips types stored before (model-only types keep theirs), `withoutExamples(type)` strips one type. Service: `PII_SERVICE_LEARNED_KEEP_EXAMPLES=false`. PHP cannot read a store that holds types without examples; the default stays `true`.
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
|
|
30
|
+
- **Redaction results no longer serialize their original values.** `mapping` and `entities` of a `RedactionResult` / `VaultRedactionResult` are still readable properties but no longer enumerable, and `toJSON()` returns `{ redactedText, entityCount }` (plus `vaultId`). A result that reaches `JSON.stringify()` (pino, winston, Sentry, an error report) carries no personal data. Before, `JSON.stringify(result)` contained the mapping and the entities with all values. Breaking for code that relied on that: spread (`{ ...result }`), `Object.keys()`, `structuredClone()` / `postMessage()` and `toEqual()` against a literal no longer see `mapping` and `entities`; use `result.mapping` / `result.entities` explicitly. `restore()` throws a `TypeError` when it gets such a copy instead of silently restoring nothing. HTTP and MCP responses are unchanged.
|
|
31
|
+
- `customEntityTypeFromJSON()` and therefore all stores accept a stored type with a pattern and no examples. `verifyCustomEntityStore()` checks that a store returns such a type unchanged.
|
|
32
|
+
- `EntityLearner.detector()` returns the same detector instance on every call.
|
|
33
|
+
|
|
8
34
|
## [0.2.0] - 2026-11-21
|
|
9
35
|
|
|
10
36
|
### Added
|
|
@@ -46,7 +72,9 @@ Privacy and crash bugs of the PHP package are fixed rather than reproduced: name
|
|
|
46
72
|
- `@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.
|
|
47
73
|
- `pii-shield` CLI: `pii-shield serve`, `pii-shield mcp [--http]`, configured with PHP's environment variables.
|
|
48
74
|
|
|
49
|
-
[Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.
|
|
75
|
+
[Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.4.0...HEAD
|
|
76
|
+
[0.4.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.3.0...v0.4.0
|
|
77
|
+
[0.3.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.2.0...v0.3.0
|
|
50
78
|
[0.2.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.1...v0.2.0
|
|
51
79
|
[0.1.1]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.0...v0.1.1
|
|
52
80
|
[0.1.0]: https://github.com/waswrongassembled/pii-shield-js/releases/tag/v0.1.0
|
package/README.md
CHANGED
|
@@ -44,10 +44,32 @@ result.mapping; // { '⟦PERSON_1⟧': 'Johann Beispielmann', '⟦SVNR_1⟧': '4
|
|
|
44
44
|
const restored = shield.restore('Antwort an ⟦PERSON_1⟧ zu ⟦SVNR_1⟧', result);
|
|
45
45
|
restored.text; // 'Antwort an Johann Beispielmann zu 4568 150392'
|
|
46
46
|
restored.unknownPlaceholders; // placeholders the model invented: []
|
|
47
|
+
|
|
48
|
+
JSON.stringify(result); // '{"redactedText":"Sehr geehrter Herr ⟦PERSON_1⟧, …","entityCount":3}'
|
|
47
49
|
```
|
|
48
50
|
|
|
51
|
+
`result.mapping` and `result.entities` hold the original values. They are readable but not enumerable, so a result that ends up in a log line, an error report or a spread copy carries no personal data: `JSON.stringify()` (pino, winston, Sentry) gives `{ redactedText, entityCount }` (plus `vaultId`), `console.log()` shows `mapping: '[hidden]'`, and spread, `Object.keys()` and `structuredClone()` copy only `redactedText`. To pass the mapping on (to a worker, a store), take `result.mapping` explicitly, or use the vault. `restore()` throws a `TypeError` when it gets such a copy instead of the result.
|
|
52
|
+
|
|
49
53
|
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()`).
|
|
50
54
|
|
|
55
|
+
### Known values
|
|
56
|
+
|
|
57
|
+
When you already know whose data a text is about, pass those values per call. They are found wherever they occur as whole words, case-insensitively and with umlauts in either spelling, even where no detector would find them:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { EntityType, PiiShield } from '@waswrongassembled/pii-shield';
|
|
61
|
+
|
|
62
|
+
const shield = new PiiShield({
|
|
63
|
+
knownValues: [
|
|
64
|
+
{ value: 'Jürgen Müller', type: EntityType.Person },
|
|
65
|
+
{ value: 'KD-99812', type: EntityType.FileNumber },
|
|
66
|
+
],
|
|
67
|
+
});
|
|
68
|
+
shield.redact('JUERGEN MUELLER, Kundennr. KD-99812').redactedText; // '⟦PERSON_1⟧, Kundennr. ⟦FILE_NUMBER_1⟧'
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
A short value never matches inside a longer word (`Ali` not in `Alibi`), known values win over the `allowlist`, and they are only held by that instance: never stored, learned or logged. The HTTP service takes the same list as `knownValues` in the body of `/v1/redact` and `/v1/mask`, for that request only. Limits: 500 values of 2–200 characters.
|
|
72
|
+
|
|
51
73
|
## Masking
|
|
52
74
|
|
|
53
75
|
Irreversible replacement, for logs or analytics. IBANs and phone numbers stay partly visible by default.
|
|
@@ -67,12 +89,63 @@ masker.mask('E-Mail j.beispielmann@example.com, IBAN AT61 1904 3002 3457 3201');
|
|
|
67
89
|
|
|
68
90
|
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`.
|
|
69
91
|
|
|
92
|
+
The key is 32 random bytes, base64-encoded. Create it once and keep it in your secret store, never in code:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
npx @waswrongassembled/pii-shield generate-key # or: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`createPiiShield()` sets up vault and learned types in one call, with safe defaults. With PostgreSQL (tables from `pii-shield db-schema`, see [docs/stores.md](docs/stores.md#postgresql)):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import pg from 'pg';
|
|
102
|
+
import { createPiiShield, previousVaultKeysFromEnv, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
|
|
103
|
+
import { PostgresCustomEntityStore, postgresVault } from '@waswrongassembled/pii-shield/postgres';
|
|
104
|
+
|
|
105
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
106
|
+
const query = pool.query.bind(pool);
|
|
107
|
+
|
|
108
|
+
const shield = await createPiiShield({
|
|
109
|
+
// PII_SHIELD_VAULT_KEY, PII_SHIELD_VAULT_PREVIOUS_KEYS; a clear error (without the value) if invalid
|
|
110
|
+
vault: postgresVault({ query, key: vaultKeyFromEnv(), previousKeys: previousVaultKeysFromEnv() }),
|
|
111
|
+
learnedTypes: new PostgresCustomEntityStore({ query }),
|
|
112
|
+
});
|
|
113
|
+
for (const note of shield.notes) console.warn(note);
|
|
114
|
+
|
|
115
|
+
const { redactedText, vaultId } = await shield.redactToVault('Herrn\nJohann Beispielmann\nSVNR 4568 150392');
|
|
116
|
+
// ... later, in any process with the same key and database:
|
|
117
|
+
const { text } = await shield.restoreFromVault(redactedText, vaultId);
|
|
118
|
+
await shield.forget(vaultId);
|
|
119
|
+
|
|
120
|
+
await shield.learner.learn({
|
|
121
|
+
name: 'INSURANCE_NUMBER',
|
|
122
|
+
description: 'Polizzennummer',
|
|
123
|
+
examples: ['VN-2026-000417', 'VN-2025-123456'],
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// On shutdown: stops the purge timer (and waits for a running purge); the pool stays yours.
|
|
127
|
+
await shield.close();
|
|
128
|
+
await pool.end();
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
What it does for you:
|
|
132
|
+
|
|
133
|
+
- **Short TTL:** mappings live 900 s (`vaultTtl`; `new PiiShield()` defaults to 3600 s), enough for a model's answer.
|
|
134
|
+
- **Expired entries are deleted**, not only hidden: at start and every 300 s (`purgeInterval`, `0` = off) on an unref'd timer. Errors go to `onError(error, 'vault-purge')`; the default logs `pii-shield: vault-purge failed (<name> <code>)`, never a message or a value.
|
|
135
|
+
- **Learned types are detected** (PiiShield's `learner` option) and **stored without examples** (`keepExamples: false`, data minimisation). Types without a pattern (model-only, e.g. pet names) are then refused with a `LearningError`: give a pattern by hand, or pass `keepExamples: true`. `EntityLearner` on its own keeps its default (`true`).
|
|
136
|
+
- **No generated keys:** a vault on a storage needs `key`. Only without `vault` it is in memory with a random key per process: mappings are lost on restart and not shared between processes (`shield.notes` says so).
|
|
137
|
+
- **Fails at start** when a table is missing or the connection does not work.
|
|
138
|
+
|
|
139
|
+
Other backends: `redisVault({ client, key })` from `/vault-redis` (Redis expires entries itself), `{ storage, key }` for any `VaultStorage`, a ready `Vault`, or `vault: false` (plain `redact()`/`restore()` only). `learnedTypes` takes any `CustomEntityStore` (`JsonFileCustomEntityStore`, ...) or an `EntityLearner`. The result is a `PiiShield`, so `piiShieldMiddleware(shield)` takes it.
|
|
140
|
+
|
|
141
|
+
The building blocks, for full control:
|
|
142
|
+
|
|
70
143
|
```ts
|
|
71
|
-
import { EncryptedVault, MemoryVaultStorage,
|
|
144
|
+
import { EncryptedVault, MemoryVaultStorage, PiiShield, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
|
|
72
145
|
|
|
73
146
|
const shield = new PiiShield({
|
|
74
|
-
//
|
|
75
|
-
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key:
|
|
147
|
+
// reads PII_SHIELD_VAULT_KEY; throws a clear error (without the value) if it is missing or invalid
|
|
148
|
+
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: vaultKeyFromEnv() }),
|
|
76
149
|
vaultTtl: 900,
|
|
77
150
|
});
|
|
78
151
|
|
|
@@ -86,21 +159,44 @@ For several processes use Redis:
|
|
|
86
159
|
|
|
87
160
|
```ts
|
|
88
161
|
import { Redis } from 'ioredis';
|
|
89
|
-
import { EncryptedVault,
|
|
162
|
+
import { EncryptedVault, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
|
|
90
163
|
import { RedisVaultStorage } from '@waswrongassembled/pii-shield/vault-redis';
|
|
91
164
|
|
|
92
165
|
const vault = new EncryptedVault({
|
|
93
166
|
storage: new RedisVaultStorage({ client: new Redis('redis://127.0.0.1:6379') }),
|
|
94
|
-
key:
|
|
167
|
+
key: vaultKeyFromEnv(), // the same key in every process
|
|
168
|
+
});
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`generateVaultKey()` exists for tools that create a key; a key generated at run time cannot read the entries after a restart or in another process.
|
|
172
|
+
|
|
173
|
+
### Key rotation
|
|
174
|
+
|
|
175
|
+
`previousKeys` keeps entries readable that were written before a key change; new entries always use `key`. Payloads stay PHP's format (PHP has no rotation: it reads only entries of its own key).
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import {
|
|
179
|
+
EncryptedVault,
|
|
180
|
+
MemoryVaultStorage,
|
|
181
|
+
previousVaultKeysFromEnv,
|
|
182
|
+
vaultKeyFromEnv,
|
|
183
|
+
} from '@waswrongassembled/pii-shield';
|
|
184
|
+
|
|
185
|
+
const vault = new EncryptedVault({
|
|
186
|
+
storage: new MemoryVaultStorage(),
|
|
187
|
+
key: vaultKeyFromEnv(), // PII_SHIELD_VAULT_KEY: the new key
|
|
188
|
+
previousKeys: previousVaultKeysFromEnv(), // PII_SHIELD_VAULT_PREVIOUS_KEYS: old keys, comma-separated
|
|
95
189
|
});
|
|
96
190
|
```
|
|
97
191
|
|
|
192
|
+
Procedure: create a new key, deploy it as `PII_SHIELD_VAULT_KEY` with the old one in `PII_SHIELD_VAULT_PREVIOUS_KEYS`, wait the longest vault TTL after the last process switched, then remove the old key. To avoid a window in which processes that still run the old configuration cannot read new entries, add the new key as a previous key everywhere first. A leaked key is not kept as a previous key: delete its entries instead. The service reads `PII_SERVICE_VAULT_PREVIOUS_KEYS` ([docs/server.md](docs/server.md#key-rotation)).
|
|
193
|
+
|
|
98
194
|
## Learned entity types
|
|
99
195
|
|
|
100
196
|
Teach a type from examples; a pattern is derived and checked against the counter-examples. Stores: `JsonFileCustomEntityStore` (same file format as PHP), `InMemoryCustomEntityStore`, `KeyValueCustomEntityStore`, `PostgresCustomEntityStore` (see [docs/stores.md](docs/stores.md)).
|
|
101
197
|
|
|
102
198
|
```ts
|
|
103
|
-
import {
|
|
199
|
+
import { EntityLearner, JsonFileCustomEntityStore, PiiShield } from '@waswrongassembled/pii-shield';
|
|
104
200
|
|
|
105
201
|
const learner = await EntityLearner.create({ store: new JsonFileCustomEntityStore('var/learned-types.json') });
|
|
106
202
|
const { type } = await learner.learn({
|
|
@@ -110,22 +206,38 @@ const { type } = await learner.learn({
|
|
|
110
206
|
});
|
|
111
207
|
type.pattern; // 'VN-\\d{4}-\\d{6}'
|
|
112
208
|
|
|
113
|
-
const shield = new PiiShield({
|
|
209
|
+
const shield = new PiiShield({ learner }); // the default detectors plus the learned types
|
|
114
210
|
shield.redact('Polizze VN-2026-000999').redactedText; // 'Polizze ⟦INSURANCE_NUMBER_1⟧'
|
|
115
211
|
```
|
|
116
212
|
|
|
213
|
+
`learner` works the same in `PiiMasker` and `EntityExtractor`, and next to your own `detectors`. Detection reads the learner's snapshot: `learn()` and `forget()` update it at once, types that other processes learned appear after `learner.refresh()` (per request or on a timer, see [docs/stores.md](docs/stores.md#several-instances-and-learned-types)).
|
|
214
|
+
|
|
215
|
+
Examples and counter-examples are stored in plain text and may be personal data. With `keepExamples: false` the learner checks the pattern against them and then stores only name, description and pattern:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
import { EntityLearner, JsonFileCustomEntityStore } from '@waswrongassembled/pii-shield';
|
|
219
|
+
|
|
220
|
+
const learner = await EntityLearner.create({
|
|
221
|
+
store: new JsonFileCustomEntityStore('var/learned-types.json'),
|
|
222
|
+
keepExamples: false,
|
|
223
|
+
});
|
|
224
|
+
await learner.dropExamples(); // once: strips types stored before, returns { stripped, kept }
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
The trade-off: plain words without a pattern (model-only types such as pet names) are then refused, because only their examples let the model find them; give a pattern by hand instead. Model-based detection knows the other types by name and description only. A type cannot be derived again from its stored examples. PHP cannot read a store that holds types without examples. `dropExamples()` keeps the examples of model-only types.
|
|
228
|
+
|
|
117
229
|
## Stores: PostgreSQL and your own
|
|
118
230
|
|
|
119
|
-
A product that already runs PostgreSQL can keep the vault and the learned types in its own database, in its own pool and, where it wants, in its own transactions. `@waswrongassembled/pii-shield/postgres` takes a `query(text, params)` function (a `pg` `Pool` or `PoolClient` fits) and never runs DDL: put `postgresSchema()` (or `pii-shield db-schema`) into your migrations.
|
|
231
|
+
A product that already runs PostgreSQL can keep the vault and the learned types in its own database, in its own pool and, where it wants, in its own transactions. `@waswrongassembled/pii-shield/postgres` takes a `query(text, params)` function (a `pg` `Pool` or `PoolClient` fits) and never runs DDL: put `postgresSchema()` (or `pii-shield db-schema`) into your migrations. `createPiiShield()` with `postgresVault()` ([above](#vault-restore-in-a-later-request)) wires the stores up and purges for you; by hand:
|
|
120
232
|
|
|
121
233
|
```ts
|
|
122
234
|
import pg from 'pg';
|
|
123
|
-
import { EncryptedVault,
|
|
235
|
+
import { EncryptedVault, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
|
|
124
236
|
import { PostgresCustomEntityStore, PostgresVaultStorage } from '@waswrongassembled/pii-shield/postgres';
|
|
125
237
|
|
|
126
238
|
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
127
239
|
const storage = new PostgresVaultStorage({ query: pool.query.bind(pool) });
|
|
128
|
-
const vault = new EncryptedVault({ storage, key:
|
|
240
|
+
const vault = new EncryptedVault({ storage, key: vaultKeyFromEnv() }); // the database only sees ciphertext
|
|
129
241
|
const store = new PostgresCustomEntityStore({ query: pool.query.bind(pool) });
|
|
130
242
|
await storage.purgeExpired(); // run regularly: expired rows must really be deleted
|
|
131
243
|
```
|
|
@@ -204,7 +316,7 @@ PII_SERVICE_TOKEN=$(openssl rand -hex 24) PII_SERVICE_VAULT_KEY=... \
|
|
|
204
316
|
npx @waswrongassembled/pii-shield serve --host 0.0.0.0 --port 8080
|
|
205
317
|
```
|
|
206
318
|
|
|
207
|
-
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).
|
|
319
|
+
Without a token only local peers are answered. `pii-shield doctor` checks the configuration before you deploy (exit code 1 on errors, `--connect` also tries Redis and PostgreSQL, never prints secrets). Configuration (environment variables, Redis, model provider), programmatic use (`startServer()`, `ServiceApi`) and a Docker image: [docs/server.md](docs/server.md).
|
|
208
320
|
|
|
209
321
|
## MCP server
|
|
210
322
|
|
|
@@ -218,15 +330,15 @@ claude mcp add pii-shield -- npx @waswrongassembled/pii-shield mcp
|
|
|
218
330
|
import {
|
|
219
331
|
EncryptedVault,
|
|
220
332
|
EntityLearner,
|
|
221
|
-
generateVaultKey,
|
|
222
333
|
InMemoryCustomEntityStore,
|
|
223
334
|
MemoryVaultStorage,
|
|
335
|
+
vaultKeyFromEnv,
|
|
224
336
|
} from '@waswrongassembled/pii-shield';
|
|
225
337
|
import { serveStdio } from '@waswrongassembled/pii-shield/mcp';
|
|
226
338
|
import { ServiceApi } from '@waswrongassembled/pii-shield/server';
|
|
227
339
|
|
|
228
340
|
const api = new ServiceApi({
|
|
229
|
-
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key:
|
|
341
|
+
vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: vaultKeyFromEnv() }),
|
|
230
342
|
learner: await EntityLearner.create({ store: new InMemoryCustomEntityStore() }),
|
|
231
343
|
});
|
|
232
344
|
await serveStdio(api); // log to stderr only: stdout belongs to the protocol
|
|
@@ -248,8 +360,8 @@ Not shared: `Entity.offset` is a UTF-16 index (`text.slice(offset, offset + valu
|
|
|
248
360
|
## Limits and security
|
|
249
361
|
|
|
250
362
|
- 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.
|
|
251
|
-
- A `RedactionResult` contains the original values (`mapping`, `entities`).
|
|
252
|
-
- 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.
|
|
363
|
+
- A `RedactionResult` contains the original values (`mapping`, `entities`). Serializing it leaves them out (see [Redact and restore](#redact-and-restore)), but `result.mapping`, `result.entities` and entity `value`s serialize in full: never log them, put them in error reports or send them to the model; send only `redactedText`. A `RestoreResult`'s `text` is the restored text with the original values. Error messages of this package never contain values.
|
|
364
|
+
- 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 (`vaultKeyFromEnv()`), rotate it with `previousKeys`, and use a short TTL.
|
|
253
365
|
- `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.
|
|
254
366
|
- 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)).
|
|
255
367
|
|
package/dist/cli.js
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The `pii-shield` command: the HTTP service (`serve`)
|
|
3
|
-
* environment variables (docs/server.md).
|
|
2
|
+
* The `pii-shield` command: the HTTP service (`serve`), the MCP server (`mcp`) and the configuration check
|
|
3
|
+
* (`doctor`), configured from environment variables (docs/server.md).
|
|
4
4
|
*/
|
|
5
5
|
import { parseArgs } from 'node:util';
|
|
6
|
+
import { reportToStderr } from './internal/background.js';
|
|
6
7
|
import { postgresSchema } from './postgres/index.js';
|
|
7
8
|
import { ConfigError, serviceFromEnv } from './server/config.js';
|
|
9
|
+
import { checkServiceConfig, formatFindings } from './server/doctor.js';
|
|
8
10
|
import { startServer } from './server/http-server.js';
|
|
11
|
+
import { generateVaultKey } from './vault/encrypted-vault.js';
|
|
9
12
|
const USAGE = `Usage:
|
|
10
13
|
pii-shield serve [--port <port>] [--host <host>] HTTP service: /v1 (and /mcp if @modelcontextprotocol/sdk is installed)
|
|
11
14
|
pii-shield mcp MCP server over STDIO
|
|
12
15
|
pii-shield mcp --http [--port <port>] [--host <host>] MCP server over Streamable HTTP (/mcp)
|
|
13
16
|
pii-shield db-schema SQL for the Postgres tables (stdout), e.g. | psql "$DATABASE_URL"
|
|
17
|
+
pii-shield generate-key A new vault key (32 bytes, base64) to stdout
|
|
18
|
+
pii-shield doctor [--connect] [--json] [--host <host>] Checks the configuration; exit code 1 on errors
|
|
14
19
|
|
|
15
20
|
Configuration: environment variables (PII_SERVICE_TOKEN, PII_SERVICE_VAULT_KEY, ...), see
|
|
16
21
|
https://github.com/waswrongassembled/pii-shield-js/blob/main/docs/server.md`;
|
|
@@ -25,6 +30,8 @@ export async function main(argv, env = process.env) {
|
|
|
25
30
|
port: { type: 'string', short: 'p' },
|
|
26
31
|
host: { type: 'string' },
|
|
27
32
|
http: { type: 'boolean' },
|
|
33
|
+
connect: { type: 'boolean' },
|
|
34
|
+
json: { type: 'boolean' },
|
|
28
35
|
help: { type: 'boolean', short: 'h' },
|
|
29
36
|
},
|
|
30
37
|
});
|
|
@@ -39,14 +46,33 @@ export async function main(argv, env = process.env) {
|
|
|
39
46
|
process.stderr.write(`${USAGE}\n`);
|
|
40
47
|
return values.help === true ? 0 : 2;
|
|
41
48
|
}
|
|
49
|
+
if (command === 'generate-key' && positionals.length === 1 && Object.keys(values).length === 0) {
|
|
50
|
+
// A one-off tool: the operator stores the key as a secret (PII_SERVICE_VAULT_KEY, PII_SHIELD_VAULT_KEY).
|
|
51
|
+
const key = generateVaultKey();
|
|
52
|
+
const encoded = Buffer.from(key);
|
|
53
|
+
process.stdout.write(`${encoded.toString('base64')}\n`);
|
|
54
|
+
encoded.fill(0);
|
|
55
|
+
key.fill(0);
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
42
58
|
if (command === 'db-schema' && positionals.length === 1 && Object.keys(values).length === 0) {
|
|
43
59
|
// DDL is never run by the service itself: the operator (or the product's migrations) applies it.
|
|
44
60
|
process.stdout.write(postgresSchema());
|
|
45
61
|
return 0;
|
|
46
62
|
}
|
|
63
|
+
if (command === 'doctor' && positionals.length === 1 && values.http === undefined && values.port === undefined) {
|
|
64
|
+
// Findings name variables, never their values: safe to paste into a ticket.
|
|
65
|
+
const findings = await checkServiceConfig(env, { connect: values.connect === true, host: values.host });
|
|
66
|
+
process.stdout.write(values.json === true
|
|
67
|
+
? `${JSON.stringify({ ok: !findings.some((f) => f.severity === 'error'), findings }, null, 2)}\n`
|
|
68
|
+
: formatFindings(findings));
|
|
69
|
+
return findings.some((f) => f.severity === 'error') ? 1 : 0;
|
|
70
|
+
}
|
|
47
71
|
if (positionals.length > 1 ||
|
|
48
72
|
(command !== 'serve' && command !== 'mcp') ||
|
|
49
|
-
(command === 'serve' && values.http === true)
|
|
73
|
+
(command === 'serve' && values.http === true) ||
|
|
74
|
+
values.connect !== undefined ||
|
|
75
|
+
values.json !== undefined) {
|
|
50
76
|
process.stderr.write(`${USAGE}\n`);
|
|
51
77
|
return 2;
|
|
52
78
|
}
|
|
@@ -71,8 +97,7 @@ export async function main(argv, env = process.env) {
|
|
|
71
97
|
}
|
|
72
98
|
const onError = (error) => {
|
|
73
99
|
// Name and code only: messages of provider errors may quote the request text.
|
|
74
|
-
|
|
75
|
-
process.stderr.write(`pii-shield: request failed (${name}${typeof code === 'string' ? ` ${code}` : ''})\n`);
|
|
100
|
+
reportToStderr(error, 'request');
|
|
76
101
|
};
|
|
77
102
|
if (command === 'mcp' && values.http !== true) {
|
|
78
103
|
const mcp = await loadMcp();
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { EntityLearner } from './learning/entity-learner.js';
|
|
2
|
+
import { type CustomEntityStore } from './learning/store.js';
|
|
3
|
+
import { PiiShield, type PiiShieldOptions } from './pii-shield.js';
|
|
4
|
+
import { type Vault, type VaultStorage } from './vault/vault.js';
|
|
5
|
+
/**
|
|
6
|
+
* A vault backend for createPiiShield(): where the ciphertext goes and the keys that encrypt it.
|
|
7
|
+
* `postgresVault()` (`/postgres`) and `redisVault()` (`/vault-redis`) build one; any VaultStorage works.
|
|
8
|
+
*/
|
|
9
|
+
export interface VaultSetup {
|
|
10
|
+
/** Receives ciphertext only (createPiiShield() puts an EncryptedVault in front of it). */
|
|
11
|
+
storage: VaultStorage;
|
|
12
|
+
/**
|
|
13
|
+
* 32 raw bytes, e.g. `vaultKeyFromEnv()`. Required: a key generated at run time could not read the
|
|
14
|
+
* entries after a restart or in another process. The vault keeps its own copy.
|
|
15
|
+
*/
|
|
16
|
+
key: Uint8Array;
|
|
17
|
+
/** Keys of earlier rotations, only for reading (see EncryptedVault), e.g. `previousVaultKeysFromEnv()`. */
|
|
18
|
+
previousKeys?: readonly Uint8Array[] | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* Deletes expired entries; createPiiShield() runs it on a timer. Default: the storage's own
|
|
21
|
+
* `purgeExpired()` if it has one (PostgresVaultStorage, MemoryVaultStorage). Redis expires entries
|
|
22
|
+
* itself and needs none. `false`: never (delete them yourself, e.g. with pg_cron).
|
|
23
|
+
*/
|
|
24
|
+
purge?: (() => Promise<unknown>) | false | undefined;
|
|
25
|
+
}
|
|
26
|
+
/** Background work of createPiiShield(); its errors go to `onError`. */
|
|
27
|
+
export type BackgroundTask = 'vault-purge';
|
|
28
|
+
export interface CreatePiiShieldOptions extends Omit<PiiShieldOptions, 'vault' | 'learner' | 'vaultTtl'> {
|
|
29
|
+
/**
|
|
30
|
+
* Where mappings are kept between redactToVault() and restoreFromVault():
|
|
31
|
+
* - omitted: in memory with a random key per process. Mappings are lost on restart and not shared
|
|
32
|
+
* between processes (see `notes`). Fine for a single process; use a persistent store otherwise.
|
|
33
|
+
* - a VaultSetup (`postgresVault()`, `redisVault()`, `{ storage, key }`): encrypted with your key.
|
|
34
|
+
* - a ready Vault (e.g. an EncryptedVault you built): used as is, nothing is purged.
|
|
35
|
+
* - `false`: no vault; redact() and restore() work, the vault methods throw.
|
|
36
|
+
*/
|
|
37
|
+
vault?: VaultSetup | Vault | false | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Store of learned entity types, or a ready EntityLearner. Default: in memory (lost on restart).
|
|
40
|
+
* Detection includes them (PiiShield's `learner` option); teach types with `shield.learner.learn()`.
|
|
41
|
+
*/
|
|
42
|
+
learnedTypes?: CustomEntityStore | EntityLearner | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Store examples and counter-examples with learned types. Default **false** (data minimisation:
|
|
45
|
+
* examples may be personal data); only name, description and pattern are stored. Types without a
|
|
46
|
+
* pattern (model-only, e.g. plain words) are then refused: give a pattern by hand. Not allowed together
|
|
47
|
+
* with a ready EntityLearner, which has its own setting.
|
|
48
|
+
*/
|
|
49
|
+
keepExamples?: boolean | undefined;
|
|
50
|
+
/** Seconds a stored mapping lives. Default 900 (15 minutes; PiiShield's own default is 3600). */
|
|
51
|
+
vaultTtl?: number | undefined;
|
|
52
|
+
/**
|
|
53
|
+
* Seconds between purges of expired vault entries (also one at start). Default 300, at most 86400;
|
|
54
|
+
* `0` turns the timer off. The timer is unref'd; close() stops it.
|
|
55
|
+
*/
|
|
56
|
+
purgeInterval?: number | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* Errors of background work (the vault purge). Default: one line to stderr with the error's name and
|
|
59
|
+
* code, never its message (a driver error can quote values). Do the same in your own handler.
|
|
60
|
+
*/
|
|
61
|
+
onError?: ((error: unknown, task: BackgroundTask) => void) | undefined;
|
|
62
|
+
}
|
|
63
|
+
/** What createPiiShield() returns: a PiiShield plus its learner and background work. */
|
|
64
|
+
export interface ManagedPiiShield extends PiiShield, AsyncDisposable {
|
|
65
|
+
/** The learner whose types detection includes; `learn()` and `forget()` apply at once. */
|
|
66
|
+
readonly learner: EntityLearner;
|
|
67
|
+
/** Notes for the operator (e.g. that the vault is in memory). Never secrets or values; log them at start. */
|
|
68
|
+
readonly notes: readonly string[];
|
|
69
|
+
/**
|
|
70
|
+
* Stops background work (the purge timer) and waits for a running purge. Connections you passed in
|
|
71
|
+
* (pool, Redis client) stay yours to close, after this. Idempotent; also `await using`.
|
|
72
|
+
*/
|
|
73
|
+
close(): Promise<void>;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A PiiShield with safe defaults in one call: an encrypted vault with a short TTL whose expired entries
|
|
77
|
+
* are purged on a timer, learned types included in detection and stored without examples.
|
|
78
|
+
*
|
|
79
|
+
* ```ts
|
|
80
|
+
* const shield = await createPiiShield({
|
|
81
|
+
* vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
|
|
82
|
+
* learnedTypes: new PostgresCustomEntityStore({ query: pool.query.bind(pool) }),
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*
|
|
86
|
+
* At start it reads the vault storage and the learned types once, so a missing table or a wrong
|
|
87
|
+
* connection fails here, not in the first request (the store's error, unchanged).
|
|
88
|
+
*
|
|
89
|
+
* @throws TypeError or RangeError for invalid options (no key for a vault, a bad interval)
|
|
90
|
+
*/
|
|
91
|
+
export declare function createPiiShield(options?: CreatePiiShieldOptions): Promise<ManagedPiiShield>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { DEFAULT_PURGE_INTERVAL, MAX_PURGE_INTERVAL, reportToStderr, schedulePurge, } from './internal/background.js';
|
|
2
|
+
import { EntityLearner } from './learning/entity-learner.js';
|
|
3
|
+
import { InMemoryCustomEntityStore } from './learning/store.js';
|
|
4
|
+
import { PiiShield } from './pii-shield.js';
|
|
5
|
+
import { EncryptedVault, generateVaultKey } from './vault/encrypted-vault.js';
|
|
6
|
+
import { MemoryVaultStorage } from './vault/memory-vault-storage.js';
|
|
7
|
+
import { assertTtl } from './vault/vault.js';
|
|
8
|
+
/**
|
|
9
|
+
* Seconds a mapping lives unless configured: as the HTTP service. Long enough for a model's answer (also a
|
|
10
|
+
* slow, streamed one), short enough that a leaked vault id or a copy of the storage is soon worthless.
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_VAULT_TTL = 900;
|
|
13
|
+
/**
|
|
14
|
+
* A PiiShield with safe defaults in one call: an encrypted vault with a short TTL whose expired entries
|
|
15
|
+
* are purged on a timer, learned types included in detection and stored without examples.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* const shield = await createPiiShield({
|
|
19
|
+
* vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
|
|
20
|
+
* learnedTypes: new PostgresCustomEntityStore({ query: pool.query.bind(pool) }),
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* At start it reads the vault storage and the learned types once, so a missing table or a wrong
|
|
25
|
+
* connection fails here, not in the first request (the store's error, unchanged).
|
|
26
|
+
*
|
|
27
|
+
* @throws TypeError or RangeError for invalid options (no key for a vault, a bad interval)
|
|
28
|
+
*/
|
|
29
|
+
export async function createPiiShield(options = {}) {
|
|
30
|
+
const { vault: vaultOption, learnedTypes, keepExamples, vaultTtl = DEFAULT_VAULT_TTL, purgeInterval = DEFAULT_PURGE_INTERVAL, onError = reportToStderr, ...shieldOptions } = options;
|
|
31
|
+
assertTtl(vaultTtl, 'The vault TTL must be positive.');
|
|
32
|
+
if (!Number.isSafeInteger(purgeInterval) || purgeInterval < 0 || purgeInterval > MAX_PURGE_INTERVAL) {
|
|
33
|
+
throw new RangeError(`The purge interval must be an integer from 0 to ${String(MAX_PURGE_INTERVAL)} seconds.`);
|
|
34
|
+
}
|
|
35
|
+
if (learnedTypes instanceof EntityLearner && keepExamples !== undefined) {
|
|
36
|
+
throw new TypeError('keepExamples is a setting of the EntityLearner: pass it there, or pass a store.');
|
|
37
|
+
}
|
|
38
|
+
const notes = [];
|
|
39
|
+
const { vault, purge } = buildVault(vaultOption, notes);
|
|
40
|
+
if (vault !== undefined) {
|
|
41
|
+
// Fail at start: no connection, no table, no rights. An id that never exists (ids are hashed).
|
|
42
|
+
await vault.fetch('pii-shield-startup-check');
|
|
43
|
+
}
|
|
44
|
+
const learner = learnedTypes instanceof EntityLearner
|
|
45
|
+
? learnedTypes
|
|
46
|
+
: await EntityLearner.create({
|
|
47
|
+
store: learnedTypes ?? new InMemoryCustomEntityStore(),
|
|
48
|
+
keepExamples: keepExamples ?? false,
|
|
49
|
+
});
|
|
50
|
+
if (learnedTypes === undefined) {
|
|
51
|
+
notes.push('Learned types: in memory; they are lost on restart.');
|
|
52
|
+
}
|
|
53
|
+
if (!learner.keepExamples && learner.snapshot.some((t) => t.pattern !== null && t.examples.length > 0)) {
|
|
54
|
+
notes.push('Learned types: types learned before still hold examples; learner.dropExamples() removes them.');
|
|
55
|
+
}
|
|
56
|
+
let schedule;
|
|
57
|
+
if (purge !== undefined && purgeInterval > 0) {
|
|
58
|
+
schedule = schedulePurge(purge, purgeInterval, (error) => {
|
|
59
|
+
onError(error, 'vault-purge');
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
else if (purge !== undefined) {
|
|
63
|
+
notes.push('Vault: expired entries are not purged (purgeInterval 0); delete them yourself.');
|
|
64
|
+
}
|
|
65
|
+
return new ManagedShield({ ...shieldOptions, ...(vault === undefined ? {} : { vault }), vaultTtl, learner }, learner, Object.freeze(notes), schedule);
|
|
66
|
+
}
|
|
67
|
+
class ManagedShield extends PiiShield {
|
|
68
|
+
learner;
|
|
69
|
+
notes;
|
|
70
|
+
#schedule;
|
|
71
|
+
constructor(options, learner, notes, schedule) {
|
|
72
|
+
super(options);
|
|
73
|
+
this.learner = learner;
|
|
74
|
+
this.notes = notes;
|
|
75
|
+
this.#schedule = schedule;
|
|
76
|
+
}
|
|
77
|
+
async close() {
|
|
78
|
+
await this.#schedule?.stop();
|
|
79
|
+
}
|
|
80
|
+
[Symbol.asyncDispose]() {
|
|
81
|
+
return this.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function buildVault(option, notes) {
|
|
85
|
+
if (option === false) {
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
if (option === undefined) {
|
|
89
|
+
// The only place a key is generated: memory dies with the process, so nothing outlives the key.
|
|
90
|
+
const storage = new MemoryVaultStorage();
|
|
91
|
+
const key = generateVaultKey();
|
|
92
|
+
try {
|
|
93
|
+
notes.push('Vault: in memory with a random key; mappings are lost on restart and not shared between processes.');
|
|
94
|
+
return { vault: new EncryptedVault({ storage, key }), purge: () => storage.purgeExpired() };
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
key.fill(0);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// Checked at run time too: callers without type checking, and a VaultStorage passed without a key.
|
|
101
|
+
if (typeof option !== 'object' || option === null) {
|
|
102
|
+
throw new TypeError('The vault must be a VaultSetup ({ storage, key }), a Vault or false.');
|
|
103
|
+
}
|
|
104
|
+
if (!('storage' in option)) {
|
|
105
|
+
if (typeof option.store !== 'function' || typeof option.fetch !== 'function') {
|
|
106
|
+
throw new TypeError('The vault must be a VaultSetup ({ storage, key }), a Vault or false. A VaultStorage alone needs a key: pass { storage, key }.');
|
|
107
|
+
}
|
|
108
|
+
return { vault: option };
|
|
109
|
+
}
|
|
110
|
+
const { storage, key, previousKeys, purge } = option;
|
|
111
|
+
if (key === undefined) {
|
|
112
|
+
// No silent fallback to a random key: entries in a persistent storage would become unreadable.
|
|
113
|
+
throw new TypeError('The vault needs a key (32 bytes), e.g. vaultKeyFromEnv(). It is never generated for a storage.');
|
|
114
|
+
}
|
|
115
|
+
const vault = new EncryptedVault({ storage, key, previousKeys });
|
|
116
|
+
if (purge === false) {
|
|
117
|
+
return { vault };
|
|
118
|
+
}
|
|
119
|
+
if (purge !== undefined) {
|
|
120
|
+
return { vault, purge };
|
|
121
|
+
}
|
|
122
|
+
const own = storage.purgeExpired;
|
|
123
|
+
return typeof own === 'function' ? { vault, purge: () => own.call(storage) } : { vault };
|
|
124
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Detector } from '../detector.js';
|
|
2
|
+
import { type Entity } from '../entity.js';
|
|
3
|
+
import { type EntityType } from '../entity-type.js';
|
|
4
|
+
/** A value the caller already knows to be personal data, e.g. the account holder's name. */
|
|
5
|
+
export interface KnownValue {
|
|
6
|
+
readonly value: string;
|
|
7
|
+
readonly type: EntityType;
|
|
8
|
+
}
|
|
9
|
+
/** The `detector` of entities found from known values; they are exempt from the allowlist. */
|
|
10
|
+
export declare const KNOWN_VALUES_DETECTOR = "known-values";
|
|
11
|
+
/**
|
|
12
|
+
* Finds values the caller passes per call (names of the account holder, their customer numbers, ...)
|
|
13
|
+
* wherever they occur as whole words:
|
|
14
|
+
*
|
|
15
|
+
* - case-insensitive (Unicode), so "MÜLLER" and "müller" match "Müller"
|
|
16
|
+
* - umlauts in either spelling: "Müller" also matches "Mueller" and a decomposed "Müller", and
|
|
17
|
+
* "Mueller" matches "Müller"; "ß" and "ss" match each other
|
|
18
|
+
* - only whole words: "Ali" does not match in "Alibi" or "Kalium"
|
|
19
|
+
* - any run of whitespace (also a line break) between the words of a value
|
|
20
|
+
*
|
|
21
|
+
* The values are held only by this instance (never stored, learned or logged); validation errors never
|
|
22
|
+
* contain them, and the detector serializes and inspects as `{ name, count }`.
|
|
23
|
+
*/
|
|
24
|
+
export declare class KnownValuesDetector implements Detector {
|
|
25
|
+
#private;
|
|
26
|
+
static readonly MAX_VALUES = 500;
|
|
27
|
+
static readonly MIN_LENGTH = 2;
|
|
28
|
+
static readonly MAX_LENGTH = 200;
|
|
29
|
+
readonly name = "known-values";
|
|
30
|
+
/** @throws TypeError on invalid input; the message never contains a value */
|
|
31
|
+
constructor(values: Iterable<KnownValue>);
|
|
32
|
+
/** Number of distinct values. */
|
|
33
|
+
get size(): number;
|
|
34
|
+
detect(text: string): Entity[];
|
|
35
|
+
toJSON(): {
|
|
36
|
+
name: string;
|
|
37
|
+
count: number;
|
|
38
|
+
};
|
|
39
|
+
toString(): string;
|
|
40
|
+
}
|