@waswrongassembled/pii-shield 0.0.0-stage → 0.1.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 (127) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +22 -0
  3. package/README.md +276 -2
  4. package/dist/ai-sdk/index.d.ts +19 -0
  5. package/dist/ai-sdk/index.js +30 -0
  6. package/dist/ai-sdk/middleware.d.ts +63 -0
  7. package/dist/ai-sdk/middleware.js +388 -0
  8. package/dist/bin.d.ts +2 -0
  9. package/dist/bin.js +9 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +124 -0
  12. package/dist/detector.d.ts +28 -0
  13. package/dist/detector.js +3 -0
  14. package/dist/detectors/at-svnr.d.ts +14 -0
  15. package/dist/detectors/at-svnr.js +31 -0
  16. package/dist/detectors/authority-context.d.ts +22 -0
  17. package/dist/detectors/authority-context.js +278 -0
  18. package/dist/detectors/birth-date.d.ts +10 -0
  19. package/dist/detectors/birth-date.js +21 -0
  20. package/dist/detectors/email.d.ts +15 -0
  21. package/dist/detectors/email.js +29 -0
  22. package/dist/detectors/file-number.d.ts +16 -0
  23. package/dist/detectors/file-number.js +20 -0
  24. package/dist/detectors/iban.d.ts +10 -0
  25. package/dist/detectors/iban.js +41 -0
  26. package/dist/detectors/license-plate.d.ts +9 -0
  27. package/dist/detectors/license-plate.js +13 -0
  28. package/dist/detectors/phone.d.ts +13 -0
  29. package/dist/detectors/phone.js +38 -0
  30. package/dist/detectors/postal-address.d.ts +14 -0
  31. package/dist/detectors/postal-address.js +19 -0
  32. package/dist/detectors/salutation-person.d.ts +18 -0
  33. package/dist/detectors/salutation-person.js +37 -0
  34. package/dist/detectors/tax-number.d.ts +14 -0
  35. package/dist/detectors/tax-number.js +33 -0
  36. package/dist/entity-extractor.d.ts +47 -0
  37. package/dist/entity-extractor.js +245 -0
  38. package/dist/entity-type.d.ts +24 -0
  39. package/dist/entity-type.js +26 -0
  40. package/dist/entity.d.ts +28 -0
  41. package/dist/entity.js +11 -0
  42. package/dist/errors.d.ts +48 -0
  43. package/dist/errors.js +49 -0
  44. package/dist/index.d.ts +42 -0
  45. package/dist/index.js +40 -0
  46. package/dist/internal/pcre.d.ts +55 -0
  47. package/dist/internal/pcre.js +102 -0
  48. package/dist/internal/php-json.d.ts +15 -0
  49. package/dist/internal/php-json.js +48 -0
  50. package/dist/internal/placeholder-stream.d.ts +24 -0
  51. package/dist/internal/placeholder-stream.js +118 -0
  52. package/dist/internal/text-spans.d.ts +8 -0
  53. package/dist/internal/text-spans.js +15 -0
  54. package/dist/learning/char-set.d.ts +29 -0
  55. package/dist/learning/char-set.js +158 -0
  56. package/dist/learning/custom-entity-detector.d.ts +26 -0
  57. package/dist/learning/custom-entity-detector.js +70 -0
  58. package/dist/learning/custom-entity-type.d.ts +49 -0
  59. package/dist/learning/custom-entity-type.js +150 -0
  60. package/dist/learning/entity-learner.d.ts +50 -0
  61. package/dist/learning/entity-learner.js +87 -0
  62. package/dist/learning/json-file-store.d.ts +36 -0
  63. package/dist/learning/json-file-store.js +132 -0
  64. package/dist/learning/learned-pattern.d.ts +48 -0
  65. package/dist/learning/learned-pattern.js +640 -0
  66. package/dist/learning/pattern-grammar.d.ts +12 -0
  67. package/dist/learning/pattern-grammar.js +148 -0
  68. package/dist/learning/pattern-learner.d.ts +10 -0
  69. package/dist/learning/pattern-learner.js +116 -0
  70. package/dist/learning/store.d.ts +51 -0
  71. package/dist/learning/store.js +84 -0
  72. package/dist/masking/partial-mask.d.ts +23 -0
  73. package/dist/masking/partial-mask.js +43 -0
  74. package/dist/masking/strategy.d.ts +10 -0
  75. package/dist/masking/strategy.js +1 -0
  76. package/dist/masking/type-label-mask.d.ts +17 -0
  77. package/dist/masking/type-label-mask.js +28 -0
  78. package/dist/mcp/index.d.ts +33 -0
  79. package/dist/mcp/index.js +146 -0
  80. package/dist/mcp/tools.d.ts +63 -0
  81. package/dist/mcp/tools.js +183 -0
  82. package/dist/model/chunks.d.ts +13 -0
  83. package/dist/model/chunks.js +74 -0
  84. package/dist/model/model-detector.d.ts +110 -0
  85. package/dist/model/model-detector.js +420 -0
  86. package/dist/model/prompt.d.ts +16 -0
  87. package/dist/model/prompt.js +192 -0
  88. package/dist/pii-masker.d.ts +27 -0
  89. package/dist/pii-masker.js +56 -0
  90. package/dist/pii-shield.d.ts +40 -0
  91. package/dist/pii-shield.js +142 -0
  92. package/dist/placeholder.d.ts +48 -0
  93. package/dist/placeholder.js +138 -0
  94. package/dist/redaction.d.ts +76 -0
  95. package/dist/redaction.js +52 -0
  96. package/dist/server/config.d.ts +23 -0
  97. package/dist/server/config.js +187 -0
  98. package/dist/server/http-server.d.ts +63 -0
  99. package/dist/server/http-server.js +241 -0
  100. package/dist/server/index.d.ts +9 -0
  101. package/dist/server/index.js +9 -0
  102. package/dist/server/model-providers.d.ts +31 -0
  103. package/dist/server/model-providers.js +158 -0
  104. package/dist/service/json-body.d.ts +14 -0
  105. package/dist/service/json-body.js +35 -0
  106. package/dist/service/local-peer.d.ts +16 -0
  107. package/dist/service/local-peer.js +83 -0
  108. package/dist/service/service-api.d.ts +75 -0
  109. package/dist/service/service-api.js +305 -0
  110. package/dist/validators/at-svnr.d.ts +8 -0
  111. package/dist/validators/at-svnr.js +21 -0
  112. package/dist/validators/de-tax-id.d.ts +8 -0
  113. package/dist/validators/de-tax-id.js +35 -0
  114. package/dist/validators/iban.d.ts +5 -0
  115. package/dist/validators/iban.js +24 -0
  116. package/dist/vault/encrypted-vault.d.ts +37 -0
  117. package/dist/vault/encrypted-vault.js +152 -0
  118. package/dist/vault/in-memory-vault.d.ts +17 -0
  119. package/dist/vault/in-memory-vault.js +39 -0
  120. package/dist/vault/memory-vault-storage.d.ts +16 -0
  121. package/dist/vault/memory-vault-storage.js +37 -0
  122. package/dist/vault/vault.d.ts +38 -0
  123. package/dist/vault/vault.js +16 -0
  124. package/dist/vault-redis/index.d.ts +28 -0
  125. package/dist/vault-redis/index.js +33 -0
  126. package/docs/openapi.yaml +422 -0
  127. package/package.json +122 -4
