@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.
Files changed (44) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/README.md +127 -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/detectors/known-values.d.ts +40 -0
  7. package/dist/detectors/known-values.js +126 -0
  8. package/dist/entity-extractor.d.ts +17 -1
  9. package/dist/entity-extractor.js +13 -2
  10. package/dist/index.d.ts +5 -3
  11. package/dist/index.js +5 -3
  12. package/dist/internal/background.d.ts +27 -0
  13. package/dist/internal/background.js +47 -0
  14. package/dist/learning/custom-entity-type.d.ts +14 -4
  15. package/dist/learning/custom-entity-type.js +23 -5
  16. package/dist/learning/entity-learner.d.ts +33 -2
  17. package/dist/learning/entity-learner.js +48 -5
  18. package/dist/learning/store.d.ts +4 -2
  19. package/dist/pii-masker.js +3 -1
  20. package/dist/pii-shield.js +3 -1
  21. package/dist/postgres/index.d.ts +20 -0
  22. package/dist/postgres/index.js +14 -0
  23. package/dist/redaction.d.ts +16 -2
  24. package/dist/redaction.js +22 -10
  25. package/dist/server/config.d.ts +5 -8
  26. package/dist/server/config.js +77 -220
  27. package/dist/server/connections.d.ts +34 -0
  28. package/dist/server/connections.js +99 -0
  29. package/dist/server/doctor.d.ts +28 -0
  30. package/dist/server/doctor.js +438 -0
  31. package/dist/server/env.d.ts +62 -0
  32. package/dist/server/env.js +197 -0
  33. package/dist/server/index.d.ts +1 -0
  34. package/dist/server/index.js +1 -0
  35. package/dist/service/service-api.js +25 -0
  36. package/dist/testing/conformance.js +8 -3
  37. package/dist/vault/encrypted-vault.d.ts +39 -2
  38. package/dist/vault/encrypted-vault.js +96 -13
  39. package/dist/vault/memory-vault-storage.d.ts +8 -1
  40. package/dist/vault/memory-vault-storage.js +20 -8
  41. package/dist/vault-redis/index.d.ts +14 -0
  42. package/dist/vault-redis/index.js +8 -0
  43. package/docs/openapi.yaml +23 -2
  44. package/package.json +1 -1
