@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,158 @@
|
|
|
1
|
+
import { ModelLocation } from '../model/model-detector.js';
|
|
2
|
+
export const MODEL_PROVIDERS = ['ollama', 'generic', 'mistral', 'openai', 'anthropic'];
|
|
3
|
+
/** Defaults of PHP's DemoServices::PROVIDERS. */
|
|
4
|
+
const DEFAULT_MODELS = {
|
|
5
|
+
ollama: 'qwen3:4b-instruct',
|
|
6
|
+
generic: '',
|
|
7
|
+
mistral: 'mistral-small-latest',
|
|
8
|
+
openai: 'gpt-5',
|
|
9
|
+
anthropic: 'claude-sonnet-5-5',
|
|
10
|
+
};
|
|
11
|
+
/** A normal answer takes a few hundred tokens; a cut answer fails closed (PHP's $answerTokens). */
|
|
12
|
+
const ANSWER_TOKENS = 1024;
|
|
13
|
+
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', '[::1]', 'host.docker.internal'];
|
|
14
|
+
/**
|
|
15
|
+
* A DetectionModel over plain `fetch` for the providers of PHP's service, with PHP's request options:
|
|
16
|
+
* deterministic (temperature 0, except OpenAI and Anthropic), no reasoning and at most 1024 answer tokens
|
|
17
|
+
* for self-hosted models, no redirects. The location follows PHP: `ollama` and `generic` are local when
|
|
18
|
+
* the URL's host is this machine (or host.docker.internal), else on-premise; the others are external.
|
|
19
|
+
*
|
|
20
|
+
* @throws TypeError for an unknown provider, a missing model, key or URL, or a URL that is not http(s)
|
|
21
|
+
*/
|
|
22
|
+
export function providerModel(settings) {
|
|
23
|
+
const { provider, apiKey } = settings;
|
|
24
|
+
const doFetch = settings.fetch ?? fetch;
|
|
25
|
+
if (!MODEL_PROVIDERS.includes(provider)) {
|
|
26
|
+
throw new TypeError(`Unknown provider "${provider}".`);
|
|
27
|
+
}
|
|
28
|
+
const trimmed = settings.model?.trim() ?? '';
|
|
29
|
+
const model = trimmed === '' ? DEFAULT_MODELS[provider] : trimmed;
|
|
30
|
+
if (model === '') {
|
|
31
|
+
throw new TypeError('Choose a model first.');
|
|
32
|
+
}
|
|
33
|
+
const endpoint = settings.endpoint?.trim() ? validEndpoint(settings.endpoint) : undefined;
|
|
34
|
+
const requireKey = (name) => {
|
|
35
|
+
if (apiKey === undefined || apiKey === '') {
|
|
36
|
+
throw new TypeError(`Set ${name} in the environment of the server to use this provider.`);
|
|
37
|
+
}
|
|
38
|
+
return apiKey;
|
|
39
|
+
};
|
|
40
|
+
const post = async (url, headers, body, signal) => {
|
|
41
|
+
const response = await doFetch(url, {
|
|
42
|
+
method: 'POST',
|
|
43
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
44
|
+
body: JSON.stringify(body),
|
|
45
|
+
redirect: 'error',
|
|
46
|
+
signal,
|
|
47
|
+
});
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
// The body may echo the request (the unredacted text): never put it into the error.
|
|
50
|
+
await response.body?.cancel();
|
|
51
|
+
throw new Error(`HTTP ${String(response.status)}`);
|
|
52
|
+
}
|
|
53
|
+
return response.json();
|
|
54
|
+
};
|
|
55
|
+
const messages = ({ system, user }) => [
|
|
56
|
+
{ role: 'system', content: system },
|
|
57
|
+
{ role: 'user', content: user },
|
|
58
|
+
];
|
|
59
|
+
switch (provider) {
|
|
60
|
+
case 'ollama': {
|
|
61
|
+
const base = endpoint ?? 'http://127.0.0.1:11434';
|
|
62
|
+
return {
|
|
63
|
+
location: locationOf(base),
|
|
64
|
+
model: {
|
|
65
|
+
name: model,
|
|
66
|
+
generate: async (prompt, { signal }) => {
|
|
67
|
+
// No chain-of-thought (faster); no JSON mode, not every model supports it.
|
|
68
|
+
const data = await post(`${base}/api/chat`, {}, {
|
|
69
|
+
model,
|
|
70
|
+
messages: messages(prompt),
|
|
71
|
+
stream: false,
|
|
72
|
+
think: false,
|
|
73
|
+
options: { temperature: 0, num_predict: ANSWER_TOKENS },
|
|
74
|
+
}, signal);
|
|
75
|
+
return text(data.message?.content);
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
case 'generic': {
|
|
81
|
+
if (endpoint === undefined) {
|
|
82
|
+
throw new TypeError('Enter the URL of the OpenAI-compatible server.');
|
|
83
|
+
}
|
|
84
|
+
const base = endpoint.replace(/\/v1\/?$/, '');
|
|
85
|
+
return {
|
|
86
|
+
location: locationOf(base),
|
|
87
|
+
model: openAiCompatible(model, `${base}/v1/chat/completions`, apiKey, {
|
|
88
|
+
temperature: 0,
|
|
89
|
+
reasoning_effort: 'none',
|
|
90
|
+
max_tokens: ANSWER_TOKENS,
|
|
91
|
+
}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
case 'mistral':
|
|
95
|
+
return {
|
|
96
|
+
location: ModelLocation.External,
|
|
97
|
+
model: openAiCompatible(model, 'https://api.mistral.ai/v1/chat/completions', requireKey('MISTRAL_API_KEY'), {
|
|
98
|
+
temperature: 0,
|
|
99
|
+
}),
|
|
100
|
+
};
|
|
101
|
+
case 'openai':
|
|
102
|
+
return {
|
|
103
|
+
location: ModelLocation.External,
|
|
104
|
+
model: openAiCompatible(model, 'https://api.openai.com/v1/chat/completions', requireKey('OPENAI_API_KEY'), {}),
|
|
105
|
+
};
|
|
106
|
+
case 'anthropic': {
|
|
107
|
+
const key = requireKey('ANTHROPIC_API_KEY');
|
|
108
|
+
return {
|
|
109
|
+
location: ModelLocation.External,
|
|
110
|
+
model: {
|
|
111
|
+
name: model,
|
|
112
|
+
// Current Claude models reject sampling parameters.
|
|
113
|
+
generate: async ({ system, user }, { signal }) => {
|
|
114
|
+
const data = await post('https://api.anthropic.com/v1/messages', { 'x-api-key': key, 'anthropic-version': '2023-06-01' }, { model, max_tokens: 4096, system, messages: [{ role: 'user', content: user }] }, signal);
|
|
115
|
+
const content = data.content ?? [];
|
|
116
|
+
return text(content
|
|
117
|
+
.filter((c) => c.type === 'text')
|
|
118
|
+
.map((c) => c.text)
|
|
119
|
+
.join(''));
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function openAiCompatible(name, url, key, options) {
|
|
126
|
+
return {
|
|
127
|
+
name,
|
|
128
|
+
generate: async (prompt, { signal }) => {
|
|
129
|
+
const data = await post(url, key === undefined || key === '' ? {} : { Authorization: `Bearer ${key}` }, { model: name, messages: messages(prompt), ...options }, signal);
|
|
130
|
+
return text(data.choices?.[0]?.message?.content);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** PHP's DemoServices::validEndpoint(): trimmed, without trailing slashes, http or https. */
|
|
136
|
+
export function validEndpoint(endpoint) {
|
|
137
|
+
const trimmed = endpoint.trim().replace(/\/+$/, '');
|
|
138
|
+
let protocol;
|
|
139
|
+
try {
|
|
140
|
+
protocol = new URL(trimmed).protocol;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
protocol = '';
|
|
144
|
+
}
|
|
145
|
+
if (protocol !== 'http:' && protocol !== 'https:') {
|
|
146
|
+
throw new TypeError('The server URL must start with http:// or https://.');
|
|
147
|
+
}
|
|
148
|
+
return trimmed;
|
|
149
|
+
}
|
|
150
|
+
function locationOf(endpoint) {
|
|
151
|
+
return LOCAL_HOSTS.includes(new URL(endpoint).hostname) ? ModelLocation.Local : ModelLocation.OnPremise;
|
|
152
|
+
}
|
|
153
|
+
function text(value) {
|
|
154
|
+
if (typeof value !== 'string') {
|
|
155
|
+
throw new TypeError('The model answered without text.');
|
|
156
|
+
}
|
|
157
|
+
return value;
|
|
158
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A request body decoded like PHP's `json_decode($body, true, 16, JSON_THROW_ON_ERROR)`: invalid UTF-8,
|
|
3
|
+
* a byte order mark, lone surrogate escapes (`"\ud800"`) and more than 15 nested arrays/objects are
|
|
4
|
+
* invalid JSON. JSON.parse() alone accepts the last three.
|
|
5
|
+
*/
|
|
6
|
+
export type JsonBody = Readonly<Record<string, unknown>>;
|
|
7
|
+
export type ParsedBody = {
|
|
8
|
+
ok: true;
|
|
9
|
+
body: JsonBody;
|
|
10
|
+
} | {
|
|
11
|
+
ok: false;
|
|
12
|
+
error: 'Invalid JSON.' | 'Expected a JSON object.';
|
|
13
|
+
};
|
|
14
|
+
export declare function parseJsonBody(bytes: Uint8Array): ParsedBody;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** PHP's depth 16 counts the scalars inside the innermost container too. */
|
|
2
|
+
const MAX_NESTING = 15;
|
|
3
|
+
const strictUtf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
4
|
+
export function parseJsonBody(bytes) {
|
|
5
|
+
let data;
|
|
6
|
+
try {
|
|
7
|
+
data = JSON.parse(strictUtf8.decode(bytes));
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return { ok: false, error: 'Invalid JSON.' };
|
|
11
|
+
}
|
|
12
|
+
if (!wellFormed(data, 0)) {
|
|
13
|
+
return { ok: false, error: 'Invalid JSON.' };
|
|
14
|
+
}
|
|
15
|
+
// A JSON list is a PHP array too, so PHP accepts it as a body (without any of the named fields).
|
|
16
|
+
if (typeof data !== 'object' || data === null) {
|
|
17
|
+
return { ok: false, error: 'Expected a JSON object.' };
|
|
18
|
+
}
|
|
19
|
+
return { ok: true, body: Array.isArray(data) ? {} : data };
|
|
20
|
+
}
|
|
21
|
+
function wellFormed(value, depth) {
|
|
22
|
+
if (typeof value === 'string') {
|
|
23
|
+
return value.isWellFormed();
|
|
24
|
+
}
|
|
25
|
+
if (typeof value !== 'object' || value === null) {
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
if (depth + 1 > MAX_NESTING) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
if (Array.isArray(value)) {
|
|
32
|
+
return value.every((item) => wellFormed(item, depth + 1));
|
|
33
|
+
}
|
|
34
|
+
return Object.entries(value).every(([key, item]) => key.isWellFormed() && wellFormed(item, depth + 1));
|
|
35
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decides whether a peer address counts as this machine: 127.0.0.1 and ::1 (exactly these, as in PHP),
|
|
3
|
+
* plus `peers`, a list of IPs or CIDRs (PHP's PII_LOCAL_PEERS). `gateway` stands for this container's
|
|
4
|
+
* default gateway (read from /proc/net/route once): in Docker, a port published on the host's
|
|
5
|
+
* 127.0.0.1 arrives from the gateway. Invalid entries are ignored.
|
|
6
|
+
*
|
|
7
|
+
* IPv4-mapped IPv6 addresses (`::ffff:127.0.0.1`, how Node reports IPv4 peers on a dual-stack socket)
|
|
8
|
+
* are compared as IPv4.
|
|
9
|
+
*/
|
|
10
|
+
export declare function localPeerMatcher(peers?: Iterable<string>, readRouteTable?: () => string): (address: string | undefined) => boolean;
|
|
11
|
+
/** Comma-separated list (PII_LOCAL_PEERS, PII_SERVICE_ALLOWED_HOSTS) → trimmed, non-empty entries. */
|
|
12
|
+
export declare function splitList(value: string | undefined): string[];
|
|
13
|
+
/**
|
|
14
|
+
* The default gateway from a Linux route table (/proc/net/route: addresses as little-endian hex), or null.
|
|
15
|
+
*/
|
|
16
|
+
export declare function defaultGateway(routeTable: string): string | null;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { BlockList, isIPv4, isIPv6 } from 'node:net';
|
|
3
|
+
/**
|
|
4
|
+
* Decides whether a peer address counts as this machine: 127.0.0.1 and ::1 (exactly these, as in PHP),
|
|
5
|
+
* plus `peers`, a list of IPs or CIDRs (PHP's PII_LOCAL_PEERS). `gateway` stands for this container's
|
|
6
|
+
* default gateway (read from /proc/net/route once): in Docker, a port published on the host's
|
|
7
|
+
* 127.0.0.1 arrives from the gateway. Invalid entries are ignored.
|
|
8
|
+
*
|
|
9
|
+
* IPv4-mapped IPv6 addresses (`::ffff:127.0.0.1`, how Node reports IPv4 peers on a dual-stack socket)
|
|
10
|
+
* are compared as IPv4.
|
|
11
|
+
*/
|
|
12
|
+
export function localPeerMatcher(peers = [], readRouteTable = () => readFileSync('/proc/net/route', 'utf8')) {
|
|
13
|
+
const list = new BlockList();
|
|
14
|
+
list.addAddress('127.0.0.1', 'ipv4');
|
|
15
|
+
list.addAddress('::1', 'ipv6');
|
|
16
|
+
for (const raw of peers) {
|
|
17
|
+
let peer = raw.trim();
|
|
18
|
+
if (peer === 'gateway') {
|
|
19
|
+
try {
|
|
20
|
+
peer = defaultGateway(readRouteTable());
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
peer = null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (peer !== null && peer !== '') {
|
|
27
|
+
addPeer(list, peer);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return (address) => {
|
|
31
|
+
if (address === undefined) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
const ip = unmapIPv4(address);
|
|
35
|
+
if (isIPv4(ip)) {
|
|
36
|
+
return list.check(ip, 'ipv4');
|
|
37
|
+
}
|
|
38
|
+
return isIPv6(ip) && list.check(ip, 'ipv6');
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Comma-separated list (PII_LOCAL_PEERS, PII_SERVICE_ALLOWED_HOSTS) → trimmed, non-empty entries. */
|
|
42
|
+
export function splitList(value) {
|
|
43
|
+
return (value ?? '')
|
|
44
|
+
.split(',')
|
|
45
|
+
.map((s) => s.trim())
|
|
46
|
+
.filter((s) => s !== '');
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The default gateway from a Linux route table (/proc/net/route: addresses as little-endian hex), or null.
|
|
50
|
+
*/
|
|
51
|
+
export function defaultGateway(routeTable) {
|
|
52
|
+
for (const line of routeTable.split('\n').slice(1)) {
|
|
53
|
+
const columns = line.trim().split(/\s+/);
|
|
54
|
+
const gateway = columns[2];
|
|
55
|
+
if (columns[1] === '00000000' && gateway !== undefined && /^[0-9a-fA-F]{8}$/.test(gateway)) {
|
|
56
|
+
const n = Number.parseInt(gateway, 16);
|
|
57
|
+
return [n & 0xff, (n >>> 8) & 0xff, (n >>> 16) & 0xff, n >>> 24].join('.');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
function addPeer(list, peer) {
|
|
63
|
+
const slash = peer.indexOf('/');
|
|
64
|
+
const ip = unmapIPv4(slash === -1 ? peer : peer.slice(0, slash));
|
|
65
|
+
const type = isIPv4(ip) ? 'ipv4' : isIPv6(ip) ? 'ipv6' : null;
|
|
66
|
+
if (type === null) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (slash === -1) {
|
|
70
|
+
list.addAddress(ip, type);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const bits = peer.slice(slash + 1);
|
|
74
|
+
const prefix = Number(bits);
|
|
75
|
+
if (!/^\d{1,3}$/.test(bits) || prefix > (type === 'ipv4' ? 32 : 128)) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
list.addSubnet(ip, prefix, type);
|
|
79
|
+
}
|
|
80
|
+
function unmapIPv4(address) {
|
|
81
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(address);
|
|
82
|
+
return mapped?.[1] ?? address;
|
|
83
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type AsyncDetector, type DetectOptions, type Detector } from '../detector.js';
|
|
2
|
+
import type { EntityLearner } from '../learning/entity-learner.js';
|
|
3
|
+
import { type Vault } from '../vault/vault.js';
|
|
4
|
+
import type { JsonBody } from './json-body.js';
|
|
5
|
+
/** The operations shared by the HTTP API and the MCP tools. */
|
|
6
|
+
export type ServiceOperation = 'redact' | 'restore' | 'mask' | 'learn' | 'entities';
|
|
7
|
+
/** Status code and JSON body (null for 204) of one API call. */
|
|
8
|
+
export interface ServiceResponse {
|
|
9
|
+
readonly status: number;
|
|
10
|
+
readonly body: Readonly<Record<string, unknown>> | null;
|
|
11
|
+
}
|
|
12
|
+
export interface ServiceRequest {
|
|
13
|
+
readonly method: string;
|
|
14
|
+
/** Decoded path, e.g. "/v1/redact". */
|
|
15
|
+
readonly path: string;
|
|
16
|
+
/** Decoded JSON body (POST), else null. */
|
|
17
|
+
readonly body: JsonBody | null;
|
|
18
|
+
readonly authorization?: string | undefined;
|
|
19
|
+
/** The peer's IP address (socket), for the localhost rule. */
|
|
20
|
+
readonly remoteAddress?: string | undefined;
|
|
21
|
+
/** Aborts model-based detection, e.g. when the client disconnects. */
|
|
22
|
+
readonly signal?: AbortSignal | undefined;
|
|
23
|
+
}
|
|
24
|
+
export interface ServiceApiOptions {
|
|
25
|
+
/** Stores the placeholder mapping between redact and restore; use an EncryptedVault. */
|
|
26
|
+
vault: Vault;
|
|
27
|
+
/** Learned types: used by every detection, managed by /v1/learn and /v1/entities. */
|
|
28
|
+
learner: EntityLearner;
|
|
29
|
+
/**
|
|
30
|
+
* Creates the detector for `"detection": "model" | "both"` (called per request), e.g. a ModelDetector.
|
|
31
|
+
* Without it those requests get 422. Which model detects is server configuration, never request input.
|
|
32
|
+
*/
|
|
33
|
+
modelDetector?: (() => AsyncDetector | Detector) | undefined;
|
|
34
|
+
/** Bearer token (PII_SERVICE_TOKEN). Without one, only local peers are answered. */
|
|
35
|
+
token?: string | undefined;
|
|
36
|
+
/** Seconds a mapping lives in the vault; default 900 (15 minutes). */
|
|
37
|
+
vaultTtl?: number;
|
|
38
|
+
/** Service mode (PII_SERVICE_ONLY=1): never trust local peers; without a token every request gets 503. */
|
|
39
|
+
requireToken?: boolean;
|
|
40
|
+
/** Which peers count as this machine; default 127.0.0.1 and ::1, see localPeerMatcher(). */
|
|
41
|
+
isLocalPeer?: (address: string | undefined) => boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Called with errors that end up as a generic 500/502 response (never with the request text). The
|
|
44
|
+
* default does nothing; a model provider's error (`cause` of a DetectionError) may quote the text.
|
|
45
|
+
*/
|
|
46
|
+
onError?: (error: unknown) => void;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The versioned HTTP API (/v1) of pii-shield as a service, framework-free: routing, authentication and
|
|
50
|
+
* the operations. Port of PHP's `ServiceApi`, same JSON shapes, status codes and messages
|
|
51
|
+
* (docs/openapi.yaml). `createServer()` (HTTP) and the MCP tools use it.
|
|
52
|
+
*
|
|
53
|
+
* The placeholder mapping never leaves the service: redact returns placeholders and a vault id, restore
|
|
54
|
+
* resolves them. Errors never contain personal data; model errors are generic (details go to onError).
|
|
55
|
+
*/
|
|
56
|
+
export declare class ServiceApi {
|
|
57
|
+
#private;
|
|
58
|
+
static readonly MAX_TEXT_LENGTH = 100000;
|
|
59
|
+
static readonly DEFAULT_VAULT_TTL = 900;
|
|
60
|
+
constructor(options: ServiceApiOptions);
|
|
61
|
+
/** Whether `"detection": "model" | "both"` is available (reported by /v1/health). */
|
|
62
|
+
get modelDetection(): boolean;
|
|
63
|
+
/** Routes, authenticates and runs one request. */
|
|
64
|
+
handle(request: ServiceRequest): Promise<ServiceResponse>;
|
|
65
|
+
/**
|
|
66
|
+
* The access rule of /v1 and /mcp: the bearer token if one is configured, otherwise local peers only;
|
|
67
|
+
* in service mode a token is required. Returns the error response, or null when access is granted.
|
|
68
|
+
*/
|
|
69
|
+
checkAccess(authorization: string | undefined, remoteAddress: string | undefined): ServiceResponse | null;
|
|
70
|
+
/**
|
|
71
|
+
* One operation without routing or authentication (the caller has authenticated), shared by the
|
|
72
|
+
* HTTP API and the MCP tools.
|
|
73
|
+
*/
|
|
74
|
+
operation(operation: ServiceOperation, body: JsonBody, options?: DetectOptions): Promise<ServiceResponse>;
|
|
75
|
+
}
|