@waswrongassembled/pii-shield 0.1.1 → 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 (46) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +135 -21
  3. package/dist/cli.js +37 -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 +26 -5
  17. package/dist/learning/store.js +4 -2
  18. package/dist/pii-masker.js +2 -1
  19. package/dist/pii-shield.js +2 -1
  20. package/dist/postgres/index.d.ts +103 -0
  21. package/dist/postgres/index.js +204 -0
  22. package/dist/redaction.d.ts +16 -2
  23. package/dist/redaction.js +22 -10
  24. package/dist/server/config.d.ts +16 -7
  25. package/dist/server/config.js +78 -126
  26. package/dist/server/connections.d.ts +34 -0
  27. package/dist/server/connections.js +99 -0
  28. package/dist/server/doctor.d.ts +28 -0
  29. package/dist/server/doctor.js +438 -0
  30. package/dist/server/env.d.ts +62 -0
  31. package/dist/server/env.js +197 -0
  32. package/dist/server/index.d.ts +1 -0
  33. package/dist/server/index.js +1 -0
  34. package/dist/testing/conformance.d.ts +64 -0
  35. package/dist/testing/conformance.js +348 -0
  36. package/dist/testing/index.d.ts +6 -0
  37. package/dist/testing/index.js +6 -0
  38. package/dist/vault/encrypted-vault.d.ts +39 -2
  39. package/dist/vault/encrypted-vault.js +96 -13
  40. package/dist/vault/memory-vault-storage.d.ts +8 -1
  41. package/dist/vault/memory-vault-storage.js +20 -8
  42. package/dist/vault/vault.d.ts +18 -2
  43. package/dist/vault-redis/index.d.ts +14 -0
  44. package/dist/vault-redis/index.js +8 -0
  45. package/docs/openapi.yaml +8 -2
  46. package/package.json +18 -3
