@waswrongassembled/pii-shield 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +22 -0
  3. package/README.md +276 -2
  4. package/dist/ai-sdk/index.d.ts +19 -0
  5. package/dist/ai-sdk/index.js +30 -0
  6. package/dist/ai-sdk/middleware.d.ts +63 -0
  7. package/dist/ai-sdk/middleware.js +388 -0
  8. package/dist/bin.d.ts +2 -0
  9. package/dist/bin.js +9 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +124 -0
  12. package/dist/detector.d.ts +28 -0
  13. package/dist/detector.js +3 -0
  14. package/dist/detectors/at-svnr.d.ts +14 -0
  15. package/dist/detectors/at-svnr.js +31 -0
  16. package/dist/detectors/authority-context.d.ts +22 -0
  17. package/dist/detectors/authority-context.js +278 -0
  18. package/dist/detectors/birth-date.d.ts +10 -0
  19. package/dist/detectors/birth-date.js +21 -0
  20. package/dist/detectors/email.d.ts +15 -0
  21. package/dist/detectors/email.js +29 -0
  22. package/dist/detectors/file-number.d.ts +16 -0
  23. package/dist/detectors/file-number.js +20 -0
  24. package/dist/detectors/iban.d.ts +10 -0
  25. package/dist/detectors/iban.js +41 -0
  26. package/dist/detectors/license-plate.d.ts +9 -0
  27. package/dist/detectors/license-plate.js +13 -0
  28. package/dist/detectors/phone.d.ts +13 -0
  29. package/dist/detectors/phone.js +38 -0
  30. package/dist/detectors/postal-address.d.ts +14 -0
  31. package/dist/detectors/postal-address.js +19 -0
  32. package/dist/detectors/salutation-person.d.ts +18 -0
  33. package/dist/detectors/salutation-person.js +37 -0
  34. package/dist/detectors/tax-number.d.ts +14 -0
  35. package/dist/detectors/tax-number.js +33 -0
  36. package/dist/entity-extractor.d.ts +47 -0
  37. package/dist/entity-extractor.js +245 -0
  38. package/dist/entity-type.d.ts +24 -0
  39. package/dist/entity-type.js +26 -0
  40. package/dist/entity.d.ts +28 -0
  41. package/dist/entity.js +11 -0
  42. package/dist/errors.d.ts +48 -0
  43. package/dist/errors.js +49 -0
  44. package/dist/index.d.ts +42 -0
  45. package/dist/index.js +40 -0
  46. package/dist/internal/pcre.d.ts +55 -0
  47. package/dist/internal/pcre.js +102 -0
  48. package/dist/internal/php-json.d.ts +15 -0
  49. package/dist/internal/php-json.js +48 -0
  50. package/dist/internal/placeholder-stream.d.ts +24 -0
  51. package/dist/internal/placeholder-stream.js +118 -0
  52. package/dist/internal/text-spans.d.ts +8 -0
  53. package/dist/internal/text-spans.js +15 -0
  54. package/dist/learning/char-set.d.ts +29 -0
  55. package/dist/learning/char-set.js +158 -0
  56. package/dist/learning/custom-entity-detector.d.ts +26 -0
  57. package/dist/learning/custom-entity-detector.js +70 -0
  58. package/dist/learning/custom-entity-type.d.ts +49 -0
  59. package/dist/learning/custom-entity-type.js +150 -0
  60. package/dist/learning/entity-learner.d.ts +50 -0
  61. package/dist/learning/entity-learner.js +87 -0
  62. package/dist/learning/json-file-store.d.ts +36 -0
  63. package/dist/learning/json-file-store.js +132 -0
  64. package/dist/learning/learned-pattern.d.ts +48 -0
  65. package/dist/learning/learned-pattern.js +640 -0
  66. package/dist/learning/pattern-grammar.d.ts +12 -0
  67. package/dist/learning/pattern-grammar.js +148 -0
  68. package/dist/learning/pattern-learner.d.ts +10 -0
  69. package/dist/learning/pattern-learner.js +116 -0
  70. package/dist/learning/store.d.ts +51 -0
  71. package/dist/learning/store.js +84 -0
  72. package/dist/masking/partial-mask.d.ts +23 -0
  73. package/dist/masking/partial-mask.js +43 -0
  74. package/dist/masking/strategy.d.ts +10 -0
  75. package/dist/masking/strategy.js +1 -0
  76. package/dist/masking/type-label-mask.d.ts +17 -0
  77. package/dist/masking/type-label-mask.js +28 -0
  78. package/dist/mcp/index.d.ts +33 -0
  79. package/dist/mcp/index.js +146 -0
  80. package/dist/mcp/tools.d.ts +63 -0
  81. package/dist/mcp/tools.js +183 -0
  82. package/dist/model/chunks.d.ts +13 -0
  83. package/dist/model/chunks.js +74 -0
  84. package/dist/model/model-detector.d.ts +110 -0
  85. package/dist/model/model-detector.js +420 -0
  86. package/dist/model/prompt.d.ts +16 -0
  87. package/dist/model/prompt.js +192 -0
  88. package/dist/pii-masker.d.ts +27 -0
  89. package/dist/pii-masker.js +56 -0
  90. package/dist/pii-shield.d.ts +40 -0
  91. package/dist/pii-shield.js +142 -0
  92. package/dist/placeholder.d.ts +48 -0
  93. package/dist/placeholder.js +138 -0
  94. package/dist/redaction.d.ts +76 -0
  95. package/dist/redaction.js +52 -0
  96. package/dist/server/config.d.ts +23 -0
  97. package/dist/server/config.js +187 -0
  98. package/dist/server/http-server.d.ts +63 -0
  99. package/dist/server/http-server.js +241 -0
  100. package/dist/server/index.d.ts +9 -0
  101. package/dist/server/index.js +9 -0
  102. package/dist/server/model-providers.d.ts +31 -0
  103. package/dist/server/model-providers.js +158 -0
  104. package/dist/service/json-body.d.ts +14 -0
  105. package/dist/service/json-body.js +35 -0
  106. package/dist/service/local-peer.d.ts +16 -0
  107. package/dist/service/local-peer.js +83 -0
  108. package/dist/service/service-api.d.ts +75 -0
  109. package/dist/service/service-api.js +305 -0
  110. package/dist/validators/at-svnr.d.ts +8 -0
  111. package/dist/validators/at-svnr.js +21 -0
  112. package/dist/validators/de-tax-id.d.ts +8 -0
  113. package/dist/validators/de-tax-id.js +35 -0
  114. package/dist/validators/iban.d.ts +5 -0
  115. package/dist/validators/iban.js +24 -0
  116. package/dist/vault/encrypted-vault.d.ts +37 -0
  117. package/dist/vault/encrypted-vault.js +152 -0
  118. package/dist/vault/in-memory-vault.d.ts +17 -0
  119. package/dist/vault/in-memory-vault.js +39 -0
  120. package/dist/vault/memory-vault-storage.d.ts +16 -0
  121. package/dist/vault/memory-vault-storage.js +37 -0
  122. package/dist/vault/vault.d.ts +38 -0
  123. package/dist/vault/vault.js +16 -0
  124. package/dist/vault-redis/index.d.ts +28 -0
  125. package/dist/vault-redis/index.js +33 -0
  126. package/docs/openapi.yaml +422 -0
  127. package/package.json +122 -4
