@waswrongassembled/pii-shield 0.2.0 → 0.4.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 (44) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/README.md +127 -15
  3. package/dist/cli.js +30 -5
  4. package/dist/create-pii-shield.d.ts +91 -0
  5. package/dist/create-pii-shield.js +124 -0
  6. package/dist/detectors/known-values.d.ts +40 -0
  7. package/dist/detectors/known-values.js +126 -0
  8. package/dist/entity-extractor.d.ts +17 -1
  9. package/dist/entity-extractor.js +13 -2
  10. package/dist/index.d.ts +5 -3
  11. package/dist/index.js +5 -3
  12. package/dist/internal/background.d.ts +27 -0
  13. package/dist/internal/background.js +47 -0
  14. package/dist/learning/custom-entity-type.d.ts +14 -4
  15. package/dist/learning/custom-entity-type.js +23 -5
  16. package/dist/learning/entity-learner.d.ts +33 -2
  17. package/dist/learning/entity-learner.js +48 -5
  18. package/dist/learning/store.d.ts +4 -2
  19. package/dist/pii-masker.js +3 -1
  20. package/dist/pii-shield.js +3 -1
  21. package/dist/postgres/index.d.ts +20 -0
  22. package/dist/postgres/index.js +14 -0
  23. package/dist/redaction.d.ts +16 -2
  24. package/dist/redaction.js +22 -10
  25. package/dist/server/config.d.ts +5 -8
  26. package/dist/server/config.js +77 -220
  27. package/dist/server/connections.d.ts +34 -0
  28. package/dist/server/connections.js +99 -0
  29. package/dist/server/doctor.d.ts +28 -0
  30. package/dist/server/doctor.js +438 -0
  31. package/dist/server/env.d.ts +62 -0
  32. package/dist/server/env.js +197 -0
  33. package/dist/server/index.d.ts +1 -0
  34. package/dist/server/index.js +1 -0
  35. package/dist/service/service-api.js +25 -0
  36. package/dist/testing/conformance.js +8 -3
  37. package/dist/vault/encrypted-vault.d.ts +39 -2
  38. package/dist/vault/encrypted-vault.js +96 -13
  39. package/dist/vault/memory-vault-storage.d.ts +8 -1
  40. package/dist/vault/memory-vault-storage.js +20 -8
  41. package/dist/vault-redis/index.d.ts +14 -0
  42. package/dist/vault-redis/index.js +8 -0
  43. package/docs/openapi.yaml +23 -2
  44. package/package.json +1 -1
@@ -19,13 +19,15 @@ export class PiiShield {
19
19
  #vault;
20
20
  #vaultTtl;
21
21
  constructor(options = {}) {
22
- const { detectors, allowlist, vault, vaultTtl = PiiShield.DEFAULT_VAULT_TTL } = options;
22
+ const { detectors, allowlist, knownValues, learner, vault, vaultTtl = PiiShield.DEFAULT_VAULT_TTL } = options;
23
23
  assertTtl(vaultTtl, 'The vault TTL must be positive.');
24
24
  this.#vault = vault;
25
25
  this.#vaultTtl = vaultTtl;
26
26
  this.#extractor = new EntityExtractor({
27
27
  ...(detectors === undefined ? {} : { detectors }),
28
28
  ...(allowlist === undefined ? {} : { allowlist }),
29
+ ...(knownValues === undefined ? {} : { knownValues }),
30
+ ...(learner === undefined ? {} : { learner }),
29
31
  });
30
32
  }
31
33
  /**
@@ -1,5 +1,6 @@
1
1
  import { type CustomEntityType } from '../learning/custom-entity-type.js';
2
2
  import { type CustomEntityStore } from '../learning/store.js';
3
+ import type { VaultSetup } from '../create-pii-shield.js';
3
4
  import { type VaultStorage } from '../vault/vault.js';
4
5
  /** What a query function resolves to: the result rows as objects keyed by column name. */
