@waswrongassembled/pii-shield 0.1.1 → 0.3.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 (46) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +135 -21
  3. package/dist/cli.js +37 -5
  4. package/dist/create-pii-shield.d.ts +91 -0
  5. package/dist/create-pii-shield.js +124 -0
  6. package/dist/entity-extractor.d.ts +7 -0
  7. package/dist/entity-extractor.js +6 -1
  8. package/dist/index.d.ts +4 -3
  9. package/dist/index.js +4 -3
  10. package/dist/internal/background.d.ts +27 -0
  11. package/dist/internal/background.js +47 -0
  12. package/dist/learning/custom-entity-type.d.ts +14 -4
  13. package/dist/learning/custom-entity-type.js +23 -5
  14. package/dist/learning/entity-learner.d.ts +33 -2
  15. package/dist/learning/entity-learner.js +48 -5
  16. package/dist/learning/store.d.ts +26 -5
  17. package/dist/learning/store.js +4 -2
  18. package/dist/pii-masker.js +2 -1
  19. package/dist/pii-shield.js +2 -1
  20. package/dist/postgres/index.d.ts +103 -0
  21. package/dist/postgres/index.js +204 -0
  22. package/dist/redaction.d.ts +16 -2
  23. package/dist/redaction.js +22 -10
  24. package/dist/server/config.d.ts +16 -7
  25. package/dist/server/config.js +78 -126
  26. package/dist/server/connections.d.ts +34 -0
  27. package/dist/server/connections.js +99 -0
  28. package/dist/server/doctor.d.ts +28 -0
  29. package/dist/server/doctor.js +438 -0
  30. package/dist/server/env.d.ts +62 -0
  31. package/dist/server/env.js +197 -0
  32. package/dist/server/index.d.ts +1 -0
  33. package/dist/server/index.js +1 -0
  34. package/dist/testing/conformance.d.ts +64 -0
  35. package/dist/testing/conformance.js +348 -0
  36. package/dist/testing/index.d.ts +6 -0
  37. package/dist/testing/index.js +6 -0
  38. package/dist/vault/encrypted-vault.d.ts +39 -2
  39. package/dist/vault/encrypted-vault.js +96 -13
  40. package/dist/vault/memory-vault-storage.d.ts +8 -1
  41. package/dist/vault/memory-vault-storage.js +20 -8
  42. package/dist/vault/vault.d.ts +18 -2
  43. package/dist/vault-redis/index.d.ts +14 -0
  44. package/dist/vault-redis/index.js +8 -0
  45. package/docs/openapi.yaml +8 -2
  46. package/package.json +18 -3
