@waswrongassembled/pii-shield 0.3.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 CHANGED
@@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.4.0] - 2026-11-23
9
+
10
+ ### Added
11
+
12
+ - Known values per call: `knownValues: [{ value, type }]` for `PiiShield`, `PiiMasker` and `EntityExtractor`, and in the bodies of `POST /v1/redact` and `POST /v1/mask`. Each value is found wherever it occurs as a whole word, case-insensitively, with umlauts in either spelling (`Müller` / `Mueller` / decomposed, `ß` / `ss`) and any whitespace between its words; a short value never matches inside a longer word (`Ali` not in `Alibi`). Known values win over the allowlist and, in the service, apply regardless of `types`. Overlaps with rule findings are resolved like any other (longer span first), so placeholders never nest. The values are held only for the call: never stored, learned or logged, validation errors (`TypeError`, HTTP 400) never contain them, and the detector serializes as `{ name, count }`. Limits: 500 values, 2–200 characters each. `KnownValuesDetector` is exported. Without `knownValues` nothing changes.
13
+
8
14
  ## [0.3.0] - 2026-11-22
9
15
 
10
16
  ### Added
@@ -66,7 +72,8 @@ Privacy and crash bugs of the PHP package are fixed rather than reproduced: name
66
72
  - `@waswrongassembled/pii-shield/mcp` (peer `@modelcontextprotocol/sdk`): the MCP tools `redact_text`, `restore_text`, `mask_text`, `learn_entity_type` and `list_entity_types` over STDIO and Streamable HTTP.
67
73
  - `pii-shield` CLI: `pii-shield serve`, `pii-shield mcp [--http]`, configured with PHP's environment variables.
68
74
 
