@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.
- package/CHANGELOG.md +38 -0
- package/LICENSE +22 -0
- package/README.md +276 -2
- package/dist/ai-sdk/index.d.ts +19 -0
- package/dist/ai-sdk/index.js +30 -0
- package/dist/ai-sdk/middleware.d.ts +63 -0
- package/dist/ai-sdk/middleware.js +388 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +124 -0
- package/dist/detector.d.ts +28 -0
- package/dist/detector.js +3 -0
- package/dist/detectors/at-svnr.d.ts +14 -0
- package/dist/detectors/at-svnr.js +31 -0
- package/dist/detectors/authority-context.d.ts +22 -0
- package/dist/detectors/authority-context.js +278 -0
- package/dist/detectors/birth-date.d.ts +10 -0
- package/dist/detectors/birth-date.js +21 -0
- package/dist/detectors/email.d.ts +15 -0
- package/dist/detectors/email.js +29 -0
- package/dist/detectors/file-number.d.ts +16 -0
- package/dist/detectors/file-number.js +20 -0
- package/dist/detectors/iban.d.ts +10 -0
- package/dist/detectors/iban.js +41 -0
- package/dist/detectors/license-plate.d.ts +9 -0
- package/dist/detectors/license-plate.js +13 -0
- package/dist/detectors/phone.d.ts +13 -0
- package/dist/detectors/phone.js +38 -0
- package/dist/detectors/postal-address.d.ts +14 -0
- package/dist/detectors/postal-address.js +19 -0
- package/dist/detectors/salutation-person.d.ts +18 -0
- package/dist/detectors/salutation-person.js +37 -0
- package/dist/detectors/tax-number.d.ts +14 -0
- package/dist/detectors/tax-number.js +33 -0
- package/dist/entity-extractor.d.ts +47 -0
- package/dist/entity-extractor.js +245 -0
- package/dist/entity-type.d.ts +24 -0
- package/dist/entity-type.js +26 -0
- package/dist/entity.d.ts +28 -0
- package/dist/entity.js +11 -0
- package/dist/errors.d.ts +48 -0
- package/dist/errors.js +49 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +40 -0
- package/dist/internal/pcre.d.ts +55 -0
- package/dist/internal/pcre.js +102 -0
- package/dist/internal/php-json.d.ts +15 -0
- package/dist/internal/php-json.js +48 -0
- package/dist/internal/placeholder-stream.d.ts +24 -0
- package/dist/internal/placeholder-stream.js +118 -0
- package/dist/internal/text-spans.d.ts +8 -0
- package/dist/internal/text-spans.js +15 -0
- package/dist/learning/char-set.d.ts +29 -0
- package/dist/learning/char-set.js +158 -0
- package/dist/learning/custom-entity-detector.d.ts +26 -0
- package/dist/learning/custom-entity-detector.js +70 -0
- package/dist/learning/custom-entity-type.d.ts +49 -0
- package/dist/learning/custom-entity-type.js +150 -0
- package/dist/learning/entity-learner.d.ts +50 -0
- package/dist/learning/entity-learner.js +87 -0
- package/dist/learning/json-file-store.d.ts +36 -0
- package/dist/learning/json-file-store.js +132 -0
- package/dist/learning/learned-pattern.d.ts +48 -0
- package/dist/learning/learned-pattern.js +640 -0
- package/dist/learning/pattern-grammar.d.ts +12 -0
- package/dist/learning/pattern-grammar.js +148 -0
- package/dist/learning/pattern-learner.d.ts +10 -0
- package/dist/learning/pattern-learner.js +116 -0
- package/dist/learning/store.d.ts +51 -0
- package/dist/learning/store.js +84 -0
- package/dist/masking/partial-mask.d.ts +23 -0
- package/dist/masking/partial-mask.js +43 -0
- package/dist/masking/strategy.d.ts +10 -0
- package/dist/masking/strategy.js +1 -0
- package/dist/masking/type-label-mask.d.ts +17 -0
- package/dist/masking/type-label-mask.js +28 -0
- package/dist/mcp/index.d.ts +33 -0
- package/dist/mcp/index.js +146 -0
- package/dist/mcp/tools.d.ts +63 -0
- package/dist/mcp/tools.js +183 -0
- package/dist/model/chunks.d.ts +13 -0
- package/dist/model/chunks.js +74 -0
- package/dist/model/model-detector.d.ts +110 -0
- package/dist/model/model-detector.js +420 -0
- package/dist/model/prompt.d.ts +16 -0
- package/dist/model/prompt.js +192 -0
- package/dist/pii-masker.d.ts +27 -0
- package/dist/pii-masker.js +56 -0
- package/dist/pii-shield.d.ts +40 -0
- package/dist/pii-shield.js +142 -0
- package/dist/placeholder.d.ts +48 -0
- package/dist/placeholder.js +138 -0
- package/dist/redaction.d.ts +76 -0
- package/dist/redaction.js +52 -0
- package/dist/server/config.d.ts +23 -0
- package/dist/server/config.js +187 -0
- package/dist/server/http-server.d.ts +63 -0
- package/dist/server/http-server.js +241 -0
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.js +9 -0
- package/dist/server/model-providers.d.ts +31 -0
- package/dist/server/model-providers.js +158 -0
- package/dist/service/json-body.d.ts +14 -0
- package/dist/service/json-body.js +35 -0
- package/dist/service/local-peer.d.ts +16 -0
- package/dist/service/local-peer.js +83 -0
- package/dist/service/service-api.d.ts +75 -0
- package/dist/service/service-api.js +305 -0
- package/dist/validators/at-svnr.d.ts +8 -0
- package/dist/validators/at-svnr.js +21 -0
- package/dist/validators/de-tax-id.d.ts +8 -0
- package/dist/validators/de-tax-id.js +35 -0
- package/dist/validators/iban.d.ts +5 -0
- package/dist/validators/iban.js +24 -0
- package/dist/vault/encrypted-vault.d.ts +37 -0
- package/dist/vault/encrypted-vault.js +152 -0
- package/dist/vault/in-memory-vault.d.ts +17 -0
- package/dist/vault/in-memory-vault.js +39 -0
- package/dist/vault/memory-vault-storage.d.ts +16 -0
- package/dist/vault/memory-vault-storage.js +37 -0
- package/dist/vault/vault.d.ts +38 -0
- package/dist/vault/vault.js +16 -0
- package/dist/vault-redis/index.d.ts +28 -0
- package/dist/vault-redis/index.js +33 -0
- package/docs/openapi.yaml +422 -0
- package/package.json +122 -4
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whitelist grammar for hand-written patterns, parsed left to right (port of PHP's PatternGrammar).
|
|
3
|
+
*
|
|
4
|
+
* Allowed: literals, escaped metacharacters, \d \D \w \W \s \S, ".", character classes "[...]"
|
|
5
|
+
* (literals, ranges, the same escapes), alternation "|", groups "(...)" and "(?:...)" WITHOUT a
|
|
6
|
+
* quantifier, and quantifiers * + ? {n} {n,} {n,m} directly after a single atom.
|
|
7
|
+
* The messages are part of the service API and identical to PHP.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
const MAX_BOUND = 100;
|
|
12
|
+
const ESCAPABLE = '.^$|()[]{}*+?\\-/~#';
|
|
13
|
+
const CLASS_SHORTHANDS = 'dDwWsS';
|
|
14
|
+
/** Why the pattern is not allowed, or null if it is. */
|
|
15
|
+
export function patternViolation(pattern) {
|
|
16
|
+
const chars = Array.from(pattern);
|
|
17
|
+
const count = chars.length;
|
|
18
|
+
let depth = 0;
|
|
19
|
+
let lastWasAtom = false;
|
|
20
|
+
let afterGroup = false;
|
|
21
|
+
let unbounded = 0;
|
|
22
|
+
for (let i = 0; i < count; ++i) {
|
|
23
|
+
const c = chars[i] ?? '';
|
|
24
|
+
switch (c) {
|
|
25
|
+
case '\\': {
|
|
26
|
+
const next = chars[i + 1];
|
|
27
|
+
if (next === undefined || (!CLASS_SHORTHANDS.includes(next) && !ESCAPABLE.includes(next))) {
|
|
28
|
+
return `the escape \\${next ?? ''} is not allowed (use \\d \\w \\s or escape a special character)`;
|
|
29
|
+
}
|
|
30
|
+
++i;
|
|
31
|
+
lastWasAtom = true;
|
|
32
|
+
afterGroup = false;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
case '[': {
|
|
36
|
+
const end = classEnd(chars, i);
|
|
37
|
+
if (end === null) {
|
|
38
|
+
return 'a character class is not closed or contains an escape that is not allowed';
|
|
39
|
+
}
|
|
40
|
+
i = end;
|
|
41
|
+
lastWasAtom = true;
|
|
42
|
+
afterGroup = false;
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
case '(':
|
|
46
|
+
if (chars[i + 1] === '?') {
|
|
47
|
+
if (chars[i + 2] !== ':') {
|
|
48
|
+
return 'only (…) and (?:…) groups are allowed (no lookarounds, flags or named groups)';
|
|
49
|
+
}
|
|
50
|
+
i += 2;
|
|
51
|
+
}
|
|
52
|
+
++depth;
|
|
53
|
+
lastWasAtom = false;
|
|
54
|
+
afterGroup = false;
|
|
55
|
+
break;
|
|
56
|
+
case ')':
|
|
57
|
+
if (depth-- === 0) {
|
|
58
|
+
return 'unbalanced parenthesis';
|
|
59
|
+
}
|
|
60
|
+
lastWasAtom = false;
|
|
61
|
+
afterGroup = true;
|
|
62
|
+
break;
|
|
63
|
+
case '|':
|
|
64
|
+
lastWasAtom = false;
|
|
65
|
+
afterGroup = false;
|
|
66
|
+
break;
|
|
67
|
+
case '*':
|
|
68
|
+
case '+':
|
|
69
|
+
case '?':
|
|
70
|
+
case '{': {
|
|
71
|
+
if (afterGroup) {
|
|
72
|
+
return 'groups must not be repeated; repeat single characters or classes instead';
|
|
73
|
+
}
|
|
74
|
+
if (!lastWasAtom) {
|
|
75
|
+
return 'a quantifier must follow a single character or class';
|
|
76
|
+
}
|
|
77
|
+
let isUnbounded = c === '*' || c === '+';
|
|
78
|
+
if (c === '{') {
|
|
79
|
+
const end = boundedQuantifierEnd(chars, i);
|
|
80
|
+
if (end === null) {
|
|
81
|
+
return `use {n}, {n,} or {n,m} with numbers up to ${String(MAX_BOUND)}`;
|
|
82
|
+
}
|
|
83
|
+
isUnbounded = chars[end - 1] === ',';
|
|
84
|
+
i = end;
|
|
85
|
+
}
|
|
86
|
+
if (isUnbounded && ++unbounded > 1) {
|
|
87
|
+
return 'at most one unbounded repetition (*, + or {n,}) per pattern; use {n,m}';
|
|
88
|
+
}
|
|
89
|
+
if (chars[i + 1] === '?' || chars[i + 1] === '+') {
|
|
90
|
+
return 'lazy and possessive quantifiers are not allowed';
|
|
91
|
+
}
|
|
92
|
+
lastWasAtom = false;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
case '^':
|
|
96
|
+
case '$':
|
|
97
|
+
return 'anchors are not allowed; patterns are matched as whole words anyway';
|
|
98
|
+
case ']':
|
|
99
|
+
case '}':
|
|
100
|
+
return `unexpected "${c}"; escape it as \\${c}`;
|
|
101
|
+
default:
|
|
102
|
+
lastWasAtom = true;
|
|
103
|
+
afterGroup = false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return depth === 0 ? null : 'unbalanced parenthesis';
|
|
107
|
+
}
|
|
108
|
+
/** Index of the closing "]", or null. */
|
|
109
|
+
function classEnd(chars, start) {
|
|
110
|
+
let i = start + 1;
|
|
111
|
+
if (chars[i] === '^') {
|
|
112
|
+
++i;
|
|
113
|
+
}
|
|
114
|
+
for (let first = true; i < chars.length; ++i, first = false) {
|
|
115
|
+
const c = chars[i];
|
|
116
|
+
if (c === ']' && !first) {
|
|
117
|
+
return i;
|
|
118
|
+
}
|
|
119
|
+
if (c === '[') {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
if (c === '\\') {
|
|
123
|
+
const next = chars[i + 1];
|
|
124
|
+
if (next === undefined || (!CLASS_SHORTHANDS.includes(next) && !ESCAPABLE.includes(next))) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
++i;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
/** Index of the closing "}", or null. */
|
|
133
|
+
function boundedQuantifierEnd(chars, start) {
|
|
134
|
+
let body = '';
|
|
135
|
+
let i = start + 1;
|
|
136
|
+
for (; i < chars.length && chars[i] !== '}'; ++i) {
|
|
137
|
+
body += chars[i] ?? '';
|
|
138
|
+
}
|
|
139
|
+
// PHP's check has no /u (\d is ASCII), and its $ also matches before a final "\n".
|
|
140
|
+
const m = /^([0-9]{1,3})(?:,([0-9]{0,3}))?\n?$/.exec(body);
|
|
141
|
+
if (chars[i] !== '}' || m === null) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (Number(m[1]) > MAX_BOUND || (m[2] !== undefined && m[2] !== '' && Number(m[2]) > MAX_BOUND)) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
return i;
|
|
148
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Derives a pattern (PCRE syntax, as stored) from examples, e.g. "AB-1234/56" + "XY-9876/01" → `[A-Z]{2}-\d{4}/\d{2}`.
|
|
3
|
+
*
|
|
4
|
+
* Each example is split into runs of upper-case letters, lower-case letters, digits, whitespace and
|
|
5
|
+
* single other characters. Examples with the same shape are merged (lengths become ranges, runs that
|
|
6
|
+
* are identical in all of at least two examples stay literal); different shapes become alternatives.
|
|
7
|
+
*
|
|
8
|
+
* @throws LearningError, with code `LEARNING_PLAIN_WORDS` when the examples are plain words
|
|
9
|
+
*/
|
|
10
|
+
export declare function learnPattern(examples: readonly string[], counterExamples?: readonly string[]): string;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { LearningError } from '../errors.js';
|
|
2
|
+
import { codePointLength, DIGIT, phpTrim, SPACE } from '../internal/pcre.js';
|
|
3
|
+
import { LearnedPattern } from './learned-pattern.js';
|
|
4
|
+
const MAX_SHAPES = 5;
|
|
5
|
+
const CLASSES = { U: '[A-Z]', L: '[a-z]', D: String.raw `\d` };
|
|
6
|
+
/** Used only when the examples contain umlauts, to keep patterns readable otherwise. */
|
|
7
|
+
const UMLAUT_CLASSES = { U: '[A-ZÄÖÜ]', L: '[a-zäöüß]' };
|
|
8
|
+
/** PHP: preg_match_all('/[A-ZÄÖÜ]+|[a-zäöüß]+|\d+|\s+|./u') — UCP \d and \s, "." without "\n". */
|
|
9
|
+
const TOKEN = new RegExp(`[A-ZÄÖÜ]+|[a-zäöüß]+|${DIGIT}+|${SPACE}+|[^\\n]`, 'gu');
|
|
10
|
+
/**
|
|
11
|
+
* Derives a pattern (PCRE syntax, as stored) from examples, e.g. "AB-1234/56" + "XY-9876/01" → `[A-Z]{2}-\d{4}/\d{2}`.
|
|
12
|
+
*
|
|
13
|
+
* Each example is split into runs of upper-case letters, lower-case letters, digits, whitespace and
|
|
14
|
+
* single other characters. Examples with the same shape are merged (lengths become ranges, runs that
|
|
15
|
+
* are identical in all of at least two examples stay literal); different shapes become alternatives.
|
|
16
|
+
*
|
|
17
|
+
* @throws LearningError, with code `LEARNING_PLAIN_WORDS` when the examples are plain words
|
|
18
|
+
*/
|
|
19
|
+
export function learnPattern(examples, counterExamples = []) {
|
|
20
|
+
const unique = [...new Set(examples.map(phpTrim).filter((e) => e !== ''))];
|
|
21
|
+
if (unique.length === 0) {
|
|
22
|
+
throw new LearningError('At least one example is needed.');
|
|
23
|
+
}
|
|
24
|
+
const groups = new Map();
|
|
25
|
+
for (const example of unique) {
|
|
26
|
+
const tokens = tokenize(example);
|
|
27
|
+
const shape = tokens.map((t) => (t.kind === 'P' ? `P${t.text}` : t.kind)).join('\0');
|
|
28
|
+
const group = groups.get(shape);
|
|
29
|
+
if (group === undefined) {
|
|
30
|
+
groups.set(shape, [tokens]);
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
group.push(tokens);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (groups.size > MAX_SHAPES) {
|
|
37
|
+
throw new LearningError('The examples are too different to share a pattern. Split them into several types.');
|
|
38
|
+
}
|
|
39
|
+
const alternatives = [...groups.values()].map(merge);
|
|
40
|
+
const pattern = alternatives.length === 1 ? (alternatives[0] ?? '') : `(?:${alternatives.join('|')})`;
|
|
41
|
+
if (!isSpecific([...groups.values()])) {
|
|
42
|
+
throw new LearningError('Plain words cannot be learned as a pattern; they would match ordinary text. Use model-based detection for names and words.', 'LEARNING_PLAIN_WORDS');
|
|
43
|
+
}
|
|
44
|
+
// Learned patterns always compile; like preg_match() returning false, a failure would match nothing.
|
|
45
|
+
const compiled = LearnedPattern.compile(pattern);
|
|
46
|
+
counterExamples.forEach((counter, i) => {
|
|
47
|
+
if (compiled instanceof LearnedPattern && compiled.matchesWhole(phpTrim(counter))) {
|
|
48
|
+
throw new LearningError(`The learned pattern ${pattern} also matches counter-example ${String(i + 1)}. Add more examples or enter a pattern by hand.`);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
return pattern;
|
|
52
|
+
}
|
|
53
|
+
function tokenize(example) {
|
|
54
|
+
return Array.from(example.matchAll(TOKEN), ([run]) => ({ kind: kindOf(run), text: run }));
|
|
55
|
+
}
|
|
56
|
+
function kindOf(run) {
|
|
57
|
+
if (/^[A-ZÄÖÜ]/u.test(run)) {
|
|
58
|
+
return 'U';
|
|
59
|
+
}
|
|
60
|
+
if (/^[a-zäöüß]/u.test(run)) {
|
|
61
|
+
return 'L';
|
|
62
|
+
}
|
|
63
|
+
if (/^[0-9]+$/.test(run)) {
|
|
64
|
+
return 'D'; // ctype_digit(): ASCII only, so other digits are literals
|
|
65
|
+
}
|
|
66
|
+
if (phpTrim(run) === '') {
|
|
67
|
+
return 'S'; // trim(): ASCII whitespace only
|
|
68
|
+
}
|
|
69
|
+
return 'P';
|
|
70
|
+
}
|
|
71
|
+
function merge(examples) {
|
|
72
|
+
let pattern = '';
|
|
73
|
+
(examples[0] ?? []).forEach((token, i) => {
|
|
74
|
+
const texts = examples.map((tokens) => tokens[i]?.text ?? '');
|
|
75
|
+
const lengths = texts.map(codePointLength);
|
|
76
|
+
const min = Math.min(...lengths);
|
|
77
|
+
const max = Math.max(...lengths);
|
|
78
|
+
if (token.kind === 'P') {
|
|
79
|
+
pattern += escape(token.text);
|
|
80
|
+
}
|
|
81
|
+
else if (token.kind === 'S') {
|
|
82
|
+
pattern += String.raw `\s` + quantifier(min, max); // bounded on purpose
|
|
83
|
+
}
|
|
84
|
+
else if (examples.length > 1 && new Set(texts).size === 1) {
|
|
85
|
+
pattern += escape(token.text);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
pattern += classFor(token.kind, texts) + quantifier(min, max);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
return pattern;
|
|
92
|
+
}
|
|
93
|
+
function classFor(kind, texts) {
|
|
94
|
+
const hasUmlaut = /[ÄÖÜäöüß]/u.test(texts.join(''));
|
|
95
|
+
return (hasUmlaut ? UMLAUT_CLASSES[kind] : undefined) ?? CLASSES[kind] ?? '';
|
|
96
|
+
}
|
|
97
|
+
function quantifier(min, max) {
|
|
98
|
+
if (min === 1 && max === 1) {
|
|
99
|
+
return '';
|
|
100
|
+
}
|
|
101
|
+
return min === max ? `{${String(min)}}` : `{${String(min)},${String(max)}}`;
|
|
102
|
+
}
|
|
103
|
+
/** A pattern made of letter classes only would match ordinary words. */
|
|
104
|
+
function isSpecific(groups) {
|
|
105
|
+
return groups.every((examples) => {
|
|
106
|
+
const firstExample = examples[0] ?? [];
|
|
107
|
+
const kinds = firstExample.map((t) => t.kind);
|
|
108
|
+
const hasConstant = examples.length > 1 &&
|
|
109
|
+
firstExample.some((t, i) => (t.kind === 'U' || t.kind === 'L') && new Set(examples.map((tokens) => tokens[i]?.text)).size === 1);
|
|
110
|
+
return kinds.includes('D') || kinds.includes('P') || hasConstant;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** PHP escapes = ! < > : too, which PatternGrammar then rejects (kept for parity). */
|
|
114
|
+
function escape(text) {
|
|
115
|
+
return text.replace(/[.\\+*?[\]^$(){}=!<>|:#~]/gu, '\\$&');
|
|
116
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type CustomEntityType } from './custom-entity-type.js';
|
|
2
|
+
/**
|
|
3
|
+
* Where learned entity types live. Default: JsonFileCustomEntityStore; any key-value backend
|
|
4
|
+
* (Redis, a database) via KeyValueCustomEntityStore.
|
|
5
|
+
*/
|
|
6
|
+
export interface CustomEntityStore {
|
|
7
|
+
/** Sorted by name. */
|
|
8
|
+
all(): Promise<CustomEntityType[]>;
|
|
9
|
+
get(name: string): Promise<CustomEntityType | null>;
|
|
10
|
+
/** Adds the type or replaces the one with the same name. */
|
|
11
|
+
save(type: CustomEntityType): Promise<void>;
|
|
12
|
+
remove(name: string): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** Sorted by name with PHP's strcmp() (byte order; names are ASCII). Stable, like PHP 8's usort(). */
|
|
15
|
+
export declare function sortByName(types: CustomEntityType[]): CustomEntityType[];
|
|
16
|
+
/** Types from decoded stored data: every JSON array or object entry is validated, other entries are skipped. */
|
|
17
|
+
export declare function typesFromJSON(data: unknown): CustomEntityType[];
|
|
18
|
+
/** Learned types in memory, e.g. for tests or a single process that learns at start-up. */
|
|
19
|
+
export declare class InMemoryCustomEntityStore implements CustomEntityStore {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(types?: Iterable<CustomEntityType>);
|
|
22
|
+
all(): Promise<CustomEntityType[]>;
|
|
23
|
+
get(name: string): Promise<CustomEntityType | null>;
|
|
24
|
+
save(type: CustomEntityType): Promise<void>;
|
|
25
|
+
remove(name: string): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/** The minimal string key-value API KeyValueCustomEntityStore needs (Redis, Valkey, a database table, ...). */
|
|
28
|
+
export interface KeyValueStore {
|
|
29
|
+
get(key: string): Promise<string | null | undefined>;
|
|
30
|
+
set(key: string, value: string): Promise<unknown>;
|
|
31
|
+
}
|
|
32
|
+
export interface KeyValueCustomEntityStoreOptions {
|
|
33
|
+
/** Default "pii_shield.learned_types", PHP's CacheCustomEntityStore key. */
|
|
34
|
+
key?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Learned types in a key-value store, as one JSON list under one key without expiry (port of PHP's
|
|
38
|
+
* CacheCustomEntityStore). The value is the same JSON shape as the file store, not PHP's PSR-6
|
|
39
|
+
* serialisation, so PHP and Node cannot share the key (docs/DEVIATIONS.md).
|
|
40
|
+
*
|
|
41
|
+
* save() and remove() read, change and write the whole list: serialise writers across processes
|
|
42
|
+
* yourself (e.g. a Redis lock); writes through one instance are serialised.
|
|
43
|
+
*/
|
|
44
|
+
export declare class KeyValueCustomEntityStore implements CustomEntityStore {
|
|
45
|
+
#private;
|
|
46
|
+
constructor(kv: KeyValueStore, options?: KeyValueCustomEntityStoreOptions);
|
|
47
|
+
all(): Promise<CustomEntityType[]>;
|
|
48
|
+
get(name: string): Promise<CustomEntityType | null>;
|
|
49
|
+
save(type: CustomEntityType): Promise<void>;
|
|
50
|
+
remove(name: string): Promise<void>;
|
|
51
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { PiiShieldError } from '../errors.js';
|
|
2
|
+
import { customEntityTypeFromJSON } from './custom-entity-type.js';
|
|
3
|
+
/** Sorted by name with PHP's strcmp() (byte order; names are ASCII). Stable, like PHP 8's usort(). */
|
|
4
|
+
export function sortByName(types) {
|
|
5
|
+
return types.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
6
|
+
}
|
|
7
|
+
/** Types from decoded stored data: every JSON array or object entry is validated, other entries are skipped. */
|
|
8
|
+
export function typesFromJSON(data) {
|
|
9
|
+
const entries = typeof data === 'object' && data !== null ? Object.values(data) : [];
|
|
10
|
+
return sortByName(entries.filter((e) => typeof e === 'object' && e !== null).map((e) => customEntityTypeFromJSON(e)));
|
|
11
|
+
}
|
|
12
|
+
/** Learned types in memory, e.g. for tests or a single process that learns at start-up. */
|
|
13
|
+
export class InMemoryCustomEntityStore {
|
|
14
|
+
#types = new Map();
|
|
15
|
+
constructor(types = []) {
|
|
16
|
+
for (const type of types) {
|
|
17
|
+
this.#types.set(type.name, type);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
all() {
|
|
21
|
+
return Promise.resolve(sortByName([...this.#types.values()]));
|
|
22
|
+
}
|
|
23
|
+
get(name) {
|
|
24
|
+
return Promise.resolve(this.#types.get(name) ?? null);
|
|
25
|
+
}
|
|
26
|
+
save(type) {
|
|
27
|
+
this.#types.delete(type.name);
|
|
28
|
+
this.#types.set(type.name, type);
|
|
29
|
+
return Promise.resolve();
|
|
30
|
+
}
|
|
31
|
+
remove(name) {
|
|
32
|
+
this.#types.delete(name);
|
|
33
|
+
return Promise.resolve();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Learned types in a key-value store, as one JSON list under one key without expiry (port of PHP's
|
|
38
|
+
* CacheCustomEntityStore). The value is the same JSON shape as the file store, not PHP's PSR-6
|
|
39
|
+
* serialisation, so PHP and Node cannot share the key (docs/DEVIATIONS.md).
|
|
40
|
+
*
|
|
41
|
+
* save() and remove() read, change and write the whole list: serialise writers across processes
|
|
42
|
+
* yourself (e.g. a Redis lock); writes through one instance are serialised.
|
|
43
|
+
*/
|
|
44
|
+
export class KeyValueCustomEntityStore {
|
|
45
|
+
#kv;
|
|
46
|
+
#key;
|
|
47
|
+
#queue = Promise.resolve();
|
|
48
|
+
constructor(kv, options = {}) {
|
|
49
|
+
this.#kv = kv;
|
|
50
|
+
this.#key = options.key ?? 'pii_shield.learned_types';
|
|
51
|
+
}
|
|
52
|
+
async all() {
|
|
53
|
+
const raw = await this.#kv.get(this.#key);
|
|
54
|
+
if (raw === null || raw === undefined) {
|
|
55
|
+
return [];
|
|
56
|
+
}
|
|
57
|
+
let data;
|
|
58
|
+
try {
|
|
59
|
+
data = JSON.parse(raw);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// No cause: V8's JSON.parse() message quotes the stored text, which holds examples.
|
|
63
|
+
throw new PiiShieldError(`The key "${this.#key}" does not contain a list of learned types.`, 'LEARNING_STORE_CORRUPT');
|
|
64
|
+
}
|
|
65
|
+
// PHP ignores a non-array value here.
|
|
66
|
+
return typesFromJSON(data);
|
|
67
|
+
}
|
|
68
|
+
async get(name) {
|
|
69
|
+
return (await this.all()).find((t) => t.name === name) ?? null;
|
|
70
|
+
}
|
|
71
|
+
save(type) {
|
|
72
|
+
return this.#write((types) => [...types.filter((t) => t.name !== type.name), type]);
|
|
73
|
+
}
|
|
74
|
+
remove(name) {
|
|
75
|
+
return this.#write((types) => types.filter((t) => t.name !== name));
|
|
76
|
+
}
|
|
77
|
+
#write(change) {
|
|
78
|
+
const run = this.#queue.then(async () => {
|
|
79
|
+
await this.#kv.set(this.#key, JSON.stringify(change(await this.all())));
|
|
80
|
+
});
|
|
81
|
+
this.#queue = run.catch(() => undefined);
|
|
82
|
+
return run;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Entity } from '../entity.js';
|
|
2
|
+
import type { MaskingStrategy } from './strategy.js';
|
|
3
|
+
export interface PartialMaskOptions {
|
|
4
|
+
/** Visible characters at the start; default 0. */
|
|
5
|
+
keepStart?: number;
|
|
6
|
+
/** Visible characters at the end; default 0. */
|
|
7
|
+
keepEnd?: number;
|
|
8
|
+
/** Replacement for each hidden character; default "*". */
|
|
9
|
+
maskChar?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Keeps the first and last n characters, masks everything else except whitespace:
|
|
13
|
+
* "AT61 1904 3002 3457 3201" → "AT61 **** **** **** 3201".
|
|
14
|
+
*
|
|
15
|
+
* Characters are code points, as PHP's mb_str_split() counts them. Values not longer than
|
|
16
|
+
* keepStart + keepEnd are masked completely, otherwise nothing would be hidden.
|
|
17
|
+
* Leaks length and format by design; meant for logs and previews, not for model providers.
|
|
18
|
+
*/
|
|
19
|
+
export declare class PartialMask implements MaskingStrategy {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(options?: PartialMaskOptions);
|
|
22
|
+
mask(entity: Entity): string;
|
|
23
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** PHP's ctype_space() on one character: ASCII whitespace only, so a no-break space is masked. */
|
|
2
|
+
const ASCII_SPACE = /^[\t\n\v\f\r ]$/;
|
|
3
|
+
/**
|
|
4
|
+
* Keeps the first and last n characters, masks everything else except whitespace:
|
|
5
|
+
* "AT61 1904 3002 3457 3201" → "AT61 **** **** **** 3201".
|
|
6
|
+
*
|
|
7
|
+
* Characters are code points, as PHP's mb_str_split() counts them. Values not longer than
|
|
8
|
+
* keepStart + keepEnd are masked completely, otherwise nothing would be hidden.
|
|
9
|
+
* Leaks length and format by design; meant for logs and previews, not for model providers.
|
|
10
|
+
*/
|
|
11
|
+
export class PartialMask {
|
|
12
|
+
#keepStart;
|
|
13
|
+
#keepEnd;
|
|
14
|
+
#maskChar;
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
const { keepStart = 0, keepEnd = 0, maskChar = '*' } = options;
|
|
17
|
+
for (const keep of [keepStart, keepEnd]) {
|
|
18
|
+
if (!Number.isInteger(keep) || keep < 0) {
|
|
19
|
+
throw new RangeError(keep < 0 ? 'Characters to keep must not be negative.' : 'Characters to keep must be an integer.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
this.#keepStart = keepStart;
|
|
23
|
+
this.#keepEnd = keepEnd;
|
|
24
|
+
this.#maskChar = maskChar;
|
|
25
|
+
}
|
|
26
|
+
mask(entity) {
|
|
27
|
+
const chars = [...entity.value];
|
|
28
|
+
const visible = chars.filter((c) => !ASCII_SPACE.test(c)).length;
|
|
29
|
+
const fullyMasked = visible <= this.#keepStart + this.#keepEnd;
|
|
30
|
+
let result = '';
|
|
31
|
+
let position = 0;
|
|
32
|
+
for (const char of chars) {
|
|
33
|
+
if (ASCII_SPACE.test(char)) {
|
|
34
|
+
result += char;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const keep = !fullyMasked && (position < this.#keepStart || position >= visible - this.#keepEnd);
|
|
38
|
+
result += keep ? char : this.#maskChar;
|
|
39
|
+
position++;
|
|
40
|
+
}
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Entity } from '../entity.js';
|
|
2
|
+
/** Irreversible replacement text for an entity. A plain function `(entity) => string` works wherever a strategy is accepted. */
|
|
3
|
+
export interface MaskingStrategy {
|
|
4
|
+
mask(entity: Entity): string;
|
|
5
|
+
}
|
|
6
|
+
export type MaskingFunction = (entity: Entity) => string;
|
|
7
|
+
/** Irreversible masking for logs, debug output and previews. Use a Redactor for text that goes to a model provider. */
|
|
8
|
+
export interface Masker {
|
|
9
|
+
mask(text: string): string;
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Entity } from '../entity.js';
|
|
2
|
+
import type { MaskingStrategy } from './strategy.js';
|
|
3
|
+
export interface TypeLabelMaskOptions {
|
|
4
|
+
/**
|
|
5
|
+
* PHP sprintf format that receives the type name (e.g. "PERSON"), default "[%s]". Supported: `%s` (once),
|
|
6
|
+
* `%1$s` and `%%`; anything else throws a TypeError. Or a function of the type name.
|
|
7
|
+
*/
|
|
8
|
+
format?: string | ((type: string) => string);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Replaces the whole value with its type name: "Maria Musterfrau" → "[PERSON]". Learned types use their name.
|
|
12
|
+
*/
|
|
13
|
+
export declare class TypeLabelMask implements MaskingStrategy {
|
|
14
|
+
#private;
|
|
15
|
+
constructor(options?: TypeLabelMaskOptions);
|
|
16
|
+
mask(entity: Entity): string;
|
|
17
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { typeName } from '../entity.js';
|
|
2
|
+
const DIRECTIVE = /%(?:%|1\$s|s)|%/g;
|
|
3
|
+
/**
|
|
4
|
+
* Replaces the whole value with its type name: "Maria Musterfrau" → "[PERSON]". Learned types use their name.
|
|
5
|
+
*/
|
|
6
|
+
export class TypeLabelMask {
|
|
7
|
+
#format;
|
|
8
|
+
constructor(options = {}) {
|
|
9
|
+
const { format = '[%s]' } = options;
|
|
10
|
+
this.#format = typeof format === 'function' ? format : compile(format);
|
|
11
|
+
}
|
|
12
|
+
mask(entity) {
|
|
13
|
+
return this.#format(typeName(entity));
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** The subset of PHP's sprintf() that a single string argument can satisfy. */
|
|
17
|
+
function compile(format) {
|
|
18
|
+
let plain = 0;
|
|
19
|
+
for (const [directive] of format.matchAll(DIRECTIVE)) {
|
|
20
|
+
if (directive === '%') {
|
|
21
|
+
throw new TypeError('The type label format supports only %s, %1$s and %%.');
|
|
22
|
+
}
|
|
23
|
+
if (directive === '%s' && ++plain > 1) {
|
|
24
|
+
throw new TypeError('The type label format may contain %s only once; use %1$s to repeat the type.');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return (type) => format.replace(DIRECTIVE, (directive) => (directive === '%%' ? '%' : type));
|
|
28
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Readable, Writable } from 'node:stream';
|
|
2
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import type { McpHttpHandler } from '../server/http-server.js';
|
|
4
|
+
import type { ServiceApi } from '../service/service-api.js';
|
|
5
|
+
export { callTool, InvalidToolCall, SERVER_INFO, SERVER_INSTRUCTIONS, type ToolDefinition, type ToolResult, TOOLS, } from './tools.js';
|
|
6
|
+
/**
|
|
7
|
+
* An MCP server with the pii-shield tools on top of a ServiceApi. One server serves one transport
|
|
8
|
+
* (connect it with `server.connect(transport)`); the API can be shared.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createMcpServer(api: ServiceApi): McpServer;
|
|
11
|
+
export interface StdioOptions {
|
|
12
|
+
stdin?: Readable;
|
|
13
|
+
stdout?: Writable;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Serves the tools over STDIO (for Claude Code, Claude Desktop, the MCP Inspector). Nothing else may
|
|
17
|
+
* write to stdout while it runs; log to stderr. Resolves with the server once connected.
|
|
18
|
+
*/
|
|
19
|
+
export declare function serveStdio(api: ServiceApi, options?: StdioOptions): Promise<McpServer>;
|
|
20
|
+
export interface McpHttpHandlerOptions {
|
|
21
|
+
/** Sessions idle longer than this are closed; default 3600000 (1 hour). */
|
|
22
|
+
sessionIdleMs?: number;
|
|
23
|
+
/** At most this many open sessions; the least recently used is closed first. Default 1000. */
|
|
24
|
+
maxSessions?: number;
|
|
25
|
+
/** Largest POST body in bytes; default 2 MiB. */
|
|
26
|
+
maxBodyBytes?: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Streamable HTTP for `startServer({ mcp })` / `createRequestListener({ mcp })`, which guard /mcp like
|
|
30
|
+
* /v1 (host names, origin, JSON, bearer token or local peer). Stateful: `initialize` opens a session
|
|
31
|
+
* (`Mcp-Session-Id`), each session has its own server; answers are JSON, not SSE.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createMcpHttpHandler(api: ServiceApi, options?: McpHttpHandlerOptions): McpHttpHandler;
|