@@ -0,0 +1,204 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/postgres: VaultStorage and CustomEntityStore on PostgreSQL. No driver
3
+ * dependency: both take a `query(text, params)` function, so a `pg` Pool, a `PoolClient` inside the
4
+ * product's transaction or a wrapper around another driver all work.
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { PiiShieldError, VaultError } from '../errors.js';
8
+ import { customEntityTypeFromJSON } from '../learning/custom-entity-type.js';
9
+ import { sortByName } from '../learning/store.js';
10
+ import { assertTtl } from '../vault/vault.js';
11
+ /** Default table of PostgresVaultStorage. */
12
+ export const DEFAULT_VAULT_TABLE = 'pii_shield_vault';
13
+ /** Default table of PostgresCustomEntityStore. */
14
+ export const DEFAULT_TYPES_TABLE = 'pii_shield_learned_types';
15
+ /**
16
+ * Stores vault ciphertext in a table (`id text primary key, payload bytea, expires_at timestamptz`, see
17
+ * postgresSchema()). Use it behind EncryptedVault, never on its own: the database then only sees
18
+ * ciphertext and the key stays outside it.
19
+ *
20
+ * - The row id is `sha256hex(id)`, like RedisVaultStorage: ids may come from outside.
21
+ * - Expiry uses the database clock (`now()`, the start of the current transaction), not the app clock:
22
+ * several app servers with skewed clocks agree. Reads ignore expired rows; purgeExpired() deletes them,
23
+ * which must happen regularly (storage limitation, Art. 5(1)(e) GDPR).
24
+ */
25
+ export class PostgresVaultStorage {
26
+ #query;
27
+ #sql;
28
+ constructor(options) {
29
+ this.#query = options.query;
30
+ const table = quoteTable(options.table ?? DEFAULT_VAULT_TABLE);
31
+ this.#sql = {
32
+ put: `INSERT INTO ${table} (id, payload, expires_at) VALUES ($1, $2, now() + make_interval(secs => $3)) ` +
33
+ 'ON CONFLICT (id) DO UPDATE SET payload = EXCLUDED.payload, expires_at = EXCLUDED.expires_at',
34
+ get: `SELECT payload FROM ${table} WHERE id = $1 AND expires_at > now()`,
35
+ remove: `DELETE FROM ${table} WHERE id = $1`,
36
+ // SKIP LOCKED: purges running at the same time (several servers) neither wait for nor deadlock
37
+ // each other, and rows being rewritten by put() are left alone. The count comes back as a row,
38
+ // so the query function needs no rowCount.
39
+ purge: `WITH expired AS (SELECT id FROM ${table} WHERE expires_at <= now() FOR UPDATE SKIP LOCKED), ` +
40
+ `deleted AS (DELETE FROM ${table} AS t USING expired WHERE t.id = expired.id RETURNING 1) ` +
41
+ 'SELECT count(*) AS deleted FROM deleted',
42
+ };
43
+ }
44
+ async put(id, payload, ttlSeconds) {
45
+ assertTtl(ttlSeconds);
46
+ // A Buffer over exactly the view's bytes: drivers send a Buffer as binary.
47
+ await this.#query(this.#sql.put, [
48
+ vaultKey(id),
49
+ Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength),
50
+ ttlSeconds,
51
+ ]);
52
+ }
53
+ async get(id) {
54
+ const { rows } = await this.#query(this.#sql.get, [vaultKey(id)]);
55
+ const payload = column(rows[0], 'payload');
56
+ if (payload === undefined) {
57
+ return null;
58
+ }
59
+ if (!(payload instanceof Uint8Array)) {
60
+ throw new VaultError('The vault table returned a payload that is not binary (bytea).', 'VAULT_CORRUPT');
61
+ }
62
+ return new Uint8Array(payload);
63
+ }
64
+ async remove(id) {
65
+ await this.#query(this.#sql.remove, [vaultKey(id)]);
66
+ }
67
+ /**
68
+ * Deletes expired rows (by the database clock). Run it regularly, e.g. from a timer, a cron job or
69
+ * `pg_cron`; the HTTP service does it every `PII_SERVICE_VAULT_PURGE_INTERVAL` seconds.
70
+ *
71
+ * @returns the number of deleted rows
72
+ */
73
+ async purgeExpired() {
74
+ const { rows } = await this.#query(this.#sql.purge, []);
75
+ const deleted = Number(column(rows[0], 'deleted') ?? 0);
76
+ return Number.isFinite(deleted) ? deleted : 0;
77
+ }
78
+ }
79
+ /**
80
+ * The vault of createPiiShield() on PostgreSQL: a PostgresVaultStorage behind an EncryptedVault with your
81
+ * key, whose expired rows createPiiShield() purges on its timer (`purgeExpired()`).
82
+ *
83
+ * ```ts
84
+ * const shield = await createPiiShield({
85
+ * vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
86
+ * });
87
+ * ```
88
+ */
89
+ export function postgresVault(options) {
90
+ const { key, previousKeys, ...store } = options;
91
+ return { storage: new PostgresVaultStorage(store), key, previousKeys };
92
+ }
93
+ /**
94
+ * Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
95
+ * postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
96
+ * names from any number of processes never lose each other.
97
+ *
98
+ * `data` is the type's JSON (the shape of JsonFileCustomEntityStore's entries); rows are validated with
99
+ * customEntityTypeFromJSON() when read. Examples are plain text and may be personal data: grant access
100
+ * to the table like to other personal data, and remember that a deleted row stays in WAL, backups and,
101
+ * until VACUUM, in the table file.
102
+ */
103
+ export class PostgresCustomEntityStore {
104
+ #query;
105
+ #sql;
106
+ constructor(options) {
107
+ this.#query = options.query;
108
+ const table = quoteTable(options.table ?? DEFAULT_TYPES_TABLE);
109
+ this.#sql = {
110
+ all: `SELECT name, data FROM ${table}`,
111
+ get: `SELECT name, data FROM ${table} WHERE name = $1`,
112
+ save: `INSERT INTO ${table} (name, data) VALUES ($1, $2::jsonb) ON CONFLICT (name) DO UPDATE SET data = EXCLUDED.data`,
113
+ remove: `DELETE FROM ${table} WHERE name = $1`,
114
+ };
115
+ }
116
+ async all() {
117
+ const { rows } = await this.#query(this.#sql.all, []);
118
+ // Sorted here, not with ORDER BY: byte order like the other stores, whatever the column's collation.
119
+ return sortByName(rows.map((row) => typeFromRow(row)));
120
+ }
121
+ async get(name) {
122
+ const { rows } = await this.#query(this.#sql.get, [name]);
123
+ return rows.length === 0 ? null : typeFromRow(rows[0]);
124
+ }
125
+ async save(type) {
126
+ await this.#query(this.#sql.save, [type.name, JSON.stringify(type)]);
127
+ }
128
+ async remove(name) {
129
+ await this.#query(this.#sql.remove, [name]);
130
+ }
131
+ }
132
+ /**
133
+ * The DDL for both tables, idempotent (`CREATE … IF NOT EXISTS`), for the product's own migrations or
134
+ * `psql`. The library never runs DDL itself. A schema in a qualified name must exist already.
135
+ *
136
+ * The application's database role needs only `SELECT, INSERT, UPDATE, DELETE` on the two tables.
137
+ */
138
+ export function postgresSchema(options = {}) {
139
+ const statements = [];
140
+ const { vaultTable = DEFAULT_VAULT_TABLE, typesTable = DEFAULT_TYPES_TABLE } = options;
141
+ if (vaultTable !== null) {
142
+ const table = quoteTable(vaultTable);
143
+ const index = quoteIdentifier(`${tableName(vaultTable)}_expires_at_idx`);
144
+ statements.push(`CREATE TABLE IF NOT EXISTS ${table} (\n id text PRIMARY KEY,\n payload bytea NOT NULL,\n expires_at timestamptz NOT NULL\n);`, `CREATE INDEX IF NOT EXISTS ${index} ON ${table} (expires_at);`, `COMMENT ON TABLE ${table} IS 'pii-shield vault: encrypted placeholder mappings (ciphertext only). Delete expired rows regularly (purgeExpired()).';`);
145
+ }
146
+ if (typesTable !== null) {
147
+ const table = quoteTable(typesTable);
148
+ statements.push(`CREATE TABLE IF NOT EXISTS ${table} (\n name text PRIMARY KEY,\n data jsonb NOT NULL\n);`, `COMMENT ON TABLE ${table} IS 'pii-shield learned entity types. Examples are plain text and may be personal data.';`);
149
+ }
150
+ return `${statements.join('\n')}\n`;
151
+ }
152
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,47}$/;
153
+ /**
154
+ * `"table"` or `"schema"."table"`, after checking each part against IDENTIFIER. The pattern has no
155
+ * quote, so quoting cannot be escaped; the name is never part of an error message beyond that check.
156
+ */
157
+ function quoteTable(name) {
158
+ if (typeof name !== 'string') {
159
+ throw new TypeError('The table name must be a string.');
160
+ }
161
+ const parts = name.split('.');
162
+ if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part))) {
163
+ throw new RangeError('The table name must be an identifier ([A-Za-z_][A-Za-z0-9_]*, at most 48 characters), optionally schema-qualified (schema.table).');
164
+ }
165
+ return parts.map(quoteIdentifier).join('.');
166
+ }
167
+ function quoteIdentifier(identifier) {
168
+ return `"${identifier}"`;
169
+ }
170
+ /** The table part of a (validated) qualified name. */
171
+ function tableName(qualified) {
172
+ return qualified.slice(qualified.lastIndexOf('.') + 1);
173
+ }
174
+ function vaultKey(id) {
175
+ return createHash('sha256').update(id, 'utf8').digest('hex');
176
+ }
177
+ function column(row, name) {
178
+ return typeof row === 'object' && row !== null && Object.hasOwn(row, name)
179
+ ? row[name]
180
+ : undefined;
181
+ }
182
+ function typeFromRow(row) {
183
+ let data = column(row, 'data');
184
+ if (typeof data === 'string') {
185
+ // Drivers that do not parse jsonb return text. No cause: V8's JSON.parse() message quotes the text.
186
+ try {
187
+ data = JSON.parse(data);
188
+ }
189
+ catch {
190
+ data = undefined;
191
+ }
192
+ }
193
+ if (typeof data !== 'object' || data === null) {
194
+ throw corrupt();
195
+ }
196
+ const type = customEntityTypeFromJSON(data);
197
+ if (type.name !== column(row, 'name')) {
198
+ throw corrupt();
199
+ }
200
+ return type;
201
+ }
202
+ function corrupt() {
203
+ return new PiiShieldError('The learned types table contains a row that is not a learned type.', 'LEARNING_STORE_CORRUPT');
204
+ }
@@ -10,8 +10,15 @@ export type PlaceholderMapping = Readonly<Record<string, string>>;
10
10
  * Result of a redaction. Holds the original values: never log it, persist it or send it to a model provider