@@ -0,0 +1,126 @@
1
+ import { createEntity } from '../entity.js';
2
+ import { isEntityType } from '../entity-type.js';
3
+ import { codePointLength, SPACE, WORD_END, WORD_START } from '../internal/pcre.js';
4
+ /** The `detector` of entities found from known values; they are exempt from the allowlist. */
5
+ export const KNOWN_VALUES_DETECTOR = 'known-values';
6
+ const UMLAUTS = { ä: 'a', ö: 'o', ü: 'u' };
7
+ const SYNTAX = /[\\^$.*+?()[\]{}|/]/gu;
8
+ const LIST_MESSAGE = 'knownValues must be a list of { value, type } objects.';
9
+ /**
10
+ * Finds values the caller passes per call (names of the account holder, their customer numbers, ...)
11
+ * wherever they occur as whole words:
12
+ *
13
+ * - case-insensitive (Unicode), so "MÜLLER" and "müller" match "Müller"
14
+ * - umlauts in either spelling: "Müller" also matches "Mueller" and a decomposed "Müller", and
15
+ * "Mueller" matches "Müller"; "ß" and "ss" match each other
16
+ * - only whole words: "Ali" does not match in "Alibi" or "Kalium"
17
+ * - any run of whitespace (also a line break) between the words of a value
18
+ *
19
+ * The values are held only by this instance (never stored, learned or logged); validation errors never
20
+ * contain them, and the detector serializes and inspects as `{ name, count }`.
21
+ */
22
+ export class KnownValuesDetector {
23
+ static MAX_VALUES = 500;
24
+ static MIN_LENGTH = 2;
25
+ static MAX_LENGTH = 200;
26
+ name = KNOWN_VALUES_DETECTOR;
27
+ #needles;
28
+ /** @throws TypeError on invalid input; the message never contains a value */
29
+ constructor(values) {
30
+ if (typeof values?.[Symbol.iterator] !== 'function') {
31
+ throw new TypeError(LIST_MESSAGE);
32
+ }
33
+ const needles = new Map();
34
+ let count = 0;
35
+ for (const item of values) {
36
+ if (++count > KnownValuesDetector.MAX_VALUES) {
37
+ throw new TypeError(`knownValues accepts at most ${String(KnownValuesDetector.MAX_VALUES)} values.`);
38
+ }
39
+ const { value, type } = checked(item);
40
+ const key = `${type}\0${value.toLowerCase()}`;
41
+ if (!needles.has(key)) {
42
+ needles.set(key, { pattern: new RegExp(`${WORD_START}(?:${pattern(value)})${WORD_END}`, 'giu'), type });
43
+ }
44
+ }
45
+ this.#needles = [...needles.values()];
46
+ }
47
+ /** Number of distinct values. */
48
+ get size() {
49
+ return this.#needles.length;
50
+ }
51
+ detect(text) {
52
+ const entities = [];
53
+ for (const { pattern, type } of this.#needles) {
54
+ for (const match of text.matchAll(pattern)) {
55
+ entities.push(createEntity({ type, value: match[0], offset: match.index, confidence: 1, detector: KNOWN_VALUES_DETECTOR }));
56
+ }
57
+ }
58
+ return entities;
59
+ }
60
+ toJSON() {
61
+ return { name: this.name, count: this.size };
62
+ }
63
+ toString() {
64
+ return `KnownValuesDetector(${String(this.size)} values)`;
65
+ }
66
+ [Symbol.for('nodejs.util.inspect.custom')]() {
67
+ return this.toString();
68
+ }
69
+ }
70
+ function checked(item) {
71
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
72
+ throw new TypeError(LIST_MESSAGE);
73
+ }
74
+ const { value, type } = item;
75
+ if (typeof value !== 'string') {
76
+ throw new TypeError('Each known value must be a string.');
77
+ }
78
+ if (typeof type !== 'string' || !isEntityType(type)) {
79
+ throw new TypeError('Each known value needs a built-in entity type.');
80
+ }
81
+ const trimmed = value.normalize('NFC').trim();
82
+ const length = codePointLength(trimmed);
83
+ if (length < KnownValuesDetector.MIN_LENGTH) {
84
+ throw new TypeError(`Known values must be at least ${String(KnownValuesDetector.MIN_LENGTH)} characters long.`);
85
+ }
86
+ if (length > KnownValuesDetector.MAX_LENGTH) {
87
+ throw new TypeError(`Known values must be at most ${String(KnownValuesDetector.MAX_LENGTH)} characters long.`);
88
+ }
89
+ return { value: trimmed, type };
90
+ }
91
+ /** Regex source for one value: literal characters, spelling variants of umlauts and ß, flexible whitespace. */
92
+ function pattern(value) {
93
+ return value
94
+ .split(new RegExp(`${SPACE}+`, 'u'))
95
+ .map((word) => {
96
+ const chars = Array.from(word);
97
+ let source = '';
98
+ for (let i = 0; i < chars.length; i++) {
99
+ const char = chars[i] ?? '';
100
+ const lower = char.toLowerCase();
101
+ const next = (chars[i + 1] ?? '').toLowerCase();
102
+ const base = UMLAUTS[lower];
103
+ if (base !== undefined) {
104
+ source += umlaut(base);
105
+ }
106
+ else if (next === 'e' && (lower === 'a' || lower === 'o' || lower === 'u')) {
107
+ source += umlaut(lower);
108
+ i++;
109
+ }
110
+ else if (lower === 'ß' || (lower === 's' && next === 's')) {
111
+ source += '(?:ss|ß)';
112
+ i += lower === 's' ? 1 : 0;
113
+ }
114
+ else {
115
+ source += char.replace(SYNTAX, '\\$&');
116
+ }
117
+ }
118
+ return source;
119
+ })
120
+ .join(`${SPACE}+`);
121
+ }
122
+ /** "ü", "u" + combining diaeresis or "ue" (case-insensitive through the flags). */
123
+ function umlaut(base) {
124
+ const composed = `${base}̈`.normalize('NFC');
125
+ return `(?:${composed}|${base}\\u0308|${base}e)`;
126
+ }
@@ -1,13 +1,29 @@
1
1
  import { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction } from './detector.js';
2
+ import { type KnownValue } from './detectors/known-values.js';
2
3
  import { type Entity } from './entity.js';