5
6
  export interface PostgresQueryResult {
@@ -50,6 +51,25 @@ export declare class PostgresVaultStorage implements VaultStorage {
50
51
  */
51
52
  purgeExpired(): Promise<number>;
52
53
  }
54
+ export interface PostgresVaultOptions extends PostgresStoreOptions {
55
+ /** 32 raw bytes, e.g. `vaultKeyFromEnv()`. Required: the rows outlive the process. */
56
+ key: Uint8Array;
57
+ /** Keys of earlier rotations, only for reading, e.g. `previousVaultKeysFromEnv()`. */
58
+ previousKeys?: readonly Uint8Array[] | undefined;
59
+ }
60
+ /**
61
+ * The vault of createPiiShield() on PostgreSQL: a PostgresVaultStorage behind an EncryptedVault with your
62
+ * key, whose expired rows createPiiShield() purges on its timer (`purgeExpired()`).
63
+ *
64
+ * ```ts
65
+ * const shield = await createPiiShield({
66
+ * vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
67
+ * });
68
+ * ```
69
+ */
70
+ export declare function postgresVault(options: PostgresVaultOptions): VaultSetup & {
71
+ storage: PostgresVaultStorage;
72
+ };
53
73
  /**
54
74
  * Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
55
75
  * postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
@@ -76,6 +76,20 @@ export class PostgresVaultStorage {
76
76
  return Number.isFinite(deleted) ? deleted : 0;
77
77
  }
78
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
+ }
79
93
  /**
80
94
  * Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
81
95
  * postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
@@ -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[];
@@ -26,10 +24,9 @@ export interface ServiceFromEnvOptions {
26
24
  }
27
25
  /**
28
26
  * Builds the service from environment variables (names as in the PHP service where they exist; see
29
- * 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.
30
29
  *
31
30
  * @throws ConfigError
32
31
  */
33
- export declare function serviceFromEnv(env?: Readonly<Record<string, string | undefined>>, options?: ServiceFromEnvOptions): Promise<EnvService>;
34
- /** Seconds between two purges of expired vault rows (Postgres). */
35
- export declare const DEFAULT_PURGE_INTERVAL = 300;
32
+ export declare function serviceFromEnv(env?: Env, options?: ServiceFromEnvOptions): Promise<EnvService>;
@@ -1,244 +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
20
  export async function serviceFromEnv(env = process.env, options = {}) {
22
- const get = (name) => {
23
- const value = env[name];
24
- return value === undefined || value === '' ? undefined : value;
25
- };
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
- };
45
- const onError = options.onError ??
46
- ((error, task) => {
47
- const { name = 'Error', code } = (error ?? {});
48
- process.stderr.write(`pii-shield: ${task} failed (${name}${typeof code === 'string' ? ` ${code}` : ''})\n`);
49
- });
50
- let pool;
51
- const databaseUrl = get('PII_SERVICE_DATABASE_URL');
52
- const connectPostgres = async () => {
53
- if (databaseUrl === undefined) {
54
- throw new ConfigError('Set PII_SERVICE_DATABASE_URL to use the postgres store.');
55
- }
56
- if (pool === undefined) {
57
- if (!/^postgres(?:ql)?:\/\//.test(databaseUrl) || !URL.canParse(databaseUrl)) {
58
- // Never quote the URL: it usually contains the password.
59
- throw new ConfigError('PII_SERVICE_DATABASE_URL must be a postgres:// or postgresql:// URL.');
60
- }
61
- let Pool;
62
- try {
63
- const pg = (await import('pg'));
64
- Pool = pg.Pool ?? pg.default?.Pool;
65
- }
66
- catch {
67
- // reported below
68
- }
69
- if (Pool === undefined) {
70
- throw new ConfigError('The postgres store needs the package "pg" (npm install pg).');
71
- }
72
- pool = new Pool({ connectionString: databaseUrl });
73
- // An idle connection that fails (database restart) must not crash the process.
74
- pool.on('error', (error) => {
75
- onError(error, 'database');
76
- });
77
- }
78
- const connected = pool;
79
- return (text, params) => connected.query(text, params);
80
- };
81
- /** An error message for the operator, without the database URL or its password. */
82
- const safeMessage = (e) => {
83
- let message = e instanceof Error ? e.message : String(e);
84
- if (databaseUrl !== undefined) {
85
- message = message.split(databaseUrl).join('<PII_SERVICE_DATABASE_URL>');
86
- const password = URL.canParse(databaseUrl) ? decodeURIComponent(new URL(databaseUrl).password) : '';
87
- if (password !== '') {
88
- message = message.split(password).join('***');
89
- }
90
- }
91
- return message;
92
- };
93
- let purgeTimer;
94
- let purging;
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 = [];
95
33
  try {
96
34
  // Vault
97
- const keyBase64 = get('PII_SERVICE_VAULT_KEY');
98
- let key;
99
- if (keyBase64 === undefined) {
100
- key = generateVaultKey();
101
- }
102
- else {
103
- try {
104
- key = parseVaultKey(keyBase64);
105
- }
106
- catch {
107
- throw new ConfigError('PII_SERVICE_VAULT_KEY must be 32 bytes, base64-encoded.');
108
- }
109
- }
110
- 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);
111
40
  let storage;
112
41
  if (vaultStore === 'memory') {
113
42
  storage = new MemoryVaultStorage();
114
43
  notes.push('Vault: in memory; mappings are lost on restart.');
115
44
  }
116
- else if (vaultStore === 'redis' || vaultStore === 'postgres') {
117
- if (keyBase64 === undefined) {
118
- throw new ConfigError(`The ${vaultStore} vault store needs PII_SERVICE_VAULT_KEY, or mappings cannot be read after a restart.`);
45
+ else if (vaultStore === 'redis') {
46
+ const { RedisVaultStorage } = await import('../vault-redis/index.js');
47
+ storage = new RedisVaultStorage({ client: await connection.redis() });
48
+ }
49
+ else {
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".`);
119
57
  }
120
- if (vaultStore === 'redis') {
121
- const { RedisVaultStorage } = await import('../vault-redis/index.js');
122
- storage = new RedisVaultStorage({ client: await connectRedis() });
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.');
123
62
  }
124
63
  else {
125
- const { PostgresVaultStorage } = await import('../postgres/index.js');
126
- const postgres = new PostgresVaultStorage({ query: await connectPostgres() });
127
- try {
128
- await postgres.get('pii-shield-startup-check'); // fail at start: no connection, no table, no rights
129
- }
130
- catch (e) {
131
- throw new ConfigError(`The vault table cannot be read: ${safeMessage(e)}. Create the tables with "pii-shield db-schema".`);
132
- }
133
- storage = postgres;
134
- const interval = integer(get('PII_SERVICE_VAULT_PURGE_INTERVAL'), 'PII_SERVICE_VAULT_PURGE_INTERVAL', DEFAULT_PURGE_INTERVAL, 0);
135
- if (interval > 86_400) {
136
- throw new ConfigError('PII_SERVICE_VAULT_PURGE_INTERVAL must be at most 86400 (one day).');
137
- }
138
- if (interval === 0) {
139
- notes.push('Vault: expired rows are not purged (PII_SERVICE_VAULT_PURGE_INTERVAL=0); delete them yourself.');
140
- }
141
- else {
142
- // Expired rows are personal data past their storage period (Art. 5(1)(e) GDPR): delete them.
143
- const purge = () => {
144
- purging ??= postgres
145
- .purgeExpired()
146
- .then(() => undefined, (e) => {
147
- onError(e, 'vault-purge');
148
- })
149
- .finally(() => {
150
- purging = undefined;
151
- });
152
- };
153
- purge();
154
- purgeTimer = setInterval(purge, interval * 1000).unref();
155
- }
64
+ purge = schedulePurge(() => postgres.purgeExpired(), interval, (e) => {
65
+ onError(e, 'vault-purge');
66
+ });
156
67
  }
157
68
  }
158
- else {
159
- throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory", "redis" or "postgres".');
160
- }
161
- const vaultTtl = integer(get('PII_SERVICE_VAULT_TTL'), 'PII_SERVICE_VAULT_TTL', ServiceApi.DEFAULT_VAULT_TTL);
69
+ const vaultTtl = readVaultTtl(get);
162
70
  // Learned types
163
- const learnedFile = get('PII_SERVICE_LEARNED_TYPES');
164
- const learnedStore = get('PII_SERVICE_LEARNED_STORE') ?? (learnedFile === undefined ? 'memory' : 'file');
71
+ const learned = readLearnedStore(get);
165
72
  let store;
166
- if (learnedStore === 'file') {
167
- if (learnedFile === undefined) {
168
- throw new ConfigError('Set PII_SERVICE_LEARNED_TYPES to the JSON file of learned types.');
169
- }
170
- store = new JsonFileCustomEntityStore(learnedFile);
73
+ if (learned.kind === 'file') {
74
+ store = new JsonFileCustomEntityStore(learned.file ?? '');
171
75
  }
172
- else if (learnedStore === 'memory') {
76
+ else if (learned.kind === 'memory') {
173
77
  store = new InMemoryCustomEntityStore();
174
78
  notes.push('Learned types: in memory; set PII_SERVICE_LEARNED_TYPES to keep them.');
175
79
  }
176
- else if (learnedStore === 'redis') {
177
- store = new KeyValueCustomEntityStore(await connectRedis());
178
- }
179
- else if (learnedStore === 'postgres') {
180
- const { PostgresCustomEntityStore } = await import('../postgres/index.js');
181
- store = new PostgresCustomEntityStore({ query: await connectPostgres() });
80
+ else if (learned.kind === 'redis') {
81
+ store = new KeyValueCustomEntityStore(await connection.redis());
182
82
  }
183
83
  else {
184
- throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory", "redis" or "postgres".');
84
+ const { PostgresCustomEntityStore } = await import('../postgres/index.js');
85
+ store = new PostgresCustomEntityStore({ query: await connection.postgres() });
185
86
  }
87
+ const keepExamples = readKeepExamples(get);
186
88
  let learner;
187
89
  try {
188
- learner = await EntityLearner.create({ store });
90
+ learner = await EntityLearner.create({ store, keepExamples });
189
91
  }
190
92
  catch (e) {
191
- throw new ConfigError(`The learned types cannot be read: ${safeMessage(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.');
192
97
  }
193
98
  // Model
194
- let modelDetector;
195
- const provider = get('PII_SERVICE_MODEL_PROVIDER');
196
- if (provider !== undefined) {
197
- if (!MODEL_PROVIDERS.includes(provider)) {
198
- throw new ConfigError(`PII_SERVICE_MODEL_PROVIDER must be one of ${MODEL_PROVIDERS.join(', ')}.`);
199
- }
200
- const keys = {
201
- ollama: undefined,
202
- generic: get('PII_SERVICE_MODEL_KEY') ?? get('PII_DEMO_GENERIC_KEY'),
203
- mistral: get('MISTRAL_API_KEY'),
204
- openai: get('OPENAI_API_KEY'),
205
- anthropic: get('ANTHROPIC_API_KEY'),
206
- };
207
- const typed = provider;
208
- let resolved;
209
- try {
210
- resolved = providerModel({
211
- provider: typed,
212
- model: get('PII_SERVICE_MODEL'),
213
- endpoint: get('PII_SERVICE_MODEL_URL') ?? (typed === 'ollama' ? get('PII_DEMO_OLLAMA_URL') : undefined),
214
- apiKey: keys[typed],
215
- });
216
- }
217
- catch (e) {
218
- throw new ConfigError(e instanceof Error ? e.message : String(e));
219
- }
220
- const acknowledged = get('PII_SERVICE_ACKNOWLEDGE_EXTERNAL') === 'true';
221
- if (resolved.location === 'external' && !acknowledged) {
222
- 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.`);
223
- }
224
- const options = {
225
- model: resolved.model,
226
- location: resolved.location,
227
- 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,
228
106
  learnedTypes: learner,
229
- // Self-hosted models answer only when done; allow for large models on modest hardware (PHP: 170 s).
230
- timeout: integer(get('PII_SERVICE_MODEL_TIMEOUT'), 'PII_SERVICE_MODEL_TIMEOUT', 170) * 1000,
231
- };
232
- try {
233
- new ModelDetector(options); // fail at start, not per request (external without acknowledgement)
234
- }
235
- catch (e) {
236
- throw new ConfigError(e instanceof Error ? e.message : String(e));
237
- }
238
- modelDetector = () => new ModelDetector(options);
239
- }
107
+ timeout: model.timeout,
108
+ });
240
109
  const api = new ServiceApi({
241
- vault: new EncryptedVault({ storage, key }),
110
+ vault: new EncryptedVault({ storage, key, previousKeys: keys.previousKeys }), // copies the keys
242
111
  learner,
243
112
  modelDetector,
244
113
  token: get('PII_SERVICE_TOKEN'),
@@ -246,37 +115,25 @@ export async function serviceFromEnv(env = process.env, options = {}) {
246
115
  requireToken: get('PII_SERVICE_ONLY') === '1',
247
116
  isLocalPeer: localPeerMatcher(splitList(get('PII_LOCAL_PEERS'))),
248
117
  });
249
- key.fill(0);
250
118
  return {
251
119
  api,
252
120
  allowedHosts: splitList(get('PII_SERVICE_ALLOWED_HOSTS')),
253
- maxBodyBytes: integer(get('PII_SERVICE_MAX_BODY_BYTES'), 'PII_SERVICE_MAX_BODY_BYTES', DEFAULT_MAX_BODY_BYTES),
254
- host: get('PII_SERVICE_HOST') ?? '127.0.0.1',
255
- port: integer(get('PII_SERVICE_PORT'), 'PII_SERVICE_PORT', 8088, 0),
121
+ ...readListen(get),
256
122
  notes,
257
123
  close: async () => {
258
- clearInterval(purgeTimer);
259
- await purging;
260
- await Promise.all([redis?.quit(), pool?.end()]);
124
+ await purge?.stop();
125
+ await connection.close();
261
126
  },
262
127
  };
263
128
  }
264
129
  catch (e) {
265
- clearInterval(purgeTimer);
266
- await purging;
267
- await Promise.all([redis?.quit().catch(() => undefined), pool?.end().catch(() => undefined)]);
130
+ await purge?.stop();
131
+ await connection.closeQuietly();
268
132
  throw e;
269
133
  }
270
- }
271
- /** Seconds between two purges of expired vault rows (Postgres). */
272
- export const DEFAULT_PURGE_INTERVAL = 300;
273
- function integer(value, name, fallback, min = 1) {
274
- if (value === undefined) {
275
- return fallback;
276
- }
277
- const n = Number(value);
278
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min) {
279
- 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
+ }
280
138
  }
281
- return n;
282
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;