11
11
  * (send `redactedText` only).
12
12
  *
13
- * A frozen plain object. `JSON.stringify` includes the mapping (it is the data you restore from);
14
- * only `util.inspect` / `console.log` in Node hide it, like PHP's `__debugInfo()`.
13
+ * A frozen object whose `mapping` and `entities` are readable but not enumerable, so what loggers and
14
+ * error reporters do with an object never reaches the original values:
15
+ * - `JSON.stringify()` (pino, winston, Sentry, ...) calls `toJSON()`: `{ redactedText, entityCount }`
16
+ * (plus `vaultId`); `util.inspect()` / `console.log()` show `mapping: '[hidden]'`, like PHP's `__debugInfo()`.
17
+ * - Spread (`{ ...result }`), `Object.keys()`, `Object.entries()` and `structuredClone()` (`postMessage()`)
18
+ * copy only `redactedText` (and `vaultId`). To keep or pass on the mapping, use `result.mapping`
19
+ * explicitly (a plain object, serialized like the JSON PHP stores in its vault), or the vault.
20
+ *
21
+ * Results of your own Redactor implementation are whatever objects it returns.
15
22
  *
16
23
  * `PiiShield.redactToVault()` returns a VaultRedactionResult, which adds the `vaultId`.
17
24
  */