4
+ import type { EntityLearner } from './learning/entity-learner.js';
3
5
  export interface EntityExtractorOptions {
4
6
  /**
5
7
  * Detectors to run; defaults to defaultDetectors(). Async detectors (e.g. ModelDetector) only work
6
8
  * with the async APIs (extractAsync(), redactAsync(), redactToVault(), maskAsync()).
7
9
  */
8
10
  detectors?: Iterable<Detector | DetectorFunction | AsyncDetector>;
9
- /** Values that are never treated as PII (exact match). */
11
+ /**
12
+ * Also detect the patterns of these learned types: adds `learner.detector()` after the detectors
13
+ * (unless it is already among them). It reads the learner's snapshot, which learn() and forget()
14
+ * update; call `learner.refresh()` to pick up types other processes learned.
15
+ */
16
+ learner?: Pick<EntityLearner, 'detector'>;
17
+ /** Values that are never treated as PII (exact match). Known values are exempt. */
10
18
  allowlist?: Iterable<string>;
19
+ /**
20
+ * Values known to be personal data (e.g. the account holder's name), found case-insensitively, in
21
+ * either umlaut spelling and only as whole words; see KnownValuesDetector. They win over the allowlist.
22
+ * Held only by this instance, never stored or learned.
23
+ *
24
+ * @throws TypeError (from the constructor) on invalid values; the message never contains a value
25
+ */
26
+ knownValues?: Iterable<KnownValue>;
11
27
  }
12
28
  /**
13
29
  * Offline, regex- and checksum-based detectors for all entity types.
@@ -4,6 +4,7 @@ import { BirthDateDetector } from './detectors/birth-date.js';
4
4
  import { EmailDetector } from './detectors/email.js';
5
5
  import { FileNumberDetector } from './detectors/file-number.js';
6
6
  import { IbanDetector } from './detectors/iban.js';
7
+ import { KNOWN_VALUES_DETECTOR, KnownValuesDetector } from './detectors/known-values.js';
7
8
  import { LicensePlateDetector } from './detectors/license-plate.js';
8
9
  import { PhoneDetector } from './detectors/phone.js';
9
10
  import { PostalAddressDetector } from './detectors/postal-address.js';
@@ -63,7 +64,15 @@ export class EntityExtractor {
63
64
  #detectors;
64
65
  #allowlist;
65
66
  constructor(options = {}) {
66
- this.#detectors = [...(options.detectors ?? defaultDetectors())];
67
+ const detectors = [...(options.detectors ?? defaultDetectors())];
68
+ const learned = options.learner?.detector();
69
+ if (learned !== undefined && !detectors.includes(learned)) {
70
+ detectors.push(learned);
71
+ }
72
+ if (options.knownValues !== undefined) {
73
+ detectors.push(new KnownValuesDetector(options.knownValues));
74
+ }
75
+ this.#detectors = detectors;
67
76
  this.#allowlist = new Set(options.allowlist);
68
77
  }
69
78
  /** Whether a detector needs the async APIs. */
@@ -129,7 +138,9 @@ export class EntityExtractor {
129
138
  return normalized === text ? entities : withOriginalValues(text, entities);
130
139
  }
131
140
  #withoutAllowed(entities) {
132
- return this.#allowlist.size === 0 ? entities : entities.filter((e) => !this.#allowlist.has(e.value));
141
+ return this.#allowlist.size === 0
142
+ ? entities
143
+ : entities.filter((e) => e.detector === KNOWN_VALUES_DETECTOR || !this.#allowlist.has(e.value));
133
144
  }
134
145
  }
135
146
  /** Replaces characters that break line- and space-based patterns, one UTF-16 unit for one. */
package/dist/index.d.ts CHANGED
@@ -4,11 +4,13 @@
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';
10
11
  export { FileNumberDetector } from './detectors/file-number.js';
11
12
  export { IbanDetector } from './detectors/iban.js';
13
+ export { KNOWN_VALUES_DETECTOR, KnownValuesDetector, type KnownValue } from './detectors/known-values.js';
12
14
  export { LicensePlateDetector } from './detectors/license-plate.js';
13
15
  export { PhoneDetector } from './detectors/phone.js';
14
16
  export { PostalAddressDetector } from './detectors/postal-address.js';
