@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,187 @@
1
+ import { ModelDetector } from '../model/model-detector.js';
2
+ import { EntityLearner } from '../learning/entity-learner.js';
3
+ import { JsonFileCustomEntityStore } from '../learning/json-file-store.js';
4
+ import { InMemoryCustomEntityStore, KeyValueCustomEntityStore } from '../learning/store.js';
5
+ import { localPeerMatcher, splitList } from '../service/local-peer.js';
6
+ import { ServiceApi } from '../service/service-api.js';
7
+ import { EncryptedVault, generateVaultKey, parseVaultKey } from '../vault/encrypted-vault.js';
8
+ import { MemoryVaultStorage } from '../vault/memory-vault-storage.js';
9
+ import { DEFAULT_MAX_BODY_BYTES } from './http-server.js';
10
+ import { MODEL_PROVIDERS, providerModel } from './model-providers.js';
11
+ /** A configuration problem; the message names the variable, never a secret. */
12
+ export class ConfigError extends Error {
13
+ name = 'ConfigError';
14
+ }
15
+ /**
16
+ * Builds the service from environment variables (names as in the PHP service where they exist; see
17
+ * docs/server.md). Used by the `pii-shield` CLI.
18
+ *
19
+ * @throws ConfigError
20
+ */
21
+ export async function serviceFromEnv(env = process.env) {
22
+ const get = (name) => {
23
+ const value = env[name];
24
+ return value === undefined || value === '' ? undefined : value;
25
+ };
26
+ const notes = [];
27
+ let redis;
28
+ const connectRedis = async () => {
29
+ const url = get('PII_SERVICE_REDIS_URL') ?? get('PII_DEMO_REDIS_URL');
30
+ if (url === undefined) {
31
+ throw new ConfigError('Set PII_SERVICE_REDIS_URL to use the redis store.');
32
+ }
33
+ if (redis === undefined) {
34
+ let Redis;
35
+ try {
36
+ ({ Redis } = (await import('ioredis')));
37
+ }
38
+ catch {
39
+ throw new ConfigError('The redis store needs the package "ioredis" (npm install ioredis).');
40
+ }
41
+ redis = new Redis(url);
42
+ }
43
+ return redis;
44
+ };
45
+ try {
46
+ // Vault
47
+ const keyBase64 = get('PII_SERVICE_VAULT_KEY');
48
+ let key;
49
+ if (keyBase64 === undefined) {
50
+ key = generateVaultKey();
51
+ }
52
+ else {
53
+ try {
54
+ key = parseVaultKey(keyBase64);
55
+ }
56
+ catch {
57
+ throw new ConfigError('PII_SERVICE_VAULT_KEY must be 32 bytes, base64-encoded.');
58
+ }
59
+ }
60
+ const vaultStore = get('PII_SERVICE_VAULT_STORE') ?? 'memory';
61
+ let storage;
62
+ if (vaultStore === 'memory') {
63
+ storage = new MemoryVaultStorage();
64
+ notes.push('Vault: in memory; mappings are lost on restart.');
65
+ }
66
+ else if (vaultStore === 'redis') {
67
+ if (keyBase64 === undefined) {
68
+ throw new ConfigError('The redis vault store needs PII_SERVICE_VAULT_KEY, or mappings cannot be read after a restart.');
69
+ }
70
+ const { RedisVaultStorage } = await import('../vault-redis/index.js');
71
+ storage = new RedisVaultStorage({ client: await connectRedis() });
72
+ }
73
+ else {
74
+ throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory" or "redis".');
75
+ }
76
+ const vaultTtl = integer(get('PII_SERVICE_VAULT_TTL'), 'PII_SERVICE_VAULT_TTL', ServiceApi.DEFAULT_VAULT_TTL);
77
+ // Learned types
78
+ const learnedFile = get('PII_SERVICE_LEARNED_TYPES');
79
+ const learnedStore = get('PII_SERVICE_LEARNED_STORE') ?? (learnedFile === undefined ? 'memory' : 'file');
80
+ let store;
81
+ if (learnedStore === 'file') {
82
+ if (learnedFile === undefined) {
83
+ throw new ConfigError('Set PII_SERVICE_LEARNED_TYPES to the JSON file of learned types.');
84
+ }
85
+ store = new JsonFileCustomEntityStore(learnedFile);
86
+ }
87
+ else if (learnedStore === 'memory') {
88
+ store = new InMemoryCustomEntityStore();
89
+ notes.push('Learned types: in memory; set PII_SERVICE_LEARNED_TYPES to keep them.');
90
+ }
91
+ else if (learnedStore === 'redis') {
92
+ store = new KeyValueCustomEntityStore(await connectRedis());
93
+ }
94
+ else {
95
+ throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory" or "redis".');
96
+ }
97
+ let learner;
98
+ try {
99
+ learner = await EntityLearner.create({ store });
100
+ }
101
+ catch (e) {
102
+ throw new ConfigError(`The learned types cannot be read: ${e instanceof Error ? e.message : String(e)}`);
103
+ }
104
+ // Model
105
+ let modelDetector;
106
+ const provider = get('PII_SERVICE_MODEL_PROVIDER');
107
+ if (provider !== undefined) {
108
+ if (!MODEL_PROVIDERS.includes(provider)) {
109
+ throw new ConfigError(`PII_SERVICE_MODEL_PROVIDER must be one of ${MODEL_PROVIDERS.join(', ')}.`);
110
+ }
111
+ const keys = {
112
+ ollama: undefined,
113
+ generic: get('PII_SERVICE_MODEL_KEY') ?? get('PII_DEMO_GENERIC_KEY'),
114
+ mistral: get('MISTRAL_API_KEY'),
115
+ openai: get('OPENAI_API_KEY'),
116
+ anthropic: get('ANTHROPIC_API_KEY'),
117
+ };
118
+ const typed = provider;
119
+ let resolved;
120
+ try {
121
+ resolved = providerModel({
122
+ provider: typed,
123
+ model: get('PII_SERVICE_MODEL'),
124
+ endpoint: get('PII_SERVICE_MODEL_URL') ?? (typed === 'ollama' ? get('PII_DEMO_OLLAMA_URL') : undefined),
125
+ apiKey: keys[typed],
126
+ });
127
+ }
128
+ catch (e) {
129
+ throw new ConfigError(e instanceof Error ? e.message : String(e));
130
+ }
131
+ const acknowledged = get('PII_SERVICE_ACKNOWLEDGE_EXTERNAL') === 'true';
132
+ if (resolved.location === 'external' && !acknowledged) {
133
+ throw new ConfigError(`${provider} is an external provider: detection sends the unredacted text there. Set PII_SERVICE_ACKNOWLEDGE_EXTERNAL=true after checking the data processing agreement and third-country transfers.`);
134
+ }
135
+ const options = {
136
+ model: resolved.model,
137
+ location: resolved.location,
138
+ acknowledgeExternalTransfer: acknowledged,
139
+ learnedTypes: learner,
140
+ // Self-hosted models answer only when done; allow for large models on modest hardware (PHP: 170 s).
141
+ timeout: integer(get('PII_SERVICE_MODEL_TIMEOUT'), 'PII_SERVICE_MODEL_TIMEOUT', 170) * 1000,
142
+ };
143
+ try {
144
+ new ModelDetector(options); // fail at start, not per request (external without acknowledgement)
145
+ }
146
+ catch (e) {
147
+ throw new ConfigError(e instanceof Error ? e.message : String(e));
148
+ }
149
+ modelDetector = () => new ModelDetector(options);
150
+ }
151
+ const api = new ServiceApi({
152
+ vault: new EncryptedVault({ storage, key }),
153
+ learner,
154
+ modelDetector,
155
+ token: get('PII_SERVICE_TOKEN'),
156
+ vaultTtl,
157
+ requireToken: get('PII_SERVICE_ONLY') === '1',
158
+ isLocalPeer: localPeerMatcher(splitList(get('PII_LOCAL_PEERS'))),
159
+ });
160
+ key.fill(0);
161
+ return {
162
+ api,
163
+ allowedHosts: splitList(get('PII_SERVICE_ALLOWED_HOSTS')),
164
+ maxBodyBytes: integer(get('PII_SERVICE_MAX_BODY_BYTES'), 'PII_SERVICE_MAX_BODY_BYTES', DEFAULT_MAX_BODY_BYTES),
165
+ host: get('PII_SERVICE_HOST') ?? '127.0.0.1',
166
+ port: integer(get('PII_SERVICE_PORT'), 'PII_SERVICE_PORT', 8088, 0),
167
+ notes,
168
+ close: async () => {
169
+ await redis?.quit();
170
+ },
171
+ };
172
+ }
173
+ catch (e) {
174
+ await redis?.quit().catch(() => undefined);
175
+ throw e;
176
+ }
177
+ }
178
+ function integer(value, name, fallback, min = 1) {
179
+ if (value === undefined) {
180
+ return fallback;
181
+ }
182
+ const n = Number(value);
183
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min) {
184
+ throw new ConfigError(`${name} must be an integer of at least ${String(min)}.`);
185
+ }
186
+ return n;
187
+ }
@@ -0,0 +1,63 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ import type { AddressInfo } from 'node:net';
3
+ import type { ServiceApi } from '../service/service-api.js';
4
+ /** Serves /mcp (Streamable HTTP); see `createMcpHttpHandler()` in `@waswrongassembled/pii-shield/mcp`. */
5
+ export interface McpHttpHandler {
6
+ /** Answers one request to /mcp; the request guard has already checked host, origin and access. */
7
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
8
+ /** Closes all MCP sessions. */
9
+ close(): Promise<void>;
10
+ }
11
+ export interface RequestListenerOptions {
12
+ api: ServiceApi;
13
+ /** Serve /v1 (default true). */
14
+ v1?: boolean;
15
+ /** Serve /mcp with this handler (default: no /mcp). */
16
+ mcp?: McpHttpHandler | undefined;
17
+ /** Host names to answer besides 127.0.0.1, localhost and [::1] (PII_SERVICE_ALLOWED_HOSTS). */
18
+ allowedHosts?: Iterable<string>;
19
+ /** Largest request body in bytes, default 2 MiB (a 100,000 character text fits even fully escaped). */
20
+ maxBodyBytes?: number;
21
+ /** Browser origins allowed on /mcp besides the server's own; default the MCP Inspector's. */
22
+ mcpBrowserOrigins?: Iterable<string>;
23
+ /** Called with unexpected errors (500); never receives request text. */
24
+ onError?: (error: unknown) => void;
25
+ }
26
+ export interface ServerOptions extends RequestListenerOptions {
27
+ /** Default 8088. 0 picks a free port. */
28
+ port?: number;
29
+ /** Default 127.0.0.1. */
30
+ host?: string;
31
+ }
32
+ /** A started server; `close()` stops it gracefully. */
33
+ export interface PiiShieldServer {
34
+ readonly server: Server;
35
+ /** e.g. "http://127.0.0.1:8088" */
36
+ readonly url: string;
37
+ readonly address: AddressInfo;
38
+ /**
39
+ * Stops accepting connections, closes MCP sessions and waits for running requests, at most
40
+ * `timeoutMs` (default 10000), then closes the remaining connections.
41
+ */
42
+ close(timeoutMs?: number): Promise<void>;
43
+ [Symbol.asyncDispose](): Promise<void>;
44
+ }
45
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
46
+ /** Browser-based MCP tools allowed besides same-origin requests (the MCP Inspector's default). */
47
+ export declare const MCP_BROWSER_ORIGINS: readonly string[];
48
+ /** docs/openapi.yaml of this package, served at /v1/openapi.yaml. */
49
+ export declare function openapiDocument(): Promise<string>;
50
+ /**
51
+ * The request listener of the pii-shield service: /v1 (ServiceApi) and optionally /mcp, behind the
52
+ * checks of PHP's RequestGuard:
53
+ *
54
+ * - only known host names (DNS rebinding): 421;
55
+ * - POST only as `application/json`, no foreign browser Origin (CSRF): 403;
56
+ * - /v1 and /mcp need the bearer token, or come from a local peer when no token is configured;
57
+ * - security headers on every response, no CORS.
58
+ *
59
+ * Mount it in your own `node:http` server or use `startServer()`.
60
+ */
61
+ export declare function createRequestListener(options: RequestListenerOptions): (req: IncomingMessage, res: ServerResponse) => void;
62
+ /** Starts the service on `host:port` (default 127.0.0.1:8088). */
63
+ export declare function startServer(options: ServerOptions): Promise<PiiShieldServer>;
@@ -0,0 +1,241 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { createServer as createHttpServer } from 'node:http';
3
+ import { parseJsonBody } from '../service/json-body.js';
4
+ export const DEFAULT_MAX_BODY_BYTES = 2 * 1024 * 1024;
5
+ /** Browser-based MCP tools allowed besides same-origin requests (the MCP Inspector's default). */
6
+ export const MCP_BROWSER_ORIGINS = Object.freeze(['http://localhost:6274', 'http://127.0.0.1:6274']);
7
+ const LOCAL_HOSTS = ['127.0.0.1', 'localhost', '[::1]'];
8
+ const OPENAPI_PATH = '/v1/openapi.yaml';
9
+ const SECURITY_HEADERS = {
10
+ 'Content-Security-Policy': "default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
11
+ 'X-Content-Type-Options': 'nosniff',
12
+ 'Referrer-Policy': 'no-referrer',
13
+ 'Cache-Control': 'no-store',
14
+ };
15
+ let openapi;
16
+ /** docs/openapi.yaml of this package, served at /v1/openapi.yaml. */
17
+ export function openapiDocument() {
18
+ openapi ??= readFile(new URL('../../docs/openapi.yaml', import.meta.url), 'utf8');
19
+ return openapi;
20
+ }
21
+ /**
22
+ * The request listener of the pii-shield service: /v1 (ServiceApi) and optionally /mcp, behind the
23
+ * checks of PHP's RequestGuard:
24
+ *
25
+ * - only known host names (DNS rebinding): 421;
26
+ * - POST only as `application/json`, no foreign browser Origin (CSRF): 403;
27
+ * - /v1 and /mcp need the bearer token, or come from a local peer when no token is configured;
28
+ * - security headers on every response, no CORS.
29
+ *
30
+ * Mount it in your own `node:http` server or use `startServer()`.
31
+ */
32
+ export function createRequestListener(options) {
33
+ const { api, v1 = true, mcp, maxBodyBytes = DEFAULT_MAX_BODY_BYTES } = options;
34
+ const hosts = new Set([...LOCAL_HOSTS, ...[...(options.allowedHosts ?? [])].map((h) => h.toLowerCase())]);
35
+ const mcpOrigins = new Set(options.mcpBrowserOrigins ?? MCP_BROWSER_ORIGINS);
36
+ const onError = options.onError ??
37
+ (() => {
38
+ // silent by default
39
+ });
40
+ async function handle(req, res) {
41
+ for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
42
+ res.setHeader(name, value);
43
+ }
44
+ const method = req.method ?? 'GET';
45
+ const path = rawUrlDecode((req.url ?? '/').replace(/[?#].*$/s, ''));
46
+ const isMcp = mcp !== undefined && path === '/mcp';
47
+ const isOpenapi = v1 && path === OPENAPI_PATH && (method === 'GET' || method === 'HEAD');
48
+ const isV1 = v1 && path.startsWith('/v1/') && path.length > '/v1/'.length;
49
+ if (!isMcp && !isV1) {
50
+ send(res, { status: 404, body: { error: 'Not found.' } });
51
+ return;
52
+ }
53
+ const host = parseHost(req.headers.host);
54
+ if (!hosts.has(host.name)) {
55
+ send(res, { status: 421, body: { error: 'Unknown host.' } });
56
+ return;
57
+ }
58
+ const origin = req.headers.origin;
59
+ const foreignOrigin = origin !== undefined && origin !== host.origin && !(isMcp && mcpOrigins.has(origin));
60
+ const notJson = method === 'POST' && !(req.headers['content-type'] ?? '').startsWith('application/json');
61
+ if (foreignOrigin || notJson) {
62
+ send(res, {
63
+ status: 403,
64
+ body: { error: 'Send JSON (Content-Type: application/json) from a non-browser client or this page.' },
65
+ });
66
+ return;
67
+ }
68
+ if (isMcp) {
69
+ const denied = api.checkAccess(req.headers.authorization, req.socket.remoteAddress);
70
+ if (denied !== null) {
71
+ send(res, denied);
72
+ return;
73
+ }
74
+ await mcp.handle(req, res);
75
+ return;
76
+ }
77
+ if (isOpenapi) {
78
+ res.writeHead(200, { 'Content-Type': 'application/yaml; charset=utf-8' });
79
+ res.end(method === 'HEAD' ? undefined : await openapiDocument());
80
+ return;
81
+ }
82
+ let body = null;
83
+ if (method === 'POST') {
84
+ const bytes = await readBody(req, maxBodyBytes);
85
+ if (bytes === null) {
86
+ res.setHeader('Connection', 'close');
87
+ res.once('finish', () => req.socket.destroy());
88
+ send(res, { status: 413, body: { error: 'The request body is too large.' } });
89
+ return;
90
+ }
91
+ const parsed = parseJsonBody(bytes);
92
+ if (!parsed.ok) {
93
+ send(res, { status: 400, body: { error: parsed.error } });
94
+ return;
95
+ }
96
+ body = parsed.body;
97
+ }
98
+ const aborted = new AbortController();
99
+ const onClose = () => {
100
+ if (!res.writableFinished) {
101
+ aborted.abort(new Error('The client closed the connection.'));
102
+ }
103
+ };
104
+ res.once('close', onClose);
105
+ try {
106
+ send(res, await api.handle({
107
+ method,
108
+ path,
109
+ body,
110
+ authorization: req.headers.authorization,
111
+ remoteAddress: req.socket.remoteAddress,
112
+ signal: aborted.signal,
113
+ }));
114
+ }
115
+ finally {
116
+ res.off('close', onClose);
117
+ }
118
+ }
119
+ return (req, res) => {
120
+ handle(req, res).catch((e) => {
121
+ if (!res.headersSent && !res.destroyed) {
122
+ onError(e);
123
+ send(res, { status: 500, body: { error: 'Internal server error.' } });
124
+ }
125
+ else if (!res.destroyed) {
126
+ onError(e);
127
+ res.destroy();
128
+ }
129
+ });
130
+ };
131
+ }
132
+ /** Starts the service on `host:port` (default 127.0.0.1:8088). */
133
+ export async function startServer(options) {
134
+ const { port = 8088, host = '127.0.0.1' } = options;
135
+ const server = createHttpServer(createRequestListener(options));
136
+ await new Promise((resolve, reject) => {
137
+ server.once('error', reject);
138
+ server.listen(port, host, () => {
139
+ server.off('error', reject);
140
+ resolve();
141
+ });
142
+ });
143
+ const address = server.address();
144
+ const urlHost = address.family === 'IPv6' ? `[${address.address}]` : address.address;
145
+ let closing;
146
+ // While closing, a connection that finishes its response is closed instead of kept alive.
147
+ server.on('request', (_req, res) => {
148
+ res.once('finish', () => {
149
+ if (closing !== undefined) {
150
+ setImmediate(() => {
151
+ server.closeIdleConnections();
152
+ });
153
+ }
154
+ });
155
+ });
156
+ const close = (timeoutMs = 10_000) => {
157
+ closing ??= (async () => {
158
+ const closed = new Promise((resolve) => server.close(() => {
159
+ resolve();
160
+ }));
161
+ server.closeIdleConnections();
162
+ await options.mcp?.close();
163
+ const timer = setTimeout(() => {
164
+ server.closeAllConnections();
165
+ }, timeoutMs);
166
+ try {
167
+ await closed;
168
+ }
169
+ finally {
170
+ clearTimeout(timer);
171
+ }
172
+ })();
173
+ return closing;
174
+ };
175
+ return {
176
+ server,
177
+ url: `http://${urlHost}:${String(address.port)}`,
178
+ address,
179
+ close,
180
+ [Symbol.asyncDispose]: () => close(),
181
+ };
182
+ }
183
+ function send(res, response) {
184
+ if (response.status === 204 || response.body === null) {
185
+ res.writeHead(response.status);
186
+ res.end();
187
+ return;
188
+ }
189
+ const json = JSON.stringify(response.body);
190
+ res.writeHead(response.status, {
191
+ 'Content-Type': 'application/json',
192
+ 'Content-Length': Buffer.byteLength(json),
193
+ });
194
+ res.end(json);
195
+ }
196
+ /** Reads the body; null when it is larger than `limit` bytes. */
197
+ async function readBody(req, limit) {
198
+ const declared = Number(req.headers['content-length'] ?? 0);
199
+ if (declared > limit) {
200
+ return null;
201
+ }
202
+ const chunks = [];
203
+ let size = 0;
204
+ for await (const chunk of req) {
205
+ size += chunk.length;
206
+ if (size > limit) {
207
+ return null;
208
+ }
209
+ chunks.push(chunk);
210
+ }
211
+ return Buffer.concat(chunks);
212
+ }
213
+ /**
214
+ * The Host header as Symfony sees it: the lower-case name without port, and the request's own origin
215
+ * (`http://` + name, plus the port unless it is 80).
216
+ */
217
+ function parseHost(header) {
218
+ const value = (header ?? '').toLowerCase();
219
+ const port = /:(\d+)$/.exec(value);
220
+ const name = port === null ? value : value.slice(0, port.index);
221
+ const origin = port === null || port[1] === '80' ? `http://${name}` : `http://${name}:${port[1] ?? ''}`;
222
+ return { name, origin };
223
+ }
224
+ /** PHP's rawurldecode(): %XX sequences become bytes, everything else stays. */
225
+ function rawUrlDecode(path) {
226
+ if (!path.includes('%')) {
227
+ return path;
228
+ }
229
+ const bytes = [];
230
+ for (let i = 0; i < path.length; i++) {
231
+ const hex = path.slice(i + 1, i + 3);
232
+ if (path[i] === '%' && /^[0-9a-fA-F]{2}$/.test(hex)) {
233
+ bytes.push(Number.parseInt(hex, 16));
234
+ i += 2;
235
+ }
236
+ else {
237
+ bytes.push(...Buffer.from(path[i] ?? '', 'utf8'));
238
+ }
239
+ }
240
+ return Buffer.from(bytes).toString('utf8');
241
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/server: pii-shield as an HTTP service (/v1, docs/openapi.yaml), on plain
3
+ * `node:http`, with the same endpoints, JSON shapes, status codes, messages and request checks as the
4
+ * PHP service. The `pii-shield` CLI (`pii-shield serve`, `pii-shield mcp`) is built on it.
5
+ */
6
+ export { createRequestListener, DEFAULT_MAX_BODY_BYTES, MCP_BROWSER_ORIGINS, type McpHttpHandler, openapiDocument, type PiiShieldServer, type RequestListenerOptions, type ServerOptions, startServer, } from './http-server.js';
7
+ export { type JsonBody, parseJsonBody, type ParsedBody } from '../service/json-body.js';
8
+ export { defaultGateway, localPeerMatcher, splitList } from '../service/local-peer.js';
9
+ export { ServiceApi, type ServiceApiOptions, type ServiceOperation, type ServiceRequest, type ServiceResponse, } from '../service/service-api.js';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/server: pii-shield as an HTTP service (/v1, docs/openapi.yaml), on plain
3
+ * `node:http`, with the same endpoints, JSON shapes, status codes, messages and request checks as the
4
+ * PHP service. The `pii-shield` CLI (`pii-shield serve`, `pii-shield mcp`) is built on it.
5
+ */
6
+ export { createRequestListener, DEFAULT_MAX_BODY_BYTES, MCP_BROWSER_ORIGINS, openapiDocument, startServer, } from './http-server.js';
7
+ export { parseJsonBody } from '../service/json-body.js';
8
+ export { defaultGateway, localPeerMatcher, splitList } from '../service/local-peer.js';
9
+ export { ServiceApi, } from '../service/service-api.js';
@@ -0,0 +1,31 @@
1
+ import type { DetectionModel } from '../model/model-detector.js';
2
+ import { ModelLocation } from '../model/model-detector.js';
3
+ /** Providers of PHP's service configuration (PII_SERVICE_MODEL_PROVIDER). */
4
+ export type ModelProvider = 'ollama' | 'generic' | 'mistral' | 'openai' | 'anthropic';
5
+ export declare const MODEL_PROVIDERS: readonly ModelProvider[];
6
+ export interface ProviderSettings {
7
+ provider: ModelProvider;
8
+ /** Model name; default per provider as in PHP (none for `generic`). */
9
+ model?: string | undefined;
10
+ /** Server URL for `ollama` (default http://127.0.0.1:11434) and `generic` (OpenAI-compatible, required). */
11
+ endpoint?: string | undefined;
12
+ /** API key: required for mistral, openai, anthropic; optional for generic. */
13
+ apiKey?: string | undefined;
14
+ /** For tests: the fetch implementation. */
15
+ fetch?: typeof fetch;
16
+ }
17
+ export interface ResolvedProvider {
18
+ model: DetectionModel;
19
+ location: ModelLocation;
20
+ }
21
+ /**
22
+ * A DetectionModel over plain `fetch` for the providers of PHP's service, with PHP's request options:
23
+ * deterministic (temperature 0, except OpenAI and Anthropic), no reasoning and at most 1024 answer tokens
24
+ * for self-hosted models, no redirects. The location follows PHP: `ollama` and `generic` are local when
25
+ * the URL's host is this machine (or host.docker.internal), else on-premise; the others are external.
26
+ *
27
+ * @throws TypeError for an unknown provider, a missing model, key or URL, or a URL that is not http(s)
28
+ */
29
+ export declare function providerModel(settings: ProviderSettings): ResolvedProvider;
30
+ /** PHP's DemoServices::validEndpoint(): trimmed, without trailing slashes, http or https. */
31
+ export declare function validEndpoint(endpoint: string): string;