@@ -26,6 +33,11 @@ export interface VaultRedactionResult extends RedactionResult {
26
33
  /** 32 lowercase hex characters (16 random bytes). Pass it to restoreFromVault() and forget(). */
27
34
  readonly vaultId: string;
28
35
  }
36
+ /**
37
+ * Result of a restore: a frozen plain object that serializes in full. `text` is the restored text with the
38
+ * original values, the output you asked for, so treat it like the original text; the placeholder lists
39
+ * hold no personal data.
40
+ */
29
41
  export interface RestoreResult {
30
42
  readonly text: string;
31
43
  /** Placeholders found in the text that are not in the mapping (the model invented them), in order of appearance. */
@@ -70,6 +82,8 @@ export declare function withVaultId(result: RedactionResult, vaultId: string): V
70
82
  /**
71
83
  * Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
72
84
  * Placeholders that are not in the mapping stay as they were found.
85
+ *
86
+ * @throws TypeError for a copy of a RedactionResult without its mapping (JSON, `structuredClone()`, spread)
73
87
  */
74
88
  export declare function restorePlaceholders(text: string, source: RedactionResult | PlaceholderMapping): RestoreResult;
75
89
  /** The distinct entity types of a redaction, in order of first appearance (PHP's foundTypes()). */
package/dist/redaction.js CHANGED
@@ -2,26 +2,38 @@ import { replacePlaceholders } from './placeholder.js';
2
2
  const INSPECT = Symbol.for('nodejs.util.inspect.custom');
3
3
  /** @internal */
4
4
  export function createRedactionResult(redactedText, mapping, entities) {
5
- const result = { redactedText, mapping: Object.freeze(mapping), entities: Object.freeze(entities) };
6
- Object.defineProperty(result, INSPECT, {
7
- value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length }),
8
- });
9
- return Object.freeze(result);
5
+ return hideOriginals({ redactedText }, Object.freeze(mapping), Object.freeze(entities));
10
6
  }
11
7
  /** @internal */