@@ -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
+ }
@@ -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';
@@ -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';
@@ -0,0 +1,64 @@
1
+ import type { CustomEntityStore } from '../learning/store.js';
2
+ import type { VaultStorage } from '../vault/vault.js';
3
+ /** Which rules of a conformance suite ran and which were skipped for lack of an option. */
4
+ export interface VerifyReport {
5
+ readonly passed: readonly string[];
6
+ /** Rules that need an option the caller did not give (e.g. `expire`), with the option's name. */
7
+ readonly skipped: readonly string[];
8
+ }
9
+ /** A function that returns a store; it may be async. */
10
+ type Factory<S> = () => S | Promise<S>;
11
+ export interface VerifyVaultStorageOptions<S extends VaultStorage = VaultStorage> {
12
+ /**
13
+ * Makes the entry `id` (written through `storage`) expired, as if its TTL had passed. Needed for the
14
+ * expiry rules, because a backend that keeps time itself (a database's `now()`, Redis) cannot be
15
+ * given a fake clock. Examples: advance an injected clock; for Postgres
16
+ * `UPDATE … SET expires_at = now() - interval '1 second' WHERE id = <hashed id>`.
17
+ * Expiring more than this entry (advancing a shared clock) is fine.
18
+ */
19
+ expire?: (storage: S, id: string) => void | Promise<void>;
20
+ /**
21
+ * Without `expire`: test expiry with a real TTL of 1 second and a wait of 1.5 seconds. Slow, so it
22
+ * is opt-in. Without either option the expiry rules are skipped (see the report).
23
+ */
24
+ realTimeExpiry?: boolean;
25
+ /**
26
+ * Another instance over the same backend as `storage` (another connection, another process's
27
+ * view). Enables the rule that entries written through one instance are read through another.
28
+ */
29
+ secondInstance?: (storage: S) => VaultStorage | Promise<VaultStorage>;
30
+ }
31
+ export interface VerifyCustomEntityStoreOptions<S extends CustomEntityStore = CustomEntityStore> {
32
+ /**
33
+ * Another instance over the same backend as `store`. Enables the rule that concurrent writes of
34
+ * different names through two instances are all kept (which KeyValueCustomEntityStore does not do).
35
+ */
36
+ secondInstance?: (store: S) => CustomEntityStore | Promise<CustomEntityStore>;
37
+ }
38
+ /**
39
+ * Checks that a VaultStorage keeps the contract documented on the interface: unknown and expired ids
40
+ * give null, payloads are binary-safe and copied, put() overwrites, remove() of an unknown id is a
41
+ * no-op, TTLs are validated, ids are independent of each other.
42
+ *
43
+ * `factory` is called once per rule. Instances may share one backend: the ids of a run are random,
44
+ * so a shared database or Redis needs no cleanup between rules. Data is synthetic.
45
+ *
46
+ * Runs under any test runner: `await verifyVaultStorage(() => new MyStorage())` inside a test.
47
+ *
48
+ * @returns which rules passed and which were skipped for lack of an option
49
+ * @throws AssertionError naming the first rule that failed (the original error is its `cause`)
50
+ */
51
+ export declare function verifyVaultStorage<S extends VaultStorage>(factory: Factory<S>, options?: VerifyVaultStorageOptions<S>): Promise<VerifyReport>;
52
+ /**
53
+ * Checks that a CustomEntityStore keeps the contract documented on the interface: get() and save()
54
+ * round-trip types exactly, save() replaces, all() is sorted by name in byte order, remove() of an
55
+ * unknown name is a no-op, and concurrent writes of different names are all kept.
56
+ *
57
+ * `factory` is called once per rule and must return an empty store (e.g. truncate the table first).
58
+ * Data is synthetic.
59
+ *
60
+ * @returns which rules passed and which were skipped for lack of an option
61
+ * @throws AssertionError naming the first rule that failed (the original error is its `cause`)
62
+ */
63
+ export declare function verifyCustomEntityStore<S extends CustomEntityStore>(factory: Factory<S>, options?: VerifyCustomEntityStoreOptions<S>): Promise<VerifyReport>;
64
+ export {};
@@ -0,0 +1,348 @@
1
+ import assert, { AssertionError } from 'node:assert/strict';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { setTimeout as sleep } from 'node:timers/promises';
4
+ import { defineCustomEntityType, withoutExamples } from '../learning/custom-entity-type.js';
5
+ /**
6
+ * Checks that a VaultStorage keeps the contract documented on the interface: unknown and expired ids
7
+ * give null, payloads are binary-safe and copied, put() overwrites, remove() of an unknown id is a
8
+ * no-op, TTLs are validated, ids are independent of each other.
9
+ *
10
+ * `factory` is called once per rule. Instances may share one backend: the ids of a run are random,
11
+ * so a shared database or Redis needs no cleanup between rules. Data is synthetic.
12
+ *
13
+ * Runs under any test runner: `await verifyVaultStorage(() => new MyStorage())` inside a test.
14
+ *
15
+ * @returns which rules passed and which were skipped for lack of an option
16
+ * @throws AssertionError naming the first rule that failed (the original error is its `cause`)
17
+ */
18
+ export async function verifyVaultStorage(factory, options = {}) {
19
+ const { expire, realTimeExpiry = false, secondInstance } = options;
20
+ const run = randomBytes(6).toString('hex');
21
+ const id = (name) => `pii-shield-conformance-${run}-${name}`;
22
+ const bytes = (...values) => Uint8Array.from(values);
23
+ const assertBytes = (actual, expected, what) => {
24
+ assert.ok(actual instanceof Uint8Array, `${what}: expected a Uint8Array, got ${describe(actual)}`);
25
+ assert.deepEqual(new Uint8Array(actual), expected, what);
26
+ };
27
+ const canExpire = expire !== undefined || realTimeExpiry;
28
+ /** Puts an entry and makes it expire, by the hook or by waiting. */
29
+ const putExpired = async (storage, key, payload) => {
30
+ if (expire !== undefined) {
31
+ await storage.put(key, payload, 60);
32
+ await expire(storage, key);
33
+ }
34
+ else {
35
+ await storage.put(key, payload, 1);
36
+ await sleep(1500);
37
+ }
38
+ };
39
+ const rules = [
40
+ {
41
+ name: 'get() of an unknown id gives null',
42
+ run: async () => {
43
+ assert.equal(await (await factory()).get(id('unknown')), null);
44
+ },
45
+ },
46
+ {
47
+ name: 'put() then get() gives the payload back',
48
+ run: async () => {
49
+ const storage = await factory();
50
+ const payload = Uint8Array.from({ length: 256 }, (_, i) => i);
51
+ await storage.put(id('a'), payload, 60);
52
+ assertBytes(await storage.get(id('a')), payload, 'every byte value 0..255');
53
+ },
54
+ },
55
+ {
56
+ name: 'payloads of any length are binary-safe',
57
+ run: async () => {
58
+ const storage = await factory();
59
+ const cases = [
60
+ ['empty', new Uint8Array(0)],
61
+ ['zero bytes', new Uint8Array(32)],
62
+ ['invalid UTF-8', bytes(0xc3, 0x28, 0xff, 0xfe, 0x00, 0xed, 0xa0, 0x80)],
63
+ ['64 KiB', new Uint8Array(randomBytes(64 * 1024))],
64
+ ];
65
+ for (const [name, payload] of cases) {
66
+ await storage.put(id(name), payload, 60);
67
+ }
68
+ for (const [name, payload] of cases) {
69
+ assertBytes(await storage.get(id(name)), payload, name);
70
+ }
71
+ },
72
+ },
73
+ {
74
+ name: 'put() stores only the bytes of a view, not its whole buffer',
75
+ run: async () => {
76
+ const storage = await factory();
77
+ await storage.put(id('view'), bytes(9, 1, 2, 3, 9).subarray(1, 4), 60);
78
+ assertBytes(await storage.get(id('view')), bytes(1, 2, 3), 'subarray(1, 4)');
79
+ },
80
+ },
81
+ {
82
+ name: 'payloads are copied in and out',
83
+ run: async () => {
84
+ const storage = await factory();
85
+ const payload = bytes(1, 2, 3);
86
+ await storage.put(id('copy'), payload, 60);
87
+ payload.fill(0);
88
+ const first = await storage.get(id('copy'));
89
+ assertBytes(first, bytes(1, 2, 3), 'after changing the array passed to put()');
90
+ first?.fill(0);
91
+ assertBytes(await storage.get(id('copy')), bytes(1, 2, 3), 'after changing the array get() returned');
92
+ },
93
+ },
94
+ {
95
+ name: 'put() overwrites an existing entry',
96
+ run: async () => {
97
+ const storage = await factory();
98
+ await storage.put(id('overwrite'), bytes(1), 60);
99
+ await storage.put(id('overwrite'), bytes(2, 2), 120);
100
+ assertBytes(await storage.get(id('overwrite')), bytes(2, 2), 'second put()');
101
+ },
102
+ },
103
+ {
104
+ name: 'ids are independent and may contain any characters',
105
+ run: async () => {
106
+ const storage = await factory();
107
+ const ids = [
108
+ 'id-1',
109
+ 'ID-1',
110
+ 'id-1 ',
111
+ '',
112
+ 'ü-✓-😀',
113
+ 'a/b:c@d*?%_\\',
114
+ "x'; DELETE FROM vault; --",
115
+ '\u0000nul',
116
+ 'x'.repeat(2000),
117
+ ].map((suffix) => id(suffix));
118
+ for (const [i, key] of ids.entries()) {
119
+ await storage.put(key, bytes(i, 0xff), 60);
120
+ }
121
+ for (const [i, key] of ids.entries()) {
122
+ assertBytes(await storage.get(key), bytes(i, 0xff), `id #${String(i + 1)}`);
123
+ }
124
+ },
125
+ },
126
+ {
127
+ name: 'remove() deletes only its entry, remove() of an unknown id is a no-op',
128
+ run: async () => {
129
+ const storage = await factory();
130
+ await storage.put(id('keep'), bytes(1), 60);
131
+ await storage.put(id('remove'), bytes(2), 60);
132
+ await storage.remove(id('remove'));
133
+ await storage.remove(id('remove'));
134
+ await storage.remove(id('never-stored'));
135
+ assert.equal(await storage.get(id('remove')), null, 'removed entry');
136
+ assertBytes(await storage.get(id('keep')), bytes(1), 'other entry');
137
+ },
138
+ },
139
+ {
140
+ name: 'put() rejects a TTL that is not a positive integer, and stores nothing',
141
+ run: async () => {
142
+ const storage = await factory();
143
+ for (const ttl of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
144
+ await assert.rejects(() => storage.put(id('ttl'), bytes(1), ttl), (e) => e instanceof RangeError || e instanceof TypeError, `TTL ${String(ttl)} must reject the Promise with a RangeError or TypeError`);
145
+ }
146
+ assert.equal(await storage.get(id('ttl')), null);
147
+ },
148
+ },
149
+ {
150
+ name: 'get() of an expired entry gives null',
151
+ missing: canExpire ? undefined : 'expire',
152
+ run: async () => {
153
+ const storage = await factory();
154
+ await putExpired(storage, id('expired'), bytes(1));
155
+ assert.equal(await storage.get(id('expired')), null);
156
+ },
157
+ },
158
+ {
159
+ name: 'put() over an expired entry stores it again',
160
+ missing: canExpire ? undefined : 'expire',
161
+ run: async () => {
162
+ const storage = await factory();
163
+ await putExpired(storage, id('again'), bytes(1));
164
+ await storage.put(id('again'), bytes(2), 60);
165
+ assertBytes(await storage.get(id('again')), bytes(2), 'second put()');
166
+ },
167
+ },
168
+ {
169
+ name: 'entries are shared between instances over the same backend',
170
+ missing: secondInstance === undefined ? 'secondInstance' : undefined,
171
+ run: async () => {
172
+ if (secondInstance === undefined) {
173
+ return; // skipped, see missing
174
+ }
175
+ const storage = await factory();
176
+ const other = await secondInstance(storage);
177
+ await storage.put(id('shared'), bytes(7), 60);
178
+ assertBytes(await other.get(id('shared')), bytes(7), 'read through the second instance');
179
+ await other.remove(id('shared'));
180
+ assert.equal(await storage.get(id('shared')), null, 'removed through the second instance');
181
+ },
182
+ },
183
+ ];
184
+ return runRules('VaultStorage', rules);
185
+ }
186
+ /**
187
+ * Checks that a CustomEntityStore keeps the contract documented on the interface: get() and save()
188
+ * round-trip types exactly, save() replaces, all() is sorted by name in byte order, remove() of an
189
+ * unknown name is a no-op, and concurrent writes of different names are all kept.
190
+ *
191
+ * `factory` is called once per rule and must return an empty store (e.g. truncate the table first).
192
+ * Data is synthetic.
193
+ *
194
+ * @returns which rules passed and which were skipped for lack of an option
195
+ * @throws AssertionError naming the first rule that failed (the original error is its `cause`)
196
+ */
197
+ export async function verifyCustomEntityStore(factory, options = {}) {
198
+ const { secondInstance } = options;
199
+ const names = (types) => types.map((t) => t.name);
200
+ const rules = [
201
+ {
202
+ name: 'all() of an empty store gives [] (the factory must return an empty store)',
203
+ run: async () => {
204
+ assert.deepEqual(await (await factory()).all(), []);
205
+ },
206
+ },
207
+ {
208
+ name: 'get() of an unknown name gives null',
209
+ run: async () => {
210
+ assert.equal(await (await factory()).get('UNKNOWN_TYPE'), null);
211
+ },
212
+ },
213
+ {
214
+ name: 'save() then get() and all() give the type back unchanged (also without examples)',
215
+ run: async () => {
216
+ const store = await factory();
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
+ ];
223
+ for (const type of types) {
224
+ await store.save(type);
225
+ }
226
+ for (const type of types) {
227
+ assert.deepEqual(await store.get(type.name), type, type.name);
228
+ }
229
+ assert.deepEqual(await store.all(), sortedByByteOrder(types));
230
+ },
231
+ },
232
+ {
233
+ name: 'save() replaces the type with the same name',
234
+ run: async () => {
235
+ const store = await factory();
236
+ await store.save(syntheticType('TEST_CODE'));
237
+ const replacement = syntheticType('TEST_CODE', 'Replaced synthetic test type');
238
+ await store.save(replacement);
239
+ assert.deepEqual(await store.get('TEST_CODE'), replacement);
240
+ assert.deepEqual(await store.all(), [replacement]);
241
+ },
242
+ },
243
+ {
244
+ name: 'all() is sorted by name in byte order',
245
+ run: async () => {
246
+ const store = await factory();
247
+ // A locale collation would sort A_CODE before AB_CODE and B_CODE before B2_CODE.
248
+ for (const name of ['ZETA_CODE', 'A_CODE', 'B_CODE', 'AB_CODE', 'B2_CODE']) {
249
+ await store.save(syntheticType(name));
250
+ }
251
+ assert.deepEqual(names(await store.all()), ['AB_CODE', 'A_CODE', 'B2_CODE', 'B_CODE', 'ZETA_CODE']);
252
+ },
253
+ },
254
+ {
255
+ name: 'remove() deletes only its type, remove() of an unknown name is a no-op',
256
+ run: async () => {
257
+ const store = await factory();
258
+ await store.save(syntheticType('KEEP_CODE'));
259
+ await store.save(syntheticType('DROP_CODE'));
260
+ await store.remove('DROP_CODE');
261
+ await store.remove('DROP_CODE');
262
+ await store.remove('NEVER_SAVED');
263
+ assert.equal(await store.get('DROP_CODE'), null, 'removed type');
264
+ assert.deepEqual(names(await store.all()), ['KEEP_CODE']);
265
+ },
266
+ },
267
+ {
268
+ name: 'concurrent writes of different names are all kept',
269
+ run: async () => {
270
+ const store = await factory();
271
+ await Promise.all(range(8).map((i) => store.save(syntheticType(`CODE_${String(i)}`))));
272
+ assert.deepEqual(names(await store.all()), range(8).map((i) => `CODE_${String(i)}`));
273
+ await Promise.all([
274
+ ...range(4).map((i) => store.remove(`CODE_${String(i)}`)),
275
+ ...range(4).map((i) => store.save(syntheticType(`NEW_${String(i)}`))),
276
+ ]);
277
+ assert.deepEqual(names(await store.all()), [
278
+ ...range(4).map((i) => `CODE_${String(i + 4)}`),
279
+ ...range(4).map((i) => `NEW_${String(i)}`),
280
+ ]);
281
+ },
282
+ },
283
+ {
284
+ name: 'concurrent writes through two instances over the same backend are all kept',
285
+ missing: secondInstance === undefined ? 'secondInstance' : undefined,
286
+ run: async () => {
287
+ if (secondInstance === undefined) {
288
+ return; // skipped, see missing
289
+ }
290
+ const store = await factory();
291
+ const other = await secondInstance(store);
292
+ await Promise.all(range(8).map((i) => (i % 2 === 0 ? store : other).save(syntheticType(`CODE_${String(i)}`))));
293
+ assert.deepEqual(names(await store.all()), range(8).map((i) => `CODE_${String(i)}`));
294
+ assert.deepEqual(names(await other.all()), range(8).map((i) => `CODE_${String(i)}`));
295
+ },
296
+ },
297
+ ];
298
+ return runRules('CustomEntityStore', rules);
299
+ }
300
+ async function runRules(contract, rules) {
301
+ const passed = [];
302
+ const skipped = [];
303
+ for (const rule of rules) {
304
+ if (rule.missing !== undefined) {
305
+ skipped.push(`${rule.name} (needs the option "${rule.missing}")`);
306
+ continue;
307
+ }
308
+ try {
309
+ await rule.run();
310
+ }
311
+ catch (e) {
312
+ const inner = e instanceof AssertionError ? e : undefined;
313
+ const detail = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
314
+ const error = new AssertionError({
315
+ message: `${contract} contract violated: ${rule.name}\n${detail}`,
316
+ actual: inner?.actual,
317
+ expected: inner?.expected,
318
+ operator: inner?.operator ?? 'fail',
319
+ });
320
+ error.cause = e;
321
+ throw error;
322
+ }
323
+ passed.push(rule.name);
324
+ }
325
+ return { passed, skipped };
326
+ }
327
+ function syntheticType(name, description = 'Synthetic test type') {
328
+ return defineCustomEntityType({ name, description, examples: ['TST-0001', 'TST-0002'], pattern: null });
329
+ }
330
+ /** A type with a pattern and characters that JSON, jsonb and text encodings must keep. */
331
+ function richType() {
332
+ return defineCustomEntityType({
333
+ name: 'RICH_TEST_CODE',
334
+ description: 'Synthetische Testart: "Zitat" \\ / & ü ✓ 😀 
 Ende',
335
+ examples: ['TST-0001', 'TST-9999'],
336
+ counterExamples: ['TSX-0001', 'Ölbaum "Nord" \\ 7 😀 
'],
337
+ pattern: String.raw `TST-\d{4}`,
338
+ });
339
+ }
340
+ function sortedByByteOrder(types) {
341
+ return [...types].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
342
+ }
343
+ function range(n) {
344
+ return Array.from({ length: n }, (_, i) => i);
345
+ }
346
+ function describe(value) {
347
+ return value === null ? 'null' : typeof value === 'object' ? value.constructor.name : typeof value;
348
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/testing: conformance suites for storage adapters. They check the
3
+ * contracts of `VaultStorage` and `CustomEntityStore` with `node:assert` only, so they run under any test
4
+ * runner (vitest, jest, `node:test`, mocha) without a peer dependency. All test data is synthetic.
5
+ */
6
+ export { verifyCustomEntityStore, type VerifyCustomEntityStoreOptions, verifyVaultStorage, type VerifyReport, type VerifyVaultStorageOptions, } from './conformance.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/testing: conformance suites for storage adapters. They check the
3
+ * contracts of `VaultStorage` and `CustomEntityStore` with `node:assert` only, so they run under any test
4
+ * runner (vitest, jest, `node:test`, mocha) without a peer dependency. All test data is synthetic.
5
+ */
6
+ export { verifyCustomEntityStore, verifyVaultStorage, } from './conformance.js';