@@ -19,8 +21,8 @@ export { defaultDetectors, EntityExtractor, surname, type EntityExtractorOptions
19
21
  export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
22
  export { DetectionError, type DetectionErrorCode, LearningError, type LearningErrorCode, PiiShieldError, VaultError, type VaultErrorCode, } from './errors.js';
21
23
  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';
24
+ export { CUSTOM_ENTITY_TYPE_LIMITS, type CustomEntityType, customEntityTypeFromJSON, type CustomEntityTypeInit, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
25
+ export { type DropExamplesResult, EntityLearner, type EntityLearnerOptions, type LearningResult, } from './learning/entity-learner.js';
24
26
  export { JsonFileCustomEntityStore, type JsonFileCustomEntityStoreOptions } from './learning/json-file-store.js';
25
27
  export { patternViolation } from './learning/pattern-grammar.js';
26
28
  export { learnPattern } from './learning/pattern-learner.js';
@@ -36,7 +38,7 @@ export { foundTypes, type PlaceholderMapping, type RedactionResult, type Redacto
36
38
  export { isValidAtSvnr } from './validators/at-svnr.js';
37
39
  export { isValidDeTaxId } from './validators/de-tax-id.js';
38
40
  export { isValidIban } from './validators/iban.js';
39
- export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
41
+ export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
40
42
  export { InMemoryVault, type InMemoryVaultOptions } from './vault/in-memory-vault.js';
41
43
  export { MemoryVaultStorage, type MemoryVaultStorageOptions } from './vault/memory-vault-storage.js';
42
44
  export type { Clock, Vault, VaultStorage } from './vault/vault.js';
package/dist/index.js CHANGED
@@ -4,11 +4,13 @@
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';
10
11
  export { FileNumberDetector } from './detectors/file-number.js';
11
12
  export { IbanDetector } from './detectors/iban.js';
13
+ export { KNOWN_VALUES_DETECTOR, KnownValuesDetector } from './detectors/known-values.js';
12
14
  export { LicensePlateDetector } from './detectors/license-plate.js';
13
15
  export { PhoneDetector } from './detectors/phone.js';
14
16
  export { PostalAddressDetector } from './detectors/postal-address.js';
@@ -19,8 +21,8 @@ export { defaultDetectors, EntityExtractor, surname } from './entity-extractor.j
19
21
  export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
22
  export { DetectionError, LearningError, PiiShieldError, VaultError, } from './errors.js';
21
23
  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';
24
+ export { CUSTOM_ENTITY_TYPE_LIMITS, customEntityTypeFromJSON, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
25
+ export { EntityLearner, } from './learning/entity-learner.js';
24
26
  export { JsonFileCustomEntityStore } from './learning/json-file-store.js';
25
27
  export { patternViolation } from './learning/pattern-grammar.js';
26
28
  export { learnPattern } from './learning/pattern-learner.js';
@@ -35,6 +37,6 @@ export { foundTypes, restorePlaceholders, } from './redaction.js';
35
37
  export { isValidAtSvnr } from './validators/at-svnr.js';
36
38
  export { isValidDeTaxId } from './validators/de-tax-id.js';
37
39
  export { isValidIban } from './validators/iban.js';
38
- export { EncryptedVault, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
40
+ export { EncryptedVault, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
39
41
  export { InMemoryVault } from './vault/in-memory-vault.js';
40
42
  export { MemoryVaultStorage } from './vault/memory-vault-storage.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Background work shared by createPiiShield() and the service (serviceFromEnv()): the periodic purge of
3
+ * expired vault entries and the default report of its errors.
4
+ */
5
+ /**
6
+ * `Name CODE` of an error, for log lines. Never the message: driver and provider messages can quote
7
+ * values (a pg error's `detail`, a provider echoing the request text).
8
+ */
9
+ export declare function describeError(error: unknown): string;
10
+ /** The default `onError`: one line to stderr with the task, the error's name and code, nothing else. */
11
+ export declare function reportToStderr(error: unknown, task: string): void;
12
+ /** Seconds between two purges of expired vault entries, unless configured otherwise. */
13
+ export declare const DEFAULT_PURGE_INTERVAL = 300;
14
+ /** The longest purge interval accepted: one day. */
15
+ export declare const MAX_PURGE_INTERVAL = 86400;
16
+ export interface PurgeSchedule {
17
+ /** Stops the timer and waits for a purge that is running. Idempotent. */
18
+ stop(): Promise<void>;
19
+ }
20
+ /**
21
+ * Runs `purge` at once and then every `intervalSeconds`, on an unref'd timer (it never keeps the process
22
+ * alive). Purges never overlap: a tick while one is running is skipped. Failures go to `onError`.
23
+ *
24
+ * Expired entries are personal data past their storage period (Art. 5(1)(e) GDPR): they must really be
25
+ * deleted, not only hidden by the read filter.
26
+ */
27
+ export declare function schedulePurge(purge: () => Promise<unknown>, intervalSeconds: number, onError: (error: unknown) => void): PurgeSchedule;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Background work shared by createPiiShield() and the service (serviceFromEnv()): the periodic purge of
3
+ * expired vault entries and the default report of its errors.
4
+ */
5
+ /**
6
+ * `Name CODE` of an error, for log lines. Never the message: driver and provider messages can quote
7
+ * values (a pg error's `detail`, a provider echoing the request text).
8
+ */
9
+ export function describeError(error) {
10
+ const { name = 'Error', code } = (error ?? {});
11
+ return `${typeof name === 'string' ? name : 'Error'}${typeof code === 'string' ? ` ${code}` : ''}`;
12
+ }
13
+ /** The default `onError`: one line to stderr with the task, the error's name and code, nothing else. */
14
+ export function reportToStderr(error, task) {
15
+ process.stderr.write(`pii-shield: ${task} failed (${describeError(error)})\n`);
16
+ }
17
+ /** Seconds between two purges of expired vault entries, unless configured otherwise. */
18
+ export const DEFAULT_PURGE_INTERVAL = 300;
19
+ /** The longest purge interval accepted: one day. */
20
+ export const MAX_PURGE_INTERVAL = 86_400;
21
+ /**
22
+ * Runs `purge` at once and then every `intervalSeconds`, on an unref'd timer (it never keeps the process
23
+ * alive). Purges never overlap: a tick while one is running is skipped. Failures go to `onError`.
24
+ *
25
+ * Expired entries are personal data past their storage period (Art. 5(1)(e) GDPR): they must really be
26
+ * deleted, not only hidden by the read filter.
27
+ */
28
+ export function schedulePurge(purge, intervalSeconds, onError) {
29
+ let running;
30
+ const run = () => {
31
+ running ??= purge()
32
+ .then(() => undefined, (e) => {
33
+ onError(e);
34
+ })
35
+ .finally(() => {
36
+ running = undefined;
37
+ });
38
+ };
39
+ run();
40
+ const timer = setInterval(run, intervalSeconds * 1000).unref();
41
+ return {
42
+ stop: async () => {
43
+ clearInterval(timer);
44
+ await running;
45
+ },
46
+ };
47
+ }
@@ -11,15 +11,16 @@ export declare const CUSTOM_ENTITY_TYPE_LIMITS: Readonly<{
11
11
  *
12
12
  * Validated, frozen data; its JSON form is exactly PHP's `CustomEntityType::toArray()`, so
13
13
  * `JSON.stringify(type)` gives the stored shape. Create it with `defineCustomEntityType()` or
14
- * `customEntityTypeFromJSON()`. Examples are stored, so they must be synthetic or anonymised.
14
+ * `customEntityTypeFromJSON()`. Examples are stored, so they must be synthetic or anonymised; a type
15
+ * with a pattern can drop them (`withoutExamples()`, `EntityLearner` option `keepExamples: false`).
15
16
  */
16
17
  export interface CustomEntityType {
17
18
  /** UPPER_SNAKE_CASE, becomes the placeholder name (⟦NAME_1⟧). */
18
19
  readonly name: string;
19
20
  readonly description: string;
20
- /** Values that are this type. */
21
+ /** Values that are this type; empty only for a type with a pattern whose examples were dropped. */
21
22
  readonly examples: readonly string[];
22
- /** Similar values that are not. */
23
+ /** Similar values that are not (empty when the examples were dropped). */
23
24
  readonly counterExamples: readonly string[];
24
25
  /** Regular expression in PCRE syntax without delimiters (see PatternGrammar), or null for model-only types. */
25
26
  readonly pattern: string | null;
@@ -37,10 +38,19 @@ export interface CustomEntityTypeInit {
37
38
  * @throws LearningError
38
39
  */
39
40
  export declare function defineCustomEntityType(init: CustomEntityTypeInit): CustomEntityType;
41
+ /**
42
+ * The type without its examples and counter-examples, so that only name, description and pattern are
43
+ * stored (data minimisation). Detection by the pattern is unchanged; model-based detection then knows the
44
+ * type only by name and description. PHP cannot read such a type (its `fromArray()` requires an example).
45
+ *
46
+ * @throws LearningError when the type has no pattern: a model-only type is found only through its examples
47
+ */
48
+ export declare function withoutExamples(type: CustomEntityType): CustomEntityType;
40
49
  /**
41
50
  * Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
42
51
  * fields become empty, non-string list entries are dropped, unknown keys are ignored, an empty pattern
43
- * means model-only. Every field is then validated.
52
+ * means model-only. Every field is then validated. Unlike PHP, a type with a pattern may have no
53
+ * examples (see withoutExamples()).
44
54
  *
45
55
  * @throws LearningError
46
56
  */
@@ -17,6 +17,23 @@ const compiledPatterns = new WeakMap();
17
17
  * @throws LearningError
18
18
  */
19
19
  export function defineCustomEntityType(init) {
20
+ return buildType(init, true);
21
+ }
22
+ /**
23
+ * The type without its examples and counter-examples, so that only name, description and pattern are
24
+ * stored (data minimisation). Detection by the pattern is unchanged; model-based detection then knows the
25
+ * type only by name and description. PHP cannot read such a type (its `fromArray()` requires an example).
26
+ *
27
+ * @throws LearningError when the type has no pattern: a model-only type is found only through its examples
28
+ */
29
+ export function withoutExamples(type) {
30
+ if (type.pattern === null) {
31
+ throw new LearningError(`"${type.name}" has no pattern, so only model-based detection finds it, and it needs the examples for that. Keep its examples or give it a pattern.`);
32
+ }
33
+ return buildType({ ...type, examples: [], counterExamples: [] }, false);
34
+ }
35
+ /** Without `requireExamples`, a type with a pattern may have none (stored after withoutExamples()). */
36
+ function buildType(init, requireExamples) {
20
37
  const { name, description, examples, counterExamples = [], pattern = null } = init;
21
38
  // PHP's pattern has no /u and no D modifier: $ also matches before a final "\n".
22
39
  if (!/^[A-Z][A-Z0-9_]{1,39}\n?$/.test(name)) {
@@ -25,7 +42,7 @@ export function defineCustomEntityType(init) {
25
42
  if (isEntityType(name)) {
26
43
  throw new LearningError(`"${name}" is a built-in type. Choose another name.`);
27
44
  }
28
- if (examples.length === 0) {
45
+ if (examples.length === 0 && (requireExamples || pattern === null)) {
29
46
  throw new LearningError('At least one example is needed.');
30
47
  }
31
48
  // Description and examples reach the detection model: keep them short, single-line data.
@@ -54,7 +71,8 @@ export function defineCustomEntityType(init) {
54
71
  /**
55
72
  * Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
56
73
  * fields become empty, non-string list entries are dropped, unknown keys are ignored, an empty pattern
57
- * means model-only. Every field is then validated.
74
+ * means model-only. Every field is then validated. Unlike PHP, a type with a pattern may have no
75
+ * examples (see withoutExamples()).
58
76
  *
59
77
  * @throws LearningError
60
78
  */
@@ -62,19 +80,19 @@ export function customEntityTypeFromJSON(data) {
62
80
  const record = isPhpArray(data) ? data : {};
63
81
  const strings = (list) => isPhpArray(list) ? Object.values(list).filter((v) => typeof v === 'string') : [];
64
82
  const { name, description, examples, counterExamples, pattern } = record;
65
- return defineCustomEntityType({
83
+ return buildType({
66
84
  name: typeof name === 'string' ? name : '',
67
85
  description: typeof description === 'string' ? description : '',
68
86
  examples: strings(examples),
69
87
  counterExamples: strings(counterExamples),
70
88
  pattern: typeof pattern === 'string' && pattern !== '' ? pattern : null,
71
- });
89
+ }, false);
72
90
  }
73
91
  /** The compiled pattern of a type (validating it first if it did not come from defineCustomEntityType()). */
74
92
  export function compiledPattern(type) {
75
93
  let compiled = compiledPatterns.get(type);
76
94
  if (compiled === undefined) {
77
- compiled = compiledPatterns.get(defineCustomEntityType(type)) ?? null;
95
+ compiled = compiledPatterns.get(buildType(type, false)) ?? null;
78
96
  compiledPatterns.set(type, compiled);
79
97
  }
80
98
  return compiled;
@@ -10,6 +10,24 @@ export interface EntityLearnerOptions {
10
10
  store: CustomEntityStore;
11
11
  /** Derives a pattern from examples; default learnPattern(). */
12
12
  learnPattern?: (examples: readonly string[], counterExamples: readonly string[]) => string;
13
+ /**
14
+ * Store examples and counter-examples with the type. Default true (PHP's behaviour and file format).
15
+ *
16
+ * With false, learn() checks the pattern against the examples and then stores only name, description
17
+ * and pattern (data minimisation: examples may be personal data). Consequences: types without a pattern
18
+ * (plain words, model-only) are refused, because only the examples let the model find them; the model
19
+ * knows the other types by name and description only; a stored type cannot be re-derived from its
20
+ * examples later; PHP cannot read a store that holds such types. Types stored before keep their
21
+ * examples until dropExamples().
22
+ */
23
+ keepExamples?: boolean;
24
+ }
25
+ /** Result of EntityLearner.dropExamples(): type names only. */
26
+ export interface DropExamplesResult {
27
+ /** Types whose examples were removed. */
28
+ readonly stripped: readonly string[];
29
+ /** Model-only types: they keep their examples, without them nothing would find them. */
30
+ readonly kept: readonly string[];
13
31
  }
14
32
  /**
15
33
  * Teach pii-shield new entity types from examples ("mask things like this too").
@@ -24,6 +42,8 @@ export interface EntityLearnerOptions {
24
42
  export declare class EntityLearner {
25
43
  #private;
26
44
  constructor(options: EntityLearnerOptions);
45
+ /** Whether learn() stores examples and counter-examples (option `keepExamples`). */
46
+ get keepExamples(): boolean;
27
47
  /** A learner whose snapshot is already loaded from the store. */
28
48
  static create(options: EntityLearnerOptions): Promise<EntityLearner>;
29
49
  /**
@@ -33,18 +53,29 @@ export declare class EntityLearner {
33
53
  */
34
54
  learn(init: CustomEntityTypeInit): Promise<LearningResult>;
35
55
  /**
36
- * Same as learn(), without saving: for trying out examples.
56
+ * Same as learn(), without saving: for trying out examples. The type is what learn() would store
57
+ * (without examples if `keepExamples` is false).
37
58
  *
38
59
  * @throws LearningError
39
60
  */
40
61
  preview(init: CustomEntityTypeInit): LearningResult;
41
62
  forget(name: string): Promise<void>;
63
+ /**
64
+ * Removes the examples and counter-examples of every stored type that has a pattern (e.g. after
65
+ * switching to `keepExamples: false`). Model-only types keep theirs. Run it as a one-off migration:
66
+ * a type another process learns at the same time can be overwritten with its older version.
67
+ */
68
+ dropExamples(): Promise<DropExamplesResult>;
42
69
  /** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
43
70
  types(): Promise<CustomEntityType[]>;
44
71
  /** Reloads the snapshot the detector uses. */
45
72
  refresh(): Promise<void>;
46
73
  /** The types in the current snapshot. */
47
74
  get snapshot(): readonly CustomEntityType[];
48
- /** A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take effect. */
75
+ /**
76
+ * A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take
77
+ * effect. Always the same instance, so `new PiiShield({ learner })` can tell when it is already among
78
+ * the detectors.
79
+ */
49
80
  detector(): Detector;
50
81
  }
@@ -1,7 +1,7 @@
1
1
  import { LearningError } from '../errors.js';
2
2
  import { phpTrim } from '../internal/pcre.js';
3
3
  import { LearnedTypesDetector } from './custom-entity-detector.js';
4
- import { defineCustomEntityType } from './custom-entity-type.js';
4
+ import { defineCustomEntityType, withoutExamples, } from './custom-entity-type.js';
5
5
  import { learnPattern } from './pattern-learner.js';
6
6
  const MODEL_ONLY_NOTE = 'No pattern: plain words would match ordinary text. Only model-based detection finds this type.';
7
7
  /**
@@ -17,10 +17,17 @@ const MODEL_ONLY_NOTE = 'No pattern: plain words would match ordinary text. Only
17
17
  export class EntityLearner {
18
18
  #store;
19
19
  #learnPattern;
20
+ #keepExamples;
20
21
  #snapshot = [];
22
+ #detector;
21
23
  constructor(options) {
22
24
  this.#store = options.store;
23
25
  this.#learnPattern = options.learnPattern ?? learnPattern;
26
+ this.#keepExamples = options.keepExamples ?? true;
27
+ }
28
+ /** Whether learn() stores examples and counter-examples (option `keepExamples`). */
29
+ get keepExamples() {
30
+ return this.#keepExamples;
24
31
  }
25
32
  /** A learner whose snapshot is already loaded from the store. */
26
33
  static async create(options) {
@@ -40,7 +47,8 @@ export class EntityLearner {
40
47
  return result;
41
48
  }
42
49
  /**
43
- * Same as learn(), without saving: for trying out examples.
50
+ * Same as learn(), without saving: for trying out examples. The type is what learn() would store
51
+ * (without examples if `keepExamples` is false).
44
52
  *
45
53
  * @throws LearningError
46
54
  */
@@ -60,12 +68,42 @@ export class EntityLearner {
60
68
  note = MODEL_ONLY_NOTE;
61
69
  }
62
70
  }
63
- return Object.freeze({ type: defineCustomEntityType({ ...init, counterExamples, pattern }), note });
71
+ // Validated with the examples (the pattern must match them) before they are dropped.
72
+ const type = defineCustomEntityType({ ...init, counterExamples, pattern });
73
+ if (this.#keepExamples) {
74
+ return Object.freeze({ type, note });
75
+ }
76
+ if (type.pattern === null) {
77
+ throw new LearningError('These examples give no pattern, and this learner does not keep examples, which model-based detection would need to find the type. Enter a pattern by hand.');
78
+ }
79
+ return Object.freeze({ type: withoutExamples(type), note });
64
80
  }
65
81
  async forget(name) {
66
82
  await this.#store.remove(name);
67
83
  await this.refresh();
68
84
  }
85
+ /**
86
+ * Removes the examples and counter-examples of every stored type that has a pattern (e.g. after
87
+ * switching to `keepExamples: false`). Model-only types keep theirs. Run it as a one-off migration:
88
+ * a type another process learns at the same time can be overwritten with its older version.
89
+ */
90
+ async dropExamples() {
91
+ const stripped = [];
92
+ const kept = [];
93
+ for (const type of await this.#store.all()) {
94
+ if (type.examples.length === 0 && type.counterExamples.length === 0) {
95
+ continue;
96
+ }
97
+ if (type.pattern === null) {
98
+ kept.push(type.name);
99
+ continue;
100
+ }
101
+ await this.#store.save(withoutExamples(type));
102
+ stripped.push(type.name);
103
+ }
104
+ await this.refresh();
105
+ return Object.freeze({ stripped: Object.freeze(stripped), kept: Object.freeze(kept) });
106
+ }
69
107
  /** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
70
108
  async types() {
71
109
  const types = await this.#store.all();
@@ -80,8 +118,13 @@ export class EntityLearner {
80
118
  get snapshot() {
81
119
  return this.#snapshot;
82
120
  }
83
- /** A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take effect. */
121
+ /**
122
+ * A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take
123
+ * effect. Always the same instance, so `new PiiShield({ learner })` can tell when it is already among
124
+ * the detectors.
125
+ */
84
126
  detector() {
85
- return new LearnedTypesDetector(() => this.#snapshot);
127
+ this.#detector ??= new LearnedTypesDetector(() => this.#snapshot);
128
+ return this.#detector;
86
129
  }
87
130
  }
@@ -6,14 +6,16 @@ import { type CustomEntityType } from './custom-entity-type.js';
6
6
  * `@waswrongassembled/pii-shield/testing`.
7
7
  *
8
8
  * Examples and counter-examples are stored in plain text and may be personal data: treat the backend
9
- * like any other store of personal data (access rights, backups, deletion through `remove()`).
9
+ * like any other store of personal data (access rights, backups, deletion through `remove()`), or store
10
+ * none (EntityLearner option `keepExamples: false`).
10
11
  *
11
12
  * Contract every implementation keeps:
12
13
  * - `all()` is sorted by name in byte order (sortByName(), PHP's strcmp()), independent of a
13
14
  * database collation.
14
15
  * - `get()` of an unknown name gives `null`; `save()` replaces a type with the same name; `remove()` of
15
16
  * an unknown name is a no-op.
16
- * - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved.
17
+ * - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved, also types
18
+ * with a pattern and no examples (withoutExamples()).
17
19
  * - Concurrent `save()`/`remove()` calls for different names must not lose each other's writes.
18
20
  * KeyValueCustomEntityStore keeps this only for writes through one instance: its read-modify-write
19
21
  * of the whole list loses writes across processes unless you serialise them yourself.
@@ -22,10 +22,12 @@ export class PiiMasker {
22
22
  #strategies;
23
23
  #fallback;
24
24
  constructor(options = {}) {
25
- const { detectors, allowlist, strategies = {}, fallback = new TypeLabelMask() } = options;
25
+ const { detectors, allowlist, knownValues, learner, strategies = {}, fallback = new TypeLabelMask() } = options;
26
26
  this.#extractor = new EntityExtractor({
27
27
  ...(detectors === undefined ? {} : { detectors }),
28
28
  ...(allowlist === undefined ? {} : { allowlist }),
29
+ ...(knownValues === undefined ? {} : { knownValues }),
30
+ ...(learner === undefined ? {} : { learner }),
29
31
  });
30
32
  const merged = new Map();
31
33
  for (const [type, strategy] of [...Object.entries(defaultMaskingStrategies()), ...Object.entries(strategies)]) {