@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,305 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { isAsyncDetector } from '../detector.js';
3
+ import { EmailDetector } from '../detectors/email.js';
4
+ import { PhoneDetector } from '../detectors/phone.js';
5
+ import { defaultDetectors } from '../entity-extractor.js';
6
+ import { isEntityType } from '../entity-type.js';
7
+ import { DetectionError, LearningError, PiiShieldError, VaultError } from '../errors.js';
8
+ import { codePointLength } from '../internal/pcre.js';
9
+ import { PiiMasker } from '../pii-masker.js';
10
+ import { PiiShield } from '../pii-shield.js';
11
+ import { assertTtl } from '../vault/vault.js';
12
+ import { localPeerMatcher } from './local-peer.js';
13
+ const ROUTES = {
14
+ '/v1/redact': 'redact',
15
+ '/v1/restore': 'restore',
16
+ '/v1/mask': 'mask',
17
+ '/v1/learn': 'learn',
18
+ '/v1/entities': 'entities',
19
+ };
20
+ const ENTITY_PATH = /^\/v1\/entities\/([A-Z][A-Z0-9_]{1,39})$/;
21
+ const VAULT_PATH = /^\/v1\/vault\/([0-9a-f]{32})$/;
22
+ const PLACEHOLDER_TYPE = /^⟦(.+)_\p{Nd}+⟧$/u;
23
+ /** A client error (400): the request is malformed. */
24
+ class BadRequest extends Error {
25
+ }
26
+ /**
27
+ * The versioned HTTP API (/v1) of pii-shield as a service, framework-free: routing, authentication and
28
+ * the operations. Port of PHP's `ServiceApi`, same JSON shapes, status codes and messages
29
+ * (docs/openapi.yaml). `createServer()` (HTTP) and the MCP tools use it.
30
+ *
31
+ * The placeholder mapping never leaves the service: redact returns placeholders and a vault id, restore
32
+ * resolves them. Errors never contain personal data; model errors are generic (details go to onError).
33
+ */
34
+ export class ServiceApi {
35
+ static MAX_TEXT_LENGTH = 100_000;
36
+ static DEFAULT_VAULT_TTL = 900;
37
+ #vault;
38
+ #learner;
39
+ #modelDetector;
40
+ #token;
41
+ #vaultTtl;
42
+ #requireToken;
43
+ #isLocalPeer;
44
+ #onError;
45
+ constructor(options) {
46
+ this.#vault = options.vault;
47
+ this.#learner = options.learner;
48
+ this.#modelDetector = options.modelDetector;
49
+ this.#token = options.token === '' ? undefined : options.token;
50
+ this.#vaultTtl = options.vaultTtl ?? ServiceApi.DEFAULT_VAULT_TTL;
51
+ this.#requireToken = options.requireToken ?? false;
52
+ this.#isLocalPeer = options.isLocalPeer ?? localPeerMatcher();
53
+ this.#onError =
54
+ options.onError ??
55
+ (() => {
56
+ // silent by default
57
+ });
58
+ assertTtl(this.#vaultTtl, 'The vault TTL must be positive.');
59
+ }
60
+ /** Whether `"detection": "model" | "both"` is available (reported by /v1/health). */
61
+ get modelDetection() {
62
+ return this.#modelDetector !== undefined;
63
+ }
64
+ /** Routes, authenticates and runs one request. */
65
+ async handle(request) {
66
+ const { method, path } = request;
67
+ if (path === '/v1/health') {
68
+ return method === 'GET' ? ok({ status: 'ok', modelDetection: this.modelDetection }) : error(405, 'Use GET.');
69
+ }
70
+ const denied = this.checkAccess(request.authorization, request.remoteAddress);
71
+ if (denied !== null) {
72
+ return denied;
73
+ }
74
+ const operation = Object.hasOwn(ROUTES, path) ? ROUTES[path] : undefined;
75
+ if (operation !== undefined) {
76
+ const allowed = operation === 'entities' ? 'GET' : 'POST';
77
+ return method === allowed
78
+ ? this.operation(operation, request.body ?? {}, { signal: request.signal })
79
+ : error(405, `Use ${allowed}.`);
80
+ }
81
+ const entity = ENTITY_PATH.exec(path);
82
+ if (entity?.[1] !== undefined) {
83
+ return method === 'DELETE' ? this.#guarded(() => this.#forgetType(entity[1] ?? '')) : error(405, 'Use DELETE.');
84
+ }
85
+ const vault = VAULT_PATH.exec(path);
86
+ if (vault?.[1] !== undefined) {
87
+ if (method !== 'DELETE') {
88
+ return error(405, 'Use DELETE.');
89
+ }
90
+ return this.#guarded(async () => {
91
+ await this.#vault.delete(vault[1] ?? '');
92
+ return { status: 204, body: null };
93
+ });
94
+ }
95
+ return error(404, 'Not found.');
96
+ }
97
+ /**
98
+ * The access rule of /v1 and /mcp: the bearer token if one is configured, otherwise local peers only;
99
+ * in service mode a token is required. Returns the error response, or null when access is granted.
100
+ */
101
+ checkAccess(authorization, remoteAddress) {
102
+ if (this.#token === undefined) {
103
+ if (this.#requireToken) {
104
+ return error(503, 'Set PII_SERVICE_TOKEN to use this service.');
105
+ }
106
+ return this.#isLocalPeer(remoteAddress) ? null : error(401, 'Missing or invalid bearer token.');
107
+ }
108
+ return authorization !== undefined && constantTimeEquals(`Bearer ${this.#token}`, authorization)
109
+ ? null
110
+ : error(401, 'Missing or invalid bearer token.');
111
+ }
112
+ /**
113
+ * One operation without routing or authentication (the caller has authenticated), shared by the
114
+ * HTTP API and the MCP tools.
115
+ */
116
+ operation(operation, body, options = {}) {
117
+ return this.#guarded(() => {
118
+ switch (operation) {
119
+ case 'redact':
120
+ return this.#redact(body, options);
121
+ case 'restore':
122
+ return this.#restore(body);
123
+ case 'mask':
124
+ return this.#mask(body, options);
125
+ case 'learn':
126
+ return this.#learn(body);
127
+ case 'entities':
128
+ return this.#entities();
129
+ }
130
+ });
131
+ }
132
+ async #guarded(run) {
133
+ try {
134
+ return await run();
135
+ }
136
+ catch (e) {
137
+ if (e instanceof BadRequest) {
138
+ return error(400, e.message);
139
+ }
140
+ if (e instanceof LearningError) {
141
+ return error(422, e.message);
142
+ }
143
+ if (e instanceof DetectionError) {
144
+ this.#onError(e);
145
+ // Details (model name, URLs, provider errors) stay on the server.
146
+ return error(502, 'Model-based detection failed.');
147
+ }
148
+ if (e instanceof PiiShieldError) {
149
+ this.#onError(e);
150
+ return error(500, 'Detection failed.');
151
+ }
152
+ throw e;
153
+ }
154
+ }
155
+ async #redact(body, options) {
156
+ const detectors = await this.#detectors(body);
157
+ const allowlist = strings(body, 'allowlist');
158
+ const text = textOf(body);
159
+ const shield = new PiiShield({ detectors, vault: this.#vault, vaultTtl: this.#vaultTtl, allowlist });
160
+ const redaction = await shield.redactToVault(text, options);
161
+ return ok({
162
+ text: redaction.redactedText,
163
+ vaultId: redaction.vaultId,
164
+ expiresIn: this.#vaultTtl,
165
+ placeholders: Object.keys(redaction.mapping).map((placeholder) => ({
166
+ placeholder,
167
+ type: PLACEHOLDER_TYPE.exec(placeholder)?.[1] ?? placeholder,
168
+ })),
169
+ });
170
+ }
171
+ async #restore(body) {
172
+ const vaultId = field(body, 'vaultId');
173
+ const text = textOf(body);
174
+ let restored;
175
+ try {
176
+ restored = await new PiiShield({ detectors: [], vault: this.#vault }).restoreFromVault(text, typeof vaultId === 'string' ? vaultId : '');
177
+ }
178
+ catch (e) {
179
+ if (e instanceof VaultError) {
180
+ return error(404, 'Unknown or expired vault id. Redact the text again.');
181
+ }
182
+ throw e;
183
+ }
184
+ return ok({
185
+ text: restored.text,
186
+ unknownPlaceholders: restored.unknownPlaceholders,
187
+ unusedPlaceholders: restored.unusedPlaceholders,
188
+ });
189
+ }
190
+ async #mask(body, options) {
191
+ const detectors = await this.#detectors(body);
192
+ const allowlist = strings(body, 'allowlist');
193
+ const text = textOf(body);
194
+ return ok({ text: await new PiiMasker({ detectors, allowlist }).maskAsync(text, options) });
195
+ }
196
+ async #learn(body) {
197
+ const name = field(body, 'name');
198
+ const description = field(body, 'description');
199
+ const pattern = field(body, 'pattern');
200
+ const init = {
201
+ name: typeof name === 'string' ? name : '',
202
+ description: typeof description === 'string' ? description : '',
203
+ examples: strings(body, 'examples'),
204
+ counterExamples: strings(body, 'counterExamples'),
205
+ pattern: typeof pattern === 'string' ? pattern : null,
206
+ };
207
+ const dryRun = field(body, 'dryRun') === true;
208
+ const result = dryRun ? this.#learner.preview(init) : await this.#learner.learn(init);
209
+ return { status: dryRun ? 200 : 201, body: { type: result.type, note: result.note, saved: !dryRun } };
210
+ }
211
+ async #entities() {
212
+ return ok({ types: await this.#learner.types() });
213
+ }
214
+ async #forgetType(name) {
215
+ if (!(await this.#learner.types()).some((t) => t.name === name)) {
216
+ return error(404, `No learned type "${name}".`);
217
+ }
218
+ await this.#learner.forget(name);
219
+ return { status: 204, body: null };
220
+ }
221
+ /** Built-in patterns, learned types and, on request, the configured model. */
222
+ async #detectors(body) {
223
+ const detection = field(body, 'detection') ?? 'regex';
224
+ if (detection !== 'regex' && detection !== 'model' && detection !== 'both') {
225
+ throw new BadRequest('"detection" must be "regex", "model" or "both".');
226
+ }
227
+ // Other processes may have learned types since (PHP reads the store at every detection).
228
+ await this.#learner.refresh();
229
+ const detectors = [this.#learner.detector()];
230
+ if (detection !== 'model') {
231
+ const keepAuthorityContacts = field(body, 'keepAuthorityContacts') !== false;
232
+ for (const detector of defaultDetectors()) {
233
+ detectors.push(detector instanceof EmailDetector
234
+ ? new EmailDetector({ keepAuthorityContacts })
235
+ : detector instanceof PhoneDetector
236
+ ? new PhoneDetector({ keepAuthorityContacts })
237
+ : detector);
238
+ }
239
+ }
240
+ if (detection !== 'regex') {
241
+ if (this.#modelDetector === undefined) {
242
+ throw new LearningError('Model-based detection is not configured on this server.');
243
+ }
244
+ detectors.push(this.#modelDetector());
245
+ }
246
+ if (field(body, 'types') === undefined) {
247
+ return detectors;
248
+ }
249
+ const types = new Set();
250
+ for (const type of strings(body, 'types')) {
251
+ if (!isEntityType(type)) {
252
+ throw new BadRequest(`Unknown type "${type}".`);
253
+ }
254
+ types.add(type);
255
+ }
256
+ return detectors.map((d) => onlyTypes(d, types));
257
+ }
258
+ }
259
+ /**
260
+ * Keeps only findings of the given built-in types. Learned types have the type OTHER, so like PHP's
261
+ * RequestScopedDetector this drops them unless OTHER is listed.
262
+ */
263
+ function onlyTypes(detector, types) {
264
+ const keep = (entities) => entities.filter((e) => types.has(e.type));
265
+ if (isAsyncDetector(detector)) {
266
+ return {
267
+ async: true,
268
+ detect: async (text, options) => keep(await detector.detect(text, options)),
269
+ };
270
+ }
271
+ return { detect: (text) => keep(detector.detect(text)) };
272
+ }
273
+ /** A body field; PHP's `$body[$key] ?? null` (null counts as missing). Own properties only. */
274
+ function field(body, key) {
275
+ return Object.hasOwn(body, key) ? (body[key] ?? undefined) : undefined;
276
+ }
277
+ function textOf(body) {
278
+ const text = field(body, 'text');
279
+ if (typeof text !== 'string') {
280
+ throw new BadRequest('"text" must be a string.');
281
+ }
282
+ if (codePointLength(text) > ServiceApi.MAX_TEXT_LENGTH) {
283
+ throw new BadRequest(`"text" is longer than ${String(ServiceApi.MAX_TEXT_LENGTH)} characters.`);
284
+ }
285
+ return text;
286
+ }
287
+ /** A list of strings; missing = empty. A JSON object counts as a list of its values (a PHP array). */
288
+ function strings(body, key) {
289
+ const value = field(body, key) ?? [];
290
+ const items = Array.isArray(value) ? value : typeof value === 'object' ? Object.values(value) : [null];
291
+ if (!items.every((item) => typeof item === 'string')) {
292
+ throw new BadRequest(`"${key}" must be a list of strings.`);
293
+ }
294
+ return items;
295
+ }
296
+ function constantTimeEquals(expected, actual) {
297
+ const digest = (s) => createHash('sha256').update(s, 'utf8').digest();
298
+ return timingSafeEqual(digest(expected), digest(actual));
299
+ }
300
+ function ok(body) {
301
+ return { status: 200, body };
302
+ }
303
+ function error(status, message) {
304
+ return { status, body: { error: message } };
305
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Austrian social security number (Sozialversicherungsnummer).
3
+ *
4
+ * Format: 3-digit serial, 1 check digit, 6-digit birth date (DDMMYY).
5
+ * Check digit = sum(digit_i * weight_i) mod 11 with weights 3,7,9,(check),5,8,4,2,1,6.
6
+ * A remainder of 10 is never issued. ASCII whitespace and hyphens are ignored; any decimal digit (\p{Nd}) counts (PHP: ASCII only).
7
+ */
8
+ export declare function isValidAtSvnr(candidate: string): boolean;
@@ -0,0 +1,21 @@
1
+ import { asciiDigits } from '../internal/pcre.js';
2
+ const WEIGHTS = [3, 7, 9, 0, 5, 8, 4, 2, 1, 6];
3
+ /**
4
+ * Austrian social security number (Sozialversicherungsnummer).
5
+ *
6
+ * Format: 3-digit serial, 1 check digit, 6-digit birth date (DDMMYY).
7
+ * Check digit = sum(digit_i * weight_i) mod 11 with weights 3,7,9,(check),5,8,4,2,1,6.
8
+ * A remainder of 10 is never issued. ASCII whitespace and hyphens are ignored; any decimal digit (\p{Nd}) counts (PHP: ASCII only).
9
+ */
10
+ export function isValidAtSvnr(candidate) {
11
+ const digits = asciiDigits(candidate).replace(/[\t\n\v\f\r -]/g, '');
12
+ if (!/^[1-9][0-9]{9}$/.test(digits)) {
13
+ return false;
14
+ }
15
+ let sum = 0;
16
+ WEIGHTS.forEach((weight, i) => {
17
+ sum += Number(digits[i]) * weight;
18
+ });
19
+ const check = sum % 11;
20
+ return check !== 10 && check === Number(digits[3]);
21
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * German tax identification number (Steuerliche Identifikationsnummer, 11 digits).
3
+ *
4
+ * Structure: no leading zero; within the first 10 digits exactly one digit occurs
5
+ * two or three times, all others at most once. Check digit: ISO 7064 MOD 11,10.
6
+ * Spaces are ignored, any decimal digit (\p{Nd}) counts (PHP: ASCII only). Like PHP's "$", a single trailing "\n" is accepted.
7
+ */
8
+ export declare function isValidDeTaxId(candidate: string): boolean;
@@ -0,0 +1,35 @@
1
+ import { asciiDigits } from '../internal/pcre.js';
2
+ /**
3
+ * German tax identification number (Steuerliche Identifikationsnummer, 11 digits).
4
+ *
5
+ * Structure: no leading zero; within the first 10 digits exactly one digit occurs
6
+ * two or three times, all others at most once. Check digit: ISO 7064 MOD 11,10.
7
+ * Spaces are ignored, any decimal digit (\p{Nd}) counts (PHP: ASCII only). Like PHP's "$", a single trailing "\n" is accepted.
8
+ */
9
+ export function isValidDeTaxId(candidate) {
10
+ const digits = asciiDigits(candidate).replaceAll(' ', '');
11
+ if (!/^[1-9][0-9]{10}\n?$/.test(digits)) {
12
+ return false;
13
+ }
14
+ const counts = new Map();
15
+ for (const digit of digits.slice(0, 10)) {
16
+ counts.set(digit, (counts.get(digit) ?? 0) + 1);
17
+ }
18
+ const repeated = [...counts.values()].filter((count) => count > 1);
19
+ if (repeated.length !== 1 || Math.max(...repeated) > 3) {
20
+ return false;
21
+ }
22
+ let product = 10;
23
+ for (let i = 0; i < 10; i++) {
24
+ let sum = (Number(digits[i]) + product) % 10;
25
+ if (sum === 0) {
26
+ sum = 10;
27
+ }
28
+ product = (sum * 2) % 11;
29
+ }
30
+ let check = 11 - product;
31
+ if (check === 10) {
32
+ check = 0;
33
+ }
34
+ return check === Number(digits[10]);
35
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * IBAN according to ISO 13616 (mod 97 check). ASCII whitespace is ignored, ASCII letters are case-insensitive,
3
+ * any decimal digit (\p{Nd}) counts (PHP: ASCII only).
4
+ */
5
+ export declare function isValidIban(candidate: string): boolean;
@@ -0,0 +1,24 @@
1
+ import { asciiDigits } from '../internal/pcre.js';
2
+ /**
3
+ * IBAN according to ISO 13616 (mod 97 check). ASCII whitespace is ignored, ASCII letters are case-insensitive,
4
+ * any decimal digit (\p{Nd}) counts (PHP: ASCII only).
5
+ */
6
+ export function isValidIban(candidate) {
7
+ // PHP's strtoupper() only maps a-z.
8
+ const iban = asciiDigits(candidate)
9
+ .replace(/[\t\n\v\f\r ]/g, '')
10
+ .replace(/[a-z]/g, (c) => c.toUpperCase());
11
+ if (!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/.test(iban)) {
12
+ return false;
13
+ }
14
+ const rearranged = iban.slice(4) + iban.slice(0, 4);
15
+ let remainder = 0;
16
+ for (const char of rearranged) {
17
+ const code = char.charCodeAt(0);
18
+ const value = code <= 0x39 ? char : String(code - 55);
19
+ for (const digit of value) {
20
+ remainder = (remainder * 10 + Number(digit)) % 97;
21
+ }
22
+ }
23
+ return remainder === 1;
24
+ }
@@ -0,0 +1,37 @@
1
+ import type { PlaceholderMapping } from '../redaction.js';
2
+ import { type Vault, type VaultStorage } from './vault.js';
3
+ export interface EncryptedVaultOptions {
4
+ /** Where the ciphertext goes; it never sees clear text. */
5
+ storage: VaultStorage;
6
+ /** 32 raw bytes, see generateVaultKey() and parseVaultKey(). The vault keeps its own copy. */
7
+ key: Uint8Array;
8
+ }
9
+ /**
10
+ * Encrypts mappings with XChaCha20-Poly1305 before they reach the storage. Byte-compatible with PHP's
11
+ * EncryptedVault: payload `nonce(24) || ciphertext+tag`, the vault id (UTF-8) as associated data, and
12
+ * the plaintext encoded like PHP's `json_encode()`. PHP and Node read each other's entries.
13
+ *
14
+ * The vault id is bound as associated data, so a ciphertext copied to another id fails to decrypt.
15
+ * This is the only supported way to persist mappings.
16
+ */
17
+ export declare class EncryptedVault implements Vault {
18
+ #private;
19
+ constructor(options: EncryptedVaultOptions);
20
+ store(id: string, mapping: PlaceholderMapping, ttlSeconds: number): Promise<void>;
21
+ fetch(id: string): Promise<PlaceholderMapping | null>;
22
+ delete(id: string): Promise<void>;
23
+ }
24
+ /** A new random key (32 raw bytes). Store it base64-encoded as a secret; read it back with parseVaultKey(). */
25
+ export declare function generateVaultKey(): Uint8Array;
26
+ /**
27
+ * Decodes a base64 key (e.g. from an environment variable or a secret file; surrounding whitespace is
28
+ * ignored). Throws without echoing the input.
29
+ */
30
+ export declare function parseVaultKey(base64: string): Uint8Array;
31
+ /**
32
+ * Encrypts a mapping with a given nonce: the seam for byte-parity tests with PHP payloads. Not public API:
33
+ * reusing a nonce breaks XChaCha20-Poly1305.
34
+ *
35
+ * @internal
36
+ */
37
+ export declare function encryptMapping(key: Uint8Array, id: string, mapping: PlaceholderMapping, nonce: Uint8Array): Uint8Array;
@@ -0,0 +1,152 @@
1
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
2
+ import { VaultError } from '../errors.js';
3
+ import { encodePhpJson } from '../internal/php-json.js';
4
+ import { assertTtl } from './vault.js';
5
+ const KEY_BYTES = 32;
6
+ const NONCE_BYTES = 24;
7
+ /**
8
+ * Encrypts mappings with XChaCha20-Poly1305 before they reach the storage. Byte-compatible with PHP's
9
+ * EncryptedVault: payload `nonce(24) || ciphertext+tag`, the vault id (UTF-8) as associated data, and
10
+ * the plaintext encoded like PHP's `json_encode()`. PHP and Node read each other's entries.
11
+ *
12
+ * The vault id is bound as associated data, so a ciphertext copied to another id fails to decrypt.
13
+ * This is the only supported way to persist mappings.
14
+ */
15
+ export class EncryptedVault {
16
+ #storage;
17
+ #key;
18
+ constructor(options) {
19
+ const { storage, key } = options;
20
+ if (!(key instanceof Uint8Array)) {
21
+ throw new TypeError('The key must be a Uint8Array of 32 raw bytes, see parseVaultKey().');
22
+ }
23
+ if (key.length !== KEY_BYTES) {
24
+ throw new RangeError(`The key must be ${String(KEY_BYTES)} bytes long.`);
25
+ }
26
+ this.#storage = storage;
27
+ this.#key = key.slice();
28
+ }
29
+ async store(id, mapping, ttlSeconds) {
30
+ assertTtl(ttlSeconds);
31
+ const nonce = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_BYTES));
32
+ await this.#storage.put(id, encryptMapping(this.#key, id, mapping, nonce), ttlSeconds);
33
+ }
34
+ async fetch(id) {
35
+ const payload = await this.#storage.get(id);
36
+ if (payload === null) {
37
+ return null;
38
+ }
39
+ let plaintext;
40
+ try {
41
+ if (payload.length <= NONCE_BYTES) {
42
+ throw new RangeError('payload too short');
43
+ }
44
+ plaintext = xchacha20poly1305(this.#key, payload.subarray(0, NONCE_BYTES), utf8(id)).decrypt(payload.subarray(NONCE_BYTES));
45
+ }
46
+ catch {
47
+ throw new VaultError('Vault entry cannot be decrypted (wrong key or tampered data).', 'VAULT_DECRYPTION_FAILED');
48
+ }
49
+ try {
50
+ return decodeMapping(plaintext);
51
+ }
52
+ finally {
53
+ plaintext.fill(0);
54
+ }
55
+ }
56
+ async delete(id) {
57
+ await this.#storage.remove(id);
58
+ }
59
+ }
60
+ /** A new random key (32 raw bytes). Store it base64-encoded as a secret; read it back with parseVaultKey(). */
61
+ export function generateVaultKey() {
62
+ return globalThis.crypto.getRandomValues(new Uint8Array(KEY_BYTES));
63
+ }
64
+ /** Canonical base64 (with padding), as PHP's base64_encode() writes it. Linear: fixed-size groups. */
65
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
66
+ /**
67
+ * Decodes a base64 key (e.g. from an environment variable or a secret file; surrounding whitespace is
68
+ * ignored). Throws without echoing the input.
69
+ */
70
+ export function parseVaultKey(base64) {
71
+ const trimmed = base64.trim();
72
+ if (!BASE64.test(trimmed)) {
73
+ throw new TypeError('The key must be base64-encoded.');
74
+ }
75
+ const decoded = Buffer.from(trimmed, 'base64');
76
+ const key = new Uint8Array(decoded);
77
+ decoded.fill(0);
78
+ if (key.length !== KEY_BYTES) {
79
+ key.fill(0);
80
+ throw new RangeError(`The key must be ${String(KEY_BYTES)} bytes long.`);
81
+ }
82
+ return key;
83
+ }
84
+ /**
85
+ * Encrypts a mapping with a given nonce: the seam for byte-parity tests with PHP payloads. Not public API:
86
+ * reusing a nonce breaks XChaCha20-Poly1305.
87
+ *
88
+ * @internal
89
+ */
90
+ export function encryptMapping(key, id, mapping, nonce) {
91
+ const plaintext = utf8(encodePhpJson(mapping));
92
+ try {
93
+ const ciphertext = xchacha20poly1305(key, nonce, utf8(id)).encrypt(plaintext);
94
+ const payload = new Uint8Array(NONCE_BYTES + ciphertext.length);
95
+ payload.set(nonce);
96
+ payload.set(ciphertext, NONCE_BYTES);
97
+ return payload;
98
+ }
99
+ finally {
100
+ plaintext.fill(0);
101
+ }
102
+ }
103
+ function utf8(text) {
104
+ return new TextEncoder().encode(text);
105
+ }
106
+ // fatal: invalid UTF-8 fails like PHP's json_decode(); ignoreBOM: keep a BOM so JSON.parse() rejects it like PHP.
107
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
108
+ /** Integer-like keys become ints in a PHP array, which PHP's EncryptedVault rejects as corrupt. */
109
+ const PHP_INT_KEY = /^(?:0|-?[1-9][0-9]{0,18})$/;
110
+ const PHP_INT_MIN = -(2n ** 63n);
111
+ const PHP_INT_MAX = 2n ** 63n - 1n;
112
+ /**
113
+ * PHP's `json_decode()` plus its string-map check. Errors carry no cause: JSON.parse() messages quote the
114
+ * plaintext, which holds personal data.
115
+ */
116
+ function decodeMapping(plaintext) {
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(decoder.decode(plaintext));
120
+ }
121
+ catch {
122
+ throw corrupt();
123
+ }
124
+ if (Array.isArray(parsed)) {
125
+ // PHP encodes an empty mapping as [], a non-empty list has integer keys.
126
+ if (parsed.length === 0) {
127
+ return Object.freeze({});
128
+ }
129
+ throw corrupt();
130
+ }
131
+ if (typeof parsed !== 'object' || parsed === null) {
132
+ throw corrupt();
133
+ }
134
+ const entries = Object.entries(parsed);
135
+ for (const [placeholder, original] of entries) {
136
+ if (typeof original !== 'string' || isPhpIntKey(placeholder)) {
137
+ throw corrupt();
138
+ }
139
+ }
140
+ // fromEntries defines own properties, so a "__proto__" key stays a key.
141
+ return Object.freeze(Object.fromEntries(entries));
142
+ }
143
+ function isPhpIntKey(key) {
144
+ if (!PHP_INT_KEY.test(key)) {
145
+ return false;
146
+ }
147
+ const value = BigInt(key);
148
+ return value >= PHP_INT_MIN && value <= PHP_INT_MAX;
149
+ }
150
+ function corrupt() {
151
+ return new VaultError('Vault entry is corrupt.', 'VAULT_CORRUPT');
152
+ }
@@ -0,0 +1,17 @@
1
+ import type { PlaceholderMapping } from '../redaction.js';
2
+ import { type Clock, type Vault } from './vault.js';
3
+ export interface InMemoryVaultOptions {
4
+ /** Milliseconds since the epoch; defaults to `Date.now`. */
5
+ clock?: Clock;
6
+ }
7
+ /**
8
+ * Process-local vault. Suitable for one request or one long-running worker; not shared between processes.
9
+ * Expired mappings are purged on every write, so long-running workers do not accumulate data.
10
+ */
11
+ export declare class InMemoryVault implements Vault {
12
+ #private;
13
+ constructor(options?: InMemoryVaultOptions);
14
+ store(id: string, mapping: PlaceholderMapping, ttlSeconds: number): Promise<void>;
15
+ fetch(id: string): Promise<PlaceholderMapping | null>;
16
+ delete(id: string): Promise<void>;
17
+ }
@@ -0,0 +1,39 @@
1
+ import { assertTtl } from './vault.js';
2
+ /**
3
+ * Process-local vault. Suitable for one request or one long-running worker; not shared between processes.
4
+ * Expired mappings are purged on every write, so long-running workers do not accumulate data.
5
+ */
6
+ export class InMemoryVault {
7
+ #entries = new Map();
8
+ #clock;
9
+ constructor(options = {}) {
10
+ this.#clock = options.clock ?? Date.now;
11
+ }
12
+ async store(id, mapping, ttlSeconds) {
13
+ assertTtl(ttlSeconds);
14
+ const now = this.#clock();
15
+ for (const [key, entry] of this.#entries) {
16
+ if (entry.expiresAt <= now) {
17
+ this.#entries.delete(key);
18
+ }
19
+ }
20
+ this.#entries.set(id, {
21
+ mapping: Object.freeze(Object.fromEntries(Object.entries(mapping))),
22
+ expiresAt: now + ttlSeconds * 1000,
23
+ });
24
+ }
25
+ async fetch(id) {
26
+ const entry = this.#entries.get(id);
27
+ if (entry === undefined) {
28
+ return null;
29
+ }
30
+ if (entry.expiresAt <= this.#clock()) {
31
+ this.#entries.delete(id);
32
+ return null;
33
+ }
34
+ return entry.mapping;
35
+ }
36
+ async delete(id) {
37
+ this.#entries.delete(id);
38
+ }
39
+ }
@@ -0,0 +1,16 @@
1
+ import { type Clock, type VaultStorage } from './vault.js';
2
+ export interface MemoryVaultStorageOptions {
3
+ /** Milliseconds since the epoch; defaults to `Date.now`. */
4
+ clock?: Clock;
5
+ }
6
+ /**
7
+ * Process-local VaultStorage with expiry, for tests and single-process apps that want EncryptedVault's
8
+ * behaviour without a server. Expired entries are purged on every write. Payloads are copied in and out.
9
+ */
10
+ export declare class MemoryVaultStorage implements VaultStorage {
11
+ #private;
12
+ constructor(options?: MemoryVaultStorageOptions);
13
+ put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
14
+ get(id: string): Promise<Uint8Array | null>;
15
+ remove(id: string): Promise<void>;
16
+ }