@waswrongassembled/pii-shield 0.2.0 → 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 (41) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/README.md +109 -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/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 +4 -2
  17. package/dist/pii-masker.js +2 -1
  18. package/dist/pii-shield.js +2 -1
  19. package/dist/postgres/index.d.ts +20 -0
  20. package/dist/postgres/index.js +14 -0
  21. package/dist/redaction.d.ts +16 -2
  22. package/dist/redaction.js +22 -10
  23. package/dist/server/config.d.ts +5 -8
  24. package/dist/server/config.js +77 -220
  25. package/dist/server/connections.d.ts +34 -0
  26. package/dist/server/connections.js +99 -0
  27. package/dist/server/doctor.d.ts +28 -0
  28. package/dist/server/doctor.js +438 -0
  29. package/dist/server/env.d.ts +62 -0
  30. package/dist/server/env.js +197 -0
  31. package/dist/server/index.d.ts +1 -0
  32. package/dist/server/index.js +1 -0
  33. package/dist/testing/conformance.js +8 -3
  34. package/dist/vault/encrypted-vault.d.ts +39 -2
  35. package/dist/vault/encrypted-vault.js +96 -13
  36. package/dist/vault/memory-vault-storage.d.ts +8 -1
  37. package/dist/vault/memory-vault-storage.js +20 -8
  38. package/dist/vault-redis/index.d.ts +14 -0
  39. package/dist/vault-redis/index.js +8 -0
  40. package/docs/openapi.yaml +8 -2
  41. package/package.json +1 -1
@@ -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;
@@ -0,0 +1,99 @@
1
+ import { ConfigError, readDatabaseUrl, readRedisUrl } from './env.js';
2
+ export function connections(get, options) {
3
+ let redis;
4
+ let pool;
5
+ // Both URLs can hold a password: error messages never quote them.
6
+ const secretUrls = [
7
+ [get('PII_SERVICE_DATABASE_URL'), 'PII_SERVICE_DATABASE_URL'],
8
+ [get('PII_SERVICE_REDIS_URL') ?? get('PII_DEMO_REDIS_URL'), 'PII_SERVICE_REDIS_URL'],
9
+ ];
10
+ return {
11
+ redis: async () => {
12
+ const url = readRedisUrl(get);
13
+ if (redis === undefined) {
14
+ let Redis;
15
+ try {
16
+ ({ Redis } = (await import('ioredis')));
17
+ }
18
+ catch {
19
+ throw new ConfigError('The redis store needs the package "ioredis" (npm install ioredis).');
20
+ }
21
+ if (options.failFast === true) {
22
+ const client = new Redis(url, {
23
+ lazyConnect: true,
24
+ maxRetriesPerRequest: 0,
25
+ connectTimeout: 5000,
26
+ retryStrategy: () => null,
27
+ });
28
+ // connect() rejects with the error; without a listener ioredis also prints it.
29
+ let cause;
30
+ client.on('error', (e) => {
31
+ cause ??= e;
32
+ });
33
+ try {
34
+ await client.connect();
35
+ }
36
+ catch (e) {
37
+ client.disconnect();
38
+ // connect() only says "Connection is closed."; the error event has the reason (ECONNREFUSED).
39
+ throw cause ?? e;
40
+ }
41
+ redis = client;
42
+ }
43
+ else {
44
+ redis = new Redis(url);
45
+ }
46
+ }
47
+ return redis;
48
+ },
49
+ postgres: async () => {
50
+ const url = readDatabaseUrl(get);
51
+ if (pool === undefined) {
52
+ let Pool;
53
+ try {
54
+ const pg = (await import('pg'));
55
+ Pool = pg.Pool ?? pg.default?.Pool;
56
+ }
57
+ catch {
58
+ // reported below
59
+ }
60
+ if (Pool === undefined) {
61
+ throw new ConfigError('The postgres store needs the package "pg" (npm install pg).');
62
+ }
63
+ pool = new Pool({
64
+ connectionString: url,
65
+ ...(options.failFast === true ? { connectionTimeoutMillis: 5000 } : {}),
66
+ });
67
+ pool.on('error', options.onPoolError);
68
+ }
69
+ const connected = pool;
70
+ return (text, params) => connected.query(text, params);
71
+ },
72
+ safeMessage: (e) => {
73
+ let message = e instanceof Error ? e.message : String(e);
74
+ for (const [url, name] of secretUrls) {
75
+ if (url === undefined) {
76
+ continue;
77
+ }
78
+ message = message.split(url).join(`<${name}>`);
79
+ const password = URL.canParse(url) ? decodeURIComponent(new URL(url).password) : '';
80
+ if (password !== '') {
81
+ message = message.split(password).join('***');
82
+ }
83
+ }
84
+ return message;
85
+ },
86
+ close: async () => {
87
+ await Promise.all([redis?.quit(), pool?.end()]);
88
+ },
89
+ closeQuietly: async () => {
90
+ if (options.failFast === true) {
91
+ redis?.disconnect();
92
+ }
93
+ await Promise.all([
94
+ options.failFast === true ? undefined : redis?.quit().catch(() => undefined),
95
+ pool?.end().catch(() => undefined),
96
+ ]);
97
+ },
98
+ };
99
+ }
@@ -0,0 +1,28 @@
1
+ import { type Env } from './env.js';
2
+ /** `error`: the service would not start or not work; `warning`: it works, but should be changed. */
3
+ export type FindingSeverity = 'error' | 'warning' | 'info' | 'ok';
4
+ export interface ConfigFinding {
5
+ readonly severity: FindingSeverity;
6
+ /** What was checked, a stable id such as `vault-key`, `token` or `database-tls`. */
7
+ readonly check: string;
8
+ /** For the operator; names variables, never their values. */
9
+ readonly message: string;
10
+ }
11
+ export interface CheckServiceConfigOptions {
12
+ /**
13
+ * Also connect to Redis and PostgreSQL (when configured): checks that they answer, that the tables
14
+ * exist and are readable, and the database role's rights. Reads only, never writes. Default false.
15
+ */
16
+ connect?: boolean;
17
+ /** The listen address if it is given on the command line (`--host`), else PII_SERVICE_HOST. */
18
+ host?: string | undefined;
19
+ }
20
+ /**
21
+ * Checks the service configuration in `env` (the variables of docs/server.md) and returns findings,
22
+ * errors first in each area. Nothing is printed; secrets are never part of a finding. Without
23
+ * `connect` it is static (it only looks at files for the learned types).
24
+ */
25
+ export declare function checkServiceConfig(env?: Env, options?: CheckServiceConfigOptions): Promise<ConfigFinding[]>;
26
+ /** The findings as text, one line each, and a summary. */
27
+ export declare function formatFindings(findings: readonly ConfigFinding[]): string;
28
+ export declare function countFindings(findings: readonly ConfigFinding[]): Record<FindingSeverity, number>;