@waswrongassembled/pii-shield 0.0.0-stage → 0.1.1

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 +38 -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,388 @@
1
+ import { PiiShieldError } from '../errors.js';
2
+ import { PlaceholderStreamRestorer } from '../internal/placeholder-stream.js';
3
+ /**
4
+ * A message part that cannot be redacted (a file: image, audio, PDF, …) is in the prompt. It would reach
5
+ * the provider with personal data, so the call is stopped before anything is sent (PHP's
6
+ * UnsupportedContentException). Extract the text locally (e.g. OCR) and send text only.
7
+ */
8
+ export class UnsupportedContentError extends PiiShieldError {
9
+ constructor(message) {
10
+ super(message, 'UNSUPPORTED_CONTENT');
11
+ }
12
+ }
13
+ /**
14
+ * Joins all texts of a prompt for one consistent redaction: PHP's separator, contains no character any
15
+ * detector matches. PHP throws when a text contains it (clarifile/pii-shield, PiiShieldProcessor); here it
16
+ * gets one U+2063 more than the longest run of U+2063 in the texts, so no text contains it and no
17
+ * occurrence can span a text boundary (the separator starts and ends with "\n"). Linear in the input.
18
+ */
19
+ function joinTexts(texts) {
20
+ let longest = 0;
21
+ for (const text of texts) {
22
+ for (const run of text.matchAll(/\u{2063}+/gu)) {
23
+ longest = Math.max(longest, run[0].length);
24
+ }
25
+ }
26
+ const separator = `\n${'\u{2063}'.repeat(Math.max(3, longest + 1))}\n`;
27
+ return { joined: texts.join(separator), separator };
28
+ }
29
+ /**
30
+ * AI SDK language model middleware: the provider only ever sees placeholders, the caller gets the answer
31
+ * with the original values (PHP's PiiShieldProcessor).
32
+ *
33
+ * ```ts
34
+ * const model = wrapLanguageModel({ model: openai('gpt-5'), middleware: piiShieldMiddleware(new PiiShield()) });
35
+ * ```
36
+ *
37
+ * - Prompt: all text of system, user, assistant and tool messages (text, reasoning, tool call inputs, tool
38
+ * results, approval reasons; string values of JSON, not keys) is redacted in one go, so the same value
39
+ * gets the same placeholder in every message. Every model call (every step of a tool loop) redacts the
40
+ * whole prompt again. Files in user and tool messages are rejected with `UnsupportedContentError` before
41
+ * anything is sent; files and custom parts of assistant messages pass unchanged.
42
+ * - Answer: text, reasoning, tool call inputs (JSON string values) and provider-executed tool results are
43
+ * restored, in `generate` and in streams (a placeholder split across chunks is held back until complete).
44
+ * In JSON mode (structured output) values are inserted JSON-escaped, so the JSON stays valid.
45
+ * `providerMetadata`, raw chunks and request/response bodies are passed unchanged.
46
+ *
47
+ * The mapping stays in this process: it is kept per call in a WeakMap, never in the call options.
48
+ * Async detectors (ModelDetector) work: the prompt is redacted with `redactAsync()` and the call's abort signal.
49
+ */
50
+ export function piiShieldMiddleware(shield, options = {}) {
51
+ const { vault = false, onRedact, onRestore, allowOpaqueAssistantParts = false } = options;
52
+ if (vault && !('redactToVault' in shield)) {
53
+ throw new TypeError('The vault option needs a shield with redactToVault() (a PiiShield with a vault).');
54
+ }
55
+ const redactions = new WeakMap();
56
+ const restorerFor = (params) => {
57
+ const redaction = redactions.get(params);
58
+ return redaction === undefined ? undefined : new CallRestorer(shield, redaction.mapping, isJsonMode(params));
59
+ };
60
+ const report = (restorer) => {
61
+ onRestore?.({ unknownPlaceholders: Object.freeze([...restorer.unknown]) });
62
+ };
63
+ return {
64
+ specificationVersion: 'v4',
65
+ transformParams: async ({ params }) => {
66
+ const texts = [];
67
+ mapPromptTexts(params.prompt, (text) => {
68
+ texts.push(text);
69
+ return text;
70
+ }, allowOpaqueAssistantParts);
71
+ if (texts.length === 0) {
72
+ return params;
73
+ }
74
+ const { joined, separator } = joinTexts(texts);
75
+ const detectOptions = params.abortSignal === undefined ? {} : { signal: params.abortSignal };
76
+ const redaction = vault && 'redactToVault' in shield
77
+ ? await shield.redactToVault(joined, detectOptions)
78
+ : await shield.redactAsync(joined, detectOptions);
79
+ const redactedTexts = redaction.redactedText.split(separator);
80
+ if (redactedTexts.length !== texts.length) {
81
+ throw new Error('Redaction changed the message structure.');
82
+ }
83
+ let next = 0;
84
+ const prompt = mapPromptTexts(params.prompt, () => redactedTexts[next++] ?? '', allowOpaqueAssistantParts);
85
+ const redacted = { ...params, prompt };
86
+ redactions.set(redacted, redaction);
87
+ onRedact?.({
88
+ placeholders: Object.freeze(Object.keys(redaction.mapping)),
89
+ ...('vaultId' in redaction && typeof redaction.vaultId === 'string' ? { vaultId: redaction.vaultId } : {}),
90
+ });
91
+ return redacted;
92
+ },
93
+ wrapGenerate: async ({ doGenerate, params }) => {
94
+ const result = await doGenerate();
95
+ const restorer = restorerFor(params);
96
+ if (restorer === undefined) {
97
+ return result;
98
+ }
99
+ const restored = {
100
+ ...result,
101
+ content: result.content.map((part) => restorer.content(part)),
102
+ };
103
+ if (result.structuredOutputText !== undefined) {
104
+ restored.structuredOutputText = restorer.text(result.structuredOutputText);
105
+ }
106
+ report(restorer);
107
+ return restored;
108
+ },
109
+ wrapStream: async ({ doStream, params }) => {
110
+ const result = await doStream();
111
+ const restorer = restorerFor(params);
112
+ if (restorer === undefined) {
113
+ return result;
114
+ }
115
+ const transform = restorer.streamTransform(() => {
116
+ report(restorer);
117
+ });
118
+ return { ...result, stream: result.stream.pipeThrough(transform) };
119
+ },
120
+ };
121
+ }
122
+ /** Restores one model call's answer; collects the unknown placeholders. */
123
+ class CallRestorer {
124
+ unknown = new Set();
125
+ #shield;
126
+ #mapping;
127
+ #jsonEscaped;
128
+ #jsonMode;
129
+ constructor(shield, mapping, jsonMode) {
130
+ this.#shield = shield;
131
+ this.#mapping = mapping;
132
+ this.#jsonEscaped = Object.fromEntries(Object.entries(mapping).map(([k, v]) => [k, JSON.stringify(v).slice(1, -1)]));
133
+ this.#jsonMode = jsonMode;
134
+ }
135
+ /** Plain text. */
136
+ plain = (text) => this.#restore(text, this.#mapping);
137
+ /** Text inside JSON source: values are inserted JSON-escaped. */
138
+ jsonSource = (text) => this.#restore(text, this.#jsonEscaped);
139
+ /** Answer text: JSON source in JSON mode (structured output), else plain. */
140
+ text(text) {
141
+ return this.#jsonMode ? this.jsonSource(text) : this.plain(text);
142
+ }
143
+ /** A JSON document (a tool call input): string values are restored, keys and formatting of unchanged input kept. */
144
+ json(source) {
145
+ let value;
146
+ try {
147
+ value = JSON.parse(source);
148
+ }
149
+ catch {
150
+ return this.jsonSource(source);
151
+ }
152
+ const restored = mapStrings(value, this.plain);
153
+ return restored === value ? source : JSON.stringify(restored);
154
+ }
155
+ content(part) {
156
+ switch (part.type) {
157
+ case 'text':
158
+ return { ...part, text: this.text(part.text) };
159
+ case 'reasoning':
160
+ return { ...part, text: this.plain(part.text) };
161
+ case 'tool-call':
162
+ return { ...part, input: this.json(part.input) };
163
+ case 'tool-result':
164
+ return { ...part, result: mapStrings(part.result, this.plain) };
165
+ default:
166
+ return part;
167
+ }
168
+ }
169
+ streamTransform(onEnd) {
170
+ const open = new Map();
171
+ const restorerOf = (key, restore) => {
172
+ let restorer = open.get(key);
173
+ if (restorer === undefined) {
174
+ restorer = new PlaceholderStreamRestorer(restore);
175
+ open.set(key, restorer);
176
+ }
177
+ return restorer;
178
+ };
179
+ const textRestore = (text) => this.text(text);
180
+ const inputRestore = new Map();
181
+ const flushed = (key) => {
182
+ const rest = open.get(key)?.flush() ?? '';
183
+ open.delete(key);
184
+ return rest;
185
+ };
186
+ const emitDelta = (controller, part, delta) => {
187
+ if (delta !== '' || part.providerMetadata !== undefined) {
188
+ controller.enqueue({ ...part, delta });
189
+ }
190
+ };
191
+ return new TransformStream({
192
+ transform: (part, controller) => {
193
+ switch (part.type) {
194
+ case 'text-delta':
195
+ emitDelta(controller, part, restorerOf(`text:${part.id}`, textRestore).push(part.delta));
196
+ return;
197
+ case 'reasoning-delta':
198
+ emitDelta(controller, part, restorerOf(`reasoning:${part.id}`, this.plain).push(part.delta));
199
+ return;
200
+ case 'tool-input-start':
201
+ inputRestore.set(part.id, part.inputEncoding === 'text' ? this.plain : this.jsonSource);
202
+ controller.enqueue(part);
203
+ return;
204
+ case 'tool-input-delta':
205
+ emitDelta(controller, part, restorerOf(`tool-input:${part.id}`, inputRestore.get(part.id) ?? this.jsonSource).push(part.delta));
206
+ return;
207
+ case 'text-end':
208
+ case 'reasoning-end':
209
+ case 'tool-input-end': {
210
+ const kind = part.type.slice(0, -'-end'.length);
211
+ const rest = flushed(`${kind}:${part.id}`);
212
+ if (rest !== '') {
213
+ controller.enqueue({ type: `${kind}-delta`, id: part.id, delta: rest });
214
+ }
215
+ if (part.type === 'tool-input-end') {
216
+ inputRestore.delete(part.id);
217
+ }
218
+ controller.enqueue(part);
219
+ return;
220
+ }
221
+ case 'tool-call':
222
+ case 'tool-result':
223
+ controller.enqueue(this.content(part));
224
+ return;
225
+ case 'finish':
226
+ this.#flushAll(open, controller);
227
+ controller.enqueue(part);
228
+ return;
229
+ default:
230
+ controller.enqueue(part);
231
+ }
232
+ },
233
+ flush: (controller) => {
234
+ this.#flushAll(open, controller);
235
+ onEnd();
236
+ },
237
+ });
238
+ }
239
+ /** Emits what is still held (a stream without -end parts) as deltas of its block. */
240
+ #flushAll(open, controller) {
241
+ for (const [key, restorer] of open) {
242
+ const rest = restorer.flush();
243
+ const separator = key.indexOf(':');
244
+ if (rest !== '') {
245
+ const type = `${key.slice(0, separator)}-delta`;
246
+ controller.enqueue({ type, id: key.slice(separator + 1), delta: rest });
247
+ }
248
+ }
249
+ open.clear();
250
+ }
251
+ #restore(text, mapping) {
252
+ const restored = this.#shield.restore(text, mapping);
253
+ for (const placeholder of restored.unknownPlaceholders) {
254
+ this.unknown.add(placeholder);
255
+ }
256
+ return restored.text;
257
+ }
258
+ }
259
+ function isJsonMode(params) {
260
+ return params.responseFormat?.type === 'json';
261
+ }
262
+ /**
263
+ * Returns a copy of the prompt with every redactable text replaced by `replace(text)`, called in prompt order.
264
+ *
265
+ * @throws UnsupportedContentError for files in user and tool messages, and for file, reasoning-file and
266
+ * custom parts of assistant messages unless `allowOpaque` is set
267
+ */
268
+ function mapPromptTexts(prompt, replace, allowOpaque) {
269
+ return prompt.map((message) => {
270
+ switch (message.role) {
271
+ case 'system':
272
+ return { ...message, content: replace(message.content) };
273
+ case 'user':
274
+ return {
275
+ ...message,
276
+ content: message.content.map((part) => {
277
+ if (part.type === 'file') {
278
+ throw unsupported('file');
279
+ }
280
+ return { ...part, text: replace(part.text) };
281
+ }),
282
+ };
283
+ case 'assistant':
284
+ return {
285
+ ...message,
286
+ content: message.content.map((part) => {
287
+ switch (part.type) {
288
+ case 'text':
289
+ case 'reasoning':
290
+ return { ...part, text: replace(part.text) };
291
+ case 'tool-call':
292
+ return { ...part, input: mapStrings(part.input, replace) };
293
+ case 'tool-result':
294
+ return { ...part, output: mapToolOutput(part.output, replace) };
295
+ case 'file':
296
+ case 'reasoning-file':
297
+ case 'custom':
298
+ if (allowOpaque) {
299
+ return part;
300
+ }
301
+ throw unsupported(part.type);
302
+ default: {
303
+ // Fail closed on part types added by later AI SDK versions.
304
+ const unknownPart = part;
305
+ throw unsupported(unknownPart.type);
306
+ }
307
+ }
308
+ }),
309
+ };
310
+ case 'tool':
311
+ return {
312
+ ...message,
313
+ content: message.content.map((part) => {
314
+ if (part.type === 'tool-result') {
315
+ return { ...part, output: mapToolOutput(part.output, replace) };
316
+ }
317
+ return part.reason === undefined ? part : { ...part, reason: replace(part.reason) };
318
+ }),
319
+ };
320
+ }
321
+ });
322
+ }
323
+ function mapToolOutput(output, replace) {
324
+ switch (output.type) {
325
+ case 'text':
326
+ case 'error-text':
327
+ return { ...output, value: replace(output.value) };
328
+ case 'json':
329
+ case 'error-json':
330
+ return { ...output, value: mapStrings(output.value, replace) };
331
+ case 'execution-denied':
332
+ return output.reason === undefined ? output : { ...output, reason: replace(output.reason) };
333
+ case 'content':
334
+ return {
335
+ ...output,
336
+ value: output.value.map((item) => {
337
+ if (item.type === 'file') {
338
+ throw unsupported('file');
339
+ }
340
+ return item.type === 'text' ? { ...item, text: replace(item.text) } : item;
341
+ }),
342
+ };
343
+ }
344
+ }
345
+ /**
346
+ * Applies `replace` to every string in arrays and plain objects (JSON values), depth-first in key order,
347
+ * each key before its value: keys can carry personal data too (e.g. `{"Maria Musterfrau": 3}`). Returns the
348
+ * same reference when nothing changed (PHP's StructuredRestorer, which keeps keys); other values (numbers,
349
+ * dates, class instances) are left as they are.
350
+ *
351
+ * @throws UnsupportedContentError if two keys of one object map to the same key
352
+ */
353
+ function mapStrings(value, replace) {
354
+ if (typeof value === 'string') {
355
+ return replace(value);
356
+ }
357
+ if (Array.isArray(value)) {
358
+ const mapped = value.map((item) => mapStrings(item, replace));
359
+ return (mapped.some((item, i) => item !== value[i]) ? mapped : value);
360
+ }
361
+ if (isPlainObject(value)) {
362
+ let changed = false;
363
+ const entries = [];
364
+ const keys = new Set();
365
+ for (const [key, item] of Object.entries(value)) {
366
+ const mappedKey = replace(key);
367
+ if (keys.has(mappedKey)) {
368
+ throw new UnsupportedContentError('Two keys of a JSON object map to the same key; it cannot be redacted.');
369
+ }
370
+ keys.add(mappedKey);
371
+ const mapped = mapStrings(item, replace);
372
+ changed ||= mappedKey !== key || mapped !== item;
373
+ entries.push([mappedKey, mapped]);
374
+ }
375
+ return (changed ? Object.fromEntries(entries) : value);
376
+ }
377
+ return value;
378
+ }
379
+ function isPlainObject(value) {
380
+ if (typeof value !== 'object' || value === null) {
381
+ return false;
382
+ }
383
+ const proto = Object.getPrototypeOf(value);
384
+ return proto === Object.prototype || proto === null;
385
+ }
386
+ function unsupported(type) {
387
+ return new UnsupportedContentError(`Content of type "${type}" cannot be redacted. Extract its text locally and send text only.`);
388
+ }
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './cli.js';
3
+ main(process.argv.slice(2)).then((code) => {
4
+ process.exitCode = code;
5
+ }, (e) => {
6
+ // Name only: a message may quote request data.
7
+ process.stderr.write(`pii-shield: unexpected ${e instanceof Error ? e.name : 'error'}\n`);
8
+ process.exitCode = 1;
9
+ });
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Runs the CLI; resolves with the exit code once a server stops (or at once on an error). */
2
+ export declare function main(argv: string[], env?: Readonly<Record<string, string | undefined>>): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The `pii-shield` command: the HTTP service (`serve`) and the MCP server (`mcp`), configured from
3
+ * environment variables (docs/server.md).
4
+ */
5
+ import { parseArgs } from 'node:util';
6
+ import { ConfigError, serviceFromEnv } from './server/config.js';
7
+ import { startServer } from './server/http-server.js';
8
+ const USAGE = `Usage:
9
+ pii-shield serve [--port <port>] [--host <host>] HTTP service: /v1 (and /mcp if @modelcontextprotocol/sdk is installed)
10
+ pii-shield mcp MCP server over STDIO
11
+ pii-shield mcp --http [--port <port>] [--host <host>] MCP server over Streamable HTTP (/mcp)
12
+
13
+ Configuration: environment variables (PII_SERVICE_TOKEN, PII_SERVICE_VAULT_KEY, ...), see
14
+ https://github.com/waswrongassembled/pii-shield-js/blob/main/docs/server.md`;
15
+ /** Runs the CLI; resolves with the exit code once a server stops (or at once on an error). */
16
+ export async function main(argv, env = process.env) {
17
+ let parsed;
18
+ try {
19
+ parsed = parseArgs({
20
+ args: argv,
21
+ allowPositionals: true,
22
+ options: {
23
+ port: { type: 'string', short: 'p' },
24
+ host: { type: 'string' },
25
+ http: { type: 'boolean' },
26
+ help: { type: 'boolean', short: 'h' },
27
+ },
28
+ });
29
+ }
30
+ catch (e) {
31
+ process.stderr.write(`${e instanceof Error ? e.message : String(e)}\n\n${USAGE}\n`);
32
+ return 2;
33
+ }
34
+ const { values, positionals } = parsed;
35
+ const command = positionals[0];
36
+ if (values.help === true || command === undefined) {
37
+ process.stderr.write(`${USAGE}\n`);
38
+ return values.help === true ? 0 : 2;
39
+ }
40
+ if (positionals.length > 1 ||
41
+ (command !== 'serve' && command !== 'mcp') ||
42
+ (command === 'serve' && values.http === true)) {
43
+ process.stderr.write(`${USAGE}\n`);
44
+ return 2;
45
+ }
46
+ const port = values.port === undefined ? undefined : Number(values.port);
47
+ if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535)) {
48
+ process.stderr.write('--port must be a port number.\n');
49
+ return 2;
50
+ }
51
+ let service;
52
+ try {
53
+ service = await serviceFromEnv(env);
54
+ }
55
+ catch (e) {
56
+ if (e instanceof ConfigError) {
57
+ process.stderr.write(`pii-shield: ${e.message}\n`);
58
+ return 1;
59
+ }
60
+ throw e;
61
+ }
62
+ for (const note of service.notes) {
63
+ process.stderr.write(`pii-shield: ${note}\n`);
64
+ }
65
+ const onError = (error) => {
66
+ // Name and code only: messages of provider errors may quote the request text.
67
+ const { name = 'Error', code } = (error ?? {});
68
+ process.stderr.write(`pii-shield: request failed (${name}${typeof code === 'string' ? ` ${code}` : ''})\n`);
69
+ };
70
+ if (command === 'mcp' && values.http !== true) {
71
+ const mcp = await loadMcp();
72
+ if (mcp === null) {
73
+ await service.close();
74
+ return 1;
75
+ }
76
+ const server = await mcp.serveStdio(service.api);
77
+ await new Promise((resolve) => {
78
+ server.server.onclose = resolve;
79
+ process.once('SIGINT', resolve);
80
+ process.once('SIGTERM', resolve);
81
+ });
82
+ await server.close();
83
+ await service.close();
84
+ return 0;
85
+ }
86
+ const mcp = await loadMcp(command === 'serve');
87
+ if (mcp === null && command === 'mcp') {
88
+ await service.close();
89
+ return 1;
90
+ }
91
+ const server = await startServer({
92
+ api: service.api,
93
+ v1: command === 'serve',
94
+ mcp: mcp === null ? undefined : mcp.createMcpHttpHandler(service.api, { maxBodyBytes: service.maxBodyBytes }),
95
+ allowedHosts: service.allowedHosts,
96
+ maxBodyBytes: service.maxBodyBytes,
97
+ port: port ?? service.port,
98
+ host: values.host ?? service.host,
99
+ onError,
100
+ });
101
+ process.stderr.write(`pii-shield: listening on ${server.url}${command === 'serve' ? ' (/v1' : ' ('}${mcp === null ? '' : command === 'serve' ? ', /mcp' : '/mcp'})\n`);
102
+ await new Promise((resolve) => {
103
+ process.once('SIGINT', resolve);
104
+ process.once('SIGTERM', resolve);
105
+ });
106
+ process.stderr.write('pii-shield: shutting down\n');
107
+ await server.close();
108
+ await service.close();
109
+ return 0;
110
+ }
111
+ async function loadMcp(optional = false) {
112
+ try {
113
+ return await import('./mcp/index.js');
114
+ }
115
+ catch (e) {
116
+ if (e.code !== 'ERR_MODULE_NOT_FOUND') {
117
+ throw e;
118
+ }
119
+ process.stderr.write(optional
120
+ ? 'pii-shield: /mcp is off (install @modelcontextprotocol/sdk to enable it)\n'
121
+ : 'pii-shield: the MCP server needs the package "@modelcontextprotocol/sdk" (npm install @modelcontextprotocol/sdk)\n');
122
+ return null;
123
+ }
124
+ }
@@ -0,0 +1,28 @@
1
+ import type { Entity } from './entity.js';
2
+ /**
3
+ * Finds personal data in a text. Offsets of the returned entities are UTF-16 indices into `text`.
4
+ * A plain function `(text) => Entity[]` works wherever a detector is accepted.
5
+ */
6
+ export interface Detector {
7
+ /** Informational name, e.g. for logs. */
8
+ readonly name?: string;
9
+ detect(text: string): readonly Entity[];
10
+ }
11
+ export type DetectorFunction = (text: string) => readonly Entity[];
12
+ export interface DetectOptions {
13
+ /** Cancels the detection; the returned Promise rejects with the signal's reason. */
14
+ readonly signal?: AbortSignal | undefined;
15
+ }
16
+ /**
17
+ * A detector that needs I/O, e.g. ModelDetector. `async: true` marks it, so the synchronous APIs
18
+ * (`extract()`, `redact()`, `mask()`) can refuse it before anything is sent; use `extractAsync()`,
19
+ * `redactAsync()`, `redactToVault()` or `maskAsync()` instead.
20
+ */
21
+ export interface AsyncDetector {
22
+ readonly name?: string;
23
+ readonly async: true;
24
+ detect(text: string, options?: DetectOptions): Promise<readonly Entity[]>;
25
+ }
26
+ export declare function isAsyncDetector(detector: unknown): detector is AsyncDetector;
27
+ /** A candidate check, e.g. a checksum. */
28
+ export type Validator = (candidate: string) => boolean;
@@ -0,0 +1,3 @@
1
+ export function isAsyncDetector(detector) {
2
+ return typeof detector === 'object' && detector !== null && detector.async === true;
3
+ }
@@ -0,0 +1,14 @@
1
+ import type { Detector, Validator } from '../detector.js';
2
+ import { type Entity } from '../entity.js';
3
+ /**
4
+ * Austrian social security number: "4568 150392", "4568-150392", "4568150392", also split across a line break (OCR).
5
+ * With a hyphen or line break the last six digits must be a valid date (DDMMYY).
6
+ */
7
+ export declare class AtSvnrDetector implements Detector {
8
+ #private;
9
+ readonly name = "at_svnr";
10
+ constructor(options?: {
11
+ validator?: Validator;
12
+ });
13
+ detect(text: string): Entity[];
14
+ }
@@ -0,0 +1,31 @@
1
+ import { createEntity } from '../entity.js';
2
+ import { EntityType } from '../entity-type.js';
3
+ import { asciiDigits, checkdate, DIGIT, matchAll } from '../internal/pcre.js';
4
+ import { isValidAtSvnr } from '../validators/at-svnr.js';
5
+ const PATTERN = new RegExp(String.raw `(?<!${DIGIT})${DIGIT}{4}(?:[ -]|[ \t]*\n[ \t]*)?${DIGIT}{6}(?!${DIGIT})`, 'gu');
6
+ /**
7
+ * Austrian social security number: "4568 150392", "4568-150392", "4568150392", also split across a line break (OCR).
8
+ * With a hyphen or line break the last six digits must be a valid date (DDMMYY).
9
+ */
10
+ export class AtSvnrDetector {
11
+ name = 'at_svnr';
12
+ #validator;
13
+ constructor(options = {}) {
14
+ this.#validator = options.validator ?? isValidAtSvnr;
15
+ }
16
+ detect(text) {
17
+ return matchAll(PATTERN, text)
18
+ .filter(({ value }) => this.#validator(value) && (/^[0-9]+$/.test(asciiDigits(value).replaceAll(' ', '')) || hasBirthDate(value)))
19
+ .map(({ value, offset }) => createEntity({ type: EntityType.AtSvnr, value, offset, confidence: 1, detector: 'at_svnr' }));
20
+ }
21
+ }
22
+ /**
23
+ * A hyphen or line break also joins file numbers ("VWA-2026-100084") and a date's year with the next line,
24
+ * and the checksum passes for about one in eleven: these variants need a plausible DDMMYY birth date.
25
+ */
26
+ function hasBirthDate(value) {
27
+ const birth = asciiDigits(value)
28
+ .replace(/[^0-9]/g, '')
29
+ .slice(4);
30
+ return checkdate(Number(birth.slice(2, 4)), Number(birth.slice(0, 2)), 2000 + Number(birth.slice(4, 6)));
31
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Whether the contact at `offset` (UTF-16 index) is in a sentence that speaks for the authority.
3
+ */
4
+ export declare function isAuthorityContact(text: string, offset: number): boolean;
5
+ /**
6
+ * Whether a phone number is a mobile number (AT, DE, CH). Mobile numbers are treated as personal even
7
+ * next to authority keywords: "Ihren Einspruch haben wir unter 0664 ... notiert".
8
+ */
9
+ export declare function isMobileNumber(phone: string): boolean;
10
+ /** Whether `offset` (UTF-16 index) lies in the letterhead of an authority (see letterhead()). */
11
+ export declare function isInLetterhead(text: string, offset: number): boolean;
12
+ /**
13
+ * Whether an e-mail address belongs to the authority in the letterhead: the domain's name (the label
14
+ * before the top-level domain, e.g. "musterhausen" in "parken@musterhausen.example") equals a word of the
15
+ * line that names the authority, optionally after a known short form ("bh-musterstadt"). A similar
16
+ * domain ("musterhausen-fitness") does not count: when in doubt, the address is redacted.
17
+ *
18
+ * `authority` is the authority line of the text (authorityLine()), passed in so it is computed once per text.
19
+ */
20
+ export declare function isAuthorityEmail(text: string, email: string, authority?: string | null): boolean;
21
+ /** The line of the letterhead that names the authority, or null. */
22
+ export declare function authorityLine(text: string): string | null;