69
- [Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.3.0...HEAD
75
+ [Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.4.0...HEAD
76
+ [0.4.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.3.0...v0.4.0
70
77
  [0.3.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.2.0...v0.3.0
71
78
  [0.2.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.1...v0.2.0
72
79
  [0.1.1]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.0...v0.1.1
package/README.md CHANGED
@@ -52,6 +52,24 @@ JSON.stringify(result); // '{"redactedText":"Sehr geehrter Herr ⟦PERSON_1⟧,
52
52
 
53
53
  Detected types: `PERSON`, `EMAIL`, `PHONE`, `IBAN`, `SVNR`, `TAX_ID`, `FILE_NUMBER`, `BIRTH_DATE`, `LICENSE_PLATE`, `ADDRESS` (see `EntityType`), plus your learned types. Choose detectors with `new PiiShield({ detectors: [...] })` (default: `defaultDetectors()`).
54
54
 
55
+ ### Known values
56
+
57
+ When you already know whose data a text is about, pass those values per call. They are found wherever they occur as whole words, case-insensitively and with umlauts in either spelling, even where no detector would find them:
58
+
59
+ ```ts
60
+ import { EntityType, PiiShield } from '@waswrongassembled/pii-shield';
61
+
62
+ const shield = new PiiShield({
63
+ knownValues: [
64
+ { value: 'Jürgen Müller', type: EntityType.Person },
65
+ { value: 'KD-99812', type: EntityType.FileNumber },
66
+ ],
67
+ });
68
+ shield.redact('JUERGEN MUELLER, Kundennr. KD-99812').redactedText; // '⟦PERSON_1⟧, Kundennr. ⟦FILE_NUMBER_1⟧'
69
+ ```
70
+
71
+ A short value never matches inside a longer word (`Ali` not in `Alibi`), known values win over the `allowlist`, and they are only held by that instance: never stored, learned or logged. The HTTP service takes the same list as `knownValues` in the body of `/v1/redact` and `/v1/mask`, for that request only. Limits: 500 values of 2–200 characters.
72
+
55
73
  ## Masking
56
74
 
57
75
  Irreversible replacement, for logs or analytics. IBANs and phone numbers stay partly visible by default.
@@ -0,0 +1,40 @@
1
+ import type { Detector } from '../detector.js';
2
+ import { type Entity } from '../entity.js';
3
+ import { type EntityType } from '../entity-type.js';
4
+ /** A value the caller already knows to be personal data, e.g. the account holder's name. */
5
+ export interface KnownValue {
6
+ readonly value: string;
7
+ readonly type: EntityType;
8
+ }
9
+ /** The `detector` of entities found from known values; they are exempt from the allowlist. */
10
+ export declare const KNOWN_VALUES_DETECTOR = "known-values";
11
+ /**
12
+ * Finds values the caller passes per call (names of the account holder, their customer numbers, ...)
13
+ * wherever they occur as whole words:
14
+ *
15
+ * - case-insensitive (Unicode), so "MÜLLER" and "müller" match "Müller"
16
+ * - umlauts in either spelling: "Müller" also matches "Mueller" and a decomposed "Müller", and
17
+ * "Mueller" matches "Müller"; "ß" and "ss" match each other
18
+ * - only whole words: "Ali" does not match in "Alibi" or "Kalium"
19
+ * - any run of whitespace (also a line break) between the words of a value
20
+ *
21
+ * The values are held only by this instance (never stored, learned or logged); validation errors never
22
+ * contain them, and the detector serializes and inspects as `{ name, count }`.
23
+ */
24
+ export declare class KnownValuesDetector implements Detector {
25
+ #private;
26
+ static readonly MAX_VALUES = 500;
27
+ static readonly MIN_LENGTH = 2;
28
+ static readonly MAX_LENGTH = 200;
29
+ readonly name = "known-values";
30
+ /** @throws TypeError on invalid input; the message never contains a value */
31
+ constructor(values: Iterable<KnownValue>);
32
+ /** Number of distinct values. */
33
+ get size(): number;
34
+ detect(text: string): Entity[];
35
+ toJSON(): {
36
+ name: string;
37
+ count: number;
38
+ };
39
+ toString(): string;
40
+ }
@@ -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,4 +1,5 @@
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';
3
4
  import type { EntityLearner } from './learning/entity-learner.js';
4
5
  export interface EntityExtractorOptions {
@@ -13,8 +14,16 @@ export interface EntityExtractorOptions {
13
14
  * update; call `learner.refresh()` to pick up types other processes learned.
14
15
  */
15
16
  learner?: Pick<EntityLearner, 'detector'>;
16
- /** Values that are never treated as PII (exact match). */
17
+ /** Values that are never treated as PII (exact match). Known values are exempt. */
17
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>;
18
27
  }
19
28
  /**
20
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';
@@ -68,6 +69,9 @@ export class EntityExtractor {
68
69
  if (learned !== undefined && !detectors.includes(learned)) {
69
70
  detectors.push(learned);
70
71
  }
72
+ if (options.knownValues !== undefined) {
73
+ detectors.push(new KnownValuesDetector(options.knownValues));
74
+ }
71
75
  this.#detectors = detectors;
72
76
  this.#allowlist = new Set(options.allowlist);
73
77
  }
@@ -134,7 +138,9 @@ export class EntityExtractor {
134
138
  return normalized === text ? entities : withOriginalValues(text, entities);
135
139
  }
136
140
  #withoutAllowed(entities) {
137
- 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));
138
144
  }
139
145
  }
140
146
  /** Replaces characters that break line- and space-based patterns, one UTF-16 unit for one. */
package/dist/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export { BirthDateDetector } from './detectors/birth-date.js';
10
10
  export { EmailDetector, type ContactDetectorOptions } from './detectors/email.js';
11
11
  export { FileNumberDetector } from './detectors/file-number.js';
12
12
  export { IbanDetector } from './detectors/iban.js';
13
+ export { KNOWN_VALUES_DETECTOR, KnownValuesDetector, type KnownValue } from './detectors/known-values.js';
13
14
  export { LicensePlateDetector } from './detectors/license-plate.js';
14
15
  export { PhoneDetector } from './detectors/phone.js';
15
16
  export { PostalAddressDetector } from './detectors/postal-address.js';
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { BirthDateDetector } from './detectors/birth-date.js';
10
10
  export { EmailDetector } from './detectors/email.js';
11
11
  export { FileNumberDetector } from './detectors/file-number.js';
12
12
  export { IbanDetector } from './detectors/iban.js';
13
+ export { KNOWN_VALUES_DETECTOR, KnownValuesDetector } from './detectors/known-values.js';
13
14
  export { LicensePlateDetector } from './detectors/license-plate.js';
14
15
  export { PhoneDetector } from './detectors/phone.js';
15
16
  export { PostalAddressDetector } from './detectors/postal-address.js';
@@ -22,10 +22,11 @@ export class PiiMasker {
22
22
  #strategies;
23
23
  #fallback;
24
24
  constructor(options = {}) {
25
- const { detectors, allowlist, learner, 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 }),
29
30
  ...(learner === undefined ? {} : { learner }),
30
31
  });
31
32
  const merged = new Map();
@@ -19,13 +19,14 @@ export class PiiShield {
19
19
  #vault;
20
20
  #vaultTtl;
21
21
  constructor(options = {}) {
22
- const { detectors, allowlist, learner, vault, vaultTtl = PiiShield.DEFAULT_VAULT_TTL } = options;
22
+ const { detectors, allowlist, knownValues, learner, vault, vaultTtl = PiiShield.DEFAULT_VAULT_TTL } = options;
23
23
  assertTtl(vaultTtl, 'The vault TTL must be positive.');
24
24
  this.#vault = vault;
25
25
  this.#vaultTtl = vaultTtl;
26
26
  this.#extractor = new EntityExtractor({
27
27
  ...(detectors === undefined ? {} : { detectors }),
28
28
  ...(allowlist === undefined ? {} : { allowlist }),
29
+ ...(knownValues === undefined ? {} : { knownValues }),
29
30
  ...(learner === undefined ? {} : { learner }),
30
31
  });
31
32
  }
@@ -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));
package/docs/openapi.yaml CHANGED
@@ -317,6 +317,21 @@ components:
317
317
  type: array
318
318
  items: { type: string }
319
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' }
320
335
  keepAuthorityContacts:
321
336
  type: boolean
322
337
  default: true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waswrongassembled/pii-shield",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Reversible PII redaction for LLM applications with DACH recognizers (AT SVNR, IBAN, tax numbers) and checksum validation. Wire-compatible port of clarifile/pii-shield.",
5
5
  "license": "MIT",
6
6
  "author": {