@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
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the service's environment variables (docs/server.md). serviceFromEnv() and the configuration
|
|
3
|
+
* check (`pii-shield doctor`, checkServiceConfig()) share these functions, so they cannot drift apart.
|
|
4
|
+
* Every error is a ConfigError whose message names the variable, never its value.
|
|
5
|
+
*/
|
|
6
|
+
import { ModelDetector } from '../model/model-detector.js';
|
|
7
|
+
import { parseVaultKey, previousVaultKeysFromEnv } from '../vault/encrypted-vault.js';
|
|
8
|
+
import { DEFAULT_PURGE_INTERVAL, MAX_PURGE_INTERVAL } from '../internal/background.js';
|
|
9
|
+
import { ServiceApi } from '../service/service-api.js';
|
|
10
|
+
import { DEFAULT_MAX_BODY_BYTES } from './http-server.js';
|
|
11
|
+
import { MODEL_PROVIDERS, providerModel } from './model-providers.js';
|
|
12
|
+
/** A configuration problem; the message names the variable, never a secret. */
|
|
13
|
+
export class ConfigError extends Error {
|
|
14
|
+
name = 'ConfigError';
|
|
15
|
+
}
|
|
16
|
+
export function envGetter(env) {
|
|
17
|
+
return (name) => {
|
|
18
|
+
const value = env[name];
|
|
19
|
+
return value === undefined || value === '' ? undefined : value;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export function integer(value, name, fallback, min = 1) {
|
|
23
|
+
if (value === undefined) {
|
|
24
|
+
return fallback;
|
|
25
|
+
}
|
|
26
|
+
const n = Number(value);
|
|
27
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min) {
|
|
28
|
+
throw new ConfigError(`${name} must be an integer of at least ${String(min)}.`);
|
|
29
|
+
}
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
/** PII_SERVICE_VAULT_KEY decoded, or undefined when not set. The caller wipes it after use. */
|
|
33
|
+
export function readVaultKey(get) {
|
|
34
|
+
const keyBase64 = get('PII_SERVICE_VAULT_KEY');
|
|
35
|
+
if (keyBase64 === undefined) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
return parseVaultKey(keyBase64);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new ConfigError('PII_SERVICE_VAULT_KEY must be 32 bytes, base64-encoded.');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** PII_SERVICE_VAULT_PREVIOUS_KEYS decoded (`[]` when not set). The caller wipes them after use. */
|
|
46
|
+
export function readPreviousVaultKeys(get, env) {
|
|
47
|
+
if (get('PII_SERVICE_VAULT_PREVIOUS_KEYS') === undefined) {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
if (get('PII_SERVICE_VAULT_KEY') === undefined) {
|
|
51
|
+
throw new ConfigError('PII_SERVICE_VAULT_PREVIOUS_KEYS needs PII_SERVICE_VAULT_KEY (the current key).');
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
return previousVaultKeysFromEnv('PII_SERVICE_VAULT_PREVIOUS_KEYS', env);
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
// The message names the variable and the entry's position, never a key.
|
|
58
|
+
throw new ConfigError(e instanceof Error ? e.message : String(e));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Both keys, decoded. The caller wipes them after use. */
|
|
62
|
+
export function readVaultKeys(get, env) {
|
|
63
|
+
const key = readVaultKey(get);
|
|
64
|
+
try {
|
|
65
|
+
return { key, previousKeys: readPreviousVaultKeys(get, env) };
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
key?.fill(0);
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export function readVaultStore(get) {
|
|
73
|
+
const store = get('PII_SERVICE_VAULT_STORE') ?? 'memory';
|
|
74
|
+
if (store !== 'memory' && store !== 'redis' && store !== 'postgres') {
|
|
75
|
+
throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory", "redis" or "postgres".');
|
|
76
|
+
}
|
|
77
|
+
return store;
|
|
78
|
+
}
|
|
79
|
+
/** A persistent vault store needs a fixed key: a random one could not read the entries after a restart. */
|
|
80
|
+
export function assertVaultKeyFor(store, hasKey) {
|
|
81
|
+
if (store !== 'memory' && !hasKey) {
|
|
82
|
+
throw new ConfigError(`The ${store} vault store needs PII_SERVICE_VAULT_KEY, or mappings cannot be read after a restart.`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function readVaultTtl(get) {
|
|
86
|
+
return integer(get('PII_SERVICE_VAULT_TTL'), 'PII_SERVICE_VAULT_TTL', ServiceApi.DEFAULT_VAULT_TTL);
|
|
87
|
+
}
|
|
88
|
+
/** Seconds between purges of expired Postgres vault rows; 0 = off. */
|
|
89
|
+
export function readPurgeInterval(get) {
|
|
90
|
+
const interval = integer(get('PII_SERVICE_VAULT_PURGE_INTERVAL'), 'PII_SERVICE_VAULT_PURGE_INTERVAL', DEFAULT_PURGE_INTERVAL, 0);
|
|
91
|
+
if (interval > MAX_PURGE_INTERVAL) {
|
|
92
|
+
throw new ConfigError('PII_SERVICE_VAULT_PURGE_INTERVAL must be at most 86400 (one day).');
|
|
93
|
+
}
|
|
94
|
+
return interval;
|
|
95
|
+
}
|
|
96
|
+
export function readLearnedStore(get) {
|
|
97
|
+
const file = get('PII_SERVICE_LEARNED_TYPES');
|
|
98
|
+
const kind = get('PII_SERVICE_LEARNED_STORE') ?? (file === undefined ? 'memory' : 'file');
|
|
99
|
+
if (kind !== 'file' && kind !== 'memory' && kind !== 'redis' && kind !== 'postgres') {
|
|
100
|
+
throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory", "redis" or "postgres".');
|
|
101
|
+
}
|
|
102
|
+
if (kind === 'file' && file === undefined) {
|
|
103
|
+
throw new ConfigError('Set PII_SERVICE_LEARNED_TYPES to the JSON file of learned types.');
|
|
104
|
+
}
|
|
105
|
+
return { kind, file };
|
|
106
|
+
}
|
|
107
|
+
export function readKeepExamples(get) {
|
|
108
|
+
const keepExamples = get('PII_SERVICE_LEARNED_KEEP_EXAMPLES') ?? 'true';
|
|
109
|
+
if (keepExamples !== 'true' && keepExamples !== 'false') {
|
|
110
|
+
throw new ConfigError('PII_SERVICE_LEARNED_KEEP_EXAMPLES must be "true" or "false".');
|
|
111
|
+
}
|
|
112
|
+
return keepExamples === 'true';
|
|
113
|
+
}
|
|
114
|
+
export function readRedisUrl(get) {
|
|
115
|
+
const url = get('PII_SERVICE_REDIS_URL') ?? get('PII_DEMO_REDIS_URL');
|
|
116
|
+
if (url === undefined) {
|
|
117
|
+
throw new ConfigError('Set PII_SERVICE_REDIS_URL to use the redis store.');
|
|
118
|
+
}
|
|
119
|
+
return url;
|
|
120
|
+
}
|
|
121
|
+
/** PII_SERVICE_DATABASE_URL, checked to be a postgres URL (the message never quotes it: it holds the password). */
|
|
122
|
+
export function readDatabaseUrl(get) {
|
|
123
|
+
const url = get('PII_SERVICE_DATABASE_URL');
|
|
124
|
+
if (url === undefined) {
|
|
125
|
+
throw new ConfigError('Set PII_SERVICE_DATABASE_URL to use the postgres store.');
|
|
126
|
+
}
|
|
127
|
+
if (!/^postgres(?:ql)?:\/\//.test(url) || !URL.canParse(url)) {
|
|
128
|
+
throw new ConfigError('PII_SERVICE_DATABASE_URL must be a postgres:// or postgresql:// URL.');
|
|
129
|
+
}
|
|
130
|
+
return url;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The model provider (PII_SERVICE_MODEL_PROVIDER and its settings), or undefined without one. Refuses an
|
|
134
|
+
* external provider without PII_SERVICE_ACKNOWLEDGE_EXTERNAL=true.
|
|
135
|
+
*/
|
|
136
|
+
export function readModel(get) {
|
|
137
|
+
const provider = get('PII_SERVICE_MODEL_PROVIDER');
|
|
138
|
+
if (provider === undefined) {
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
if (!MODEL_PROVIDERS.includes(provider)) {
|
|
142
|
+
throw new ConfigError(`PII_SERVICE_MODEL_PROVIDER must be one of ${MODEL_PROVIDERS.join(', ')}.`);
|
|
143
|
+
}
|
|
144
|
+
const keys = {
|
|
145
|
+
ollama: undefined,
|
|
146
|
+
generic: get('PII_SERVICE_MODEL_KEY') ?? get('PII_DEMO_GENERIC_KEY'),
|
|
147
|
+
mistral: get('MISTRAL_API_KEY'),
|
|
148
|
+
openai: get('OPENAI_API_KEY'),
|
|
149
|
+
anthropic: get('ANTHROPIC_API_KEY'),
|
|
150
|
+
};
|
|
151
|
+
const typed = provider;
|
|
152
|
+
let resolved;
|
|
153
|
+
try {
|
|
154
|
+
resolved = providerModel({
|
|
155
|
+
provider: typed,
|
|
156
|
+
model: get('PII_SERVICE_MODEL'),
|
|
157
|
+
endpoint: get('PII_SERVICE_MODEL_URL') ?? (typed === 'ollama' ? get('PII_DEMO_OLLAMA_URL') : undefined),
|
|
158
|
+
apiKey: keys[typed],
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
throw new ConfigError(e instanceof Error ? e.message : String(e));
|
|
163
|
+
}
|
|
164
|
+
const acknowledged = get('PII_SERVICE_ACKNOWLEDGE_EXTERNAL') === 'true';
|
|
165
|
+
if (resolved.location === 'external' && !acknowledged) {
|
|
166
|
+
throw new ConfigError(`${provider} is an external provider: detection sends the unredacted text there. Set PII_SERVICE_ACKNOWLEDGE_EXTERNAL=true after checking the data processing agreement and third-country transfers.`);
|
|
167
|
+
}
|
|
168
|
+
const config = {
|
|
169
|
+
provider: typed,
|
|
170
|
+
model: resolved.model,
|
|
171
|
+
location: resolved.location,
|
|
172
|
+
acknowledged,
|
|
173
|
+
// Self-hosted models answer only when done; allow for large models on modest hardware (PHP: 170 s).
|
|
174
|
+
timeout: integer(get('PII_SERVICE_MODEL_TIMEOUT'), 'PII_SERVICE_MODEL_TIMEOUT', 170) * 1000,
|
|
175
|
+
};
|
|
176
|
+
try {
|
|
177
|
+
// Fail at start, not per request.
|
|
178
|
+
new ModelDetector({
|
|
179
|
+
model: config.model,
|
|
180
|
+
location: config.location,
|
|
181
|
+
acknowledgeExternalTransfer: acknowledged,
|
|
182
|
+
timeout: config.timeout,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
throw new ConfigError(e instanceof Error ? e.message : String(e));
|
|
187
|
+
}
|
|
188
|
+
return config;
|
|
189
|
+
}
|
|
190
|
+
/** Listen address and request limits. */
|
|
191
|
+
export function readListen(get) {
|
|
192
|
+
return {
|
|
193
|
+
maxBodyBytes: integer(get('PII_SERVICE_MAX_BODY_BYTES'), 'PII_SERVICE_MAX_BODY_BYTES', DEFAULT_MAX_BODY_BYTES),
|
|
194
|
+
host: get('PII_SERVICE_HOST') ?? '127.0.0.1',
|
|
195
|
+
port: integer(get('PII_SERVICE_PORT'), 'PII_SERVICE_PORT', 8088, 0),
|
|
196
|
+
};
|
|
197
|
+
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* PHP service. The `pii-shield` CLI (`pii-shield serve`, `pii-shield mcp`) is built on it.
|
|
5
5
|
*/
|
|
6
6
|
export { createRequestListener, DEFAULT_MAX_BODY_BYTES, MCP_BROWSER_ORIGINS, type McpHttpHandler, openapiDocument, type PiiShieldServer, type RequestListenerOptions, type ServerOptions, startServer, } from './http-server.js';
|
|
7
|
+
export { checkServiceConfig, type CheckServiceConfigOptions, type ConfigFinding, type FindingSeverity, formatFindings, } from './doctor.js';
|
|
7
8
|
export { type JsonBody, parseJsonBody, type ParsedBody } from '../service/json-body.js';
|
|
8
9
|
export { defaultGateway, localPeerMatcher, splitList } from '../service/local-peer.js';
|
|
9
10
|
export { ServiceApi, type ServiceApiOptions, type ServiceOperation, type ServiceRequest, type ServiceResponse, } from '../service/service-api.js';
|
package/dist/server/index.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* PHP service. The `pii-shield` CLI (`pii-shield serve`, `pii-shield mcp`) is built on it.
|
|
5
5
|
*/
|
|
6
6
|
export { createRequestListener, DEFAULT_MAX_BODY_BYTES, MCP_BROWSER_ORIGINS, openapiDocument, startServer, } from './http-server.js';
|
|
7
|
+
export { checkServiceConfig, formatFindings, } from './doctor.js';
|
|
7
8
|
export { parseJsonBody } from '../service/json-body.js';
|
|
8
9
|
export { defaultGateway, localPeerMatcher, splitList } from '../service/local-peer.js';
|
|
9
10
|
export { ServiceApi, } from '../service/service-api.js';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { isAsyncDetector } from '../detector.js';
|
|
3
3
|
import { EmailDetector } from '../detectors/email.js';
|
|
4
|
+
import { KnownValuesDetector } from '../detectors/known-values.js';
|
|
4
5
|
import { PhoneDetector } from '../detectors/phone.js';
|
|
5
6
|
import { defaultDetectors } from '../entity-extractor.js';
|
|
6
7
|
import { isEntityType } from '../entity-type.js';
|
|
@@ -155,6 +156,7 @@ export class ServiceApi {
|
|
|
155
156
|
async #redact(body, options) {
|
|
156
157
|
const detectors = await this.#detectors(body);
|
|
157
158
|
const allowlist = strings(body, 'allowlist');
|
|
159
|
+
detectors.push(...knownValues(body));
|
|
158
160
|
const text = textOf(body);
|
|
159
161
|
const shield = new PiiShield({ detectors, vault: this.#vault, vaultTtl: this.#vaultTtl, allowlist });
|
|
160
162
|
const redaction = await shield.redactToVault(text, options);
|
|
@@ -190,6 +192,7 @@ export class ServiceApi {
|
|
|
190
192
|
async #mask(body, options) {
|
|
191
193
|
const detectors = await this.#detectors(body);
|
|
192
194
|
const allowlist = strings(body, 'allowlist');
|
|
195
|
+
detectors.push(...knownValues(body));
|
|
193
196
|
const text = textOf(body);
|
|
194
197
|
return ok({ text: await new PiiMasker({ detectors, allowlist }).maskAsync(text, options) });
|
|
195
198
|
}
|
|
@@ -293,6 +296,28 @@ function strings(body, key) {
|
|
|
293
296
|
}
|
|
294
297
|
return items;
|
|
295
298
|
}
|
|
299
|
+
/**
|
|
300
|
+
* The detector for `knownValues` ([{ value, type }]), or none. Added after the `types` filter, so known
|
|
301
|
+
* values always apply. Messages never contain a value.
|
|
302
|
+
*/
|
|
303
|
+
function knownValues(body) {
|
|
304
|
+
const list = field(body, 'knownValues');
|
|
305
|
+
if (list === undefined) {
|
|
306
|
+
return [];
|
|
307
|
+
}
|
|
308
|
+
if (!Array.isArray(list)) {
|
|
309
|
+
throw new BadRequest('"knownValues" must be a list of {"value", "type"} objects.');
|
|
310
|
+
}
|
|
311
|
+
try {
|
|
312
|
+
return [new KnownValuesDetector(list)];
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
if (e instanceof TypeError) {
|
|
316
|
+
throw new BadRequest(`"knownValues": ${e.message}`);
|
|
317
|
+
}
|
|
318
|
+
throw e;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
296
321
|
function constantTimeEquals(expected, actual) {
|
|
297
322
|
const digest = (s) => createHash('sha256').update(s, 'utf8').digest();
|
|
298
323
|
return timingSafeEqual(digest(expected), digest(actual));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import assert, { AssertionError } from 'node:assert/strict';
|
|
2
2
|
import { randomBytes } from 'node:crypto';
|
|
3
3
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
-
import { defineCustomEntityType } from '../learning/custom-entity-type.js';
|
|
4
|
+
import { defineCustomEntityType, withoutExamples } from '../learning/custom-entity-type.js';
|
|
5
5
|
/**
|
|
6
6
|
* Checks that a VaultStorage keeps the contract documented on the interface: unknown and expired ids
|
|
7
7
|
* give null, payloads are binary-safe and copied, put() overwrites, remove() of an unknown id is a
|
|
@@ -211,10 +211,15 @@ export async function verifyCustomEntityStore(factory, options = {}) {
|
|
|
211
211
|
},
|
|
212
212
|
},
|
|
213
213
|
{
|
|
214
|
-
name: 'save() then get() and all() give the type back unchanged',
|
|
214
|
+
name: 'save() then get() and all() give the type back unchanged (also without examples)',
|
|
215
215
|
run: async () => {
|
|
216
216
|
const store = await factory();
|
|
217
|
-
|
|
217
|
+
// A type stored without examples (EntityLearner option keepExamples: false) must load as well.
|
|
218
|
+
const types = [
|
|
219
|
+
syntheticType('TEST_CODE'),
|
|
220
|
+
richType(),
|
|
221
|
+
withoutExamples({ ...richType(), name: 'BARE_TEST_CODE' }),
|
|
222
|
+
];
|
|
218
223
|
for (const type of types) {
|
|
219
224
|
await store.save(type);
|
|
220
225
|
}
|
|
@@ -3,8 +3,17 @@ import { type Vault, type VaultStorage } from './vault.js';
|
|
|
3
3
|
export interface EncryptedVaultOptions {
|
|
4
4
|
/** Where the ciphertext goes; it never sees clear text. */
|
|
5
5
|
storage: VaultStorage;
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* 32 raw bytes, see vaultKeyFromEnv() and parseVaultKey(). Encrypts every new entry and decrypts.
|
|
8
|
+
* The vault keeps its own copy.
|
|
9
|
+
*/
|
|
7
10
|
key: Uint8Array;
|
|
11
|
+
/**
|
|
12
|
+
* Keys of earlier rotations (32 raw bytes each, see previousVaultKeysFromEnv()): only for reading
|
|
13
|
+
* entries written before the rotation, tried in order after `key`. Drop a key once the longest TTL
|
|
14
|
+
* since the rotation has passed. The vault keeps its own copies. Node only, PHP has a single key.
|
|
15
|
+
*/
|
|
16
|
+
previousKeys?: readonly Uint8Array[] | undefined;
|
|
8
17
|
}
|
|
9
18
|
/**
|
|
10
19
|
* Encrypts mappings with XChaCha20-Poly1305 before they reach the storage. Byte-compatible with PHP's
|
|
@@ -13,6 +22,10 @@ export interface EncryptedVaultOptions {
|
|
|
13
22
|
*
|
|
14
23
|
* The vault id is bound as associated data, so a ciphertext copied to another id fails to decrypt.
|
|
15
24
|
* This is the only supported way to persist mappings.
|
|
25
|
+
*
|
|
26
|
+
* Key rotation (Node only): pass the new `key` and the old one in `previousKeys`. New entries are
|
|
27
|
+
* encrypted with `key`; reading tries `key`, then each previous key. Payloads stay PHP's format, so PHP
|
|
28
|
+
* reads every entry written with the key it has.
|
|
16
29
|
*/
|
|
17
30
|
export declare class EncryptedVault implements Vault {
|
|
18
31
|
#private;
|
|
@@ -21,13 +34,36 @@ export declare class EncryptedVault implements Vault {
|
|
|
21
34
|
fetch(id: string): Promise<PlaceholderMapping | null>;
|
|
22
35
|
delete(id: string): Promise<void>;
|
|
23
36
|
}
|
|
24
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* A new random key (32 raw bytes), for creating a key once (`npx @waswrongassembled/pii-shield generate-key`
|
|
39
|
+
* prints one base64-encoded). Keep it as a secret and read it with vaultKeyFromEnv() or parseVaultKey(); a
|
|
40
|
+
* key generated at run time cannot read entries after a restart or in another process.
|
|
41
|
+
*/
|
|
25
42
|
export declare function generateVaultKey(): Uint8Array;
|
|
26
43
|
/**
|
|
27
44
|
* Decodes a base64 key (e.g. from an environment variable or a secret file; surrounding whitespace is
|
|
28
45
|
* ignored). Throws without echoing the input.
|
|
29
46
|
*/
|
|
30
47
|
export declare function parseVaultKey(base64: string): Uint8Array;
|
|
48
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
49
|
+
/**
|
|
50
|
+
* Reads the vault key (32 bytes, base64) from an environment variable, default `PII_SHIELD_VAULT_KEY`
|
|
51
|
+
* (the service reads `PII_SERVICE_VAULT_KEY`). Create a key once with
|
|
52
|
+
* `npx @waswrongassembled/pii-shield generate-key`.
|
|
53
|
+
*
|
|
54
|
+
* @throws TypeError if the variable is missing, empty or not a 32-byte base64 key; the message names the
|
|
55
|
+
* variable, never its value
|
|
56
|
+
*/
|
|
57
|
+
export declare function vaultKeyFromEnv(name?: string, env?: Env): Uint8Array;
|
|
58
|
+
/**
|
|
59
|
+
* Reads the keys of earlier rotations (comma-separated, each 32 bytes base64) for
|
|
60
|
+
* `EncryptedVault`'s `previousKeys`, default variable `PII_SHIELD_VAULT_PREVIOUS_KEYS`. Missing or empty
|
|
61
|
+
* gives `[]`.
|
|
62
|
+
*
|
|
63
|
+
* @throws TypeError if an entry is not a 32-byte base64 key; the message names the variable and the
|
|
64
|
+
* entry's position, never a value
|
|
65
|
+
*/
|
|
66
|
+
export declare function previousVaultKeysFromEnv(name?: string, env?: Env): Uint8Array[];
|
|
31
67
|
/**
|
|
32
68
|
* Encrypts a mapping with a given nonce: the seam for byte-parity tests with PHP payloads. Not public API:
|
|
33
69
|
* reusing a nonce breaks XChaCha20-Poly1305.
|
|
@@ -35,3 +71,4 @@ export declare function parseVaultKey(base64: string): Uint8Array;
|
|
|
35
71
|
* @internal
|
|
36
72
|
*/
|
|
37
73
|
export declare function encryptMapping(key: Uint8Array, id: string, mapping: PlaceholderMapping, nonce: Uint8Array): Uint8Array;
|
|
74
|
+
export {};
|
|
@@ -11,20 +11,31 @@ const NONCE_BYTES = 24;
|
|
|
11
11
|
*
|
|
12
12
|
* The vault id is bound as associated data, so a ciphertext copied to another id fails to decrypt.
|
|
13
13
|
* This is the only supported way to persist mappings.
|
|
14
|
+
*
|
|
15
|
+
* Key rotation (Node only): pass the new `key` and the old one in `previousKeys`. New entries are
|
|
16
|
+
* encrypted with `key`; reading tries `key`, then each previous key. Payloads stay PHP's format, so PHP
|
|
17
|
+
* reads every entry written with the key it has.
|
|
14
18
|
*/
|
|
15
19
|
export class EncryptedVault {
|
|
16
20
|
#storage;
|
|
17
21
|
#key;
|
|
22
|
+
/** `key` first, then the previous keys. */
|
|
23
|
+
#decryptionKeys;
|
|
18
24
|
constructor(options) {
|
|
19
25
|
const { storage, key } = options;
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
const previousKeys = options.previousKeys ?? [];
|
|
27
|
+
assertKey(key, 'The key');
|
|
28
|
+
if (!Array.isArray(previousKeys)) {
|
|
29
|
+
throw new TypeError('The previous keys must be an array of keys.');
|
|
22
30
|
}
|
|
23
|
-
|
|
24
|
-
|
|
31
|
+
const previous = [];
|
|
32
|
+
for (const [i, candidate] of previousKeys.entries()) {
|
|
33
|
+
assertKey(candidate, `Previous key ${String(i + 1)}`);
|
|
34
|
+
previous.push(candidate);
|
|
25
35
|
}
|
|
26
36
|
this.#storage = storage;
|
|
27
37
|
this.#key = key.slice();
|
|
38
|
+
this.#decryptionKeys = Object.freeze([this.#key, ...previous.map((k) => k.slice())]);
|
|
28
39
|
}
|
|
29
40
|
async store(id, mapping, ttlSeconds) {
|
|
30
41
|
assertTtl(ttlSeconds);
|
|
@@ -36,14 +47,9 @@ export class EncryptedVault {
|
|
|
36
47
|
if (payload === null) {
|
|
37
48
|
return null;
|
|
38
49
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
throw new RangeError('payload too short');
|
|
43
|
-
}
|
|
44
|
-
plaintext = xchacha20poly1305(this.#key, payload.subarray(0, NONCE_BYTES), utf8(id)).decrypt(payload.subarray(NONCE_BYTES));
|
|
45
|
-
}
|
|
46
|
-
catch {
|
|
50
|
+
const plaintext = decryptWithAny(this.#decryptionKeys, id, payload);
|
|
51
|
+
if (plaintext === null) {
|
|
52
|
+
// Same error whichever key failed, without a cause: nothing about the keys leaves the vault.
|
|
47
53
|
throw new VaultError('Vault entry cannot be decrypted (wrong key or tampered data).', 'VAULT_DECRYPTION_FAILED');
|
|
48
54
|
}
|
|
49
55
|
try {
|
|
@@ -57,7 +63,37 @@ export class EncryptedVault {
|
|
|
57
63
|
await this.#storage.remove(id);
|
|
58
64
|
}
|
|
59
65
|
}
|
|
60
|
-
/**
|
|
66
|
+
/** The plaintext, or null if no key authenticates the payload (or it is too short). */
|
|
67
|
+
function decryptWithAny(keys, id, payload) {
|
|
68
|
+
if (payload.length <= NONCE_BYTES) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const nonce = payload.subarray(0, NONCE_BYTES);
|
|
72
|
+
const ciphertext = payload.subarray(NONCE_BYTES);
|
|
73
|
+
const associatedData = utf8(id);
|
|
74
|
+
for (const key of keys) {
|
|
75
|
+
try {
|
|
76
|
+
return xchacha20poly1305(key, nonce, associatedData).decrypt(ciphertext);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// wrong key or tampered data: try the next key
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
function assertKey(key, what) {
|
|
85
|
+
if (!(key instanceof Uint8Array)) {
|
|
86
|
+
throw new TypeError(`${what} must be a Uint8Array of 32 raw bytes, see parseVaultKey().`);
|
|
87
|
+
}
|
|
88
|
+
if (key.length !== KEY_BYTES) {
|
|
89
|
+
throw new RangeError(`${what} must be ${String(KEY_BYTES)} bytes long.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* A new random key (32 raw bytes), for creating a key once (`npx @waswrongassembled/pii-shield generate-key`
|
|
94
|
+
* prints one base64-encoded). Keep it as a secret and read it with vaultKeyFromEnv() or parseVaultKey(); a
|
|
95
|
+
* key generated at run time cannot read entries after a restart or in another process.
|
|
96
|
+
*/
|
|
61
97
|
export function generateVaultKey() {
|
|
62
98
|
return globalThis.crypto.getRandomValues(new Uint8Array(KEY_BYTES));
|
|
63
99
|
}
|
|
@@ -81,6 +117,53 @@ export function parseVaultKey(base64) {
|
|
|
81
117
|
}
|
|
82
118
|
return key;
|
|
83
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Reads the vault key (32 bytes, base64) from an environment variable, default `PII_SHIELD_VAULT_KEY`
|
|
122
|
+
* (the service reads `PII_SERVICE_VAULT_KEY`). Create a key once with
|
|
123
|
+
* `npx @waswrongassembled/pii-shield generate-key`.
|
|
124
|
+
*
|
|
125
|
+
* @throws TypeError if the variable is missing, empty or not a 32-byte base64 key; the message names the
|
|
126
|
+
* variable, never its value
|
|
127
|
+
*/
|
|
128
|
+
export function vaultKeyFromEnv(name = 'PII_SHIELD_VAULT_KEY', env = process.env) {
|
|
129
|
+
const value = env[name];
|
|
130
|
+
if (value === undefined || value.trim() === '') {
|
|
131
|
+
throw new TypeError(`${name} is not set. Set it to a vault key (32 bytes, base64), e.g. from "npx @waswrongassembled/pii-shield generate-key".`);
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
return parseVaultKey(value);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
throw new TypeError(`${name} must be a vault key of 32 bytes, base64-encoded.`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Reads the keys of earlier rotations (comma-separated, each 32 bytes base64) for
|
|
142
|
+
* `EncryptedVault`'s `previousKeys`, default variable `PII_SHIELD_VAULT_PREVIOUS_KEYS`. Missing or empty
|
|
143
|
+
* gives `[]`.
|
|
144
|
+
*
|
|
145
|
+
* @throws TypeError if an entry is not a 32-byte base64 key; the message names the variable and the
|
|
146
|
+
* entry's position, never a value
|
|
147
|
+
*/
|
|
148
|
+
export function previousVaultKeysFromEnv(name = 'PII_SHIELD_VAULT_PREVIOUS_KEYS', env = process.env) {
|
|
149
|
+
const entries = (env[name] ?? '')
|
|
150
|
+
.split(',')
|
|
151
|
+
.map((entry) => entry.trim())
|
|
152
|
+
.filter((entry) => entry !== '');
|
|
153
|
+
const keys = [];
|
|
154
|
+
for (const [i, entry] of entries.entries()) {
|
|
155
|
+
try {
|
|
156
|
+
keys.push(parseVaultKey(entry));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
for (const key of keys) {
|
|
160
|
+
key.fill(0);
|
|
161
|
+
}
|
|
162
|
+
throw new TypeError(`${name} must be a comma-separated list of vault keys (32 bytes, base64-encoded); entry ${String(i + 1)} is not.`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return keys;
|
|
166
|
+
}
|
|
84
167
|
/**
|
|
85
168
|
* Encrypts a mapping with a given nonce: the seam for byte-parity tests with PHP payloads. Not public API:
|
|
86
169
|
* reusing a nonce breaks XChaCha20-Poly1305.
|
|
@@ -5,7 +5,7 @@ export interface MemoryVaultStorageOptions {
|
|
|
5
5
|
}
|
|
6
6
|
/**
|
|
7
7
|
* Process-local VaultStorage with expiry, for tests and single-process apps that want EncryptedVault's
|
|
8
|
-
* behaviour without a server. Expired entries are purged on every write. Payloads are copied in and out.
|
|
8
|
+
* behaviour without a server. Expired entries are purged on every write and by purgeExpired(). Payloads are copied in and out.
|
|
9
9
|
*/
|
|
10
10
|
export declare class MemoryVaultStorage implements VaultStorage {
|
|
11
11
|
#private;
|
|
@@ -13,4 +13,11 @@ export declare class MemoryVaultStorage implements VaultStorage {
|
|
|
13
13
|
put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
|
|
14
14
|
get(id: string): Promise<Uint8Array | null>;
|
|
15
15
|
remove(id: string): Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Deletes expired entries (writes do it too). createPiiShield() calls it on its purge timer, so an idle
|
|
18
|
+
* process does not hold expired mappings.
|
|
19
|
+
*
|
|
20
|
+
* @returns the number of deleted entries
|
|
21
|
+
*/
|
|
22
|
+
purgeExpired(): Promise<number>;
|
|
16
23
|
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { assertTtl } from './vault.js';
|
|
3
3
|
/**
|
|
4
4
|
* Process-local VaultStorage with expiry, for tests and single-process apps that want EncryptedVault's
|
|
5
|
-
* behaviour without a server. Expired entries are purged on every write. Payloads are copied in and out.
|
|
5
|
+
* behaviour without a server. Expired entries are purged on every write and by purgeExpired(). Payloads are copied in and out.
|
|
6
6
|
*/
|
|
7
7
|
export class MemoryVaultStorage {
|
|
8
8
|
#entries = new Map();
|
|
@@ -12,13 +12,8 @@ export class MemoryVaultStorage {
|
|
|
12
12
|
}
|
|
13
13
|
async put(id, payload, ttlSeconds) {
|
|
14
14
|
assertTtl(ttlSeconds);
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
if (entry.expiresAt <= now) {
|
|
18
|
-
this.#entries.delete(key);
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
this.#entries.set(id, { payload: payload.slice(), expiresAt: now + ttlSeconds * 1000 });
|
|
15
|
+
await this.purgeExpired();
|
|
16
|
+
this.#entries.set(id, { payload: payload.slice(), expiresAt: this.#clock() + ttlSeconds * 1000 });
|
|
22
17
|
}
|
|
23
18
|
async get(id) {
|
|
24
19
|
const entry = this.#entries.get(id);
|
|
@@ -34,4 +29,21 @@ export class MemoryVaultStorage {
|
|
|
34
29
|
async remove(id) {
|
|
35
30
|
this.#entries.delete(id);
|
|
36
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Deletes expired entries (writes do it too). createPiiShield() calls it on its purge timer, so an idle
|
|
34
|
+
* process does not hold expired mappings.
|
|
35
|
+
*
|
|
36
|
+
* @returns the number of deleted entries
|
|
37
|
+
*/
|
|
38
|
+
async purgeExpired() {
|
|
39
|
+
const now = this.#clock();
|
|
40
|
+
let deleted = 0;
|
|
41
|
+
for (const [key, entry] of this.#entries) {
|
|
42
|
+
if (entry.expiresAt <= now) {
|
|
43
|
+
this.#entries.delete(key);
|
|
44
|
+
deleted++;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return deleted;
|
|
48
|
+
}
|
|
37
49
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { VaultSetup } from '../create-pii-shield.js';
|
|
1
2
|
import { type VaultStorage } from '../vault/vault.js';
|
|
2
3
|
/**
|
|
3
4
|
* The ioredis methods RedisVaultStorage calls. An ioredis `Redis` or `Cluster` instance satisfies it;
|
|
@@ -26,3 +27,16 @@ export declare class RedisVaultStorage implements VaultStorage {
|
|
|
26
27
|
get(id: string): Promise<Uint8Array | null>;
|
|
27
28
|
remove(id: string): Promise<void>;
|
|
28
29
|
}
|
|
30
|
+
export interface RedisVaultOptions extends RedisVaultStorageOptions {
|
|
31
|
+
/** 32 raw bytes, e.g. `vaultKeyFromEnv()`, the same in every process. Required: entries outlive the process. */
|
|
32
|
+
key: Uint8Array;
|
|
33
|
+
/** Keys of earlier rotations, only for reading, e.g. `previousVaultKeysFromEnv()`. */
|
|
34
|
+
previousKeys?: readonly Uint8Array[] | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The vault of createPiiShield() on Redis: a RedisVaultStorage behind an EncryptedVault with your key.
|
|
38
|
+
* Redis expires entries itself (`SET … EX`), so nothing needs purging. The client stays yours to quit.
|
|
39
|
+
*/
|
|
40
|
+
export declare function redisVault(options: RedisVaultOptions): VaultSetup & {
|
|
41
|
+
storage: RedisVaultStorage;
|
|
42
|
+
};
|
|
@@ -31,3 +31,11 @@ export class RedisVaultStorage {
|
|
|
31
31
|
return this.#prefix + createHash('sha256').update(id, 'utf8').digest('hex');
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* The vault of createPiiShield() on Redis: a RedisVaultStorage behind an EncryptedVault with your key.
|
|
36
|
+
* Redis expires entries itself (`SET … EX`), so nothing needs purging. The client stays yours to quit.
|
|
37
|
+
*/
|
|
38
|
+
export function redisVault(options) {
|
|
39
|
+
const { key, previousKeys, ...store } = options;
|
|
40
|
+
return { storage: new RedisVaultStorage(store), key, previousKeys };
|
|
41
|
+
}
|
package/docs/openapi.yaml
CHANGED
|
@@ -167,7 +167,10 @@ paths:
|
|
|
167
167
|
pattern; they are learned as model-only types and reach the model as few-shot examples.
|
|
168
168
|
Learned types take effect immediately for `/v1/redact` and `/v1/mask`.
|
|
169
169
|
|
|
170
|
-
Examples are stored
|
|
170
|
+
Examples are stored unless the service runs with `PII_SERVICE_LEARNED_KEEP_EXAMPLES=false`:
|
|
171
|
+
use synthetic or anonymised values only. Without stored examples, the returned type has empty
|
|
172
|
+
`examples` and `counterExamples`, and plain words without a pattern are refused with 422 (only
|
|
173
|
+
their examples would let the model find them); give a `pattern` instead. Hand-written patterns follow a
|
|
171
174
|
restricted grammar (no repeated groups, anchors, backreferences or lookarounds) to rule out
|
|
172
175
|
catastrophic backtracking.
|
|
173
176
|
operationId: learn
|
|
@@ -314,6 +317,21 @@ components:
|
|
|
314
317
|
type: array
|
|
315
318
|
items: { type: string }
|
|
316
319
|
description: Values that are never redacted (exact match), e.g. the authority's own reference.
|
|
320
|
+
knownValues:
|
|
321
|
+
type: array
|
|
322
|
+
maxItems: 500
|
|
323
|
+
description: |
|
|
324
|
+
Values the caller knows to be personal data (e.g. the account holder's name), redacted wherever
|
|
325
|
+
they occur as whole words: case-insensitive, umlauts in either spelling (ü/ue, ß/ss), any
|
|
326
|
+
whitespace between words. They apply even when `types` leaves out their type and win over
|
|
327
|
+
`allowlist`. Used for this request only: never stored, learned or logged; error messages never
|
|
328
|
+
contain them. Node service only (not in the PHP package).
|
|
329
|
+
items:
|
|
330
|
+
type: object
|
|
331
|
+
required: [value, type]
|
|
332
|
+
properties:
|
|
333
|
+
value: { type: string, minLength: 2, maxLength: 200 }
|
|
334
|
+
type: { $ref: '#/components/schemas/EntityType' }
|
|
317
335
|
keepAuthorityContacts:
|
|
318
336
|
type: boolean
|
|
319
337
|
default: true
|
|
@@ -381,7 +399,10 @@ components:
|
|
|
381
399
|
properties:
|
|
382
400
|
name: { $ref: '#/components/schemas/TypeName' }
|
|
383
401
|
description: { type: string }
|
|
384
|
-
examples:
|
|
402
|
+
examples:
|
|
403
|
+
type: array
|
|
404
|
+
items: { type: string }
|
|
405
|
+
description: Empty for a type with a pattern whose examples are not kept (PII_SERVICE_LEARNED_KEEP_EXAMPLES=false).
|
|
385
406
|
counterExamples: { type: array, items: { type: string } }
|
|
386
407
|
pattern: { type: [string, 'null'], description: null for model-only types }
|
|
387
408
|
|