@waswrongassembled/pii-shield 0.2.0 → 0.3.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 (41) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +109 -15
  3. package/dist/cli.js +30 -5
  4. package/dist/create-pii-shield.d.ts +91 -0
  5. package/dist/create-pii-shield.js +124 -0
  6. package/dist/entity-extractor.d.ts +7 -0
  7. package/dist/entity-extractor.js +6 -1
  8. package/dist/index.d.ts +4 -3
  9. package/dist/index.js +4 -3
  10. package/dist/internal/background.d.ts +27 -0
  11. package/dist/internal/background.js +47 -0
  12. package/dist/learning/custom-entity-type.d.ts +14 -4
  13. package/dist/learning/custom-entity-type.js +23 -5
  14. package/dist/learning/entity-learner.d.ts +33 -2
  15. package/dist/learning/entity-learner.js +48 -5
  16. package/dist/learning/store.d.ts +4 -2
  17. package/dist/pii-masker.js +2 -1
  18. package/dist/pii-shield.js +2 -1
  19. package/dist/postgres/index.d.ts +20 -0
  20. package/dist/postgres/index.js +14 -0
  21. package/dist/redaction.d.ts +16 -2
  22. package/dist/redaction.js +22 -10
  23. package/dist/server/config.d.ts +5 -8
  24. package/dist/server/config.js +77 -220
  25. package/dist/server/connections.d.ts +34 -0
  26. package/dist/server/connections.js +99 -0
  27. package/dist/server/doctor.d.ts +28 -0
  28. package/dist/server/doctor.js +438 -0
  29. package/dist/server/env.d.ts +62 -0
  30. package/dist/server/env.js +197 -0
  31. package/dist/server/index.d.ts +1 -0
  32. package/dist/server/index.js +1 -0
  33. package/dist/testing/conformance.js +8 -3
  34. package/dist/vault/encrypted-vault.d.ts +39 -2
  35. package/dist/vault/encrypted-vault.js +96 -13
  36. package/dist/vault/memory-vault-storage.d.ts +8 -1
  37. package/dist/vault/memory-vault-storage.js +20 -8
  38. package/dist/vault-redis/index.d.ts +14 -0
  39. package/dist/vault-redis/index.js +8 -0
  40. package/docs/openapi.yaml +8 -2
  41. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.3.0] - 2026-11-22
9
+
10
+ ### Added
11
+
12
+ - `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.
13
+ - `postgresVault({ query, key, previousKeys?, table? })` in `/postgres` and `redisVault({ client, key, previousKeys?, prefix? })` in `/vault-redis` build the vault for `createPiiShield()`.
14
+ - `MemoryVaultStorage.purgeExpired()` deletes expired entries and returns their number.
15
+ - `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.
16
+ - 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.
17
+ - `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.
18
+ - `pii-shield generate-key` prints a new vault key (base64). Examples now read the key with `vaultKeyFromEnv()` instead of generating one at run time.
19
+ - `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.
20
+ - `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`.
21
+
22
+ ### Changed
23
+
24
+ - **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.
25
+ - `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.
26
+ - `EntityLearner.detector()` returns the same detector instance on every call.
27
+
8
28
  ## [0.2.0] - 2026-11-21
9
29
 
10
30
  ### Added
@@ -46,7 +66,8 @@ Privacy and crash bugs of the PHP package are fixed rather than reproduced: name
46
66
  - `@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
67
  - `pii-shield` CLI: `pii-shield serve`, `pii-shield mcp [--http]`, configured with PHP's environment variables.
48
68
 