12
8
  export function withVaultId(result, vaultId) {
13
- const { redactedText, mapping, entities } = result;
14
- const withId = { redactedText, mapping, entities, vaultId };
15
- Object.defineProperty(withId, INSPECT, {
16
- value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length, vaultId }),
9
+ return hideOriginals({ redactedText: result.redactedText, vaultId }, result.mapping, result.entities);
10
+ }
11
+ /**
12
+ * Adds `mapping` and `entities` as readable, non-enumerable properties, a `toJSON()` and a `util.inspect`
13
+ * view without them, and freezes the result (see RedactionResult).
14
+ */
15
+ function hideOriginals(visible, mapping, entities) {
16
+ const { redactedText, vaultId } = visible;
17
+ const withId = vaultId === undefined ? {} : { vaultId };
18
+ Object.defineProperties(visible, {
19
+ mapping: { value: mapping },
20
+ entities: { value: entities },
21
+ toJSON: { value: () => ({ redactedText, entityCount: entities.length, ...withId }) },
22
+ [INSPECT]: { value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length, ...withId }) },
17
23
  });
18
- return Object.freeze(withId);
24
+ return Object.freeze(visible);
19
25
  }
20
26
  /**
21
27
  * Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
22
28
  * Placeholders that are not in the mapping stay as they were found.
29
+ *
30
+ * @throws TypeError for a copy of a RedactionResult without its mapping (JSON, `structuredClone()`, spread)
23
31
  */
24
32
  export function restorePlaceholders(text, source) {
33
+ if (!isRedactionResult(source) && typeof source.redactedText === 'string') {
34
+ // Placeholders never are "redactedText", so this is a result copy that lost its mapping.
35
+ throw new TypeError('This redaction result has no mapping (JSON, structuredClone() and spread leave it out): pass result.mapping, or use the vault.');
36
+ }
25
37
  const mapping = isRedactionResult(source) ? source.mapping : source;
26
38
  const seen = new Set();
27
39
  const unknown = new Set();
@@ -1,8 +1,6 @@
1
1
  import { ServiceApi } from '../service/service-api.js';
2
- /** A configuration problem; the message names the variable, never a secret. */
3
- export declare class ConfigError extends Error {
4
- readonly name = "ConfigError";
5
- }
2
+ import { ConfigError, type Env } from './env.js';
3
+ export { ConfigError };
6
4
  export interface EnvService {
7
5
  api: ServiceApi;
8
6
  allowedHosts: string[];
@@ -11,13 +9,24 @@ export interface EnvService {
11
9
  port: number;
12
10
  /** Notes for the operator (stderr), e.g. that mappings do not survive a restart. Never secrets. */
13
11
  notes: string[];
14
- /** Closes connections the configuration opened (Redis). */
12
+ /** Stops background tasks (vault purge) and closes connections the configuration opened (Redis, Postgres). */
15
13
  close(): Promise<void>;
16
14
  }
15
+ /** Background work of the service; its errors go to `onError`. */
16
+ export type BackgroundTask = 'vault-purge' | 'database';
17
+ export interface ServiceFromEnvOptions {
18
+ /**
19
+ * Errors of background work: the periodic vault purge and idle database connections. Default:
20
+ * name and code to stderr. The error may carry driver details (a pg error's `detail` can quote row
21
+ * values): log name and code, not the whole error.
22
+ */
23
+ onError?: (error: unknown, task: BackgroundTask) => void;
24
+ }
17
25
  /**
18
26
  * Builds the service from environment variables (names as in the PHP service where they exist; see
19
- * docs/server.md). Used by the `pii-shield` CLI.
27
+ * docs/server.md). Used by the `pii-shield` CLI. `pii-shield doctor` (checkServiceConfig()) checks the
28
+ * same variables with the same rules.
20
29
  *
21
30
  * @throws ConfigError
22
31
  */
23
- export declare function serviceFromEnv(env?: Readonly<Record<string, string | undefined>>): Promise<EnvService>;
32
+ export declare function serviceFromEnv(env?: Env, options?: ServiceFromEnvOptions): Promise<EnvService>;
@@ -1,155 +1,113 @@
1
- import { ModelDetector } from '../model/model-detector.js';
1
+ import { reportToStderr, schedulePurge } from '../internal/background.js';
2
2
  import { EntityLearner } from '../learning/entity-learner.js';
3
3
  import { JsonFileCustomEntityStore } from '../learning/json-file-store.js';
4
4
  import { InMemoryCustomEntityStore, KeyValueCustomEntityStore } from '../learning/store.js';
5
+ import { ModelDetector } from '../model/model-detector.js';
5
6
  import { localPeerMatcher, splitList } from '../service/local-peer.js';
6
7
  import { ServiceApi } from '../service/service-api.js';
7
- import { EncryptedVault, generateVaultKey, parseVaultKey } from '../vault/encrypted-vault.js';
8
+ import { EncryptedVault, generateVaultKey } from '../vault/encrypted-vault.js';
8
9
  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
- }
10
+ import { connections } from './connections.js';
11
+ import { assertVaultKeyFor, ConfigError, envGetter, readKeepExamples, readLearnedStore, readListen, readModel, readPurgeInterval, readVaultKeys, readVaultStore, readVaultTtl, } from './env.js';
12
+ export { ConfigError };
15
13
  /**
16
14
  * 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.
15
+ * docs/server.md). Used by the `pii-shield` CLI. `pii-shield doctor` (checkServiceConfig()) checks the
16
+ * same variables with the same rules.
18
17
  *
19
18
  * @throws ConfigError
20
19
  */
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
- };
20
+ export async function serviceFromEnv(env = process.env, options = {}) {
21
+ const get = envGetter(env);
26
22
  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
- };
23
+ const onError = options.onError ?? reportToStderr;
24
+ const connection = connections(get, {
25
+ // An idle connection that fails (database restart) must not crash the process.
26
+ onPoolError: (error) => {
27
+ onError(error, 'database');
28
+ },
29
+ });
30
+ let purge;
31
+ /** Decoded keys, wiped when this function returns (the vault keeps its own copies). */
32
+ const keyMaterial = [];
45
33
  try {
46
34
  // 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';
35
+ const keys = readVaultKeys(get, env);
36
+ const key = keys.key ?? generateVaultKey();
37
+ keyMaterial.push(key, ...keys.previousKeys);
38
+ const vaultStore = readVaultStore(get);
39
+ assertVaultKeyFor(vaultStore, keys.key !== undefined);
61
40
  let storage;
62
41
  if (vaultStore === 'memory') {
63
42
  storage = new MemoryVaultStorage();
64
43
  notes.push('Vault: in memory; mappings are lost on restart.');
65
44
  }
66
45
  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
46
  const { RedisVaultStorage } = await import('../vault-redis/index.js');
71
- storage = new RedisVaultStorage({ client: await connectRedis() });
47
+ storage = new RedisVaultStorage({ client: await connection.redis() });
72
48
  }
