@waswrongassembled/pii-shield 0.1.1 → 0.2.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.
- package/CHANGELOG.md +15 -1
- package/README.md +29 -9
- package/dist/cli.js +7 -0
- package/dist/learning/store.d.ts +24 -5
- package/dist/learning/store.js +4 -2
- package/dist/postgres/index.d.ts +83 -0
- package/dist/postgres/index.js +190 -0
- package/dist/server/config.d.ts +14 -2
- package/dist/server/config.js +105 -10
- package/dist/testing/conformance.d.ts +64 -0
- package/dist/testing/conformance.js +343 -0
- package/dist/testing/index.d.ts +6 -0
- package/dist/testing/index.js +6 -0
- package/dist/vault/vault.d.ts +18 -2
- package/package.json +18 -3
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.2.0] - 2026-11-21
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- `@waswrongassembled/pii-shield/postgres`: `PostgresVaultStorage` and `PostgresCustomEntityStore` keep the vault and the learned types in PostgreSQL. They take a driver-agnostic `query(text, params)` function (a `pg` `Pool` or `PoolClient` fits) and work inside the caller's transaction. Vault ids are hashed, expiry uses the database clock, and `purgeExpired()` deletes expired rows. Learned types are stored one row per type. `postgresSchema()` returns idempotent DDL for your migrations; the library never runs DDL itself.
|
|
13
|
+
- `@waswrongassembled/pii-shield/testing`: `verifyVaultStorage()` and `verifyCustomEntityStore()` check a store against the contracts, with `node:assert` only, under any test runner. Every built-in store passes them.
|
|
14
|
+
- Service: `PII_SERVICE_VAULT_STORE=postgres`, `PII_SERVICE_LEARNED_STORE=postgres` and `PII_SERVICE_DATABASE_URL` (optional peer `pg` 8). Expired vault rows are purged at start and every `PII_SERVICE_VAULT_PURGE_INTERVAL` seconds (default 300). `pii-shield db-schema` prints the DDL. `serviceFromEnv()` takes an `onError` hook for background errors.
|
|
15
|
+
- docs/stores.md: the store contracts, writing your own adapter, PostgreSQL and data protection.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- The contracts of `VaultStorage` and `CustomEntityStore` are documented in their TSDoc: expired entries read as `null`, `put()`/`save()` overwrite, removing an unknown id or name is a no-op, payloads are binary-safe, `all()` is sorted in byte order, and concurrent writes of different names are kept. `KeyValueCustomEntityStore` does not keep the last rule across processes; its TSDoc now says so.
|
|
20
|
+
|
|
8
21
|
## [0.1.1] - 2026-11-21
|
|
9
22
|
|
|
10
23
|
No changes to the library code. First release through the release workflow: staged on npm with Trusted Publishing and a provenance attestation, approved with 2FA (0.1.0 was published by hand without provenance).
|
|
@@ -33,6 +46,7 @@ Privacy and crash bugs of the PHP package are fixed rather than reproduced: name
|
|
|
33
46
|
- `@waswrongassembled/pii-shield/mcp` (peer `@modelcontextprotocol/sdk`): the MCP tools `redact_text`, `restore_text`, `mask_text`, `learn_entity_type` and `list_entity_types` over STDIO and Streamable HTTP.
|
|
34
47
|
- `pii-shield` CLI: `pii-shield serve`, `pii-shield mcp [--http]`, configured with PHP's environment variables.
|
|
35
48
|
|
|
36
|
-
[Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.
|
|
49
|
+
[Unreleased]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.2.0...HEAD
|
|
50
|
+
[0.2.0]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.1...v0.2.0
|
|
37
51
|
[0.1.1]: https://github.com/waswrongassembled/pii-shield-js/compare/v0.1.0...v0.1.1
|
|
38
52
|
[0.1.0]: https://github.com/waswrongassembled/pii-shield-js/releases/tag/v0.1.0
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ TypeScript port of [`clarifile/pii-shield`](https://github.com/massiveart/clarif
|
|
|
5
5
|
|
|
6
6
|
Personal data in a text is replaced by placeholders (`⟦PERSON_1⟧`, `⟦IBAN_1⟧`) before the text goes to a language model; the answer gets the original values back. Detection runs locally (regular expressions plus checksums, optionally a model you choose), so the LLM provider only ever sees placeholders.
|
|
7
7
|
|
|
8
|
-
**Status:** 0.1.0 (release prepared, see [docs/RELEASING.md](docs/RELEASING.md)), a feature-complete port of the PHP package: detection, redaction and restore, masking, an encrypted vault (in memory or
|
|
8
|
+
**Status:** 0.1.0 (release prepared, see [docs/RELEASING.md](docs/RELEASING.md)), a feature-complete port of the PHP package: detection, redaction and restore, masking, an encrypted vault (in memory, Redis or PostgreSQL), learned entity types, a model-based detector, Vercel AI SDK middleware, an HTTP service, an MCP server and a CLI. See [CHANGELOG.md](CHANGELOG.md).
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
@@ -15,13 +15,15 @@ npm install @waswrongassembled/pii-shield
|
|
|
15
15
|
|
|
16
16
|
Requires Node >= 22.12. The package is ESM only; `require()` works on Node >= 22.12 (require(esm)). The core depends only on `@noble/ciphers`. Optional peer dependencies, needed only for their subpath:
|
|
17
17
|
|
|
18
|
-
| Subpath | Needs
|
|
19
|
-
| ------------------------------------------- |
|
|
20
|
-
| `@waswrongassembled/pii-shield` | -
|
|
21
|
-
| `@waswrongassembled/pii-shield/vault-redis` | `ioredis` (5 or 6)
|
|
22
|
-
| `@waswrongassembled/pii-shield/
|
|
23
|
-
| `@waswrongassembled/pii-shield/
|
|
24
|
-
| `@waswrongassembled/pii-shield/
|
|
18
|
+
| Subpath | Needs |
|
|
19
|
+
| ------------------------------------------- | --------------------------------------------- |
|
|
20
|
+
| `@waswrongassembled/pii-shield` | - |
|
|
21
|
+
| `@waswrongassembled/pii-shield/vault-redis` | `ioredis` (5 or 6) |
|
|
22
|
+
| `@waswrongassembled/pii-shield/postgres` | - (any driver; `pg` fits) |
|
|
23
|
+
| `@waswrongassembled/pii-shield/testing` | - |
|
|
24
|
+
| `@waswrongassembled/pii-shield/ai-sdk` | `ai` (7) |
|
|
25
|
+
| `@waswrongassembled/pii-shield/mcp` | `@modelcontextprotocol/sdk` |
|
|
26
|
+
| `@waswrongassembled/pii-shield/server` | - (`/mcp` needs the MCP SDK, Postgres `pg` 8) |
|
|
25
27
|
|
|
26
28
|
All examples use synthetic data. Every `ts` block in this README is type-checked against the source by `test/readme-examples.test.ts`.
|
|
27
29
|
|
|
@@ -95,7 +97,7 @@ const vault = new EncryptedVault({
|
|
|
95
97
|
|
|
96
98
|
## Learned entity types
|
|
97
99
|
|
|
98
|
-
Teach a type from examples; a pattern is derived and checked against the counter-examples. Stores: `JsonFileCustomEntityStore` (same file format as PHP), `InMemoryCustomEntityStore`, `KeyValueCustomEntityStore
|
|
100
|
+
Teach a type from examples; a pattern is derived and checked against the counter-examples. Stores: `JsonFileCustomEntityStore` (same file format as PHP), `InMemoryCustomEntityStore`, `KeyValueCustomEntityStore`, `PostgresCustomEntityStore` (see [docs/stores.md](docs/stores.md)).
|
|
99
101
|
|
|
100
102
|
```ts
|
|
101
103
|
import { defaultDetectors, EntityLearner, JsonFileCustomEntityStore, PiiShield } from '@waswrongassembled/pii-shield';
|
|
@@ -112,6 +114,24 @@ const shield = new PiiShield({ detectors: [...defaultDetectors(), learner.detect
|
|
|
112
114
|
shield.redact('Polizze VN-2026-000999').redactedText; // 'Polizze ⟦INSURANCE_NUMBER_1⟧'
|
|
113
115
|
```
|
|
114
116
|
|
|
117
|
+
## Stores: PostgreSQL and your own
|
|
118
|
+
|
|
119
|
+
A product that already runs PostgreSQL can keep the vault and the learned types in its own database, in its own pool and, where it wants, in its own transactions. `@waswrongassembled/pii-shield/postgres` takes a `query(text, params)` function (a `pg` `Pool` or `PoolClient` fits) and never runs DDL: put `postgresSchema()` (or `pii-shield db-schema`) into your migrations.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import pg from 'pg';
|
|
123
|
+
import { EncryptedVault, generateVaultKey } from '@waswrongassembled/pii-shield';
|
|
124
|
+
import { PostgresCustomEntityStore, PostgresVaultStorage } from '@waswrongassembled/pii-shield/postgres';
|
|
125
|
+
|
|
126
|
+
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
|
|
127
|
+
const storage = new PostgresVaultStorage({ query: pool.query.bind(pool) });
|
|
128
|
+
const vault = new EncryptedVault({ storage, key: generateVaultKey() }); // the database only sees ciphertext
|
|
129
|
+
const store = new PostgresCustomEntityStore({ query: pool.query.bind(pool) });
|
|
130
|
+
await storage.purgeExpired(); // run regularly: expired rows must really be deleted
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The contracts every store keeps, the conformance suites for your own adapter (`verifyVaultStorage()`, `verifyCustomEntityStore()` from `@waswrongassembled/pii-shield/testing`, runner-agnostic), transactions, purging and data protection: [docs/stores.md](docs/stores.md).
|
|
134
|
+
|
|
115
135
|
## Model-based detection
|
|
116
136
|
|
|
117
137
|
`ModelDetector` asks a language model for entities the patterns miss (names without a salutation, free-form addresses). It sends the **unredacted** text to that model, so `location` is required, and an `external` provider also needs `acknowledgeExternalTransfer: true` (data processing agreement, possibly a third-country transfer). It is async: use `redactAsync()`, `redactToVault()` or `maskAsync()`.
|
package/dist/cli.js
CHANGED
|
@@ -3,12 +3,14 @@
|
|
|
3
3
|
* environment variables (docs/server.md).
|
|
4
4
|
*/
|
|
5
5
|
import { parseArgs } from 'node:util';
|
|
6
|
+
import { postgresSchema } from './postgres/index.js';
|
|
6
7
|
import { ConfigError, serviceFromEnv } from './server/config.js';
|
|
7
8
|
import { startServer } from './server/http-server.js';
|
|
8
9
|
const USAGE = `Usage:
|
|
9
10
|
pii-shield serve [--port <port>] [--host <host>] HTTP service: /v1 (and /mcp if @modelcontextprotocol/sdk is installed)
|
|
10
11
|
pii-shield mcp MCP server over STDIO
|
|
11
12
|
pii-shield mcp --http [--port <port>] [--host <host>] MCP server over Streamable HTTP (/mcp)
|
|
13
|
+
pii-shield db-schema SQL for the Postgres tables (stdout), e.g. | psql "$DATABASE_URL"
|
|
12
14
|
|
|
13
15
|
Configuration: environment variables (PII_SERVICE_TOKEN, PII_SERVICE_VAULT_KEY, ...), see
|
|
14
16
|
https://github.com/waswrongassembled/pii-shield-js/blob/main/docs/server.md`;
|
|
@@ -37,6 +39,11 @@ export async function main(argv, env = process.env) {
|
|
|
37
39
|
process.stderr.write(`${USAGE}\n`);
|
|
38
40
|
return values.help === true ? 0 : 2;
|
|
39
41
|
}
|
|
42
|
+
if (command === 'db-schema' && positionals.length === 1 && Object.keys(values).length === 0) {
|
|
43
|
+
// DDL is never run by the service itself: the operator (or the product's migrations) applies it.
|
|
44
|
+
process.stdout.write(postgresSchema());
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
40
47
|
if (positionals.length > 1 ||
|
|
41
48
|
(command !== 'serve' && command !== 'mcp') ||
|
|
42
49
|
(command === 'serve' && values.http === true)) {
|
package/dist/learning/store.d.ts
CHANGED
|
@@ -1,14 +1,31 @@
|
|
|
1
1
|
import { type CustomEntityType } from './custom-entity-type.js';
|
|
2
2
|
/**
|
|
3
|
-
* Where learned entity types live.
|
|
4
|
-
* (
|
|
3
|
+
* Where learned entity types live. Built in: JsonFileCustomEntityStore, InMemoryCustomEntityStore,
|
|
4
|
+
* KeyValueCustomEntityStore (any key-value backend) and PostgresCustomEntityStore
|
|
5
|
+
* (`@waswrongassembled/pii-shield/postgres`). Check your own with `verifyCustomEntityStore()` from
|
|
6
|
+
* `@waswrongassembled/pii-shield/testing`.
|
|
7
|
+
*
|
|
8
|
+
* Examples and counter-examples are stored in plain text and may be personal data: treat the backend
|
|
9
|
+
* like any other store of personal data (access rights, backups, deletion through `remove()`).
|
|
10
|
+
*
|
|
11
|
+
* Contract every implementation keeps:
|
|
12
|
+
* - `all()` is sorted by name in byte order (sortByName(), PHP's strcmp()), independent of a
|
|
13
|
+
* database collation.
|
|
14
|
+
* - `get()` of an unknown name gives `null`; `save()` replaces a type with the same name; `remove()` of
|
|
15
|
+
* an unknown name is a no-op.
|
|
16
|
+
* - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved.
|
|
17
|
+
* - Concurrent `save()`/`remove()` calls for different names must not lose each other's writes.
|
|
18
|
+
* KeyValueCustomEntityStore keeps this only for writes through one instance: its read-modify-write
|
|
19
|
+
* of the whole list loses writes across processes unless you serialise them yourself.
|
|
5
20
|
*/
|
|
6
21
|
export interface CustomEntityStore {
|
|
7
|
-
/** Sorted by name. */
|
|
22
|
+
/** Sorted by name (byte order). */
|
|
8
23
|
all(): Promise<CustomEntityType[]>;
|
|
24
|
+
/** @returns null if there is no type with this name */
|
|
9
25
|
get(name: string): Promise<CustomEntityType | null>;
|
|
10
26
|
/** Adds the type or replaces the one with the same name. */
|
|
11
27
|
save(type: CustomEntityType): Promise<void>;
|
|
28
|
+
/** Deletes the type; resolves also if there is none. */
|
|
12
29
|
remove(name: string): Promise<void>;
|
|
13
30
|
}
|
|
14
31
|
/** Sorted by name with PHP's strcmp() (byte order; names are ASCII). Stable, like PHP 8's usort(). */
|
|
@@ -38,8 +55,10 @@ export interface KeyValueCustomEntityStoreOptions {
|
|
|
38
55
|
* CacheCustomEntityStore). The value is the same JSON shape as the file store, not PHP's PSR-6
|
|
39
56
|
* serialisation, so PHP and Node cannot share the key (docs/DEVIATIONS.md).
|
|
40
57
|
*
|
|
41
|
-
* save() and remove() read, change and write the whole list:
|
|
42
|
-
*
|
|
58
|
+
* save() and remove() read, change and write the whole list: writes through one instance are
|
|
59
|
+
* serialised, but writes from several processes (or instances) can lose each other's changes. Serialise
|
|
60
|
+
* them yourself (e.g. a Redis lock), or use a store with one record per type such as
|
|
61
|
+
* PostgresCustomEntityStore.
|
|
43
62
|
*/
|
|
44
63
|
export declare class KeyValueCustomEntityStore implements CustomEntityStore {
|
|
45
64
|
#private;
|
package/dist/learning/store.js
CHANGED
|
@@ -38,8 +38,10 @@ export class InMemoryCustomEntityStore {
|
|
|
38
38
|
* CacheCustomEntityStore). The value is the same JSON shape as the file store, not PHP's PSR-6
|
|
39
39
|
* serialisation, so PHP and Node cannot share the key (docs/DEVIATIONS.md).
|
|
40
40
|
*
|
|
41
|
-
* save() and remove() read, change and write the whole list:
|
|
42
|
-
*
|
|
41
|
+
* save() and remove() read, change and write the whole list: writes through one instance are
|
|
42
|
+
* serialised, but writes from several processes (or instances) can lose each other's changes. Serialise
|
|
43
|
+
* them yourself (e.g. a Redis lock), or use a store with one record per type such as
|
|
44
|
+
* PostgresCustomEntityStore.
|
|
43
45
|
*/
|
|
44
46
|
export class KeyValueCustomEntityStore {
|
|
45
47
|
#kv;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type CustomEntityType } from '../learning/custom-entity-type.js';
|
|
2
|
+
import { type CustomEntityStore } from '../learning/store.js';
|
|
3
|
+
import { type VaultStorage } from '../vault/vault.js';
|
|
4
|
+
/** What a query function resolves to: the result rows as objects keyed by column name. */
|
|
5
|
+
export interface PostgresQueryResult {
|
|
6
|
+
rows: readonly unknown[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Runs one parameterised statement (`$1`, `$2`, ...) and resolves with its rows. The shape of `pg`'s
|
|
10
|
+
* `query()`: pass `pool.query.bind(pool)`, `client.query.bind(client)` or `(text, params) => pool.query(text, params)`.
|
|
11
|
+
* For another driver, wrap it, e.g. postgres.js: `(text, params) => sql.unsafe(text, params).then((rows) => ({ rows }))`.
|
|
12
|
+
*
|
|
13
|
+
* The stores never open or end transactions: every call is one statement, so they take part in
|
|
14
|
+
* whatever transaction the connection behind the function is in.
|
|
15
|
+
*/
|
|
16
|
+
export type PostgresQuery = (text: string, params: unknown[]) => Promise<PostgresQueryResult>;
|
|
17
|
+
/** Default table of PostgresVaultStorage. */
|
|
18
|
+
export declare const DEFAULT_VAULT_TABLE = "pii_shield_vault";
|
|
19
|
+
/** Default table of PostgresCustomEntityStore. */
|
|
20
|
+
export declare const DEFAULT_TYPES_TABLE = "pii_shield_learned_types";
|
|
21
|
+
export interface PostgresStoreOptions {
|
|
22
|
+
query: PostgresQuery;
|
|
23
|
+
/**
|
|
24
|
+
* Table name, optionally schema-qualified (`app.pii_vault`). Each part must be a plain identifier
|
|
25
|
+
* (`[A-Za-z_][A-Za-z0-9_]*`, at most 48 characters); it is always double-quoted, so the case is kept.
|
|
26
|
+
*/
|
|
27
|
+
table?: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Stores vault ciphertext in a table (`id text primary key, payload bytea, expires_at timestamptz`, see
|
|
31
|
+
* postgresSchema()). Use it behind EncryptedVault, never on its own: the database then only sees
|
|
32
|
+
* ciphertext and the key stays outside it.
|
|
33
|
+
*
|
|
34
|
+
* - The row id is `sha256hex(id)`, like RedisVaultStorage: ids may come from outside.
|
|
35
|
+
* - Expiry uses the database clock (`now()`, the start of the current transaction), not the app clock:
|
|
36
|
+
* several app servers with skewed clocks agree. Reads ignore expired rows; purgeExpired() deletes them,
|
|
37
|
+
* which must happen regularly (storage limitation, Art. 5(1)(e) GDPR).
|
|
38
|
+
*/
|
|
39
|
+
export declare class PostgresVaultStorage implements VaultStorage {
|
|
40
|
+
#private;
|
|
41
|
+
constructor(options: PostgresStoreOptions);
|
|
42
|
+
put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
|
|
43
|
+
get(id: string): Promise<Uint8Array | null>;
|
|
44
|
+
remove(id: string): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Deletes expired rows (by the database clock). Run it regularly, e.g. from a timer, a cron job or
|
|
47
|
+
* `pg_cron`; the HTTP service does it every `PII_SERVICE_VAULT_PURGE_INTERVAL` seconds.
|
|
48
|
+
*
|
|
49
|
+
* @returns the number of deleted rows
|
|
50
|
+
*/
|
|
51
|
+
purgeExpired(): Promise<number>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
|
|
55
|
+
* postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
|
|
56
|
+
* names from any number of processes never lose each other.
|
|
57
|
+
*
|
|
58
|
+
* `data` is the type's JSON (the shape of JsonFileCustomEntityStore's entries); rows are validated with
|
|
59
|
+
* customEntityTypeFromJSON() when read. Examples are plain text and may be personal data: grant access
|
|
60
|
+
* to the table like to other personal data, and remember that a deleted row stays in WAL, backups and,
|
|
61
|
+
* until VACUUM, in the table file.
|
|
62
|
+
*/
|
|
63
|
+
export declare class PostgresCustomEntityStore implements CustomEntityStore {
|
|
64
|
+
#private;
|
|
65
|
+
constructor(options: PostgresStoreOptions);
|
|
66
|
+
all(): Promise<CustomEntityType[]>;
|
|
67
|
+
get(name: string): Promise<CustomEntityType | null>;
|
|
68
|
+
save(type: CustomEntityType): Promise<void>;
|
|
69
|
+
remove(name: string): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
export interface PostgresSchemaOptions {
|
|
72
|
+
/** Vault table (default `pii_shield_vault`); `null` leaves it out. */
|
|
73
|
+
vaultTable?: string | null;
|
|
74
|
+
/** Learned types table (default `pii_shield_learned_types`); `null` leaves it out. */
|
|
75
|
+
typesTable?: string | null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The DDL for both tables, idempotent (`CREATE … IF NOT EXISTS`), for the product's own migrations or
|
|
79
|
+
* `psql`. The library never runs DDL itself. A schema in a qualified name must exist already.
|
|
80
|
+
*
|
|
81
|
+
* The application's database role needs only `SELECT, INSERT, UPDATE, DELETE` on the two tables.
|
|
82
|
+
*/
|
|
83
|
+
export declare function postgresSchema(options?: PostgresSchemaOptions): string;
|
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
* Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
|
|
81
|
+
* postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
|
|
82
|
+
* names from any number of processes never lose each other.
|
|
83
|
+
*
|
|
84
|
+
* `data` is the type's JSON (the shape of JsonFileCustomEntityStore's entries); rows are validated with
|
|
85
|
+
* customEntityTypeFromJSON() when read. Examples are plain text and may be personal data: grant access
|
|
86
|
+
* to the table like to other personal data, and remember that a deleted row stays in WAL, backups and,
|
|
87
|
+
* until VACUUM, in the table file.
|
|
88
|
+
*/
|
|
89
|
+
export class PostgresCustomEntityStore {
|
|
90
|
+
#query;
|
|
91
|
+
#sql;
|
|
92
|
+
constructor(options) {
|
|
93
|
+
this.#query = options.query;
|
|
94
|
+
const table = quoteTable(options.table ?? DEFAULT_TYPES_TABLE);
|
|
95
|
+
this.#sql = {
|
|
96
|
+
all: `SELECT name, data FROM ${table}`,
|
|
97
|
+
get: `SELECT name, data FROM ${table} WHERE name = $1`,
|
|
98
|
+
save: `INSERT INTO ${table} (name, data) VALUES ($1, $2::jsonb) ON CONFLICT (name) DO UPDATE SET data = EXCLUDED.data`,
|
|
99
|
+
remove: `DELETE FROM ${table} WHERE name = $1`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async all() {
|
|
103
|
+
const { rows } = await this.#query(this.#sql.all, []);
|
|
104
|
+
// Sorted here, not with ORDER BY: byte order like the other stores, whatever the column's collation.
|
|
105
|
+
return sortByName(rows.map((row) => typeFromRow(row)));
|
|
106
|
+
}
|
|
107
|
+
async get(name) {
|
|
108
|
+
const { rows } = await this.#query(this.#sql.get, [name]);
|
|
109
|
+
return rows.length === 0 ? null : typeFromRow(rows[0]);
|
|
110
|
+
}
|
|
111
|
+
async save(type) {
|
|
112
|
+
await this.#query(this.#sql.save, [type.name, JSON.stringify(type)]);
|
|
113
|
+
}
|
|
114
|
+
async remove(name) {
|
|
115
|
+
await this.#query(this.#sql.remove, [name]);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The DDL for both tables, idempotent (`CREATE … IF NOT EXISTS`), for the product's own migrations or
|
|
120
|
+
* `psql`. The library never runs DDL itself. A schema in a qualified name must exist already.
|
|
121
|
+
*
|
|
122
|
+
* The application's database role needs only `SELECT, INSERT, UPDATE, DELETE` on the two tables.
|
|
123
|
+
*/
|
|
124
|
+
export function postgresSchema(options = {}) {
|
|
125
|
+
const statements = [];
|
|
126
|
+
const { vaultTable = DEFAULT_VAULT_TABLE, typesTable = DEFAULT_TYPES_TABLE } = options;
|
|
127
|
+
if (vaultTable !== null) {
|
|
128
|
+
const table = quoteTable(vaultTable);
|
|
129
|
+
const index = quoteIdentifier(`${tableName(vaultTable)}_expires_at_idx`);
|
|
130
|
+
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()).';`);
|
|
131
|
+
}
|
|
132
|
+
if (typesTable !== null) {
|
|
133
|
+
const table = quoteTable(typesTable);
|
|
134
|
+
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.';`);
|
|
135
|
+
}
|
|
136
|
+
return `${statements.join('\n')}\n`;
|
|
137
|
+
}
|
|
138
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,47}$/;
|
|
139
|
+
/**
|
|
140
|
+
* `"table"` or `"schema"."table"`, after checking each part against IDENTIFIER. The pattern has no
|
|
141
|
+
* quote, so quoting cannot be escaped; the name is never part of an error message beyond that check.
|
|
142
|
+
*/
|
|
143
|
+
function quoteTable(name) {
|
|
144
|
+
if (typeof name !== 'string') {
|
|
145
|
+
throw new TypeError('The table name must be a string.');
|
|
146
|
+
}
|
|
147
|
+
const parts = name.split('.');
|
|
148
|
+
if (parts.length > 2 || !parts.every((part) => IDENTIFIER.test(part))) {
|
|
149
|
+
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).');
|
|
150
|
+
}
|
|
151
|
+
return parts.map(quoteIdentifier).join('.');
|
|
152
|
+
}
|
|
153
|
+
function quoteIdentifier(identifier) {
|
|
154
|
+
return `"${identifier}"`;
|
|
155
|
+
}
|
|
156
|
+
/** The table part of a (validated) qualified name. */
|
|
157
|
+
function tableName(qualified) {
|
|
158
|
+
return qualified.slice(qualified.lastIndexOf('.') + 1);
|
|
159
|
+
}
|
|
160
|
+
function vaultKey(id) {
|
|
161
|
+
return createHash('sha256').update(id, 'utf8').digest('hex');
|
|
162
|
+
}
|
|
163
|
+
function column(row, name) {
|
|
164
|
+
return typeof row === 'object' && row !== null && Object.hasOwn(row, name)
|
|
165
|
+
? row[name]
|
|
166
|
+
: undefined;
|
|
167
|
+
}
|
|
168
|
+
function typeFromRow(row) {
|
|
169
|
+
let data = column(row, 'data');
|
|
170
|
+
if (typeof data === 'string') {
|
|
171
|
+
// Drivers that do not parse jsonb return text. No cause: V8's JSON.parse() message quotes the text.
|
|
172
|
+
try {
|
|
173
|
+
data = JSON.parse(data);
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
data = undefined;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (typeof data !== 'object' || data === null) {
|
|
180
|
+
throw corrupt();
|
|
181
|
+
}
|
|
182
|
+
const type = customEntityTypeFromJSON(data);
|
|
183
|
+
if (type.name !== column(row, 'name')) {
|
|
184
|
+
throw corrupt();
|
|
185
|
+
}
|
|
186
|
+
return type;
|
|
187
|
+
}
|
|
188
|
+
function corrupt() {
|
|
189
|
+
return new PiiShieldError('The learned types table contains a row that is not a learned type.', 'LEARNING_STORE_CORRUPT');
|
|
190
|
+
}
|
package/dist/server/config.d.ts
CHANGED
|
@@ -11,13 +11,25 @@ export interface EnvService {
|
|
|
11
11
|
port: number;
|
|
12
12
|
/** Notes for the operator (stderr), e.g. that mappings do not survive a restart. Never secrets. */
|
|
13
13
|
notes: string[];
|
|
14
|
-
/**
|
|
14
|
+
/** Stops background tasks (vault purge) and closes connections the configuration opened (Redis, Postgres). */
|
|
15
15
|
close(): Promise<void>;
|
|
16
16
|
}
|
|
17
|
+
/** Background work of the service; its errors go to `onError`. */
|
|
18
|
+
export type BackgroundTask = 'vault-purge' | 'database';
|
|
19
|
+
export interface ServiceFromEnvOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Errors of background work: the periodic vault purge and idle database connections. Default:
|
|
22
|
+
* name and code to stderr. The error may carry driver details (a pg error's `detail` can quote row
|
|
23
|
+
* values): log name and code, not the whole error.
|
|
24
|
+
*/
|
|
25
|
+
onError?: (error: unknown, task: BackgroundTask) => void;
|
|
26
|
+
}
|
|
17
27
|
/**
|
|
18
28
|
* Builds the service from environment variables (names as in the PHP service where they exist; see
|
|
19
29
|
* docs/server.md). Used by the `pii-shield` CLI.
|
|
20
30
|
*
|
|
21
31
|
* @throws ConfigError
|
|
22
32
|
*/
|
|
23
|
-
export declare function serviceFromEnv(env?: Readonly<Record<string, string | undefined
|
|
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;
|
package/dist/server/config.js
CHANGED
|
@@ -18,7 +18,7 @@ export class ConfigError extends Error {
|
|
|
18
18
|
*
|
|
19
19
|
* @throws ConfigError
|
|
20
20
|
*/
|
|
21
|
-
export async function serviceFromEnv(env = process.env) {
|
|
21
|
+
export async function serviceFromEnv(env = process.env, options = {}) {
|
|
22
22
|
const get = (name) => {
|
|
23
23
|
const value = env[name];
|
|
24
24
|
return value === undefined || value === '' ? undefined : value;
|
|
@@ -42,6 +42,56 @@ export async function serviceFromEnv(env = process.env) {
|
|
|
42
42
|
}
|
|
43
43
|
return redis;
|
|
44
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;
|
|
45
95
|
try {
|
|
46
96
|
// Vault
|
|
47
97
|
const keyBase64 = get('PII_SERVICE_VAULT_KEY');
|
|
@@ -63,15 +113,50 @@ export async function serviceFromEnv(env = process.env) {
|
|
|
63
113
|
storage = new MemoryVaultStorage();
|
|
64
114
|
notes.push('Vault: in memory; mappings are lost on restart.');
|
|
65
115
|
}
|
|
66
|
-
else if (vaultStore === 'redis') {
|
|
116
|
+
else if (vaultStore === 'redis' || vaultStore === 'postgres') {
|
|
67
117
|
if (keyBase64 === undefined) {
|
|
68
|
-
throw new ConfigError(
|
|
118
|
+
throw new ConfigError(`The ${vaultStore} vault store needs PII_SERVICE_VAULT_KEY, or mappings cannot be read after a restart.`);
|
|
119
|
+
}
|
|
120
|
+
if (vaultStore === 'redis') {
|
|
121
|
+
const { RedisVaultStorage } = await import('../vault-redis/index.js');
|
|
122
|
+
storage = new RedisVaultStorage({ client: await connectRedis() });
|
|
123
|
+
}
|
|
124
|
+
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
|
+
}
|
|
69
156
|
}
|
|
70
|
-
const { RedisVaultStorage } = await import('../vault-redis/index.js');
|
|
71
|
-
storage = new RedisVaultStorage({ client: await connectRedis() });
|
|
72
157
|
}
|
|
73
158
|
else {
|
|
74
|
-
throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory" or "
|
|
159
|
+
throw new ConfigError('PII_SERVICE_VAULT_STORE must be "memory", "redis" or "postgres".');
|
|
75
160
|
}
|
|
76
161
|
const vaultTtl = integer(get('PII_SERVICE_VAULT_TTL'), 'PII_SERVICE_VAULT_TTL', ServiceApi.DEFAULT_VAULT_TTL);
|
|
77
162
|
// Learned types
|
|
@@ -91,15 +176,19 @@ export async function serviceFromEnv(env = process.env) {
|
|
|
91
176
|
else if (learnedStore === 'redis') {
|
|
92
177
|
store = new KeyValueCustomEntityStore(await connectRedis());
|
|
93
178
|
}
|
|
179
|
+
else if (learnedStore === 'postgres') {
|
|
180
|
+
const { PostgresCustomEntityStore } = await import('../postgres/index.js');
|
|
181
|
+
store = new PostgresCustomEntityStore({ query: await connectPostgres() });
|
|
182
|
+
}
|
|
94
183
|
else {
|
|
95
|
-
throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory" or "
|
|
184
|
+
throw new ConfigError('PII_SERVICE_LEARNED_STORE must be "file", "memory", "redis" or "postgres".');
|
|
96
185
|
}
|
|
97
186
|
let learner;
|
|
98
187
|
try {
|
|
99
188
|
learner = await EntityLearner.create({ store });
|
|
100
189
|
}
|
|
101
190
|
catch (e) {
|
|
102
|
-
throw new ConfigError(`The learned types cannot be read: ${
|
|
191
|
+
throw new ConfigError(`The learned types cannot be read: ${safeMessage(e)}`);
|
|
103
192
|
}
|
|
104
193
|
// Model
|
|
105
194
|
let modelDetector;
|
|
@@ -166,15 +255,21 @@ export async function serviceFromEnv(env = process.env) {
|
|
|
166
255
|
port: integer(get('PII_SERVICE_PORT'), 'PII_SERVICE_PORT', 8088, 0),
|
|
167
256
|
notes,
|
|
168
257
|
close: async () => {
|
|
169
|
-
|
|
258
|
+
clearInterval(purgeTimer);
|
|
259
|
+
await purging;
|
|
260
|
+
await Promise.all([redis?.quit(), pool?.end()]);
|
|
170
261
|
},
|
|
171
262
|
};
|
|
172
263
|
}
|
|
173
264
|
catch (e) {
|
|
174
|
-
|
|
265
|
+
clearInterval(purgeTimer);
|
|
266
|
+
await purging;
|
|
267
|
+
await Promise.all([redis?.quit().catch(() => undefined), pool?.end().catch(() => undefined)]);
|
|
175
268
|
throw e;
|
|
176
269
|
}
|
|
177
270
|
}
|
|
271
|
+
/** Seconds between two purges of expired vault rows (Postgres). */
|
|
272
|
+
export const DEFAULT_PURGE_INTERVAL = 300;
|
|
178
273
|
function integer(value, name, fallback, min = 1) {
|
|
179
274
|
if (value === undefined) {
|
|
180
275
|
return fallback;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { CustomEntityStore } from '../learning/store.js';
|
|
2
|
+
import type { VaultStorage } from '../vault/vault.js';
|
|
3
|
+
/** Which rules of a conformance suite ran and which were skipped for lack of an option. */
|
|
4
|
+
export interface VerifyReport {
|
|
5
|
+
readonly passed: readonly string[];
|
|
6
|
+
/** Rules that need an option the caller did not give (e.g. `expire`), with the option's name. */
|
|
7
|
+
readonly skipped: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
/** A function that returns a store; it may be async. */
|
|
10
|
+
type Factory<S> = () => S | Promise<S>;
|
|
11
|
+
export interface VerifyVaultStorageOptions<S extends VaultStorage = VaultStorage> {
|
|
12
|
+
/**
|
|
13
|
+
* Makes the entry `id` (written through `storage`) expired, as if its TTL had passed. Needed for the
|
|
14
|
+
* expiry rules, because a backend that keeps time itself (a database's `now()`, Redis) cannot be
|
|
15
|
+
* given a fake clock. Examples: advance an injected clock; for Postgres
|
|
16
|
+
* `UPDATE … SET expires_at = now() - interval '1 second' WHERE id = <hashed id>`.
|
|
17
|
+
* Expiring more than this entry (advancing a shared clock) is fine.
|
|
18
|
+
*/
|
|
19
|
+
expire?: (storage: S, id: string) => void | Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Without `expire`: test expiry with a real TTL of 1 second and a wait of 1.5 seconds. Slow, so it
|
|
22
|
+
* is opt-in. Without either option the expiry rules are skipped (see the report).
|
|
23
|
+
*/
|
|
24
|
+
realTimeExpiry?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Another instance over the same backend as `storage` (another connection, another process's
|
|
27
|
+
* view). Enables the rule that entries written through one instance are read through another.
|
|
28
|
+
*/
|
|
29
|
+
secondInstance?: (storage: S) => VaultStorage | Promise<VaultStorage>;
|
|
30
|
+
}
|
|
31
|
+
export interface VerifyCustomEntityStoreOptions<S extends CustomEntityStore = CustomEntityStore> {
|
|
32
|
+
/**
|
|
33
|
+
* Another instance over the same backend as `store`. Enables the rule that concurrent writes of
|
|
34
|
+
* different names through two instances are all kept (which KeyValueCustomEntityStore does not do).
|
|
35
|
+
*/
|
|
36
|
+
secondInstance?: (store: S) => CustomEntityStore | Promise<CustomEntityStore>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Checks that a VaultStorage keeps the contract documented on the interface: unknown and expired ids
|
|
40
|
+
* give null, payloads are binary-safe and copied, put() overwrites, remove() of an unknown id is a
|
|
41
|
+
* no-op, TTLs are validated, ids are independent of each other.
|
|
42
|
+
*
|
|
43
|
+
* `factory` is called once per rule. Instances may share one backend: the ids of a run are random,
|
|
44
|
+
* so a shared database or Redis needs no cleanup between rules. Data is synthetic.
|
|
45
|
+
*
|
|
46
|
+
* Runs under any test runner: `await verifyVaultStorage(() => new MyStorage())` inside a test.
|
|
47
|
+
*
|
|
48
|
+
* @returns which rules passed and which were skipped for lack of an option
|
|
49
|
+
* @throws AssertionError naming the first rule that failed (the original error is its `cause`)
|
|
50
|
+
*/
|
|
51
|
+
export declare function verifyVaultStorage<S extends VaultStorage>(factory: Factory<S>, options?: VerifyVaultStorageOptions<S>): Promise<VerifyReport>;
|
|
52
|
+
/**
|
|
53
|
+
* Checks that a CustomEntityStore keeps the contract documented on the interface: get() and save()
|
|
54
|
+
* round-trip types exactly, save() replaces, all() is sorted by name in byte order, remove() of an
|
|
55
|
+
* unknown name is a no-op, and concurrent writes of different names are all kept.
|
|
56
|
+
*
|
|
57
|
+
* `factory` is called once per rule and must return an empty store (e.g. truncate the table first).
|
|
58
|
+
* Data is synthetic.
|
|
59
|
+
*
|
|
60
|
+
* @returns which rules passed and which were skipped for lack of an option
|
|
61
|
+
* @throws AssertionError naming the first rule that failed (the original error is its `cause`)
|
|
62
|
+
*/
|
|
63
|
+
export declare function verifyCustomEntityStore<S extends CustomEntityStore>(factory: Factory<S>, options?: VerifyCustomEntityStoreOptions<S>): Promise<VerifyReport>;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import assert, { AssertionError } from 'node:assert/strict';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
+
import { defineCustomEntityType } from '../learning/custom-entity-type.js';
|
|
5
|
+
/**
|
|
6
|
+
* Checks that a VaultStorage keeps the contract documented on the interface: unknown and expired ids
|
|
7
|
+
* give null, payloads are binary-safe and copied, put() overwrites, remove() of an unknown id is a
|
|
8
|
+
* no-op, TTLs are validated, ids are independent of each other.
|
|
9
|
+
*
|
|
10
|
+
* `factory` is called once per rule. Instances may share one backend: the ids of a run are random,
|
|
11
|
+
* so a shared database or Redis needs no cleanup between rules. Data is synthetic.
|
|
12
|
+
*
|
|
13
|
+
* Runs under any test runner: `await verifyVaultStorage(() => new MyStorage())` inside a test.
|
|
14
|
+
*
|
|
15
|
+
* @returns which rules passed and which were skipped for lack of an option
|
|
16
|
+
* @throws AssertionError naming the first rule that failed (the original error is its `cause`)
|
|
17
|
+
*/
|
|
18
|
+
export async function verifyVaultStorage(factory, options = {}) {
|
|
19
|
+
const { expire, realTimeExpiry = false, secondInstance } = options;
|
|
20
|
+
const run = randomBytes(6).toString('hex');
|
|
21
|
+
const id = (name) => `pii-shield-conformance-${run}-${name}`;
|
|
22
|
+
const bytes = (...values) => Uint8Array.from(values);
|
|
23
|
+
const assertBytes = (actual, expected, what) => {
|
|
24
|
+
assert.ok(actual instanceof Uint8Array, `${what}: expected a Uint8Array, got ${describe(actual)}`);
|
|
25
|
+
assert.deepEqual(new Uint8Array(actual), expected, what);
|
|
26
|
+
};
|
|
27
|
+
const canExpire = expire !== undefined || realTimeExpiry;
|
|
28
|
+
/** Puts an entry and makes it expire, by the hook or by waiting. */
|
|
29
|
+
const putExpired = async (storage, key, payload) => {
|
|
30
|
+
if (expire !== undefined) {
|
|
31
|
+
await storage.put(key, payload, 60);
|
|
32
|
+
await expire(storage, key);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
await storage.put(key, payload, 1);
|
|
36
|
+
await sleep(1500);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const rules = [
|
|
40
|
+
{
|
|
41
|
+
name: 'get() of an unknown id gives null',
|
|
42
|
+
run: async () => {
|
|
43
|
+
assert.equal(await (await factory()).get(id('unknown')), null);
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: 'put() then get() gives the payload back',
|
|
48
|
+
run: async () => {
|
|
49
|
+
const storage = await factory();
|
|
50
|
+
const payload = Uint8Array.from({ length: 256 }, (_, i) => i);
|
|
51
|
+
await storage.put(id('a'), payload, 60);
|
|
52
|
+
assertBytes(await storage.get(id('a')), payload, 'every byte value 0..255');
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'payloads of any length are binary-safe',
|
|
57
|
+
run: async () => {
|
|
58
|
+
const storage = await factory();
|
|
59
|
+
const cases = [
|
|
60
|
+
['empty', new Uint8Array(0)],
|
|
61
|
+
['zero bytes', new Uint8Array(32)],
|
|
62
|
+
['invalid UTF-8', bytes(0xc3, 0x28, 0xff, 0xfe, 0x00, 0xed, 0xa0, 0x80)],
|
|
63
|
+
['64 KiB', new Uint8Array(randomBytes(64 * 1024))],
|
|
64
|
+
];
|
|
65
|
+
for (const [name, payload] of cases) {
|
|
66
|
+
await storage.put(id(name), payload, 60);
|
|
67
|
+
}
|
|
68
|
+
for (const [name, payload] of cases) {
|
|
69
|
+
assertBytes(await storage.get(id(name)), payload, name);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'put() stores only the bytes of a view, not its whole buffer',
|
|
75
|
+
run: async () => {
|
|
76
|
+
const storage = await factory();
|
|
77
|
+
await storage.put(id('view'), bytes(9, 1, 2, 3, 9).subarray(1, 4), 60);
|
|
78
|
+
assertBytes(await storage.get(id('view')), bytes(1, 2, 3), 'subarray(1, 4)');
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: 'payloads are copied in and out',
|
|
83
|
+
run: async () => {
|
|
84
|
+
const storage = await factory();
|
|
85
|
+
const payload = bytes(1, 2, 3);
|
|
86
|
+
await storage.put(id('copy'), payload, 60);
|
|
87
|
+
payload.fill(0);
|
|
88
|
+
const first = await storage.get(id('copy'));
|
|
89
|
+
assertBytes(first, bytes(1, 2, 3), 'after changing the array passed to put()');
|
|
90
|
+
first?.fill(0);
|
|
91
|
+
assertBytes(await storage.get(id('copy')), bytes(1, 2, 3), 'after changing the array get() returned');
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: 'put() overwrites an existing entry',
|
|
96
|
+
run: async () => {
|
|
97
|
+
const storage = await factory();
|
|
98
|
+
await storage.put(id('overwrite'), bytes(1), 60);
|
|
99
|
+
await storage.put(id('overwrite'), bytes(2, 2), 120);
|
|
100
|
+
assertBytes(await storage.get(id('overwrite')), bytes(2, 2), 'second put()');
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
name: 'ids are independent and may contain any characters',
|
|
105
|
+
run: async () => {
|
|
106
|
+
const storage = await factory();
|
|
107
|
+
const ids = [
|
|
108
|
+
'id-1',
|
|
109
|
+
'ID-1',
|
|
110
|
+
'id-1 ',
|
|
111
|
+
'',
|
|
112
|
+
'ü-✓-😀',
|
|
113
|
+
'a/b:c@d*?%_\\',
|
|
114
|
+
"x'; DELETE FROM vault; --",
|
|
115
|
+
'\u0000nul',
|
|
116
|
+
'x'.repeat(2000),
|
|
117
|
+
].map((suffix) => id(suffix));
|
|
118
|
+
for (const [i, key] of ids.entries()) {
|
|
119
|
+
await storage.put(key, bytes(i, 0xff), 60);
|
|
120
|
+
}
|
|
121
|
+
for (const [i, key] of ids.entries()) {
|
|
122
|
+
assertBytes(await storage.get(key), bytes(i, 0xff), `id #${String(i + 1)}`);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: 'remove() deletes only its entry, remove() of an unknown id is a no-op',
|
|
128
|
+
run: async () => {
|
|
129
|
+
const storage = await factory();
|
|
130
|
+
await storage.put(id('keep'), bytes(1), 60);
|
|
131
|
+
await storage.put(id('remove'), bytes(2), 60);
|
|
132
|
+
await storage.remove(id('remove'));
|
|
133
|
+
await storage.remove(id('remove'));
|
|
134
|
+
await storage.remove(id('never-stored'));
|
|
135
|
+
assert.equal(await storage.get(id('remove')), null, 'removed entry');
|
|
136
|
+
assertBytes(await storage.get(id('keep')), bytes(1), 'other entry');
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: 'put() rejects a TTL that is not a positive integer, and stores nothing',
|
|
141
|
+
run: async () => {
|
|
142
|
+
const storage = await factory();
|
|
143
|
+
for (const ttl of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
|
144
|
+
await assert.rejects(() => storage.put(id('ttl'), bytes(1), ttl), (e) => e instanceof RangeError || e instanceof TypeError, `TTL ${String(ttl)} must reject the Promise with a RangeError or TypeError`);
|
|
145
|
+
}
|
|
146
|
+
assert.equal(await storage.get(id('ttl')), null);
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
name: 'get() of an expired entry gives null',
|
|
151
|
+
missing: canExpire ? undefined : 'expire',
|
|
152
|
+
run: async () => {
|
|
153
|
+
const storage = await factory();
|
|
154
|
+
await putExpired(storage, id('expired'), bytes(1));
|
|
155
|
+
assert.equal(await storage.get(id('expired')), null);
|
|
156
|
+
},
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
name: 'put() over an expired entry stores it again',
|
|
160
|
+
missing: canExpire ? undefined : 'expire',
|
|
161
|
+
run: async () => {
|
|
162
|
+
const storage = await factory();
|
|
163
|
+
await putExpired(storage, id('again'), bytes(1));
|
|
164
|
+
await storage.put(id('again'), bytes(2), 60);
|
|
165
|
+
assertBytes(await storage.get(id('again')), bytes(2), 'second put()');
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
name: 'entries are shared between instances over the same backend',
|
|
170
|
+
missing: secondInstance === undefined ? 'secondInstance' : undefined,
|
|
171
|
+
run: async () => {
|
|
172
|
+
if (secondInstance === undefined) {
|
|
173
|
+
return; // skipped, see missing
|
|
174
|
+
}
|
|
175
|
+
const storage = await factory();
|
|
176
|
+
const other = await secondInstance(storage);
|
|
177
|
+
await storage.put(id('shared'), bytes(7), 60);
|
|
178
|
+
assertBytes(await other.get(id('shared')), bytes(7), 'read through the second instance');
|
|
179
|
+
await other.remove(id('shared'));
|
|
180
|
+
assert.equal(await storage.get(id('shared')), null, 'removed through the second instance');
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
];
|
|
184
|
+
return runRules('VaultStorage', rules);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Checks that a CustomEntityStore keeps the contract documented on the interface: get() and save()
|
|
188
|
+
* round-trip types exactly, save() replaces, all() is sorted by name in byte order, remove() of an
|
|
189
|
+
* unknown name is a no-op, and concurrent writes of different names are all kept.
|
|
190
|
+
*
|
|
191
|
+
* `factory` is called once per rule and must return an empty store (e.g. truncate the table first).
|
|
192
|
+
* Data is synthetic.
|
|
193
|
+
*
|
|
194
|
+
* @returns which rules passed and which were skipped for lack of an option
|
|
195
|
+
* @throws AssertionError naming the first rule that failed (the original error is its `cause`)
|
|
196
|
+
*/
|
|
197
|
+
export async function verifyCustomEntityStore(factory, options = {}) {
|
|
198
|
+
const { secondInstance } = options;
|
|
199
|
+
const names = (types) => types.map((t) => t.name);
|
|
200
|
+
const rules = [
|
|
201
|
+
{
|
|
202
|
+
name: 'all() of an empty store gives [] (the factory must return an empty store)',
|
|
203
|
+
run: async () => {
|
|
204
|
+
assert.deepEqual(await (await factory()).all(), []);
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
name: 'get() of an unknown name gives null',
|
|
209
|
+
run: async () => {
|
|
210
|
+
assert.equal(await (await factory()).get('UNKNOWN_TYPE'), null);
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
name: 'save() then get() and all() give the type back unchanged',
|
|
215
|
+
run: async () => {
|
|
216
|
+
const store = await factory();
|
|
217
|
+
const types = [syntheticType('TEST_CODE'), richType()];
|
|
218
|
+
for (const type of types) {
|
|
219
|
+
await store.save(type);
|
|
220
|
+
}
|
|
221
|
+
for (const type of types) {
|
|
222
|
+
assert.deepEqual(await store.get(type.name), type, type.name);
|
|
223
|
+
}
|
|
224
|
+
assert.deepEqual(await store.all(), sortedByByteOrder(types));
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
name: 'save() replaces the type with the same name',
|
|
229
|
+
run: async () => {
|
|
230
|
+
const store = await factory();
|
|
231
|
+
await store.save(syntheticType('TEST_CODE'));
|
|
232
|
+
const replacement = syntheticType('TEST_CODE', 'Replaced synthetic test type');
|
|
233
|
+
await store.save(replacement);
|
|
234
|
+
assert.deepEqual(await store.get('TEST_CODE'), replacement);
|
|
235
|
+
assert.deepEqual(await store.all(), [replacement]);
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
name: 'all() is sorted by name in byte order',
|
|
240
|
+
run: async () => {
|
|
241
|
+
const store = await factory();
|
|
242
|
+
// A locale collation would sort A_CODE before AB_CODE and B_CODE before B2_CODE.
|
|
243
|
+
for (const name of ['ZETA_CODE', 'A_CODE', 'B_CODE', 'AB_CODE', 'B2_CODE']) {
|
|
244
|
+
await store.save(syntheticType(name));
|
|
245
|
+
}
|
|
246
|
+
assert.deepEqual(names(await store.all()), ['AB_CODE', 'A_CODE', 'B2_CODE', 'B_CODE', 'ZETA_CODE']);
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
name: 'remove() deletes only its type, remove() of an unknown name is a no-op',
|
|
251
|
+
run: async () => {
|
|
252
|
+
const store = await factory();
|
|
253
|
+
await store.save(syntheticType('KEEP_CODE'));
|
|
254
|
+
await store.save(syntheticType('DROP_CODE'));
|
|
255
|
+
await store.remove('DROP_CODE');
|
|
256
|
+
await store.remove('DROP_CODE');
|
|
257
|
+
await store.remove('NEVER_SAVED');
|
|
258
|
+
assert.equal(await store.get('DROP_CODE'), null, 'removed type');
|
|
259
|
+
assert.deepEqual(names(await store.all()), ['KEEP_CODE']);
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
name: 'concurrent writes of different names are all kept',
|
|
264
|
+
run: async () => {
|
|
265
|
+
const store = await factory();
|
|
266
|
+
await Promise.all(range(8).map((i) => store.save(syntheticType(`CODE_${String(i)}`))));
|
|
267
|
+
assert.deepEqual(names(await store.all()), range(8).map((i) => `CODE_${String(i)}`));
|
|
268
|
+
await Promise.all([
|
|
269
|
+
...range(4).map((i) => store.remove(`CODE_${String(i)}`)),
|
|
270
|
+
...range(4).map((i) => store.save(syntheticType(`NEW_${String(i)}`))),
|
|
271
|
+
]);
|
|
272
|
+
assert.deepEqual(names(await store.all()), [
|
|
273
|
+
...range(4).map((i) => `CODE_${String(i + 4)}`),
|
|
274
|
+
...range(4).map((i) => `NEW_${String(i)}`),
|
|
275
|
+
]);
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
name: 'concurrent writes through two instances over the same backend are all kept',
|
|
280
|
+
missing: secondInstance === undefined ? 'secondInstance' : undefined,
|
|
281
|
+
run: async () => {
|
|
282
|
+
if (secondInstance === undefined) {
|
|
283
|
+
return; // skipped, see missing
|
|
284
|
+
}
|
|
285
|
+
const store = await factory();
|
|
286
|
+
const other = await secondInstance(store);
|
|
287
|
+
await Promise.all(range(8).map((i) => (i % 2 === 0 ? store : other).save(syntheticType(`CODE_${String(i)}`))));
|
|
288
|
+
assert.deepEqual(names(await store.all()), range(8).map((i) => `CODE_${String(i)}`));
|
|
289
|
+
assert.deepEqual(names(await other.all()), range(8).map((i) => `CODE_${String(i)}`));
|
|
290
|
+
},
|
|
291
|
+
},
|
|
292
|
+
];
|
|
293
|
+
return runRules('CustomEntityStore', rules);
|
|
294
|
+
}
|
|
295
|
+
async function runRules(contract, rules) {
|
|
296
|
+
const passed = [];
|
|
297
|
+
const skipped = [];
|
|
298
|
+
for (const rule of rules) {
|
|
299
|
+
if (rule.missing !== undefined) {
|
|
300
|
+
skipped.push(`${rule.name} (needs the option "${rule.missing}")`);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
await rule.run();
|
|
305
|
+
}
|
|
306
|
+
catch (e) {
|
|
307
|
+
const inner = e instanceof AssertionError ? e : undefined;
|
|
308
|
+
const detail = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
309
|
+
const error = new AssertionError({
|
|
310
|
+
message: `${contract} contract violated: ${rule.name}\n${detail}`,
|
|
311
|
+
actual: inner?.actual,
|
|
312
|
+
expected: inner?.expected,
|
|
313
|
+
operator: inner?.operator ?? 'fail',
|
|
314
|
+
});
|
|
315
|
+
error.cause = e;
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
passed.push(rule.name);
|
|
319
|
+
}
|
|
320
|
+
return { passed, skipped };
|
|
321
|
+
}
|
|
322
|
+
function syntheticType(name, description = 'Synthetic test type') {
|
|
323
|
+
return defineCustomEntityType({ name, description, examples: ['TST-0001', 'TST-0002'], pattern: null });
|
|
324
|
+
}
|
|
325
|
+
/** A type with a pattern and characters that JSON, jsonb and text encodings must keep. */
|
|
326
|
+
function richType() {
|
|
327
|
+
return defineCustomEntityType({
|
|
328
|
+
name: 'RICH_TEST_CODE',
|
|
329
|
+
description: 'Synthetische Testart: "Zitat" \\ / & ü ✓ 😀
Ende',
|
|
330
|
+
examples: ['TST-0001', 'TST-9999'],
|
|
331
|
+
counterExamples: ['TSX-0001', 'Ölbaum "Nord" \\ 7 😀
'],
|
|
332
|
+
pattern: String.raw `TST-\d{4}`,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
function sortedByByteOrder(types) {
|
|
336
|
+
return [...types].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
337
|
+
}
|
|
338
|
+
function range(n) {
|
|
339
|
+
return Array.from({ length: n }, (_, i) => i);
|
|
340
|
+
}
|
|
341
|
+
function describe(value) {
|
|
342
|
+
return value === null ? 'null' : typeof value === 'object' ? value.constructor.name : typeof value;
|
|
343
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @waswrongassembled/pii-shield/testing: conformance suites for storage adapters. They check the
|
|
3
|
+
* contracts of `VaultStorage` and `CustomEntityStore` with `node:assert` only, so they run under any test
|
|
4
|
+
* runner (vitest, jest, `node:test`, mocha) without a peer dependency. All test data is synthetic.
|
|
5
|
+
*/
|
|
6
|
+
export { verifyCustomEntityStore, type VerifyCustomEntityStoreOptions, verifyVaultStorage, type VerifyReport, type VerifyVaultStorageOptions, } from './conformance.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @waswrongassembled/pii-shield/testing: conformance suites for storage adapters. They check the
|
|
3
|
+
* contracts of `VaultStorage` and `CustomEntityStore` with `node:assert` only, so they run under any test
|
|
4
|
+
* runner (vitest, jest, `node:test`, mocha) without a peer dependency. All test data is synthetic.
|
|
5
|
+
*/
|
|
6
|
+
export { verifyCustomEntityStore, verifyVaultStorage, } from './conformance.js';
|
package/dist/vault/vault.d.ts
CHANGED
|
@@ -19,13 +19,29 @@ export interface Vault {
|
|
|
19
19
|
delete(id: string): Promise<void>;
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
|
-
* Raw byte storage behind EncryptedVault (PHP's VaultStorageInterface).
|
|
23
|
-
*
|
|
22
|
+
* Raw byte storage behind EncryptedVault (PHP's VaultStorageInterface). Implement this to plug in any
|
|
23
|
+
* backend (Redis, a database, files, ...), and check it with `verifyVaultStorage()` from
|
|
24
|
+
* `@waswrongassembled/pii-shield/testing`.
|
|
25
|
+
*
|
|
26
|
+
* Behind EncryptedVault it only ever receives ciphertext: never use a storage on its own for mappings.
|
|
27
|
+
*
|
|
28
|
+
* Contract every implementation keeps:
|
|
29
|
+
* - Ids are arbitrary strings that may come from outside (a client's `vaultId`): map them to keys
|
|
30
|
+
* safely, e.g. by hashing, never by building a path or a query from them.
|
|
31
|
+
* - Payloads are binary-safe (every byte value, any length) and copied: later changes to the array
|
|
32
|
+
* passed to `put()` or returned by `get()` do not change the stored entry.
|
|
33
|
+
* - `put()` overwrites an existing entry, payload and expiry.
|
|
34
|
+
* - `get()` of an unknown or expired id gives `null`. Expiry is checked on read, not left to a cleanup
|
|
35
|
+
* job; expired entries must still be deleted eventually (storage limitation, Art. 5(1)(e) GDPR).
|
|
36
|
+
* - `remove()` of an unknown id is a no-op.
|
|
37
|
+
* - A TTL that is not a positive integer rejects the Promise (see assertTtl()) before anything is stored.
|
|
24
38
|
*/
|
|
25
39
|
export interface VaultStorage {
|
|
26
40
|
/** @param ttlSeconds positive integer */
|
|
27
41
|
put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
|
|
42
|
+
/** @returns a copy of the payload, or null if the id is unknown or expired */
|
|
28
43
|
get(id: string): Promise<Uint8Array | null>;
|
|
44
|
+
/** Deletes the entry; resolves also if there is none. */
|
|
29
45
|
remove(id: string): Promise<void>;
|
|
30
46
|
}
|
|
31
47
|
/** Current time in milliseconds, like `Date.now` (PHP takes a PSR-20 clock). Inject one in tests. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@waswrongassembled/pii-shield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Reversible PII redaction for LLM applications with DACH recognizers (AT SVNR, IBAN, tax numbers) and checksum validation. Wire-compatible port of clarifile/pii-shield.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
"ai-sdk",
|
|
21
21
|
"mcp",
|
|
22
22
|
"iban",
|
|
23
|
-
"dach"
|
|
23
|
+
"dach",
|
|
24
|
+
"postgres"
|
|
24
25
|
],
|
|
25
26
|
"repository": {
|
|
26
27
|
"type": "git",
|
|
@@ -54,6 +55,14 @@
|
|
|
54
55
|
"types": "./dist/mcp/index.d.ts",
|
|
55
56
|
"default": "./dist/mcp/index.js"
|
|
56
57
|
},
|
|
58
|
+
"./postgres": {
|
|
59
|
+
"types": "./dist/postgres/index.d.ts",
|
|
60
|
+
"default": "./dist/postgres/index.js"
|
|
61
|
+
},
|
|
62
|
+
"./testing": {
|
|
63
|
+
"types": "./dist/testing/index.d.ts",
|
|
64
|
+
"default": "./dist/testing/index.js"
|
|
65
|
+
},
|
|
57
66
|
"./package.json": "./package.json"
|
|
58
67
|
},
|
|
59
68
|
"bin": {
|
|
@@ -88,6 +97,7 @@
|
|
|
88
97
|
"@eslint/js": "^10.0.1",
|
|
89
98
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
90
99
|
"@types/node": "^22.20.5",
|
|
100
|
+
"@types/pg": "8.23.1",
|
|
91
101
|
"@vitest/coverage-v8": "^5.1.1",
|
|
92
102
|
"ai": "^7.0.177",
|
|
93
103
|
"ajv": "^8.20.0",
|
|
@@ -95,6 +105,7 @@
|
|
|
95
105
|
"eslint-config-prettier": "^10.1.8",
|
|
96
106
|
"globals": "^17.14.0",
|
|
97
107
|
"ioredis": "^6.0.0",
|
|
108
|
+
"pg": "8.23.1",
|
|
98
109
|
"prettier": "^3.10.1",
|
|
99
110
|
"publint": "^0.3.25",
|
|
100
111
|
"typescript": "~6.0.3",
|
|
@@ -108,7 +119,8 @@
|
|
|
108
119
|
"peerDependencies": {
|
|
109
120
|
"@modelcontextprotocol/sdk": "^1.32.0",
|
|
110
121
|
"ai": "^7.0.0",
|
|
111
|
-
"ioredis": "^5.0.0 || ^6.0.0"
|
|
122
|
+
"ioredis": "^5.0.0 || ^6.0.0",
|
|
123
|
+
"pg": "^8.0.0"
|
|
112
124
|
},
|
|
113
125
|
"peerDependenciesMeta": {
|
|
114
126
|
"@modelcontextprotocol/sdk": {
|
|
@@ -119,6 +131,9 @@
|
|
|
119
131
|
},
|
|
120
132
|
"ioredis": {
|
|
121
133
|
"optional": true
|
|
134
|
+
},
|
|
135
|
+
"pg": {
|
|
136
|
+
"optional": true
|
|
122
137
|
}
|
|
123
138
|
}
|
|
124
139
|
}
|