@waswrongassembled/pii-shield 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/README.md +135 -21
- package/dist/cli.js +37 -5
- package/dist/create-pii-shield.d.ts +91 -0
- package/dist/create-pii-shield.js +124 -0
- package/dist/entity-extractor.d.ts +7 -0
- package/dist/entity-extractor.js +6 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/internal/background.d.ts +27 -0
- package/dist/internal/background.js +47 -0
- package/dist/learning/custom-entity-type.d.ts +14 -4
- package/dist/learning/custom-entity-type.js +23 -5
- package/dist/learning/entity-learner.d.ts +33 -2
- package/dist/learning/entity-learner.js +48 -5
- package/dist/learning/store.d.ts +26 -5
- package/dist/learning/store.js +4 -2
- package/dist/pii-masker.js +2 -1
- package/dist/pii-shield.js +2 -1
- package/dist/postgres/index.d.ts +103 -0
- package/dist/postgres/index.js +204 -0
- package/dist/redaction.d.ts +16 -2
- package/dist/redaction.js +22 -10
- package/dist/server/config.d.ts +16 -7
- package/dist/server/config.js +78 -126
- package/dist/server/connections.d.ts +34 -0
- package/dist/server/connections.js +99 -0
- package/dist/server/doctor.d.ts +28 -0
- package/dist/server/doctor.js +438 -0
- package/dist/server/env.d.ts +62 -0
- package/dist/server/env.js +197 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/testing/conformance.d.ts +64 -0
- package/dist/testing/conformance.js +348 -0
- package/dist/testing/index.d.ts +6 -0
- package/dist/testing/index.js +6 -0
- package/dist/vault/encrypted-vault.d.ts +39 -2
- package/dist/vault/encrypted-vault.js +96 -13
- package/dist/vault/memory-vault-storage.d.ts +8 -1
- package/dist/vault/memory-vault-storage.js +20 -8
- package/dist/vault/vault.d.ts +18 -2
- package/dist/vault-redis/index.d.ts +14 -0
- package/dist/vault-redis/index.js +8 -0
- package/docs/openapi.yaml +8 -2
- package/package.json +18 -3
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* The public API is ported phase by phase, see docs/PLAN.md.
|
|
5
5
|
*/
|
|
6
6
|
export { type AsyncDetector, type DetectOptions, type Detector, type DetectorFunction, isAsyncDetector, type Validator, } from './detector.js';
|
|
7
|
+
export { type BackgroundTask, createPiiShield, type CreatePiiShieldOptions, type ManagedPiiShield, type VaultSetup, } from './create-pii-shield.js';
|
|
7
8
|
export { AtSvnrDetector } from './detectors/at-svnr.js';
|
|
8
9
|
export { BirthDateDetector } from './detectors/birth-date.js';
|
|
9
10
|
export { EmailDetector, type ContactDetectorOptions } from './detectors/email.js';
|
|
@@ -19,8 +20,8 @@ export { defaultDetectors, EntityExtractor, surname, type EntityExtractorOptions
|
|
|
19
20
|
export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
|
|
20
21
|
export { DetectionError, type DetectionErrorCode, LearningError, type LearningErrorCode, PiiShieldError, VaultError, type VaultErrorCode, } from './errors.js';
|
|
21
22
|
export { CustomEntityDetector, LearnedTypesDetector } from './learning/custom-entity-detector.js';
|
|
22
|
-
export { CUSTOM_ENTITY_TYPE_LIMITS, type CustomEntityType, customEntityTypeFromJSON, type CustomEntityTypeInit, defineCustomEntityType, } from './learning/custom-entity-type.js';
|
|
23
|
-
export { EntityLearner, type EntityLearnerOptions, type LearningResult } from './learning/entity-learner.js';
|
|
23
|
+
export { CUSTOM_ENTITY_TYPE_LIMITS, type CustomEntityType, customEntityTypeFromJSON, type CustomEntityTypeInit, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
|
|
24
|
+
export { type DropExamplesResult, EntityLearner, type EntityLearnerOptions, type LearningResult, } from './learning/entity-learner.js';
|
|
24
25
|
export { JsonFileCustomEntityStore, type JsonFileCustomEntityStoreOptions } from './learning/json-file-store.js';
|
|
25
26
|
export { patternViolation } from './learning/pattern-grammar.js';
|
|
26
27
|
export { learnPattern } from './learning/pattern-learner.js';
|
|
@@ -36,7 +37,7 @@ export { foundTypes, type PlaceholderMapping, type RedactionResult, type Redacto
|
|
|
36
37
|
export { isValidAtSvnr } from './validators/at-svnr.js';
|
|
37
38
|
export { isValidDeTaxId } from './validators/de-tax-id.js';
|
|
38
39
|
export { isValidIban } from './validators/iban.js';
|
|
39
|
-
export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
|
|
40
|
+
export { EncryptedVault, type EncryptedVaultOptions, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
|
|
40
41
|
export { InMemoryVault, type InMemoryVaultOptions } from './vault/in-memory-vault.js';
|
|
41
42
|
export { MemoryVaultStorage, type MemoryVaultStorageOptions } from './vault/memory-vault-storage.js';
|
|
42
43
|
export type { Clock, Vault, VaultStorage } from './vault/vault.js';
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* The public API is ported phase by phase, see docs/PLAN.md.
|
|
5
5
|
*/
|
|
6
6
|
export { isAsyncDetector, } from './detector.js';
|
|
7
|
+
export { createPiiShield, } from './create-pii-shield.js';
|
|
7
8
|
export { AtSvnrDetector } from './detectors/at-svnr.js';
|
|
8
9
|
export { BirthDateDetector } from './detectors/birth-date.js';
|
|
9
10
|
export { EmailDetector } from './detectors/email.js';
|
|
@@ -19,8 +20,8 @@ export { defaultDetectors, EntityExtractor, surname } from './entity-extractor.j
|
|
|
19
20
|
export { ENTITY_TYPES, EntityType, isEntityType } from './entity-type.js';
|
|
20
21
|
export { DetectionError, LearningError, PiiShieldError, VaultError, } from './errors.js';
|
|
21
22
|
export { CustomEntityDetector, LearnedTypesDetector } from './learning/custom-entity-detector.js';
|
|
22
|
-
export { CUSTOM_ENTITY_TYPE_LIMITS, customEntityTypeFromJSON, defineCustomEntityType, } from './learning/custom-entity-type.js';
|
|
23
|
-
export { EntityLearner } from './learning/entity-learner.js';
|
|
23
|
+
export { CUSTOM_ENTITY_TYPE_LIMITS, customEntityTypeFromJSON, defineCustomEntityType, withoutExamples, } from './learning/custom-entity-type.js';
|
|
24
|
+
export { EntityLearner, } from './learning/entity-learner.js';
|
|
24
25
|
export { JsonFileCustomEntityStore } from './learning/json-file-store.js';
|
|
25
26
|
export { patternViolation } from './learning/pattern-grammar.js';
|
|
26
27
|
export { learnPattern } from './learning/pattern-learner.js';
|
|
@@ -35,6 +36,6 @@ export { foundTypes, restorePlaceholders, } from './redaction.js';
|
|
|
35
36
|
export { isValidAtSvnr } from './validators/at-svnr.js';
|
|
36
37
|
export { isValidDeTaxId } from './validators/de-tax-id.js';
|
|
37
38
|
export { isValidIban } from './validators/iban.js';
|
|
38
|
-
export { EncryptedVault, generateVaultKey, parseVaultKey, } from './vault/encrypted-vault.js';
|
|
39
|
+
export { EncryptedVault, generateVaultKey, parseVaultKey, previousVaultKeysFromEnv, vaultKeyFromEnv, } from './vault/encrypted-vault.js';
|
|
39
40
|
export { InMemoryVault } from './vault/in-memory-vault.js';
|
|
40
41
|
export { MemoryVaultStorage } from './vault/memory-vault-storage.js';
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background work shared by createPiiShield() and the service (serviceFromEnv()): the periodic purge of
|
|
3
|
+
* expired vault entries and the default report of its errors.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* `Name CODE` of an error, for log lines. Never the message: driver and provider messages can quote
|
|
7
|
+
* values (a pg error's `detail`, a provider echoing the request text).
|
|
8
|
+
*/
|
|
9
|
+
export declare function describeError(error: unknown): string;
|
|
10
|
+
/** The default `onError`: one line to stderr with the task, the error's name and code, nothing else. */
|
|
11
|
+
export declare function reportToStderr(error: unknown, task: string): void;
|
|
12
|
+
/** Seconds between two purges of expired vault entries, unless configured otherwise. */
|
|
13
|
+
export declare const DEFAULT_PURGE_INTERVAL = 300;
|
|
14
|
+
/** The longest purge interval accepted: one day. */
|
|
15
|
+
export declare const MAX_PURGE_INTERVAL = 86400;
|
|
16
|
+
export interface PurgeSchedule {
|
|
17
|
+
/** Stops the timer and waits for a purge that is running. Idempotent. */
|
|
18
|
+
stop(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Runs `purge` at once and then every `intervalSeconds`, on an unref'd timer (it never keeps the process
|
|
22
|
+
* alive). Purges never overlap: a tick while one is running is skipped. Failures go to `onError`.
|
|
23
|
+
*
|
|
24
|
+
* Expired entries are personal data past their storage period (Art. 5(1)(e) GDPR): they must really be
|
|
25
|
+
* deleted, not only hidden by the read filter.
|
|
26
|
+
*/
|
|
27
|
+
export declare function schedulePurge(purge: () => Promise<unknown>, intervalSeconds: number, onError: (error: unknown) => void): PurgeSchedule;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background work shared by createPiiShield() and the service (serviceFromEnv()): the periodic purge of
|
|
3
|
+
* expired vault entries and the default report of its errors.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* `Name CODE` of an error, for log lines. Never the message: driver and provider messages can quote
|
|
7
|
+
* values (a pg error's `detail`, a provider echoing the request text).
|
|
8
|
+
*/
|
|
9
|
+
export function describeError(error) {
|
|
10
|
+
const { name = 'Error', code } = (error ?? {});
|
|
11
|
+
return `${typeof name === 'string' ? name : 'Error'}${typeof code === 'string' ? ` ${code}` : ''}`;
|
|
12
|
+
}
|
|
13
|
+
/** The default `onError`: one line to stderr with the task, the error's name and code, nothing else. */
|
|
14
|
+
export function reportToStderr(error, task) {
|
|
15
|
+
process.stderr.write(`pii-shield: ${task} failed (${describeError(error)})\n`);
|
|
16
|
+
}
|
|
17
|
+
/** Seconds between two purges of expired vault entries, unless configured otherwise. */
|
|
18
|
+
export const DEFAULT_PURGE_INTERVAL = 300;
|
|
19
|
+
/** The longest purge interval accepted: one day. */
|
|
20
|
+
export const MAX_PURGE_INTERVAL = 86_400;
|
|
21
|
+
/**
|
|
22
|
+
* Runs `purge` at once and then every `intervalSeconds`, on an unref'd timer (it never keeps the process
|
|
23
|
+
* alive). Purges never overlap: a tick while one is running is skipped. Failures go to `onError`.
|
|
24
|
+
*
|
|
25
|
+
* Expired entries are personal data past their storage period (Art. 5(1)(e) GDPR): they must really be
|
|
26
|
+
* deleted, not only hidden by the read filter.
|
|
27
|
+
*/
|
|
28
|
+
export function schedulePurge(purge, intervalSeconds, onError) {
|
|
29
|
+
let running;
|
|
30
|
+
const run = () => {
|
|
31
|
+
running ??= purge()
|
|
32
|
+
.then(() => undefined, (e) => {
|
|
33
|
+
onError(e);
|
|
34
|
+
})
|
|
35
|
+
.finally(() => {
|
|
36
|
+
running = undefined;
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
run();
|
|
40
|
+
const timer = setInterval(run, intervalSeconds * 1000).unref();
|
|
41
|
+
return {
|
|
42
|
+
stop: async () => {
|
|
43
|
+
clearInterval(timer);
|
|
44
|
+
await running;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -11,15 +11,16 @@ export declare const CUSTOM_ENTITY_TYPE_LIMITS: Readonly<{
|
|
|
11
11
|
*
|
|
12
12
|
* Validated, frozen data; its JSON form is exactly PHP's `CustomEntityType::toArray()`, so
|
|
13
13
|
* `JSON.stringify(type)` gives the stored shape. Create it with `defineCustomEntityType()` or
|
|
14
|
-
* `customEntityTypeFromJSON()`. Examples are stored, so they must be synthetic or anonymised
|
|
14
|
+
* `customEntityTypeFromJSON()`. Examples are stored, so they must be synthetic or anonymised; a type
|
|
15
|
+
* with a pattern can drop them (`withoutExamples()`, `EntityLearner` option `keepExamples: false`).
|
|
15
16
|
*/
|
|
16
17
|
export interface CustomEntityType {
|
|
17
18
|
/** UPPER_SNAKE_CASE, becomes the placeholder name (⟦NAME_1⟧). */
|
|
18
19
|
readonly name: string;
|
|
19
20
|
readonly description: string;
|
|
20
|
-
/** Values that are this type. */
|
|
21
|
+
/** Values that are this type; empty only for a type with a pattern whose examples were dropped. */
|
|
21
22
|
readonly examples: readonly string[];
|
|
22
|
-
/** Similar values that are not. */
|
|
23
|
+
/** Similar values that are not (empty when the examples were dropped). */
|
|
23
24
|
readonly counterExamples: readonly string[];
|
|
24
25
|
/** Regular expression in PCRE syntax without delimiters (see PatternGrammar), or null for model-only types. */
|
|
25
26
|
readonly pattern: string | null;
|
|
@@ -37,10 +38,19 @@ export interface CustomEntityTypeInit {
|
|
|
37
38
|
* @throws LearningError
|
|
38
39
|
*/
|
|
39
40
|
export declare function defineCustomEntityType(init: CustomEntityTypeInit): CustomEntityType;
|
|
41
|
+
/**
|
|
42
|
+
* The type without its examples and counter-examples, so that only name, description and pattern are
|
|
43
|
+
* stored (data minimisation). Detection by the pattern is unchanged; model-based detection then knows the
|
|
44
|
+
* type only by name and description. PHP cannot read such a type (its `fromArray()` requires an example).
|
|
45
|
+
*
|
|
46
|
+
* @throws LearningError when the type has no pattern: a model-only type is found only through its examples
|
|
47
|
+
*/
|
|
48
|
+
export declare function withoutExamples(type: CustomEntityType): CustomEntityType;
|
|
40
49
|
/**
|
|
41
50
|
* Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
|
|
42
51
|
* fields become empty, non-string list entries are dropped, unknown keys are ignored, an empty pattern
|
|
43
|
-
* means model-only. Every field is then validated.
|
|
52
|
+
* means model-only. Every field is then validated. Unlike PHP, a type with a pattern may have no
|
|
53
|
+
* examples (see withoutExamples()).
|
|
44
54
|
*
|
|
45
55
|
* @throws LearningError
|
|
46
56
|
*/
|
|
@@ -17,6 +17,23 @@ const compiledPatterns = new WeakMap();
|
|
|
17
17
|
* @throws LearningError
|
|
18
18
|
*/
|
|
19
19
|
export function defineCustomEntityType(init) {
|
|
20
|
+
return buildType(init, true);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The type without its examples and counter-examples, so that only name, description and pattern are
|
|
24
|
+
* stored (data minimisation). Detection by the pattern is unchanged; model-based detection then knows the
|
|
25
|
+
* type only by name and description. PHP cannot read such a type (its `fromArray()` requires an example).
|
|
26
|
+
*
|
|
27
|
+
* @throws LearningError when the type has no pattern: a model-only type is found only through its examples
|
|
28
|
+
*/
|
|
29
|
+
export function withoutExamples(type) {
|
|
30
|
+
if (type.pattern === null) {
|
|
31
|
+
throw new LearningError(`"${type.name}" has no pattern, so only model-based detection finds it, and it needs the examples for that. Keep its examples or give it a pattern.`);
|
|
32
|
+
}
|
|
33
|
+
return buildType({ ...type, examples: [], counterExamples: [] }, false);
|
|
34
|
+
}
|
|
35
|
+
/** Without `requireExamples`, a type with a pattern may have none (stored after withoutExamples()). */
|
|
36
|
+
function buildType(init, requireExamples) {
|
|
20
37
|
const { name, description, examples, counterExamples = [], pattern = null } = init;
|
|
21
38
|
// PHP's pattern has no /u and no D modifier: $ also matches before a final "\n".
|
|
22
39
|
if (!/^[A-Z][A-Z0-9_]{1,39}\n?$/.test(name)) {
|
|
@@ -25,7 +42,7 @@ export function defineCustomEntityType(init) {
|
|
|
25
42
|
if (isEntityType(name)) {
|
|
26
43
|
throw new LearningError(`"${name}" is a built-in type. Choose another name.`);
|
|
27
44
|
}
|
|
28
|
-
if (examples.length === 0) {
|
|
45
|
+
if (examples.length === 0 && (requireExamples || pattern === null)) {
|
|
29
46
|
throw new LearningError('At least one example is needed.');
|
|
30
47
|
}
|
|
31
48
|
// Description and examples reach the detection model: keep them short, single-line data.
|
|
@@ -54,7 +71,8 @@ export function defineCustomEntityType(init) {
|
|
|
54
71
|
/**
|
|
55
72
|
* Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
|
|
56
73
|
* fields become empty, non-string list entries are dropped, unknown keys are ignored, an empty pattern
|
|
57
|
-
* means model-only. Every field is then validated.
|
|
74
|
+
* means model-only. Every field is then validated. Unlike PHP, a type with a pattern may have no
|
|
75
|
+
* examples (see withoutExamples()).
|
|
58
76
|
*
|
|
59
77
|
* @throws LearningError
|
|
60
78
|
*/
|
|
@@ -62,19 +80,19 @@ export function customEntityTypeFromJSON(data) {
|
|
|
62
80
|
const record = isPhpArray(data) ? data : {};
|
|
63
81
|
const strings = (list) => isPhpArray(list) ? Object.values(list).filter((v) => typeof v === 'string') : [];
|
|
64
82
|
const { name, description, examples, counterExamples, pattern } = record;
|
|
65
|
-
return
|
|
83
|
+
return buildType({
|
|
66
84
|
name: typeof name === 'string' ? name : '',
|
|
67
85
|
description: typeof description === 'string' ? description : '',
|
|
68
86
|
examples: strings(examples),
|
|
69
87
|
counterExamples: strings(counterExamples),
|
|
70
88
|
pattern: typeof pattern === 'string' && pattern !== '' ? pattern : null,
|
|
71
|
-
});
|
|
89
|
+
}, false);
|
|
72
90
|
}
|
|
73
91
|
/** The compiled pattern of a type (validating it first if it did not come from defineCustomEntityType()). */
|
|
74
92
|
export function compiledPattern(type) {
|
|
75
93
|
let compiled = compiledPatterns.get(type);
|
|
76
94
|
if (compiled === undefined) {
|
|
77
|
-
compiled = compiledPatterns.get(
|
|
95
|
+
compiled = compiledPatterns.get(buildType(type, false)) ?? null;
|
|
78
96
|
compiledPatterns.set(type, compiled);
|
|
79
97
|
}
|
|
80
98
|
return compiled;
|
|
@@ -10,6 +10,24 @@ export interface EntityLearnerOptions {
|
|
|
10
10
|
store: CustomEntityStore;
|
|
11
11
|
/** Derives a pattern from examples; default learnPattern(). */
|
|
12
12
|
learnPattern?: (examples: readonly string[], counterExamples: readonly string[]) => string;
|
|
13
|
+
/**
|
|
14
|
+
* Store examples and counter-examples with the type. Default true (PHP's behaviour and file format).
|
|
15
|
+
*
|
|
16
|
+
* With false, learn() checks the pattern against the examples and then stores only name, description
|
|
17
|
+
* and pattern (data minimisation: examples may be personal data). Consequences: types without a pattern
|
|
18
|
+
* (plain words, model-only) are refused, because only the examples let the model find them; the model
|
|
19
|
+
* knows the other types by name and description only; a stored type cannot be re-derived from its
|
|
20
|
+
* examples later; PHP cannot read a store that holds such types. Types stored before keep their
|
|
21
|
+
* examples until dropExamples().
|
|
22
|
+
*/
|
|
23
|
+
keepExamples?: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** Result of EntityLearner.dropExamples(): type names only. */
|
|
26
|
+
export interface DropExamplesResult {
|
|
27
|
+
/** Types whose examples were removed. */
|
|
28
|
+
readonly stripped: readonly string[];
|
|
29
|
+
/** Model-only types: they keep their examples, without them nothing would find them. */
|
|
30
|
+
readonly kept: readonly string[];
|
|
13
31
|
}
|
|
14
32
|
/**
|
|
15
33
|
* Teach pii-shield new entity types from examples ("mask things like this too").
|
|
@@ -24,6 +42,8 @@ export interface EntityLearnerOptions {
|
|
|
24
42
|
export declare class EntityLearner {
|
|
25
43
|
#private;
|
|
26
44
|
constructor(options: EntityLearnerOptions);
|
|
45
|
+
/** Whether learn() stores examples and counter-examples (option `keepExamples`). */
|
|
46
|
+
get keepExamples(): boolean;
|
|
27
47
|
/** A learner whose snapshot is already loaded from the store. */
|
|
28
48
|
static create(options: EntityLearnerOptions): Promise<EntityLearner>;
|
|
29
49
|
/**
|
|
@@ -33,18 +53,29 @@ export declare class EntityLearner {
|
|
|
33
53
|
*/
|
|
34
54
|
learn(init: CustomEntityTypeInit): Promise<LearningResult>;
|
|
35
55
|
/**
|
|
36
|
-
* Same as learn(), without saving: for trying out examples.
|
|
56
|
+
* Same as learn(), without saving: for trying out examples. The type is what learn() would store
|
|
57
|
+
* (without examples if `keepExamples` is false).
|
|
37
58
|
*
|
|
38
59
|
* @throws LearningError
|
|
39
60
|
*/
|
|
40
61
|
preview(init: CustomEntityTypeInit): LearningResult;
|
|
41
62
|
forget(name: string): Promise<void>;
|
|
63
|
+
/**
|
|
64
|
+
* Removes the examples and counter-examples of every stored type that has a pattern (e.g. after
|
|
65
|
+
* switching to `keepExamples: false`). Model-only types keep theirs. Run it as a one-off migration:
|
|
66
|
+
* a type another process learns at the same time can be overwritten with its older version.
|
|
67
|
+
*/
|
|
68
|
+
dropExamples(): Promise<DropExamplesResult>;
|
|
42
69
|
/** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
|
|
43
70
|
types(): Promise<CustomEntityType[]>;
|
|
44
71
|
/** Reloads the snapshot the detector uses. */
|
|
45
72
|
refresh(): Promise<void>;
|
|
46
73
|
/** The types in the current snapshot. */
|
|
47
74
|
get snapshot(): readonly CustomEntityType[];
|
|
48
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take
|
|
77
|
+
* effect. Always the same instance, so `new PiiShield({ learner })` can tell when it is already among
|
|
78
|
+
* the detectors.
|
|
79
|
+
*/
|
|
49
80
|
detector(): Detector;
|
|
50
81
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LearningError } from '../errors.js';
|
|
2
2
|
import { phpTrim } from '../internal/pcre.js';
|
|
3
3
|
import { LearnedTypesDetector } from './custom-entity-detector.js';
|
|
4
|
-
import { defineCustomEntityType } from './custom-entity-type.js';
|
|
4
|
+
import { defineCustomEntityType, withoutExamples, } from './custom-entity-type.js';
|
|
5
5
|
import { learnPattern } from './pattern-learner.js';
|
|
6
6
|
const MODEL_ONLY_NOTE = 'No pattern: plain words would match ordinary text. Only model-based detection finds this type.';
|
|
7
7
|
/**
|
|
@@ -17,10 +17,17 @@ const MODEL_ONLY_NOTE = 'No pattern: plain words would match ordinary text. Only
|
|
|
17
17
|
export class EntityLearner {
|
|
18
18
|
#store;
|
|
19
19
|
#learnPattern;
|
|
20
|
+
#keepExamples;
|
|
20
21
|
#snapshot = [];
|
|
22
|
+
#detector;
|
|
21
23
|
constructor(options) {
|
|
22
24
|
this.#store = options.store;
|
|
23
25
|
this.#learnPattern = options.learnPattern ?? learnPattern;
|
|
26
|
+
this.#keepExamples = options.keepExamples ?? true;
|
|
27
|
+
}
|
|
28
|
+
/** Whether learn() stores examples and counter-examples (option `keepExamples`). */
|
|
29
|
+
get keepExamples() {
|
|
30
|
+
return this.#keepExamples;
|
|
24
31
|
}
|
|
25
32
|
/** A learner whose snapshot is already loaded from the store. */
|
|
26
33
|
static async create(options) {
|
|
@@ -40,7 +47,8 @@ export class EntityLearner {
|
|
|
40
47
|
return result;
|
|
41
48
|
}
|
|
42
49
|
/**
|
|
43
|
-
* Same as learn(), without saving: for trying out examples.
|
|
50
|
+
* Same as learn(), without saving: for trying out examples. The type is what learn() would store
|
|
51
|
+
* (without examples if `keepExamples` is false).
|
|
44
52
|
*
|
|
45
53
|
* @throws LearningError
|
|
46
54
|
*/
|
|
@@ -60,12 +68,42 @@ export class EntityLearner {
|
|
|
60
68
|
note = MODEL_ONLY_NOTE;
|
|
61
69
|
}
|
|
62
70
|
}
|
|
63
|
-
|
|
71
|
+
// Validated with the examples (the pattern must match them) before they are dropped.
|
|
72
|
+
const type = defineCustomEntityType({ ...init, counterExamples, pattern });
|
|
73
|
+
if (this.#keepExamples) {
|
|
74
|
+
return Object.freeze({ type, note });
|
|
75
|
+
}
|
|
76
|
+
if (type.pattern === null) {
|
|
77
|
+
throw new LearningError('These examples give no pattern, and this learner does not keep examples, which model-based detection would need to find the type. Enter a pattern by hand.');
|
|
78
|
+
}
|
|
79
|
+
return Object.freeze({ type: withoutExamples(type), note });
|
|
64
80
|
}
|
|
65
81
|
async forget(name) {
|
|
66
82
|
await this.#store.remove(name);
|
|
67
83
|
await this.refresh();
|
|
68
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* Removes the examples and counter-examples of every stored type that has a pattern (e.g. after
|
|
87
|
+
* switching to `keepExamples: false`). Model-only types keep theirs. Run it as a one-off migration:
|
|
88
|
+
* a type another process learns at the same time can be overwritten with its older version.
|
|
89
|
+
*/
|
|
90
|
+
async dropExamples() {
|
|
91
|
+
const stripped = [];
|
|
92
|
+
const kept = [];
|
|
93
|
+
for (const type of await this.#store.all()) {
|
|
94
|
+
if (type.examples.length === 0 && type.counterExamples.length === 0) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (type.pattern === null) {
|
|
98
|
+
kept.push(type.name);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
await this.#store.save(withoutExamples(type));
|
|
102
|
+
stripped.push(type.name);
|
|
103
|
+
}
|
|
104
|
+
await this.refresh();
|
|
105
|
+
return Object.freeze({ stripped: Object.freeze(stripped), kept: Object.freeze(kept) });
|
|
106
|
+
}
|
|
69
107
|
/** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
|
|
70
108
|
async types() {
|
|
71
109
|
const types = await this.#store.all();
|
|
@@ -80,8 +118,13 @@ export class EntityLearner {
|
|
|
80
118
|
get snapshot() {
|
|
81
119
|
return this.#snapshot;
|
|
82
120
|
}
|
|
83
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take
|
|
123
|
+
* effect. Always the same instance, so `new PiiShield({ learner })` can tell when it is already among
|
|
124
|
+
* the detectors.
|
|
125
|
+
*/
|
|
84
126
|
detector() {
|
|
85
|
-
|
|
127
|
+
this.#detector ??= new LearnedTypesDetector(() => this.#snapshot);
|
|
128
|
+
return this.#detector;
|
|
86
129
|
}
|
|
87
130
|
}
|
package/dist/learning/store.d.ts
CHANGED
|
@@ -1,14 +1,33 @@
|
|
|
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()`), or store
|
|
10
|
+
* none (EntityLearner option `keepExamples: false`).
|
|
11
|
+
*
|
|
12
|
+
* Contract every implementation keeps:
|
|
13
|
+
* - `all()` is sorted by name in byte order (sortByName(), PHP's strcmp()), independent of a
|
|
14
|
+
* database collation.
|
|
15
|
+
* - `get()` of an unknown name gives `null`; `save()` replaces a type with the same name; `remove()` of
|
|
16
|
+
* an unknown name is a no-op.
|
|
17
|
+
* - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved, also types
|
|
18
|
+
* with a pattern and no examples (withoutExamples()).
|
|
19
|
+
* - Concurrent `save()`/`remove()` calls for different names must not lose each other's writes.
|
|
20
|
+
* KeyValueCustomEntityStore keeps this only for writes through one instance: its read-modify-write
|
|
21
|
+
* of the whole list loses writes across processes unless you serialise them yourself.
|
|
5
22
|
*/
|
|
6
23
|
export interface CustomEntityStore {
|
|
7
|
-
/** Sorted by name. */
|
|
24
|
+
/** Sorted by name (byte order). */
|
|
8
25
|
all(): Promise<CustomEntityType[]>;
|
|
26
|
+
/** @returns null if there is no type with this name */
|
|
9
27
|
get(name: string): Promise<CustomEntityType | null>;
|
|
10
28
|
/** Adds the type or replaces the one with the same name. */
|
|
11
29
|
save(type: CustomEntityType): Promise<void>;
|
|
30
|
+
/** Deletes the type; resolves also if there is none. */
|
|
12
31
|
remove(name: string): Promise<void>;
|
|
13
32
|
}
|
|
14
33
|
/** Sorted by name with PHP's strcmp() (byte order; names are ASCII). Stable, like PHP 8's usort(). */
|
|
@@ -38,8 +57,10 @@ export interface KeyValueCustomEntityStoreOptions {
|
|
|
38
57
|
* CacheCustomEntityStore). The value is the same JSON shape as the file store, not PHP's PSR-6
|
|
39
58
|
* serialisation, so PHP and Node cannot share the key (docs/DEVIATIONS.md).
|
|
40
59
|
*
|
|
41
|
-
* save() and remove() read, change and write the whole list:
|
|
42
|
-
*
|
|
60
|
+
* save() and remove() read, change and write the whole list: writes through one instance are
|
|
61
|
+
* serialised, but writes from several processes (or instances) can lose each other's changes. Serialise
|
|
62
|
+
* them yourself (e.g. a Redis lock), or use a store with one record per type such as
|
|
63
|
+
* PostgresCustomEntityStore.
|
|
43
64
|
*/
|
|
44
65
|
export declare class KeyValueCustomEntityStore implements CustomEntityStore {
|
|
45
66
|
#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;
|
package/dist/pii-masker.js
CHANGED
|
@@ -22,10 +22,11 @@ export class PiiMasker {
|
|
|
22
22
|
#strategies;
|
|
23
23
|
#fallback;
|
|
24
24
|
constructor(options = {}) {
|
|
25
|
-
const { detectors, allowlist, strategies = {}, fallback = new TypeLabelMask() } = options;
|
|
25
|
+
const { detectors, allowlist, learner, strategies = {}, fallback = new TypeLabelMask() } = options;
|
|
26
26
|
this.#extractor = new EntityExtractor({
|
|
27
27
|
...(detectors === undefined ? {} : { detectors }),
|
|
28
28
|
...(allowlist === undefined ? {} : { allowlist }),
|
|
29
|
+
...(learner === undefined ? {} : { learner }),
|
|
29
30
|
});
|
|
30
31
|
const merged = new Map();
|
|
31
32
|
for (const [type, strategy] of [...Object.entries(defaultMaskingStrategies()), ...Object.entries(strategies)]) {
|
package/dist/pii-shield.js
CHANGED
|
@@ -19,13 +19,14 @@ 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, 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
|
+
...(learner === undefined ? {} : { learner }),
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
32
|
/**
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { type CustomEntityType } from '../learning/custom-entity-type.js';
|
|
2
|
+
import { type CustomEntityStore } from '../learning/store.js';
|
|
3
|
+
import type { VaultSetup } from '../create-pii-shield.js';
|
|
4
|
+
import { type VaultStorage } from '../vault/vault.js';
|
|
5
|
+
/** What a query function resolves to: the result rows as objects keyed by column name. */
|
|
6
|
+
export interface PostgresQueryResult {
|
|
7
|
+
rows: readonly unknown[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Runs one parameterised statement (`$1`, `$2`, ...) and resolves with its rows. The shape of `pg`'s
|
|
11
|
+
* `query()`: pass `pool.query.bind(pool)`, `client.query.bind(client)` or `(text, params) => pool.query(text, params)`.
|
|
12
|
+
* For another driver, wrap it, e.g. postgres.js: `(text, params) => sql.unsafe(text, params).then((rows) => ({ rows }))`.
|
|
13
|
+
*
|
|
14
|
+
* The stores never open or end transactions: every call is one statement, so they take part in
|
|
15
|
+
* whatever transaction the connection behind the function is in.
|
|
16
|
+
*/
|
|
17
|
+
export type PostgresQuery = (text: string, params: unknown[]) => Promise<PostgresQueryResult>;
|
|
18
|
+
/** Default table of PostgresVaultStorage. */
|
|
19
|
+
export declare const DEFAULT_VAULT_TABLE = "pii_shield_vault";
|
|
20
|
+
/** Default table of PostgresCustomEntityStore. */
|
|
21
|
+
export declare const DEFAULT_TYPES_TABLE = "pii_shield_learned_types";
|
|
22
|
+
export interface PostgresStoreOptions {
|
|
23
|
+
query: PostgresQuery;
|
|
24
|
+
/**
|
|
25
|
+
* Table name, optionally schema-qualified (`app.pii_vault`). Each part must be a plain identifier
|
|
26
|
+
* (`[A-Za-z_][A-Za-z0-9_]*`, at most 48 characters); it is always double-quoted, so the case is kept.
|
|
27
|
+
*/
|
|
28
|
+
table?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Stores vault ciphertext in a table (`id text primary key, payload bytea, expires_at timestamptz`, see
|
|
32
|
+
* postgresSchema()). Use it behind EncryptedVault, never on its own: the database then only sees
|
|
33
|
+
* ciphertext and the key stays outside it.
|
|
34
|
+
*
|
|
35
|
+
* - The row id is `sha256hex(id)`, like RedisVaultStorage: ids may come from outside.
|
|
36
|
+
* - Expiry uses the database clock (`now()`, the start of the current transaction), not the app clock:
|
|
37
|
+
* several app servers with skewed clocks agree. Reads ignore expired rows; purgeExpired() deletes them,
|
|
38
|
+
* which must happen regularly (storage limitation, Art. 5(1)(e) GDPR).
|
|
39
|
+
*/
|
|
40
|
+
export declare class PostgresVaultStorage implements VaultStorage {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(options: PostgresStoreOptions);
|
|
43
|
+
put(id: string, payload: Uint8Array, ttlSeconds: number): Promise<void>;
|
|
44
|
+
get(id: string): Promise<Uint8Array | null>;
|
|
45
|
+
remove(id: string): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Deletes expired rows (by the database clock). Run it regularly, e.g. from a timer, a cron job or
|
|
48
|
+
* `pg_cron`; the HTTP service does it every `PII_SERVICE_VAULT_PURGE_INTERVAL` seconds.
|
|
49
|
+
*
|
|
50
|
+
* @returns the number of deleted rows
|
|
51
|
+
*/
|
|
52
|
+
purgeExpired(): Promise<number>;
|
|
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
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
|
|
75
|
+
* postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
|
|
76
|
+
* names from any number of processes never lose each other.
|
|
77
|
+
*
|
|
78
|
+
* `data` is the type's JSON (the shape of JsonFileCustomEntityStore's entries); rows are validated with
|
|
79
|
+
* customEntityTypeFromJSON() when read. Examples are plain text and may be personal data: grant access
|
|
80
|
+
* to the table like to other personal data, and remember that a deleted row stays in WAL, backups and,
|
|
81
|
+
* until VACUUM, in the table file.
|
|
82
|
+
*/
|
|
83
|
+
export declare class PostgresCustomEntityStore implements CustomEntityStore {
|
|
84
|
+
#private;
|
|
85
|
+
constructor(options: PostgresStoreOptions);
|
|
86
|
+
all(): Promise<CustomEntityType[]>;
|
|
87
|
+
get(name: string): Promise<CustomEntityType | null>;
|
|
88
|
+
save(type: CustomEntityType): Promise<void>;
|
|
89
|
+
remove(name: string): Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
export interface PostgresSchemaOptions {
|
|
92
|
+
/** Vault table (default `pii_shield_vault`); `null` leaves it out. */
|
|
93
|
+
vaultTable?: string | null;
|
|
94
|
+
/** Learned types table (default `pii_shield_learned_types`); `null` leaves it out. */
|
|
95
|
+
typesTable?: string | null;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The DDL for both tables, idempotent (`CREATE … IF NOT EXISTS`), for the product's own migrations or
|
|
99
|
+
* `psql`. The library never runs DDL itself. A schema in a qualified name must exist already.
|
|
100
|
+
*
|
|
101
|
+
* The application's database role needs only `SELECT, INSERT, UPDATE, DELETE` on the two tables.
|
|
102
|
+
*/
|
|
103
|
+
export declare function postgresSchema(options?: PostgresSchemaOptions): string;
|