49
- [Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.2.0...HEAD
69
+ [Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.3.0...HEAD
70
+ [0.3.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.2.0...v0.3.0
50
71
  [0.2.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.1...v0.2.0
51
72
  [0.1.1]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.0...v0.1.1
52
73
  [0.1.0]: https://github.com/waswrongassembled/pii-shield-js/releases/tag/v0.1.0
package/README.md CHANGED
@@ -44,8 +44,12 @@ 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
 
51
55
  ## Masking
@@ -67,12 +71,63 @@ masker.mask('E-Mail j.beispielmann@example.com, IBAN AT61 1904 3002 3457 3201');
67
71
 
68
72
  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
73
 
74
+ The key is 32 random bytes, base64-encoded. Create it once and keep it in your secret store, never in code:
75
+
76
+ ```sh
77
+ npx @waswrongassembled/pii-shield generate-key # or: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
78
+ ```
79
+
80
+ `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)):
81
+
70
82
  ```ts
71
- import { EncryptedVault, MemoryVaultStorage, parseVaultKey, PiiShield } from '@waswrongassembled/pii-shield';
83
+ import pg from 'pg';
84
+ import { createPiiShield, previousVaultKeysFromEnv, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
85
+ import { PostgresCustomEntityStore, postgresVault } from '@waswrongassembled/pii-shield/postgres';
86
+
87
+ const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
88
+ const query = pool.query.bind(pool);
89
+
90
+ const shield = await createPiiShield({
91
+ // PII_SHIELD_VAULT_KEY, PII_SHIELD_VAULT_PREVIOUS_KEYS; a clear error (without the value) if invalid
92
+ vault: postgresVault({ query, key: vaultKeyFromEnv(), previousKeys: previousVaultKeysFromEnv() }),
93
+ learnedTypes: new PostgresCustomEntityStore({ query }),
94
+ });
95
+ for (const note of shield.notes) console.warn(note);
96
+
97
+ const { redactedText, vaultId } = await shield.redactToVault('Herrn\nJohann Beispielmann\nSVNR 4568 150392');
98
+ // ... later, in any process with the same key and database:
99
+ const { text } = await shield.restoreFromVault(redactedText, vaultId);
100
+ await shield.forget(vaultId);
101
+
102
+ await shield.learner.learn({
103
+ name: 'INSURANCE_NUMBER',
104
+ description: 'Polizzennummer',
105
+ examples: ['VN-2026-000417', 'VN-2025-123456'],
106
+ });
107
+
108
+ // On shutdown: stops the purge timer (and waits for a running purge); the pool stays yours.
109
+ await shield.close();
110
+ await pool.end();
111
+ ```
112
+
113
+ What it does for you:
114
+
115
+ - **Short TTL:** mappings live 900 s (`vaultTtl`; `new PiiShield()` defaults to 3600 s), enough for a model's answer.
116
+ - **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.
117
+ - **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`).
118
+ - **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).
119
+ - **Fails at start** when a table is missing or the connection does not work.
120
+
121
+ 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.
122
+
123
+ The building blocks, for full control:
124
+
125
+ ```ts
126
+ import { EncryptedVault, MemoryVaultStorage, PiiShield, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
72
127
 
73
128
  const shield = new PiiShield({
74
- // 32 bytes, base64; generateVaultKey() creates one
75
- vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: parseVaultKey(process.env.VAULT_KEY ?? '') }),
129
+ // reads PII_SHIELD_VAULT_KEY; throws a clear error (without the value) if it is missing or invalid
130
+ vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: vaultKeyFromEnv() }),
76
131
  vaultTtl: 900,
77
132
  });
78
133
 
@@ -86,21 +141,44 @@ For several processes use Redis:
86
141
 
87
142
  ```ts
88
143
  import { Redis } from 'ioredis';
89
- import { EncryptedVault, generateVaultKey } from '@waswrongassembled/pii-shield';
144
+ import { EncryptedVault, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
90
145
  import { RedisVaultStorage } from '@waswrongassembled/pii-shield/vault-redis';
91
146
 
92
147
  const vault = new EncryptedVault({
93
148
  storage: new RedisVaultStorage({ client: new Redis('redis://127.0.0.1:6379') }),
94
- key: generateVaultKey(), // use the same configured key in every process
149
+ key: vaultKeyFromEnv(), // the same key in every process
95
150
  });
96
151
  ```
97
152
 
153
+ `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.
154
+
155
+ ### Key rotation
156
+
157
+ `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).
158
+
159
+ ```ts
160
+ import {
161
+ EncryptedVault,
162
+ MemoryVaultStorage,
163
+ previousVaultKeysFromEnv,
164
+ vaultKeyFromEnv,
165
+ } from '@waswrongassembled/pii-shield';
166
+
167
+ const vault = new EncryptedVault({
168
+ storage: new MemoryVaultStorage(),
169
+ key: vaultKeyFromEnv(), // PII_SHIELD_VAULT_KEY: the new key
170
+ previousKeys: previousVaultKeysFromEnv(), // PII_SHIELD_VAULT_PREVIOUS_KEYS: old keys, comma-separated
171
+ });
172
+ ```
173
+
174
+ 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)).
175
+
98
176
  ## Learned entity types
99
177
 
100
178
  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
179
 
102
180
  ```ts
103
- import { defaultDetectors, EntityLearner, JsonFileCustomEntityStore, PiiShield } from '@waswrongassembled/pii-shield';
181
+ import { EntityLearner, JsonFileCustomEntityStore, PiiShield } from '@waswrongassembled/pii-shield';
104
182
 
105
183
  const learner = await EntityLearner.create({ store: new JsonFileCustomEntityStore('var/learned-types.json') });
106
184
  const { type } = await learner.learn({
@@ -110,22 +188,38 @@ const { type } = await learner.learn({
110
188
  });
111
189
  type.pattern; // 'VN-\\d{4}-\\d{6}'
112
190
 
113
- const shield = new PiiShield({ detectors: [...defaultDetectors(), learner.detector()] });
191
+ const shield = new PiiShield({ learner }); // the default detectors plus the learned types
114
192
  shield.redact('Polizze VN-2026-000999').redactedText; // 'Polizze ⟦INSURANCE_NUMBER_1⟧'
115
193
  ```
116
194
 
195
+ `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)).
196
+
197
+ 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:
198
+
199
+ ```ts
200
+ import { EntityLearner, JsonFileCustomEntityStore } from '@waswrongassembled/pii-shield';
201
+
202
+ const learner = await EntityLearner.create({
203
+ store: new JsonFileCustomEntityStore('var/learned-types.json'),
204
+ keepExamples: false,
205
+ });
206
+ await learner.dropExamples(); // once: strips types stored before, returns { stripped, kept }
207
+ ```
208
+
209
+ 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.
210
+
117
211
  ## Stores: PostgreSQL and your own
118
212
 
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.
213
+ 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
214
 
121
215
  ```ts
122
216
  import pg from 'pg';
123
- import { EncryptedVault, generateVaultKey } from '@waswrongassembled/pii-shield';
217
+ import { EncryptedVault, vaultKeyFromEnv } from '@waswrongassembled/pii-shield';
124
218
  import { PostgresCustomEntityStore, PostgresVaultStorage } from '@waswrongassembled/pii-shield/postgres';
125
219
 
126
220
  const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
127
221
  const storage = new PostgresVaultStorage({ query: pool.query.bind(pool) });
128
- const vault = new EncryptedVault({ storage, key: generateVaultKey() }); // the database only sees ciphertext
222
+ const vault = new EncryptedVault({ storage, key: vaultKeyFromEnv() }); // the database only sees ciphertext
129
223
  const store = new PostgresCustomEntityStore({ query: pool.query.bind(pool) });
130
224
  await storage.purgeExpired(); // run regularly: expired rows must really be deleted
131
225
  ```
@@ -204,7 +298,7 @@ PII_SERVICE_TOKEN=$(openssl rand -hex 24) PII_SERVICE_VAULT_KEY=... \
204
298
  npx @waswrongassembled/pii-shield serve --host 0.0.0.0 --port 8080
205
299
  ```
206
300
 
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).
301
+ 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
302
 
209
303
  ## MCP server
210
304
 
@@ -218,15 +312,15 @@ claude mcp add pii-shield -- npx @waswrongassembled/pii-shield mcp
218
312
  import {
219
313
  EncryptedVault,
220
314
  EntityLearner,
221
- generateVaultKey,
222
315
  InMemoryCustomEntityStore,
223
316
  MemoryVaultStorage,
317
+ vaultKeyFromEnv,
224
318
  } from '@waswrongassembled/pii-shield';
225
319
  import { serveStdio } from '@waswrongassembled/pii-shield/mcp';
226
320
  import { ServiceApi } from '@waswrongassembled/pii-shield/server';
227
321
 
228
322
  const api = new ServiceApi({
229
- vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: generateVaultKey() }),
323
+ vault: new EncryptedVault({ storage: new MemoryVaultStorage(), key: vaultKeyFromEnv() }),
230
324
  learner: await EntityLearner.create({ store: new InMemoryCustomEntityStore() }),
231
325
  });
232
326
  await serveStdio(api); // log to stderr only: stdout belongs to the protocol
@@ -248,8 +342,8 @@ Not shared: `Entity.offset` is a UTF-16 index (`text.slice(offset, offset + valu
248
342
  ## Limits and security
249
343
 
250
344
  - 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`). 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.
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.
345
+ - 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.
346
+ - 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
347
  - `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
348
  - 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
349
 
package/dist/cli.js CHANGED
@@ -1,16 +1,21 @@
1
1
  /**
2
- * The `pii-shield` command: the HTTP service (`serve`) and the MCP server (`mcp`), configured from
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
- const { name = 'Error', code } = (error ?? {});
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
+ }
@@ -1,11 +1,18 @@
1
1
  import { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction } from './detector.js';
2
2
  import { type Entity } from './entity.js';
3
+ import type { EntityLearner } from './learning/entity-learner.js';
3
4
  export interface EntityExtractorOptions {
4
5
  /**
5
6
  * Detectors to run; defaults to defaultDetectors(). Async detectors (e.g. ModelDetector) only work
6
7
  * with the async APIs (extractAsync(), redactAsync(), redactToVault(), maskAsync()).
7
8
  */
8
9
  detectors?: Iterable<Detector | DetectorFunction | AsyncDetector>;
10
+ /**
11
+ * Also detect the patterns of these learned types: adds `learner.detector()` after the detectors
12
+ * (unless it is already among them). It reads the learner's snapshot, which learn() and forget()
13
+ * update; call `learner.refresh()` to pick up types other processes learned.
14
+ */
15
+ learner?: Pick<EntityLearner, 'detector'>;
9
16
  /** Values that are never treated as PII (exact match). */
10
17
  allowlist?: Iterable<string>;
11
18
  }
@@ -63,7 +63,12 @@ export class EntityExtractor {
63
63
  #detectors;
64
64
  #allowlist;
65
65
  constructor(options = {}) {
66
- this.#detectors = [...(options.detectors ?? defaultDetectors())];
66
+ const detectors = [...(options.detectors ?? defaultDetectors())];
67
+ const learned = options.learner?.detector();
68
+ if (learned !== undefined && !detectors.includes(learned)) {
69
+ detectors.push(learned);
70
+ }
71
+ this.#detectors = detectors;
67
72
  this.#allowlist = new Set(options.allowlist);
68
73
  }
69
74
  /** Whether a detector needs the async APIs. */
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * The public API is ported phase by phase, see docs/PLAN.md.
5
5
  */
6
6
  export { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction, isAsyncDetector, type Validator, } from './detector.js';
7
+ export { type BackgroundTask, createPiiShield, type CreatePiiShieldOptions, type ManagedPiiShield, type VaultSetup, } from './create-pii-shield.js';
7
8
  export { AtSvnrDetector } from './detectors/at-svnr.js';
8
9
  export { BirthDateDetector } from './detectors/birth-date.js';
9
10
  export { EmailDetector, type ContactDetectorOptions } from './detectors/email.js';
@@ -19,8 +20,8 @@ export { defaultDetectors, EntityExtractor, surname, type EntityExtractorOptions
19
20
  export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
21
  export { DetectionError, type DetectionErrorCode, LearningError, type LearningErrorCode, PiiShieldError, VaultError, type VaultErrorCode, } from './errors.js';
21
22
  export { CustomEntityDetector, LearnedTypesDetector } from './learning/custom-entity-detector.js';
22
- export { CUSTOM_ENTITY_TYPE_LIMITS, type CustomEntityType, customEntityTypeFromJSON, type CustomEntityTypeInit, defineCustomEntityType, } from './learning/custom-entity-type.js';
23
- export { EntityLearner, type EntityLearnerOptions, type LearningResult } from './learning/entity-learner.js';
23
+ export { CUSTOM_ENTITY_TYPE_LIMITS, type CustomEntityType, customEntityTypeFromJSON, type CustomEntityTypeInit, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
24
+ export { type DropExamplesResult, EntityLearner, type EntityLearnerOptions, type LearningResult, } from './learning/entity-learner.js';
24
25
  export { JsonFileCustomEntityStore, type JsonFileCustomEntityStoreOptions } from './learning/json-file-store.js';
25
26
  export { patternViolation } from './learning/pattern-grammar.js';
26
27
  export { learnPattern } from './learning/pattern-learner.js';
@@ -36,7 +37,7 @@ export { foundTypes, type PlaceholderMapping, type RedactionResult, type Redacto
36
37
  export { isValidAtSvnr } from './validators/at-svnr.js';
37
38
  export { isValidDeTaxId } from './validators/de-tax-id.js';
38
39
  export { isValidIban } from './validators/iban.js';
39
- export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
40
+ export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
40
41
  export { InMemoryVault, type InMemoryVaultOptions } from './vault/in-memory-vault.js';
41
42
  export { MemoryVaultStorage, type MemoryVaultStorageOptions } from './vault/memory-vault-storage.js';
42
43
  export type { Clock, Vault, VaultStorage } from './vault/vault.js';
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * The public API is ported phase by phase, see docs/PLAN.md.
5
5
  */
6
6
  export { isAsyncDetector, } from './detector.js';
7
+ export { createPiiShield, } from './create-pii-shield.js';
7
8
  export { AtSvnrDetector } from './detectors/at-svnr.js';
8
9
  export { BirthDateDetector } from './detectors/birth-date.js';
9
10
  export { EmailDetector } from './detectors/email.js';
@@ -19,8 +20,8 @@ export { defaultDetectors, EntityExtractor, surname } from './entity-extractor.j
19
20
  export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
21
  export { DetectionError, LearningError, PiiShieldError, VaultError, } from './errors.js';
21
22
  export { CustomEntityDetector, LearnedTypesDetector } from './learning/custom-entity-detector.js';
22
- export { CUSTOM_ENTITY_TYPE_LIMITS, customEntityTypeFromJSON, defineCustomEntityType, } from './learning/custom-entity-type.js';
23
- export { EntityLearner } from './learning/entity-learner.js';
23
+ export { CUSTOM_ENTITY_TYPE_LIMITS, customEntityTypeFromJSON, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
24
+ export { EntityLearner, } from './learning/entity-learner.js';
24
25
  export { JsonFileCustomEntityStore } from './learning/json-file-store.js';
25
26
  export { patternViolation } from './learning/pattern-grammar.js';
26
27
  export { learnPattern } from './learning/pattern-learner.js';
@@ -35,6 +36,6 @@ export { foundTypes, restorePlaceholders, } from './redaction.js';
35
36
  export { isValidAtSvnr } from './validators/at-svnr.js';
36
37
  export { isValidDeTaxId } from './validators/de-tax-id.js';
37
38
  export { isValidIban } from './validators/iban.js';
38
- export { EncryptedVault, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
39
+ export { EncryptedVault, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
39
40
  export { InMemoryVault } from './vault/in-memory-vault.js';
40
41
  export { MemoryVaultStorage } from './vault/memory-vault-storage.js';