73
49
  else {
74
- throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory" or "redis".');
50
+ const { PostgresVaultStorage } = await import('../postgres/index.js');
51
+ const postgres = new PostgresVaultStorage({ query: await connection.postgres() });
52
+ try {
53
+ await postgres.get('pii-shield-startup-check'); // fail at start: no connection, no table, no rights
54
+ }
55
+ catch (e) {
56
+ throw new ConfigError(`The vault table cannot be read: ${connection.safeMessage(e)}. Create the tables with "pii-shield db-schema".`);
57
+ }
58
+ storage = postgres;
59
+ const interval = readPurgeInterval(get);
60
+ if (interval === 0) {
61
+ notes.push('Vault: expired rows are not purged (PII_SERVICE_VAULT_PURGE_INTERVAL=0); delete them yourself.');
62
+ }
63
+ else {
64
+ purge = schedulePurge(() => postgres.purgeExpired(), interval, (e) => {
65
+ onError(e, 'vault-purge');
66
+ });
67
+ }
75
68
  }
76
- const vaultTtl = integer(get('PII_SERVICE_VAULT_TTL'), 'PII_SERVICE_VAULT_TTL', ServiceApi.DEFAULT_VAULT_TTL);
69
+ const vaultTtl = readVaultTtl(get);
77
70
  // Learned types
78
- const learnedFile = get('PII_SERVICE_LEARNED_TYPES');
79
- const learnedStore = get('PII_SERVICE_LEARNED_STORE') ?? (learnedFile === undefined ? 'memory' : 'file');
71
+ const learned = readLearnedStore(get);
80
72
  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);
73
+ if (learned.kind === 'file') {
74
+ store = new JsonFileCustomEntityStore(learned.file ?? '');
86
75
  }