@@ -0,0 +1,37 @@
1
+ /* eslint-disable @typescript-eslint/require-await -- synchronous implementation of an async interface; `async` turns validation errors into rejections */
2
+ import { assertTtl } from './vault.js';
3
+ /**
4
+ * Process-local VaultStorage with expiry, for tests and single-process apps that want EncryptedVault's
5
+ * behaviour without a server. Expired entries are purged on every write. Payloads are copied in and out.
6
+ */
7
+ export class MemoryVaultStorage {
8
+ #entries = new Map();
9
+ #clock;
10
+ constructor(options = {}) {
11
+ this.#clock = options.clock ?? Date.now;
12
+ }
13
+ async put(id, payload, ttlSeconds) {
14
+ assertTtl(ttlSeconds);
15
+ const now = this.#clock();
16
+ for (const [key, entry] of this.#entries) {
17
+ if (entry.expiresAt <= now) {
18
+ this.#entries.delete(key);
19
+ }
20
+ }
21
+ this.#entries.set(id, { payload: payload.slice(), expiresAt: now + ttlSeconds * 1000 });
22
+ }
23
+ async get(id) {
24
+ const entry = this.#entries.get(id);
25
+ if (entry === undefined) {
26
+ return null;
27
+ }
28
+ if (entry.expiresAt <= this.#clock()) {
29
+ this.#entries.delete(id);
30
+ return null;
31
+ }
32
+ return entry.payload.slice();
33
+ }
34
+ async remove(id) {
35
+ this.#entries.delete(id);
36
+ }
37
+ }
@@ -0,0 +1,38 @@
1
+ import type { PlaceholderMapping } from '../redaction.js';
2
+ /**
3
+ * Stores placeholder → original mappings between requests (PHP's VaultInterface, see docs/adr/0005 there).
4
+ *
5
+ * Implementations that persist data outside the process must encrypt it: use EncryptedVault with a
6
+ * VaultStorage instead of implementing this directly.
7
+ */
8
+ export interface Vault {
9
+ /**
10
+ * @param ttlSeconds must be a positive integer; mappings must not live forever
11
+ * @throws RangeError if the TTL is not positive
12
+ */
13
+ store(id: string, mapping: PlaceholderMapping, ttlSeconds: number): Promise<void>;
14
+ /**
15
+ * @returns null if the id is unknown or expired
16
+ * @throws VaultError if stored data cannot be read (tampered, wrong key)
17
+ */
18
+ fetch(id: string): Promise<PlaceholderMapping | null>;
19
+ delete(id: string): Promise<void>;
20
+ }
21
+ /**
22
+ * Raw byte storage behind EncryptedVault (PHP's VaultStorageInterface). Only ever receives ciphertext.
23
+ * Implement this to plug in any backend (Redis, database, files, ...).
24
+ */
25
+ export interface VaultStorage {
26
+ /** @param ttlSeconds positive integer */
27
+ put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
28
+ get(id: string): Promise<Uint8Array | null>;
29
+ remove(id: string): Promise<void>;
30
+ }
31
+ /** Current time in milliseconds, like `Date.now` (PHP takes a PSR-20 clock). Inject one in tests. */
32
+ export type Clock = () => number;
33
+ /**
34
+ * Throws PHP's message for a TTL that is not positive.
35
+ *
36
+ * @internal
37
+ */
38
+ export declare function assertTtl(ttlSeconds: number, message?: string): void;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Throws PHP's message for a TTL that is not positive.
3
+ *
4
+ * @internal
5
+ */
6
+ export function assertTtl(ttlSeconds, message = 'The TTL must be positive.') {
7
+ if (typeof ttlSeconds !== 'number' || Number.isNaN(ttlSeconds)) {
8
+ throw new TypeError(`${message.slice(0, -' positive.'.length)} a number of seconds.`);
9
+ }
10
+ if (ttlSeconds <= 0) {
11
+ throw new RangeError(message);
12
+ }
13
+ if (!Number.isSafeInteger(ttlSeconds)) {
14
+ throw new TypeError(`${message.slice(0, -' positive.'.length)} an integer number of seconds.`);
15
+ }
16
+ }
@@ -0,0 +1,28 @@
1
+ import { type VaultStorage } from '../vault/vault.js';
2
+ /**
3
+ * The ioredis methods RedisVaultStorage calls. An ioredis `Redis` or `Cluster` instance satisfies it;
4
+ * so does any client with the same signatures.
5
+ */
6
+ export interface RedisClient {
7
+ set(key: string, value: Buffer, secondsToken: 'EX', seconds: number): Promise<unknown>;
8
+ getBuffer(key: string): Promise<Buffer | null>;
9
+ del(key: string): Promise<number>;
10
+ }
11
+ export interface RedisVaultStorageOptions {
12
+ client: RedisClient;
13
+ /** Prepended to every key. Default: `pii_shield_vault.` (the prefix of PHP's Psr6CacheStorage). */
14
+ prefix?: string;
15
+ }
16
+ /**
17
+ * Stores vault ciphertext in Redis with `SET … EX`, so Redis expires entries itself. Use it behind
18
+ * EncryptedVault, never on its own. Key: `prefix + sha256hex(id)` (ids may come from outside).
19
+ *
20
+ * The client's lifecycle (connect, quit) stays with the caller.
21
+ */
22
+ export declare class RedisVaultStorage implements VaultStorage {
23
+ #private;
24
+ constructor(options: RedisVaultStorageOptions);
25
+ put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
26
+ get(id: string): Promise<Uint8Array | null>;
27
+ remove(id: string): Promise<void>;
28
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/vault-redis: VaultStorage on Redis via ioredis (optional peer dependency).
3
+ */
4
+ import { createHash } from 'node:crypto';
5
+ import { assertTtl } from '../vault/vault.js';
6
+ /**
7
+ * Stores vault ciphertext in Redis with `SET … EX`, so Redis expires entries itself. Use it behind
8
+ * EncryptedVault, never on its own. Key: `prefix + sha256hex(id)` (ids may come from outside).
9
+ *
10
+ * The client's lifecycle (connect, quit) stays with the caller.
11
+ */
12
+ export class RedisVaultStorage {
13
+ #client;
14
+ #prefix;
15
+ constructor(options) {
16
+ this.#client = options.client;
17
+ this.#prefix = options.prefix ?? 'pii_shield_vault.';
18
+ }
19
+ async put(id, payload, ttlSeconds) {
20
+ assertTtl(ttlSeconds);
21
+ await this.#client.set(this.#key(id), Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength), 'EX', ttlSeconds);
22
+ }
23
+ async get(id) {
24
+ const value = await this.#client.getBuffer(this.#key(id));
25
+ return value === null ? null : new Uint8Array(value);
26
+ }
27
+ async remove(id) {
28
+ await this.#client.del(this.#key(id));
29
+ }
30
+ #key(id) {
31
+ return this.#prefix + createHash('sha256').update(id, 'utf8').digest('hex');
32
+ }
33
+ }
@@ -0,0 +1,422 @@
1
+ openapi: 3.1.0
2
+ info:
3
+ title: pii-shield HTTP API
4
+ version: 1.0.0
5
+ summary: Reversible redaction, irreversible masking and learning of personal data (PII) as a service.
6
+ description: |
7
+ pii-shield finds personal data in text (patterns with checksums for DACH formats, learned types,
8
+ and optionally a model of your choice), replaces it with placeholders such as
9
+ `⟦PERSON_1⟧` and restores the original values in a later request.
10
+
11
+ **Privacy by design**
12
+ - The placeholder → original mapping never leaves the service. `/v1/redact` returns placeholder
13
+ text and a `vaultId`; `/v1/restore` resolves placeholders server-side. The mapping is stored
14
+ encrypted (XChaCha20-Poly1305) with a TTL and can be deleted at any time.
15
+ - Which model is used for detection is server configuration, never request input.
16
+ - Model-based detection sees the unredacted text. Use a local or on-premise model; an external
17
+ provider must be explicitly acknowledged in the server configuration.
18
+
19
+ **Running it**: `npx @waswrongassembled/pii-shield serve` (see docs/server.md). Same API as the PHP
20
+ service of clarifile/pii-shield.
21
+ license:
22
+ name: MIT
23
+ servers:
24
+ - url: http://127.0.0.1:8088
25
+ description: Local service (`pii-shield serve`)
26
+ security:
27
+ - bearerAuth: []
28
+ tags:
29
+ - name: Redaction
30
+ description: Reversible, for text that goes to a model provider
31
+ - name: Masking
32
+ description: Irreversible, for logs and previews
33
+ - name: Learning
34
+ description: Teach new entity types from examples
35
+ - name: Service
36
+
37
+ paths:
38
+ /v1/redact:
39
+ post:
40
+ tags: [Redaction]
41
+ summary: Replace personal data with placeholders
42
+ description: |
43
+ Detects personal data and replaces each value with a typed placeholder. The same value gets the
44
+ same placeholder within one text. The mapping is stored server-side under `vaultId`.
45
+ operationId: redact
46
+ requestBody:
47
+ required: true
48
+ content:
49
+ application/json:
50
+ schema: { $ref: '#/components/schemas/DetectionRequest' }
51
+ example:
52
+ text: "Herrn\nJohann Beispielmann\n\nSVNR 4568 150392, Polizze VN-2026-000417. Betrag 110,00 Euro bis 15.11.2026."
53
+ responses:
54
+ '200':
55
+ description: Redacted text
56
+ content:
57
+ application/json:
58
+ schema: { $ref: '#/components/schemas/RedactResponse' }
59
+ example:
60
+ text: "Herrn\n⟦PERSON_1⟧\n\nSVNR ⟦SVNR_1⟧, Polizze ⟦INSURANCE_NUMBER_1⟧. Betrag 110,00 Euro bis 15.11.2026."
61
+ vaultId: 76058e0f76dc1fabc27b2585e8575d4f
62
+ expiresIn: 900
63
+ placeholders:
64
+ - { placeholder: '⟦PERSON_1⟧', type: PERSON }
65
+ - { placeholder: '⟦SVNR_1⟧', type: SVNR }
66
+ - { placeholder: '⟦INSURANCE_NUMBER_1⟧', type: INSURANCE_NUMBER }
67
+ '400': { $ref: '#/components/responses/BadRequest' }
68
+ '401': { $ref: '#/components/responses/Unauthorized' }
69
+ '422': { $ref: '#/components/responses/Unprocessable' }
70
+ '502': { $ref: '#/components/responses/DetectionFailed' }
71
+
72
+ /v1/restore:
73
+ post:
74
+ tags: [Redaction]
75
+ summary: Put the original values back into a text with placeholders
76
+ description: |
77
+ Typically the model's answer. Tolerates what models do to placeholders: case changes,
78
+ whitespace, space instead of underscore, markdown-escaped underscores (`⟦PERSON\_1⟧`) and ASCII
79
+ brackets (`[[PERSON_1]]`). Placeholders the model invented are left as they are and reported.
80
+ operationId: restore
81
+ requestBody:
82
+ required: true
83
+ content:
84
+ application/json:
85
+ schema:
86
+ type: object
87
+ required: [text, vaultId]
88
+ properties:
89
+ text: { type: string, maxLength: 100000 }
90
+ vaultId: { type: string, pattern: '^[0-9a-f]{32}$' }
91
+ example:
92
+ text: 'Sehr geehrter ⟦person 1⟧, Ihre SVNR ist **⟦SVNR\_1⟧**. Konto ⟦IBAN_9⟧?'
93
+ vaultId: 76058e0f76dc1fabc27b2585e8575d4f
94
+ responses:
95
+ '200':
96
+ description: Restored text
97
+ content:
98
+ application/json:
99
+ schema: { $ref: '#/components/schemas/RestoreResponse' }
100
+ example:
101
+ text: 'Sehr geehrter Johann Beispielmann, Ihre SVNR ist **4568 150392**. Konto ⟦IBAN_9⟧?'
102
+ unknownPlaceholders: ['⟦IBAN_9⟧']
103
+ unusedPlaceholders: ['⟦INSURANCE_NUMBER_1⟧']
104
+ '400': { $ref: '#/components/responses/BadRequest' }
105
+ '401': { $ref: '#/components/responses/Unauthorized' }
106
+ '404':
107
+ description: Unknown or expired vault id
108
+ content:
109
+ application/json:
110
+ schema: { $ref: '#/components/schemas/Error' }
111
+
112
+ /v1/vault/{vaultId}:
113
+ delete:
114
+ tags: [Redaction]
115
+ summary: Delete a mapping now
116
+ description: End of conversation or right to erasure (GDPR Art. 17). Otherwise mappings expire after their TTL.
117
+ operationId: forgetVault
118
+ parameters:
119
+ - name: vaultId
120
+ in: path
121
+ required: true
122
+ schema: { type: string, pattern: '^[0-9a-f]{32}$' }
123
+ responses:
124
+ '204': { description: Deleted (also if it did not exist) }
125
+ '401': { $ref: '#/components/responses/Unauthorized' }
126
+
127
+ /v1/mask:
128
+ post:
129
+ tags: [Masking]
130
+ summary: Mask personal data irreversibly
131
+ description: |
132
+ For logs and previews. IBANs keep their first and last four characters, phone numbers their last
133
+ two, everything else becomes `[TYPE]`. Nothing is stored. Never send masked text to a model
134
+ provider instead of redacted text: partial masks leak length and some characters.
135
+ operationId: mask
136
+ requestBody:
137
+ required: true
138
+ content:
139
+ application/json:
140
+ schema: { $ref: '#/components/schemas/DetectionRequest' }
141
+ example:
142
+ text: 'IBAN AT61 1904 3002 3457 3201, SVNR 4568 150392'
143
+ responses:
144
+ '200':
145
+ description: Masked text
146
+ content:
147
+ application/json:
148
+ schema:
149
+ type: object
150
+ required: [text]
151
+ properties:
152
+ text: { type: string }
153
+ example:
154
+ text: 'IBAN AT61 **** **** **** 3201, SVNR [SVNR]'
155
+ '400': { $ref: '#/components/responses/BadRequest' }
156
+ '401': { $ref: '#/components/responses/Unauthorized' }
157
+ '422': { $ref: '#/components/responses/Unprocessable' }
158
+ '502': { $ref: '#/components/responses/DetectionFailed' }
159
+
160
+ /v1/learn:
161
+ post:
162
+ tags: [Learning]
163
+ summary: Teach a new entity type from examples
164
+ description: |
165
+ A pattern is derived from the examples unless one is given (`AB-1234/56` + `XY-9876/01` →
166
+ `[A-Z]{2}-\d{4}/\d{2}`). Plain words without structure (e.g. pet names) cannot become a safe
167
+ pattern; they are learned as model-only types and reach the model as few-shot examples.
168
+ Learned types take effect immediately for `/v1/redact` and `/v1/mask`.
169
+
170
+ Examples are stored: use synthetic or anonymised values only. Hand-written patterns follow a
171
+ restricted grammar (no repeated groups, anchors, backreferences or lookarounds) to rule out
172
+ catastrophic backtracking.
173
+ operationId: learn
174
+ requestBody:
175
+ required: true
176
+ content:
177
+ application/json:
178
+ schema: { $ref: '#/components/schemas/LearnRequest' }
179
+ example:
180
+ name: INSURANCE_NUMBER
181
+ description: Polizzennummer einer Versicherung
182
+ examples: ['VN-2026-000417', 'VN-2025-998812']
183
+ counterExamples: ['VN-12']
184
+ responses:
185
+ '200':
186
+ description: Dry run, nothing saved
187
+ content:
188
+ application/json:
189
+ schema: { $ref: '#/components/schemas/LearnResponse' }
190
+ '201':
191
+ description: Learned and saved
192
+ content:
193
+ application/json:
194
+ schema: { $ref: '#/components/schemas/LearnResponse' }
195
+ example:
196
+ type:
197
+ name: INSURANCE_NUMBER
198
+ description: Polizzennummer einer Versicherung
199
+ examples: ['VN-2026-000417', 'VN-2025-998812']
200
+ counterExamples: ['VN-12']
201
+ pattern: 'VN-\d{4}-\d{6}'
202
+ note: null
203
+ saved: true
204
+ '400': { $ref: '#/components/responses/BadRequest' }
205
+ '401': { $ref: '#/components/responses/Unauthorized' }
206
+ '422': { $ref: '#/components/responses/Unprocessable' }
207
+
208
+ /v1/entities:
209
+ get:
210
+ tags: [Learning]
211
+ summary: List learned entity types
212
+ operationId: listEntityTypes
213
+ responses:
214
+ '200':
215
+ description: Learned types, sorted by name
216
+ content:
217
+ application/json:
218
+ schema:
219
+ type: object
220
+ required: [types]
221
+ properties:
222
+ types:
223
+ type: array
224
+ items: { $ref: '#/components/schemas/LearnedType' }
225
+ '401': { $ref: '#/components/responses/Unauthorized' }
226
+
227
+ /v1/entities/{name}:
228
+ delete:
229
+ tags: [Learning]
230
+ summary: Forget a learned entity type
231
+ operationId: forgetEntityType
232
+ parameters:
233
+ - name: name
234
+ in: path
235
+ required: true
236
+ schema: { $ref: '#/components/schemas/TypeName' }
237
+ responses:
238
+ '204': { description: Forgotten }
239
+ '401': { $ref: '#/components/responses/Unauthorized' }
240
+ '404':
241
+ description: No such learned type
242
+ content:
243
+ application/json:
244
+ schema: { $ref: '#/components/schemas/Error' }
245
+
246
+ /v1/health:
247
+ get:
248
+ tags: [Service]
249
+ summary: Liveness and whether model-based detection is configured
250
+ operationId: health
251
+ security: []
252
+ responses:
253
+ '200':
254
+ description: Service is up
255
+ content:
256
+ application/json:
257
+ schema:
258
+ type: object
259
+ properties:
260
+ status: { type: string, const: ok }
261
+ modelDetection: { type: boolean }
262
+
263
+ /v1/openapi.yaml:
264
+ get:
265
+ tags: [Service]
266
+ summary: This specification
267
+ operationId: openapi
268
+ security: []
269
+ responses:
270
+ '200':
271
+ description: OpenAPI document
272
+ content:
273
+ application/yaml: {}
274
+
275
+ components:
276
+ securitySchemes:
277
+ bearerAuth:
278
+ type: http
279
+ scheme: bearer
280
+ description: |
281
+ `PII_SERVICE_TOKEN` of the server. Without a configured token the service accepts requests from
282
+ localhost only. Requests must be `application/json`; browsers on other origins are rejected,
283
+ and only known host names are served (DNS-rebinding protection, `PII_SERVICE_ALLOWED_HOSTS`).
284
+
285
+ schemas:
286
+ EntityType:
287
+ type: string
288
+ description: Built-in types. Learned types use their own name (see TypeName).
289
+ enum: [PERSON, ADDRESS, SVNR, IBAN, TAX_NUMBER, FILE_NUMBER, EMAIL, PHONE, BIRTH_DATE, LICENSE_PLATE, ID_NUMBER, CREDIT_CARD, IP_ADDRESS, HEALTH, OTHER]
290
+
291
+ TypeName:
292
+ type: string
293
+ pattern: '^[A-Z][A-Z0-9_]{1,39}$'
294
+ description: UPPER_SNAKE_CASE; must not be a built-in type. Becomes the placeholder name (⟦NAME_1⟧).
295
+
296
+ DetectionRequest:
297
+ type: object
298
+ required: [text]
299
+ properties:
300
+ text: { type: string, maxLength: 100000 }
301
+ detection:
302
+ type: string
303
+ enum: [regex, model, both]
304
+ default: regex
305
+ description: |
306
+ `regex`: patterns, checksums and learned patterns, offline and deterministic.
307
+ `model`: the model configured on the server (plus learned patterns). `both`: union; on overlap
308
+ the longer finding wins, on equal length the checksum-validated one.
309
+ types:
310
+ type: array
311
+ items: { $ref: '#/components/schemas/EntityType' }
312
+ description: Only these built-in types. Learned types always apply. Default all.
313
+ allowlist:
314
+ type: array
315
+ items: { type: string }
316
+ description: Values that are never redacted (exact match), e.g. the authority's own reference.
317
+ keepAuthorityContacts:
318
+ type: boolean
319
+ default: true
320
+ description: Keep e-mail addresses and phone numbers of the sending authority (needed to act on a letter).
321
+
322
+ RedactResponse:
323
+ type: object
324
+ required: [text, vaultId, expiresIn, placeholders]
325
+ properties:
326
+ text: { type: string, description: Text with placeholders. Safe to send to a model provider. }
327
+ vaultId: { type: string, pattern: '^[0-9a-f]{32}$' }
328
+ expiresIn: { type: integer, description: Seconds until the mapping is deleted. }
329
+ placeholders:
330
+ type: array
331
+ description: Placeholders in the text and their types. Never the original values.
332
+ items:
333
+ type: object
334
+ required: [placeholder, type]
335
+ properties:
336
+ placeholder: { type: string, examples: ['⟦PERSON_1⟧'] }
337
+ type: { type: string, examples: [PERSON, INSURANCE_NUMBER] }
338
+
339
+ RestoreResponse:
340
+ type: object
341
+ required: [text, unknownPlaceholders, unusedPlaceholders]
342
+ properties:
343
+ text: { type: string }
344
+ unknownPlaceholders:
345
+ type: array
346
+ items: { type: string }
347
+ description: Placeholders the model invented; left in the text.
348
+ unusedPlaceholders:
349
+ type: array
350
+ items: { type: string }
351
+ description: Placeholders of the mapping that did not appear (informational).
352
+
353
+ LearnRequest:
354
+ type: object
355
+ required: [name, examples]
356
+ properties:
357
+ name: { $ref: '#/components/schemas/TypeName' }
358
+ description: { type: string, maxLength: 300, description: 'One line, no < or >. Helps the model.' }
359
+ examples:
360
+ type: array
361
+ minItems: 1
362
+ maxItems: 20
363
+ items: { type: string, maxLength: 100 }
364
+ counterExamples:
365
+ type: array
366
+ maxItems: 20
367
+ items: { type: string, maxLength: 100 }
368
+ description: Similar values that are not this type; the pattern must not match them.
369
+ pattern:
370
+ type: string
371
+ maxLength: 200
372
+ description: Optional regular expression without delimiters. Restricted grammar, see above.
373
+ dryRun:
374
+ type: boolean
375
+ default: false
376
+ description: Derive and validate only, do not save.
377
+
378
+ LearnedType:
379
+ type: object
380
+ required: [name, description, examples, counterExamples, pattern]
381
+ properties:
382
+ name: { $ref: '#/components/schemas/TypeName' }
383
+ description: { type: string }
384
+ examples: { type: array, items: { type: string } }
385
+ counterExamples: { type: array, items: { type: string } }
386
+ pattern: { type: [string, 'null'], description: null for model-only types }
387
+
388
+ LearnResponse:
389
+ type: object
390
+ required: [type, note, saved]
391
+ properties:
392
+ type: { $ref: '#/components/schemas/LearnedType' }
393
+ note: { type: [string, 'null'], description: 'Why the type has no pattern (model-only), if so.' }
394
+ saved: { type: boolean }
395
+
396
+ Error:
397
+ type: object
398
+ required: [error]
399
+ properties:
400
+ error: { type: string }
401
+
402
+ responses:
403
+ BadRequest:
404
+ description: Invalid input (missing text, wrong types, invalid JSON)
405
+ content:
406
+ application/json:
407
+ schema: { $ref: '#/components/schemas/Error' }
408
+ Unauthorized:
409
+ description: Missing or invalid bearer token
410
+ content:
411
+ application/json:
412
+ schema: { $ref: '#/components/schemas/Error' }
413
+ Unprocessable:
414
+ description: The request is valid JSON but cannot be done (learning failed, model detection not configured)
415
+ content:
416
+ application/json:
417
+ schema: { $ref: '#/components/schemas/Error' }
418
+ DetectionFailed:
419
+ description: The detection model failed. Fails closed; details are only in the server log.
420
+ content:
421
+ application/json:
422
+ schema: { $ref: '#/components/schemas/Error' }