@@ -0,0 +1,33 @@
1
+ import { createEntity } from '../entity.js';
2
+ import { EntityType } from '../entity-type.js';
3
+ import { DIGIT, matchAll } from '../internal/pcre.js';
4
+ import { isValidDeTaxId } from '../validators/de-tax-id.js';
5
+ const D = DIGIT;
6
+ const AT_STEUERNUMMER = new RegExp(String.raw `(?<![${D}\/])${D}{2}[ -]?${D}{3}\/${D}{4}(?![${D}\/])`, 'gu');
7
+ const DE_STEUERNUMMER = new RegExp(String.raw `(?<![${D}\/])${D}{2,3}\/${D}{3,4}\/${D}{4,5}(?![${D}\/])`, 'gu');
8
+ const DE_STEUER_ID = new RegExp(String.raw `(?<!${D})${D}{2} ?${D}{3} ?${D}{3} ?${D}{3}(?!${D})`, 'gu');
9
+ /**
10
+ * AT Steuernummer (e.g. "46 123/4567"), DE Steuernummer (e.g. "181/815/08155")
11
+ * and DE Steuer-ID (11 digits, checksum-validated).
12
+ */
13
+ export class TaxNumberDetector {
14
+ name = 'tax_number';
15
+ #taxIdValidator;
16
+ constructor(options = {}) {
17
+ this.#taxIdValidator = options.taxIdValidator ?? isValidDeTaxId;
18
+ }
19
+ detect(text) {
20
+ const entities = [];
21
+ for (const pattern of [AT_STEUERNUMMER, DE_STEUERNUMMER]) {
22
+ for (const { value, offset } of matchAll(pattern, text)) {
23
+ entities.push(createEntity({ type: EntityType.TaxNumber, value, offset, confidence: 0.9, detector: 'tax_number' }));
24
+ }
25
+ }
26
+ for (const { value, offset } of matchAll(DE_STEUER_ID, text)) {
27
+ if (this.#taxIdValidator(value)) {
28
+ entities.push(createEntity({ type: EntityType.TaxNumber, value, offset, confidence: 1, detector: 'de_tax_id' }));
29
+ }
30
+ }
31
+ return entities.sort((a, b) => a.offset - b.offset);
32
+ }
33
+ }
@@ -0,0 +1,47 @@
1
+ import { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction } from './detector.js';
2
+ import { type Entity } from './entity.js';
3
+ export interface EntityExtractorOptions {
4
+ /**
5
+ * Detectors to run; defaults to defaultDetectors(). Async detectors (e.g. ModelDetector) only work
6
+ * with the async APIs (extractAsync(), redactAsync(), redactToVault(), maskAsync()).
7
+ */
8
+ detectors?: Iterable<Detector | DetectorFunction | AsyncDetector>;
9
+ /** Values that are never treated as PII (exact match). */
10
+ allowlist?: Iterable<string>;
11
+ }
12
+ /**
13
+ * Offline, regex- and checksum-based detectors for all entity types.
14
+ */
15
+ export declare function defaultDetectors(): Detector[];
16
+ /**
17
+ * Last word of a multi-word name, or null for single-word values.
18
+ */
19
+ export declare function surname(name: string): string | null;
20
+ /**
21
+ * Runs all detectors and returns a clean, non-overlapping list of entities.
22
+ *
23
+ * - Overlaps: the longer span wins; on equal length the higher confidence wins.
24
+ * - Propagation: every further whole-word occurrence of a detected value is an entity too,
25
+ * even where no detector would have found it on its own (e.g. a file number repeated without keyword).
26
+ * - Surnames of confidently detected full names are propagated as well.
27
+ * - Line endings and spaces: detectors see "\r\n" as " \n", a lone "\r" as "\n" and no-break or thin
28
+ * spaces as " ". The replacement keeps the length, so offsets and values refer to the
29
+ * original text and restore gives back the original characters.
30
+ */
31
+ export declare class EntityExtractor {
32
+ #private;
33
+ constructor(options?: EntityExtractorOptions);
34
+ /** Whether a detector needs the async APIs. */
35
+ get isAsync(): boolean;
36
+ /**
37
+ * Non-overlapping entities, sorted by offset.
38
+ *
39
+ * @throws TypeError when an async detector is configured (nothing is sent then); use extractAsync()
40
+ */
41
+ extract(text: string): Entity[];
42
+ /**
43
+ * Like extract(), with async detectors: they run concurrently, after the synchronous ones. Results are
44
+ * the same as extract() for the same findings.
45
+ */
46
+ extractAsync(text: string, options?: DetectOptions): Promise<Entity[]>;
47
+ }
@@ -0,0 +1,245 @@
1
+ import { isAsyncDetector, } from './detector.js';
2
+ import { AtSvnrDetector } from './detectors/at-svnr.js';
3
+ import { BirthDateDetector } from './detectors/birth-date.js';
4
+ import { EmailDetector } from './detectors/email.js';
5
+ import { FileNumberDetector } from './detectors/file-number.js';
6
+ import { IbanDetector } from './detectors/iban.js';
7
+ import { LicensePlateDetector } from './detectors/license-plate.js';
8
+ import { PhoneDetector } from './detectors/phone.js';
9
+ import { PostalAddressDetector } from './detectors/postal-address.js';
10
+ import { SalutationPersonDetector } from './detectors/salutation-person.js';
11
+ import { TaxNumberDetector } from './detectors/tax-number.js';
12
+ import { createEntity, typeName } from './entity.js';
13
+ import { EntityType } from './entity-type.js';
14
+ import { codePointLength, phpTrim, SPACE } from './internal/pcre.js';
15
+ const MIN_PROPAGATION_LENGTH = 3;
16
+ /**
17
+ * Surnames are only derived from confidently detected full names; an uncertain
18
+ * "Herr Muster Bescheid" must not turn every "Bescheid" into a person.
19
+ */
20
+ const SURNAME_PROPAGATION_MIN_CONFIDENCE = 0.8;
21
+ /**
22
+ * Offline, regex- and checksum-based detectors for all entity types.
23
+ */
24
+ export function defaultDetectors() {
25
+ return [
26
+ new AtSvnrDetector(),
27
+ new IbanDetector(),
28
+ new TaxNumberDetector(),
29
+ new EmailDetector(),
30
+ new PhoneDetector(),
31
+ new BirthDateDetector(),
32
+ new FileNumberDetector(),
33
+ new LicensePlateDetector(),
34
+ new SalutationPersonDetector(),
35
+ new PostalAddressDetector(),
36
+ ];
37
+ }
38
+ /**
39
+ * Last word of a multi-word name, or null for single-word values.
40
+ */
41
+ export function surname(name) {
42
+ const parts = phpTrim(name).split(SPLIT_WORDS);
43
+ return parts.length > 1 ? (parts.at(-1) ?? null) : null;
44
+ }
45
+ const SPLIT_WORDS = new RegExp(`${SPACE}+`, 'u');
46
+ const NORMALIZE = /\r\n?|[\u{A0}\u{2007}\u{2009}\u{202F}]/gu;
47
+ const WORDS = /[\p{L}\p{N}]+/gu;
48
+ const FIRST_WORD = /[\p{L}\p{N}]+/u;
49
+ const NOT_AFTER_WORD = /(?<![\p{L}\p{N}])/uy;
50
+ const NOT_BEFORE_WORD = /(?![\p{L}\p{N}])/uy;
51
+ /**
52
+ * Runs all detectors and returns a clean, non-overlapping list of entities.
53
+ *
54
+ * - Overlaps: the longer span wins; on equal length the higher confidence wins.
55
+ * - Propagation: every further whole-word occurrence of a detected value is an entity too,
56
+ * even where no detector would have found it on its own (e.g. a file number repeated without keyword).
57
+ * - Surnames of confidently detected full names are propagated as well.
58
+ * - Line endings and spaces: detectors see "\r\n" as " \n", a lone "\r" as "\n" and no-break or thin
59
+ * spaces as " ". The replacement keeps the length, so offsets and values refer to the
60
+ * original text and restore gives back the original characters.
61
+ */
62
+ export class EntityExtractor {
63
+ #detectors;
64
+ #allowlist;
65
+ constructor(options = {}) {
66
+ this.#detectors = [...(options.detectors ?? defaultDetectors())];
67
+ this.#allowlist = new Set(options.allowlist);
68
+ }
69
+ /** Whether a detector needs the async APIs. */
70
+ get isAsync() {
71
+ return this.#detectors.some(isAsyncDetector);
72
+ }
73
+ /**
74
+ * Non-overlapping entities, sorted by offset.
75
+ *
76
+ * @throws TypeError when an async detector is configured (nothing is sent then); use extractAsync()
77
+ */
78
+ extract(text) {
79
+ const asyncDetector = this.#detectors.find(isAsyncDetector);
80
+ if (asyncDetector !== undefined) {
81
+ throw new TypeError(`The detector "${asyncDetector.name ?? 'async'}" is async. Use extractAsync(), redactAsync(), redactToVault() or maskAsync().`);
82
+ }
83
+ const normalized = normalize(text);
84
+ const detected = [];
85
+ for (const detector of this.#detectors) {
86
+ const found = typeof detector === 'function' ? detector(normalized) : detector.detect(normalized);
87
+ if (isPromiseLike(found)) {
88
+ // A function returning a Promise cannot be told apart up front; its findings would be lost.
89
+ Promise.resolve(found).catch(() => undefined);
90
+ throw new TypeError('A detector returned a Promise. Implement AsyncDetector (async: true) and use extractAsync().');
91
+ }
92
+ for (const entity of found) {
93
+ detected.push(entity);
94
+ }
95
+ }
96
+ return this.#resolve(text, normalized, detected);
97
+ }
98
+ /**
99
+ * Like extract(), with async detectors: they run concurrently, after the synchronous ones. Results are
100
+ * the same as extract() for the same findings.
101
+ */
102
+ async extractAsync(text, options = {}) {
103
+ options.signal?.throwIfAborted();
104
+ const normalized = normalize(text);
105
+ // Synchronous detectors first: if one throws, nothing has been sent to an async one yet.
106
+ const results = this.#detectors.map((detector) => {
107
+ if (isAsyncDetector(detector)) {
108
+ return Promise.resolve([]);
109
+ }
110
+ return Promise.resolve(typeof detector === 'function' ? detector(normalized) : detector.detect(normalized));
111
+ });
112
+ this.#detectors.forEach((detector, i) => {
113
+ if (isAsyncDetector(detector)) {
114
+ results[i] = detector.detect(normalized, options);
115
+ }
116
+ });
117
+ const detected = [];
118
+ for (const found of await Promise.all(results)) {
119
+ for (const entity of found) {
120
+ detected.push(entity);
121
+ }
122
+ }
123
+ return this.#resolve(text, normalized, detected);
124
+ }
125
+ #resolve(text, normalized, detected) {
126
+ // Filter before propagation (an allowed value must not seed surnames) and after it.
127
+ let entities = resolveOverlaps(this.#withoutAllowed(detected));
128
+ entities = resolveOverlaps(this.#withoutAllowed([...entities, ...propagate(normalized, entities)]));
129
+ return normalized === text ? entities : withOriginalValues(text, entities);
130
+ }
131
+ #withoutAllowed(entities) {
132
+ return this.#allowlist.size === 0 ? entities : entities.filter((e) => !this.#allowlist.has(e.value));
133
+ }
134
+ }
135
+ /** Replaces characters that break line- and space-based patterns, one UTF-16 unit for one. */
136
+ function normalize(text) {
137
+ return text.replace(NORMALIZE, (m) => (m === '\r\n' ? ' \n' : m === '\r' ? '\n' : ' '));
138
+ }
139
+ /** The same spans with the characters of the original text. */
140
+ function withOriginalValues(text, entities) {
141
+ return entities.map((e) => {
142
+ const value = text.slice(e.offset, e.offset + e.value.length);
143
+ return value === e.value ? e : { ...e, value };
144
+ });
145
+ }
146
+ /**
147
+ * Greedy: take spans by length (desc), then confidence (desc), then offset, skip anything overlapping.
148
+ * Length counts code points, as in PHP, so the order is the same for values with characters outside the BMP.
149
+ */
150
+ function resolveOverlaps(entities) {
151
+ const ranked = entities
152
+ .map((entity) => ({ entity, length: codePointLength(entity.value) }))
153
+ .sort((a, b) => b.length - a.length || b.entity.confidence - a.entity.confidence || a.entity.offset - b.entity.offset);
154
+ const kept = [];
155
+ const covered = new Set();
156
+ for (const { entity } of ranked) {
157
+ const end = entity.offset + entity.value.length;
158
+ let free = true;
159
+ for (let i = entity.offset; i < end && free; i++) {
160
+ free = !covered.has(i);
161
+ }
162
+ if (!free) {
163
+ continue;
164
+ }
165
+ for (let i = entity.offset; i < end; i++) {
166
+ covered.add(i);
167
+ }
168
+ kept.push(entity);
169
+ }
170
+ return kept.sort((a, b) => a.offset - b.offset);
171
+ }
172
+ /**
173
+ * Every whole-word occurrence of a detected value (and of the surname of a confident full name).
174
+ *
175
+ * One pass over the text instead of one regex per value. Values are indexed by their first word,
176
+ * then by the position of that word in the value and by length; at each word of the text,
177
+ * the substring of that length is looked up. Cost per word: number of distinct lengths.
178
+ */
179
+ function propagate(text, entities) {
180
+ const needles = new Map();
181
+ for (const entity of entities) {
182
+ needles.set(`${typeName(entity)}\0${entity.value}`, {
183
+ type: entity.type,
184
+ value: entity.value,
185
+ label: entity.label,
186
+ });
187
+ if (entity.type === EntityType.Person && entity.confidence >= SURNAME_PROPAGATION_MIN_CONFIDENCE) {
188
+ const last = surname(entity.value);
189
+ if (last !== null) {
190
+ needles.set(`${typeName(entity)}\0${last}`, { type: entity.type, value: last, label: entity.label });
191
+ }
192
+ }
193
+ }
194
+ // first word → its position in the value → value length → value → needles
195
+ const index = new Map();
196
+ for (const needle of needles.values()) {
197
+ const first = codePointLength(needle.value) < MIN_PROPAGATION_LENGTH ? null : FIRST_WORD.exec(needle.value);
198
+ if (first === null) {
199
+ continue;
200
+ }
201
+ const byPrefix = getOrSet(index, first[0], () => new Map());
202
+ const byLength = getOrSet(byPrefix, first.index, () => new Map());
203
+ const byValue = getOrSet(byLength, needle.value.length, () => new Map());
204
+ getOrSet(byValue, needle.value, () => []).push(needle);
205
+ }
206
+ if (index.size === 0) {
207
+ return [];
208
+ }
209
+ const hits = [];
210
+ for (const word of text.matchAll(WORDS)) {
211
+ for (const [prefix, byLength] of index.get(word[0]) ?? []) {
212
+ const start = word.index - prefix;
213
+ if (start < 0) {
214
+ continue;
215
+ }
216
+ for (const [length, byValue] of byLength) {
217
+ const candidates = byValue.get(text.slice(start, start + length));
218
+ if (candidates !== undefined && isWordBoundary(text, start, start + length)) {
219
+ for (const needle of candidates) {
220
+ hits.push([start, needle]);
221
+ }
222
+ }
223
+ }
224
+ }
225
+ }
226
+ return hits
227
+ .sort((a, b) => a[0] - b[0])
228
+ .map(([offset, { type, value, label }]) => createEntity({ type, value, offset, confidence: 0.5, detector: 'propagation', label }));
229
+ }
230
+ function isWordBoundary(text, start, end) {
231
+ NOT_AFTER_WORD.lastIndex = start;
232
+ NOT_BEFORE_WORD.lastIndex = end;
233
+ return NOT_AFTER_WORD.test(text) && NOT_BEFORE_WORD.test(text);
234
+ }
235
+ function isPromiseLike(value) {
236
+ return typeof value?.then === 'function';
237
+ }
238
+ function getOrSet(map, key, create) {
239
+ let value = map.get(key);
240
+ if (value === undefined) {
241
+ value = create();
242
+ map.set(key, value);
243
+ }
244
+ return value;
245
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The kinds of personal data. The values appear in placeholders (`⟦IBAN_1⟧`) and are identical to the PHP package.
3
+ */
4
+ export declare const EntityType: Readonly<{
5
+ readonly Person: "PERSON";
6
+ readonly Address: "ADDRESS";
7
+ readonly AtSvnr: "SVNR";
8
+ readonly Iban: "IBAN";
9
+ readonly TaxNumber: "TAX_NUMBER";
10
+ readonly FileNumber: "FILE_NUMBER";
11
+ readonly Email: "EMAIL";
12
+ readonly Phone: "PHONE";
13
+ readonly BirthDate: "BIRTH_DATE";
14
+ readonly LicensePlate: "LICENSE_PLATE";
15
+ readonly IdNumber: "ID_NUMBER";
16
+ readonly CreditCard: "CREDIT_CARD";
17
+ readonly IpAddress: "IP_ADDRESS";
18
+ readonly Health: "HEALTH";
19
+ readonly Other: "OTHER";
20
+ }>;
21
+ export type EntityType = (typeof EntityType)[keyof typeof EntityType];
22
+ /** All entity type values, in declaration order. */
23
+ export declare const ENTITY_TYPES: readonly EntityType[];
24
+ export declare function isEntityType(value: string): value is EntityType;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The kinds of personal data. The values appear in placeholders (`⟦IBAN_1⟧`) and are identical to the PHP package.
3
+ */
4
+ export const EntityType = Object.freeze({
5
+ Person: 'PERSON',
6
+ Address: 'ADDRESS',
7
+ AtSvnr: 'SVNR',
8
+ Iban: 'IBAN',
9
+ TaxNumber: 'TAX_NUMBER',
10
+ FileNumber: 'FILE_NUMBER',
11
+ Email: 'EMAIL',
12
+ Phone: 'PHONE',
13
+ BirthDate: 'BIRTH_DATE',
14
+ LicensePlate: 'LICENSE_PLATE',
15
+ // Mainly found by model-based detection (any country, any format).
16
+ IdNumber: 'ID_NUMBER',
17
+ CreditCard: 'CREDIT_CARD',
18
+ IpAddress: 'IP_ADDRESS',
19
+ Health: 'HEALTH',
20
+ Other: 'OTHER',
21
+ });
22
+ /** All entity type values, in declaration order. */
23
+ export const ENTITY_TYPES = Object.freeze(Object.values(EntityType));
24
+ export function isEntityType(value) {
25
+ return ENTITY_TYPES.includes(value);
26
+ }
@@ -0,0 +1,28 @@
1
+ import type { EntityType } from './entity-type.js';
2
+ /**
3
+ * A detected span of personal data in the original text.
4
+ *
5
+ * - `offset` is a UTF-16 index, so `text.slice(offset, offset + value.length) === value`
6
+ * (PHP counts code points; see docs/DEVIATIONS.md).
7
+ * - `label` is only present for learned types, which use `EntityType.Other` with their own name
8
+ * (e.g. "INSURANCE_NUMBER"). Built-in detectors never set it; PHP's `null` maps to an absent property.
9
+ */
10
+ export interface Entity {
11
+ readonly type: EntityType;
12
+ readonly value: string;
13
+ readonly offset: number;
14
+ readonly confidence: number;
15
+ readonly detector: string;
16
+ readonly label?: string;
17
+ }
18
+ /** Creates an entity; `confidence` defaults to 1 and `detector` to "unknown", as in PHP. */
19
+ export declare function createEntity(init: {
20
+ type: EntityType;
21
+ value: string;
22
+ offset: number;
23
+ confidence?: number;
24
+ detector?: string;
25
+ label?: string | null | undefined;
26
+ }): Entity;
27
+ /** Name used in placeholders and masks: the custom label of a learned type, otherwise the type. */
28
+ export declare function typeName(entity: Entity): string;
package/dist/entity.js ADDED
@@ -0,0 +1,11 @@
1
+ /** Creates an entity; `confidence` defaults to 1 and `detector` to "unknown", as in PHP. */
2
+ export function createEntity(init) {
3
+ const { type, value, offset, confidence = 1, detector = 'unknown', label } = init;
4
+ return label === undefined || label === null
5
+ ? { type, value, offset, confidence, detector }
6
+ : { type, value, offset, confidence, detector, label };
7
+ }
8
+ /** Name used in placeholders and masks: the custom label of a learned type, otherwise the type. */
9
+ export function typeName(entity) {
10
+ return entity.label ?? entity.type;
11
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Base class of every error pii-shield throws for a runtime condition (PHP's ExceptionInterface):
3
+ * catch this to handle any of them. Messages never contain personal data or key material.
4
+ *
5
+ * Invalid arguments (a bad TTL, a key of the wrong length) throw the built-in `TypeError` / `RangeError`.
6
+ */
7
+ export declare class PiiShieldError extends Error {
8
+ /** Stable, machine-readable error code. */
9
+ readonly code: string;
10
+ constructor(message: string, code: string, options?: ErrorOptions);
11
+ }
12
+ export type VaultErrorCode = 'VAULT_DECRYPTION_FAILED' | 'VAULT_CORRUPT' | 'VAULT_UNKNOWN_ID';
13
+ /** Stored vault data could not be read, or the vault id is unknown (PHP's VaultException). */
14
+ export declare class VaultError extends PiiShieldError {
15
+ readonly code: VaultErrorCode;
16
+ constructor(message: string, code: VaultErrorCode, options?: ErrorOptions);
17
+ }
18
+ export type LearningErrorCode = 'LEARNING_FAILED' | 'LEARNING_PLAIN_WORDS';
19
+ /**
20
+ * A custom entity type could not be learned or loaded; the message says why and how to fix it
21
+ * (PHP's LearningFailedException). `LEARNING_PLAIN_WORDS` (PHP code 1): the examples are plain words,
22
+ * which cannot become a safe pattern. Messages name positions, never example values.
23
+ */
24
+ export declare class LearningError extends PiiShieldError {
25
+ readonly code: LearningErrorCode;
26
+ constructor(message: string, code?: LearningErrorCode, options?: ErrorOptions);
27
+ }
28
+ export type DetectionErrorCode = 'DETECTION_MODEL_UNREACHABLE' | 'DETECTION_INVALID_ANSWER' | 'DETECTION_TEXT_TOO_LONG';
29
+ /**
30
+ * Model-based detection failed and must not continue: going on without the model's findings could let
31
+ * personal data through unredacted (PHP's DetectionFailedException). The message never contains the text.
32
+ *
33
+ * - `DETECTION_MODEL_UNREACHABLE`: the model call failed or timed out. The error is the `cause`; keep it
34
+ * to server logs, providers may echo the request (the unredacted text) in their messages.
35
+ * - `DETECTION_INVALID_ANSWER`: the model's answer was unusable twice; `modelAnswer` holds it.
36
+ * - `DETECTION_TEXT_TOO_LONG`: the text needs more chunks than the model detector sends.
37
+ */
38
+ export declare class DetectionError extends PiiShieldError {
39
+ readonly code: DetectionErrorCode;
40
+ /**
41
+ * The model's answer, for debugging only: it may contain personal data. Not enumerable, so
42
+ * `console.log(error)` and `JSON.stringify(error)` leave it out.
43
+ */
44
+ readonly modelAnswer?: string;
45
+ constructor(message: string, code: DetectionErrorCode, options?: ErrorOptions & {
46
+ modelAnswer?: string;
47
+ });
48
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Base class of every error pii-shield throws for a runtime condition (PHP's ExceptionInterface):
3
+ * catch this to handle any of them. Messages never contain personal data or key material.
4
+ *
5
+ * Invalid arguments (a bad TTL, a key of the wrong length) throw the built-in `TypeError` / `RangeError`.
6
+ */
7
+ export class PiiShieldError extends Error {
8
+ /** Stable, machine-readable error code. */
9
+ code;
10
+ constructor(message, code, options) {
11
+ super(message, options);
12
+ this.name = new.target.name;
13
+ this.code = code;
14
+ }
15
+ }
16
+ /** Stored vault data could not be read, or the vault id is unknown (PHP's VaultException). */
17
+ export class VaultError extends PiiShieldError {
18
+ // eslint-disable-next-line @typescript-eslint/no-useless-constructor -- narrows `code` to VaultErrorCode
19
+ constructor(message, code, options) {
20
+ super(message, code, options);
21
+ }
22
+ }
23
+ /**
24
+ * A custom entity type could not be learned or loaded; the message says why and how to fix it
25
+ * (PHP's LearningFailedException). `LEARNING_PLAIN_WORDS` (PHP code 1): the examples are plain words,
26
+ * which cannot become a safe pattern. Messages name positions, never example values.
27
+ */
28
+ export class LearningError extends PiiShieldError {
29
+ constructor(message, code = 'LEARNING_FAILED', options) {
30
+ super(message, code, options);
31
+ }
32
+ }
33
+ /**
34
+ * Model-based detection failed and must not continue: going on without the model's findings could let
35
+ * personal data through unredacted (PHP's DetectionFailedException). The message never contains the text.
36
+ *
37
+ * - `DETECTION_MODEL_UNREACHABLE`: the model call failed or timed out. The error is the `cause`; keep it
38
+ * to server logs, providers may echo the request (the unredacted text) in their messages.
39
+ * - `DETECTION_INVALID_ANSWER`: the model's answer was unusable twice; `modelAnswer` holds it.
40
+ * - `DETECTION_TEXT_TOO_LONG`: the text needs more chunks than the model detector sends.
41
+ */
42
+ export class DetectionError extends PiiShieldError {
43
+ constructor(message, code, options) {
44
+ super(message, code, options);
45
+ if (options?.modelAnswer !== undefined) {
46
+ Object.defineProperty(this, 'modelAnswer', { value: options.modelAnswer, enumerable: false });
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield: reversible PII redaction, wire-compatible with clarifile/pii-shield (PHP).
3
+ *
4
+ * The public API is ported phase by phase, see docs/PLAN.md.
5
+ */
6
+ export { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction, isAsyncDetector, type Validator, } from './detector.js';
7
+ export { AtSvnrDetector } from './detectors/at-svnr.js';
8
+ export { BirthDateDetector } from './detectors/birth-date.js';
9
+ export { EmailDetector, type ContactDetectorOptions } from './detectors/email.js';
10
+ export { FileNumberDetector } from './detectors/file-number.js';
11
+ export { IbanDetector } from './detectors/iban.js';
12
+ export { LicensePlateDetector } from './detectors/license-plate.js';
13
+ export { PhoneDetector } from './detectors/phone.js';
14
+ export { PostalAddressDetector } from './detectors/postal-address.js';
15
+ export { SalutationPersonDetector } from './detectors/salutation-person.js';
16
+ export { TaxNumberDetector } from './detectors/tax-number.js';
17
+ export { createEntity, typeName, type Entity } from './entity.js';
18
+ export { defaultDetectors, EntityExtractor, surname, type EntityExtractorOptions } from './entity-extractor.js';
19
+ export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
+ export { DetectionError, type DetectionErrorCode, LearningError, type LearningErrorCode, PiiShieldError, VaultError, type VaultErrorCode, } from './errors.js';
21
+ 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 { JsonFileCustomEntityStore, type JsonFileCustomEntityStoreOptions } from './learning/json-file-store.js';
25
+ export { patternViolation } from './learning/pattern-grammar.js';
26
+ export { learnPattern } from './learning/pattern-learner.js';
27
+ export { type CustomEntityStore, InMemoryCustomEntityStore, KeyValueCustomEntityStore, type KeyValueCustomEntityStoreOptions, type KeyValueStore, } from './learning/store.js';
28
+ export { type DetectionModel, type ModelCallOptions, ModelDetector, type ModelDetectorOptions, type ModelFunction, ModelLocation, type ModelPrompt, } from './model/model-detector.js';
29
+ export { PartialMask, type PartialMaskOptions } from './masking/partial-mask.js';
30
+ export type { Masker, MaskingFunction, MaskingStrategy } from './masking/strategy.js';
31
+ export { TypeLabelMask, type TypeLabelMaskOptions } from './masking/type-label-mask.js';
32
+ export { defaultMaskingStrategies, PiiMasker, type PiiMaskerOptions } from './pii-masker.js';
33
+ export { NullPiiShield, PiiShield, type PiiShieldOptions } from './pii-shield.js';
34
+ export { formatPlaceholder, replacePlaceholders } from './placeholder.js';
35
+ export { foundTypes, type PlaceholderMapping, type RedactionResult, type Redactor, restorePlaceholders, type RestoreResult, type VaultRedactionResult, type VaultRedactor, } from './redaction.js';
36
+ export { isValidAtSvnr } from './validators/at-svnr.js';
37
+ export { isValidDeTaxId } from './validators/de-tax-id.js';
38
+ export { isValidIban } from './validators/iban.js';
39
+ export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
40
+ export { InMemoryVault, type InMemoryVaultOptions } from './vault/in-memory-vault.js';
41
+ export { MemoryVaultStorage, type MemoryVaultStorageOptions } from './vault/memory-vault-storage.js';
42
+ export type { Clock, Vault, VaultStorage } from './vault/vault.js';
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield: reversible PII redaction, wire-compatible with clarifile/pii-shield (PHP).
3
+ *
4
+ * The public API is ported phase by phase, see docs/PLAN.md.
5
+ */
6
+ export { isAsyncDetector, } from './detector.js';
7
+ export { AtSvnrDetector } from './detectors/at-svnr.js';
8
+ export { BirthDateDetector } from './detectors/birth-date.js';
9
+ export { EmailDetector } from './detectors/email.js';
10
+ export { FileNumberDetector } from './detectors/file-number.js';
11
+ export { IbanDetector } from './detectors/iban.js';
12
+ export { LicensePlateDetector } from './detectors/license-plate.js';
13
+ export { PhoneDetector } from './detectors/phone.js';
14
+ export { PostalAddressDetector } from './detectors/postal-address.js';
15
+ export { SalutationPersonDetector } from './detectors/salutation-person.js';
16
+ export { TaxNumberDetector } from './detectors/tax-number.js';
17
+ export { createEntity, typeName } from './entity.js';
18
+ export { defaultDetectors, EntityExtractor, surname } from './entity-extractor.js';
19
+ export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
20
+ export { DetectionError, LearningError, PiiShieldError, VaultError, } from './errors.js';
21
+ 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 { JsonFileCustomEntityStore } from './learning/json-file-store.js';
25
+ export { patternViolation } from './learning/pattern-grammar.js';
26
+ export { learnPattern } from './learning/pattern-learner.js';
27
+ export { InMemoryCustomEntityStore, KeyValueCustomEntityStore, } from './learning/store.js';
28
+ export { ModelDetector, ModelLocation, } from './model/model-detector.js';
29
+ export { PartialMask } from './masking/partial-mask.js';
30
+ export { TypeLabelMask } from './masking/type-label-mask.js';
31
+ export { defaultMaskingStrategies, PiiMasker } from './pii-masker.js';
32
+ export { NullPiiShield, PiiShield } from './pii-shield.js';
33
+ export { formatPlaceholder, replacePlaceholders } from './placeholder.js';
34
+ export { foundTypes, restorePlaceholders, } from './redaction.js';
35
+ export { isValidAtSvnr } from './validators/at-svnr.js';
36
+ export { isValidDeTaxId } from './validators/de-tax-id.js';
37
+ export { isValidIban } from './validators/iban.js';
38
+ export { EncryptedVault, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
39
+ export { InMemoryVault } from './vault/in-memory-vault.js';
40
+ export { MemoryVaultStorage } from './vault/memory-vault-storage.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Building blocks that make JavaScript regexes behave like the PHP package's PCRE patterns.
3
+ *
4
+ * PHP's /u modifier turns on PCRE2_UTF and PCRE2_UCP, so \d, \w, \s and \b are Unicode-aware there,
5
+ * while JavaScript's are ASCII (\d, \w, \b) or a different Unicode set (\s). Patterns ported from a
6
+ * PHP /u regex use these classes instead. They were checked code point by code point against PHP 8.5
7
+ * (PCRE2 10.49) and Node 24 (Unicode 17).
8
+ *
9
+ * Without /u PHP matches bytes: \d, \w and \s are ASCII there, which JavaScript's \d and \w already are.
10
+ *
11
+ * @internal
12
+ */
13
+ /** PCRE UCP \w as the inside of a character class. */
14
+ export declare const WORD_CHARS: string;
15
+ /** PCRE UCP \w. */
16
+ export declare const WORD: string;
17
+ /** PCRE UCP \s as the inside of a character class: JS \s lacks U+0085 and U+180E and adds U+FEFF. */
18
+ export declare const SPACE_CHARS: string;
19
+ /** PCRE UCP \s. */
20
+ export declare const SPACE: string;
21
+ /** PCRE UCP \d. */
22
+ export declare const DIGIT: string;
23
+ /** PCRE \b at a position followed by a word character (e.g. `\bAmt`). */
24
+ export declare const WORD_START: string;
25
+ /** PCRE \b at a position preceded by a word character (e.g. `Amt\b`). */
26
+ export declare const WORD_END: string;
27
+ /** PCRE ^ with /m: PHP's PCRE only treats "\n" as a newline, JavaScript also "\r", U+2028 and U+2029. */
28
+ export declare const LINE_START: string;
29
+ /** PCRE $ with /m (see LINE_START). */
30
+ export declare const LINE_END: string;
31
+ /**
32
+ * Replaces every decimal digit (\p{Nd}: fullwidth, Arabic-Indic, Devanagari, ...) with its ASCII digit.
33
+ * Detectors match such digits via \d under PHP's /u; PHP's validators then count ASCII digits only and
34
+ * reject the match (docs/DEVIATIONS.md). Unicode assigns \p{Nd} in contiguous runs of whole 0-9 blocks,
35
+ * so a digit's value is its distance from the start of its run, modulo 10.
36
+ */
37
+ export declare function asciiDigits(text: string): string;
38
+ /** A regex match of a whole pattern or a named group, with its UTF-16 offset. */
39
+ export interface RegexMatch {
40
+ readonly value: string;
41
+ readonly offset: number;
42
+ }
43
+ /**
44
+ * All matches of a global regex in text order, like PHP's preg_match_all(). With a group name, the regex
45
+ * needs the "d" flag; matches where the group is unmatched or empty are skipped (as RegexMatcher does).
46
+ */
47
+ export declare function matchAll(regex: RegExp, text: string, group?: string): RegexMatch[];
48
+ /** Number of code points, as PHP's mb_strlen() counts. */
49
+ export declare function codePointLength(text: string): number;
50
+ /** PHP's intval() for decimal strings: leading " \t\n\r\v\f", optional sign, ASCII digits; anything else ends it. */
51
+ export declare function phpIntval(text: string): number;
52
+ /** PHP's checkdate(). */
53
+ export declare function checkdate(month: number, day: number, year: number): boolean;
54
+ /** PHP's trim() without a character list: ASCII whitespace and NUL only. */
55
+ export declare function phpTrim(text: string): string;