87
- else if (learnedStore === 'memory') {
76
+ else if (learned.kind === 'memory') {
88
77
  store = new InMemoryCustomEntityStore();
89
78
  notes.push('Learned types: in memory; set PII_SERVICE_LEARNED_TYPES to keep them.');
90
79
  }
91
- else if (learnedStore === 'redis') {
92
- store = new KeyValueCustomEntityStore(await connectRedis());
80
+ else if (learned.kind === 'redis') {
81
+ store = new KeyValueCustomEntityStore(await connection.redis());
93
82
  }
94
83
  else {
95
- throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory" or "redis".');
84
+ const { PostgresCustomEntityStore } = await import('../postgres/index.js');
85
+ store = new PostgresCustomEntityStore({ query: await connection.postgres() });
96
86
  }
87
+ const keepExamples = readKeepExamples(get);
97
88
  let learner;
98
89
  try {
99
- learner = await EntityLearner.create({ store });
90
+ learner = await EntityLearner.create({ store, keepExamples });
100
91
  }
101
92
  catch (e) {
102
- throw new ConfigError(`The learned types cannot be read: ${e instanceof Error ? e.message : String(e)}`);
93
+ throw new ConfigError(`The learned types cannot be read: ${connection.safeMessage(e)}`);
94
+ }
95
+ if (!learner.keepExamples && learner.snapshot.some((t) => t.pattern !== null && t.examples.length > 0)) {
96
+ notes.push('Learned types: types learned before still hold examples; EntityLearner.dropExamples() removes them.');
103
97
  }
104
98
  // 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,
99
+ const model = readModel(get);
100
+ const modelDetector = model === undefined
101
+ ? undefined
102
+ : () => new ModelDetector({
103
+ model: model.model,
104
+ location: model.location,
105
+ acknowledgeExternalTransfer: model.acknowledged,
139
106
  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
- }
107
+ timeout: model.timeout,
108
+ });
151
109
  const api = new ServiceApi({
152
- vault: new EncryptedVault({ storage, key }),
110
+ vault: new EncryptedVault({ storage, key, previousKeys: keys.previousKeys }), // copies the keys
153
111
  learner,
154
112
  modelDetector,
155
113
  token: get('PII_SERVICE_TOKEN'),
@@ -157,31 +115,25 @@ export async function serviceFromEnv(env = process.env) {
157
115
  requireToken: get('PII_SERVICE_ONLY') === '1',
158
116
  isLocalPeer: localPeerMatcher(splitList(get('PII_LOCAL_PEERS'))),
159
117
  });
160
- key.fill(0);
161
118
  return {
162
119
  api,
163
120
  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),
121
+ ...readListen(get),
167
122
  notes,
168
123
  close: async () => {
169
- await redis?.quit();
124
+ await purge?.stop();
125
+ await connection.close();
170
126
  },
171
127
  };
172
128
  }
173
129
  catch (e) {
174
- await redis?.quit().catch(() => undefined);
130
+ await purge?.stop();
131
+ await connection.closeQuietly();
175
132
  throw e;
176
133
  }
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)}.`);
134
+ finally {
135
+ for (const material of keyMaterial) {
136
+ material.fill(0);
137
+ }
185
138
  }
186
- return n;
187
139
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The Redis client and the Postgres pool of the service's configuration, opened on first use and shared
3
+ * by both stores. Used by serviceFromEnv() and by checkServiceConfig({ connect: true }).
4
+ */
5
+ import type { PostgresQuery } from '../postgres/index.js';
6
+ import { type EnvGetter } from './env.js';
7
+ export interface RedisLike {
8
+ getBuffer(key: string): Promise<Buffer | null>;
9
+ set(key: string, value: Buffer | string, ...args: unknown[]): Promise<unknown>;
10
+ get(key: string): Promise<string | null>;
11
+ del(key: string): Promise<number>;
12
+ ping(): Promise<unknown>;
13
+ quit(): Promise<unknown>;
14
+ connect(): Promise<unknown>;
15
+ disconnect(): void;
16
+ on(event: 'error', listener: (error: Error) => void): unknown;
17
+ }
18
+ export interface Connections {
19
+ redis(): Promise<RedisLike>;
20
+ postgres(): Promise<PostgresQuery>;
21
+ /** An error message for the operator, without the database or Redis URL or their passwords. */
22
+ safeMessage(error: unknown): string;
23
+ /** Closes what was opened. */
24
+ close(): Promise<void>;
25
+ /** Closes what was opened and ignores errors (after a failure). */
26
+ closeQuietly(): Promise<void>;
27
+ }
28
+ export interface ConnectionOptions {
29
+ /** Errors of idle pool connections (a database restart must not crash the process). */
30
+ onPoolError: (error: Error) => void;
31
+ /** Fail fast instead of reconnecting forever (for a one-off check). */
32
+ failFast?: boolean;
33
+ }
34
+ export declare function connections(get: EnvGetter, options: ConnectionOptions): Connections;