@waswrongassembled/pii-shield 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/README.md +109 -15
- package/dist/cli.js +30 -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 +4 -2
- package/dist/pii-masker.js +2 -1
- package/dist/pii-shield.js +2 -1
- package/dist/postgres/index.d.ts +20 -0
- package/dist/postgres/index.js +14 -0
- package/dist/redaction.d.ts +16 -2
- package/dist/redaction.js +22 -10
- package/dist/server/config.d.ts +5 -8
- package/dist/server/config.js +77 -220
- 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.js +8 -3
- 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-redis/index.d.ts +14 -0
- package/dist/vault-redis/index.js +8 -0
- package/docs/openapi.yaml +8 -2
- package/package.json +1 -1
|
@@ -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
|
@@ -6,14 +6,16 @@ import { type CustomEntityType } from './custom-entity-type.js';
|
|
|
6
6
|
* `@waswrongassembled/pii-shield/testing`.
|
|
7
7
|
*
|
|
8
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()`)
|
|
9
|
+
* like any other store of personal data (access rights, backups, deletion through `remove()`), or store
|
|
10
|
+
* none (EntityLearner option `keepExamples: false`).
|
|
10
11
|
*
|
|
11
12
|
* Contract every implementation keeps:
|
|
12
13
|
* - `all()` is sorted by name in byte order (sortByName(), PHP's strcmp()), independent of a
|
|
13
14
|
* database collation.
|
|
14
15
|
* - `get()` of an unknown name gives `null`; `save()` replaces a type with the same name; `remove()` of
|
|
15
16
|
* an unknown name is a no-op.
|
|
16
|
-
* - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved
|
|
17
|
+
* - Types read back are validated (customEntityTypeFromJSON()) and equal to what was saved, also types
|
|
18
|
+
* with a pattern and no examples (withoutExamples()).
|
|
17
19
|
* - Concurrent `save()`/`remove()` calls for different names must not lose each other's writes.
|
|
18
20
|
* KeyValueCustomEntityStore keeps this only for writes through one instance: its read-modify-write
|
|
19
21
|
* of the whole list loses writes across processes unless you serialise them yourself.
|
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
|
/**
|
package/dist/postgres/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type CustomEntityType } from '../learning/custom-entity-type.js';
|
|
2
2
|
import { type CustomEntityStore } from '../learning/store.js';
|
|
3
|
+
import type { VaultSetup } from '../create-pii-shield.js';
|
|
3
4
|
import { type VaultStorage } from '../vault/vault.js';
|
|
4
5
|
/** What a query function resolves to: the result rows as objects keyed by column name. */
|
|
5
6
|
export interface PostgresQueryResult {
|
|
@@ -50,6 +51,25 @@ export declare class PostgresVaultStorage implements VaultStorage {
|
|
|
50
51
|
*/
|
|
51
52
|
purgeExpired(): Promise<number>;
|
|
52
53
|
}
|
|
54
|
+
export interface PostgresVaultOptions extends PostgresStoreOptions {
|
|
55
|
+
/** 32 raw bytes, e.g. `vaultKeyFromEnv()`. Required: the rows outlive the process. */
|
|
56
|
+
key: Uint8Array;
|
|
57
|
+
/** Keys of earlier rotations, only for reading, e.g. `previousVaultKeysFromEnv()`. */
|
|
58
|
+
previousKeys?: readonly Uint8Array[] | undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The vault of createPiiShield() on PostgreSQL: a PostgresVaultStorage behind an EncryptedVault with your
|
|
62
|
+
* key, whose expired rows createPiiShield() purges on its timer (`purgeExpired()`).
|
|
63
|
+
*
|
|
64
|
+
* ```ts
|
|
65
|
+
* const shield = await createPiiShield({
|
|
66
|
+
* vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function postgresVault(options: PostgresVaultOptions): VaultSetup & {
|
|
71
|
+
storage: PostgresVaultStorage;
|
|
72
|
+
};
|
|
53
73
|
/**
|
|
54
74
|
* Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
|
|
55
75
|
* postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
|
package/dist/postgres/index.js
CHANGED
|
@@ -76,6 +76,20 @@ export class PostgresVaultStorage {
|
|
|
76
76
|
return Number.isFinite(deleted) ? deleted : 0;
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* The vault of createPiiShield() on PostgreSQL: a PostgresVaultStorage behind an EncryptedVault with your
|
|
81
|
+
* key, whose expired rows createPiiShield() purges on its timer (`purgeExpired()`).
|
|
82
|
+
*
|
|
83
|
+
* ```ts
|
|
84
|
+
* const shield = await createPiiShield({
|
|
85
|
+
* vault: postgresVault({ query: pool.query.bind(pool), key: vaultKeyFromEnv() }),
|
|
86
|
+
* });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export function postgresVault(options) {
|
|
90
|
+
const { key, previousKeys, ...store } = options;
|
|
91
|
+
return { storage: new PostgresVaultStorage(store), key, previousKeys };
|
|
92
|
+
}
|
|
79
93
|
/**
|
|
80
94
|
* Learned entity types in a table, one row per type (`name text primary key, data jsonb`, see
|
|
81
95
|
* postgresSchema()). save() is one upsert and remove() one delete, so concurrent writes of different
|
package/dist/redaction.d.ts
CHANGED
|
@@ -10,8 +10,15 @@ export type PlaceholderMapping = Readonly<Record<string, string>>;
|
|
|
10
10
|
* Result of a redaction. Holds the original values: never log it, persist it or send it to a model provider
|
|
11
11
|
* (send `redactedText` only).
|
|
12
12
|
*
|
|
13
|
-
* A frozen
|
|
14
|
-
*
|
|
13
|
+
* A frozen object whose `mapping` and `entities` are readable but not enumerable, so what loggers and
|
|
14
|
+
* error reporters do with an object never reaches the original values:
|
|
15
|
+
* - `JSON.stringify()` (pino, winston, Sentry, ...) calls `toJSON()`: `{ redactedText, entityCount }`
|
|
16
|
+
* (plus `vaultId`); `util.inspect()` / `console.log()` show `mapping: '[hidden]'`, like PHP's `__debugInfo()`.
|
|
17
|
+
* - Spread (`{ ...result }`), `Object.keys()`, `Object.entries()` and `structuredClone()` (`postMessage()`)
|
|
18
|
+
* copy only `redactedText` (and `vaultId`). To keep or pass on the mapping, use `result.mapping`
|
|
19
|
+
* explicitly (a plain object, serialized like the JSON PHP stores in its vault), or the vault.
|
|
20
|
+
*
|
|
21
|
+
* Results of your own Redactor implementation are whatever objects it returns.
|
|
15
22
|
*
|
|
16
23
|
* `PiiShield.redactToVault()` returns a VaultRedactionResult, which adds the `vaultId`.
|
|
17
24
|
*/
|
|
@@ -26,6 +33,11 @@ export interface VaultRedactionResult extends RedactionResult {
|
|
|
26
33
|
/** 32 lowercase hex characters (16 random bytes). Pass it to restoreFromVault() and forget(). */
|
|
27
34
|
readonly vaultId: string;
|
|
28
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Result of a restore: a frozen plain object that serializes in full. `text` is the restored text with the
|
|
38
|
+
* original values, the output you asked for, so treat it like the original text; the placeholder lists
|
|
39
|
+
* hold no personal data.
|
|
40
|
+
*/
|
|
29
41
|
export interface RestoreResult {
|
|
30
42
|
readonly text: string;
|
|
31
43
|
/** Placeholders found in the text that are not in the mapping (the model invented them), in order of appearance. */
|
|
@@ -70,6 +82,8 @@ export declare function withVaultId(result: RedactionResult, vaultId: string): V
|
|
|
70
82
|
/**
|
|
71
83
|
* Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
|
|
72
84
|
* Placeholders that are not in the mapping stay as they were found.
|
|
85
|
+
*
|
|
86
|
+
* @throws TypeError for a copy of a RedactionResult without its mapping (JSON, `structuredClone()`, spread)
|
|
73
87
|
*/
|
|
74
88
|
export declare function restorePlaceholders(text: string, source: RedactionResult | PlaceholderMapping): RestoreResult;
|
|
75
89
|
/** The distinct entity types of a redaction, in order of first appearance (PHP's foundTypes()). */
|
package/dist/redaction.js
CHANGED
|
@@ -2,26 +2,38 @@ import { replacePlaceholders } from './placeholder.js';
|
|
|
2
2
|
const INSPECT = Symbol.for('nodejs.util.inspect.custom');
|
|
3
3
|
/** @internal */
|
|
4
4
|
export function createRedactionResult(redactedText, mapping, entities) {
|
|
5
|
-
|
|
6
|
-
Object.defineProperty(result, INSPECT, {
|
|
7
|
-
value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length }),
|
|
8
|
-
});
|
|
9
|
-
return Object.freeze(result);
|
|
5
|
+
return hideOriginals({ redactedText }, Object.freeze(mapping), Object.freeze(entities));
|
|
10
6
|
}
|
|
11
7
|
/** @internal */
|
|
12
8
|
export function withVaultId(result, vaultId) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
return hideOriginals({ redactedText: result.redactedText, vaultId }, result.mapping, result.entities);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Adds `mapping` and `entities` as readable, non-enumerable properties, a `toJSON()` and a `util.inspect`
|
|
13
|
+
* view without them, and freezes the result (see RedactionResult).
|
|
14
|
+
*/
|
|
15
|
+
function hideOriginals(visible, mapping, entities) {
|
|
16
|
+
const { redactedText, vaultId } = visible;
|
|
17
|
+
const withId = vaultId === undefined ? {} : { vaultId };
|
|
18
|
+
Object.defineProperties(visible, {
|
|
19
|
+
mapping: { value: mapping },
|
|
20
|
+
entities: { value: entities },
|
|
21
|
+
toJSON: { value: () => ({ redactedText, entityCount: entities.length, ...withId }) },
|
|
22
|
+
[INSPECT]: { value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length, ...withId }) },
|
|
17
23
|
});
|
|
18
|
-
return Object.freeze(
|
|
24
|
+
return Object.freeze(visible);
|
|
19
25
|
}
|
|
20
26
|
/**
|
|
21
27
|
* Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
|
|
22
28
|
* Placeholders that are not in the mapping stay as they were found.
|
|
29
|
+
*
|
|
30
|
+
* @throws TypeError for a copy of a RedactionResult without its mapping (JSON, `structuredClone()`, spread)
|
|
23
31
|
*/
|
|
24
32
|
export function restorePlaceholders(text, source) {
|
|
33
|
+
if (!isRedactionResult(source) && typeof source.redactedText === 'string') {
|
|
34
|
+
// Placeholders never are "redactedText", so this is a result copy that lost its mapping.
|
|
35
|
+
throw new TypeError('This redaction result has no mapping (JSON, structuredClone() and spread leave it out): pass result.mapping, or use the vault.');
|
|
36
|
+
}
|
|
25
37
|
const mapping = isRedactionResult(source) ? source.mapping : source;
|
|
26
38
|
const seen = new Set();
|
|
27
39
|
const unknown = new Set();
|
package/dist/server/config.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { ServiceApi } from '../service/service-api.js';
|
|
2
|
-
|
|
3
|
-
export
|
|
4
|
-
readonly name = "ConfigError";
|
|
5
|
-
}
|
|
2
|
+
import { ConfigError, type Env } from './env.js';
|
|
3
|
+
export { ConfigError };
|
|
6
4
|
export interface EnvService {
|
|
7
5
|
api: ServiceApi;
|
|
8
6
|
allowedHosts: string[];
|
|
@@ -26,10 +24,9 @@ export interface ServiceFromEnvOptions {
|
|
|
26
24
|
}
|
|
27
25
|
/**
|
|
28
26
|
* Builds the service from environment variables (names as in the PHP service where they exist; see
|
|
29
|
-
* docs/server.md). Used by the `pii-shield` CLI.
|
|
27
|
+
* docs/server.md). Used by the `pii-shield` CLI. `pii-shield doctor` (checkServiceConfig()) checks the
|
|
28
|
+
* same variables with the same rules.
|
|
30
29
|
*
|
|
31
30
|
* @throws ConfigError
|
|
32
31
|
*/
|
|
33
|
-
export declare function serviceFromEnv(env?:
|
|
34
|
-
/** Seconds between two purges of expired vault rows (Postgres). */
|
|
35
|
-
export declare const DEFAULT_PURGE_INTERVAL = 300;
|
|
32
|
+
export declare function serviceFromEnv(env?: Env, options?: ServiceFromEnvOptions): Promise<EnvService>;
|