@waswrongassembled/pii-shield 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +22 -0
  3. package/README.md +276 -2
  4. package/dist/ai-sdk/index.d.ts +19 -0
  5. package/dist/ai-sdk/index.js +30 -0
  6. package/dist/ai-sdk/middleware.d.ts +63 -0
  7. package/dist/ai-sdk/middleware.js +388 -0
  8. package/dist/bin.d.ts +2 -0
  9. package/dist/bin.js +9 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +124 -0
  12. package/dist/detector.d.ts +28 -0
  13. package/dist/detector.js +3 -0
  14. package/dist/detectors/at-svnr.d.ts +14 -0
  15. package/dist/detectors/at-svnr.js +31 -0
  16. package/dist/detectors/authority-context.d.ts +22 -0
  17. package/dist/detectors/authority-context.js +278 -0
  18. package/dist/detectors/birth-date.d.ts +10 -0
  19. package/dist/detectors/birth-date.js +21 -0
  20. package/dist/detectors/email.d.ts +15 -0
  21. package/dist/detectors/email.js +29 -0
  22. package/dist/detectors/file-number.d.ts +16 -0
  23. package/dist/detectors/file-number.js +20 -0
  24. package/dist/detectors/iban.d.ts +10 -0
  25. package/dist/detectors/iban.js +41 -0
  26. package/dist/detectors/license-plate.d.ts +9 -0
  27. package/dist/detectors/license-plate.js +13 -0
  28. package/dist/detectors/phone.d.ts +13 -0
  29. package/dist/detectors/phone.js +38 -0
  30. package/dist/detectors/postal-address.d.ts +14 -0
  31. package/dist/detectors/postal-address.js +19 -0
  32. package/dist/detectors/salutation-person.d.ts +18 -0
  33. package/dist/detectors/salutation-person.js +37 -0
  34. package/dist/detectors/tax-number.d.ts +14 -0
  35. package/dist/detectors/tax-number.js +33 -0
  36. package/dist/entity-extractor.d.ts +47 -0
  37. package/dist/entity-extractor.js +245 -0
  38. package/dist/entity-type.d.ts +24 -0
  39. package/dist/entity-type.js +26 -0
  40. package/dist/entity.d.ts +28 -0
  41. package/dist/entity.js +11 -0
  42. package/dist/errors.d.ts +48 -0
  43. package/dist/errors.js +49 -0
  44. package/dist/index.d.ts +42 -0
  45. package/dist/index.js +40 -0
  46. package/dist/internal/pcre.d.ts +55 -0
  47. package/dist/internal/pcre.js +102 -0
  48. package/dist/internal/php-json.d.ts +15 -0
  49. package/dist/internal/php-json.js +48 -0
  50. package/dist/internal/placeholder-stream.d.ts +24 -0
  51. package/dist/internal/placeholder-stream.js +118 -0
  52. package/dist/internal/text-spans.d.ts +8 -0
  53. package/dist/internal/text-spans.js +15 -0
  54. package/dist/learning/char-set.d.ts +29 -0
  55. package/dist/learning/char-set.js +158 -0
  56. package/dist/learning/custom-entity-detector.d.ts +26 -0
  57. package/dist/learning/custom-entity-detector.js +70 -0
  58. package/dist/learning/custom-entity-type.d.ts +49 -0
  59. package/dist/learning/custom-entity-type.js +150 -0
  60. package/dist/learning/entity-learner.d.ts +50 -0
  61. package/dist/learning/entity-learner.js +87 -0
  62. package/dist/learning/json-file-store.d.ts +36 -0
  63. package/dist/learning/json-file-store.js +132 -0
  64. package/dist/learning/learned-pattern.d.ts +48 -0
  65. package/dist/learning/learned-pattern.js +640 -0
  66. package/dist/learning/pattern-grammar.d.ts +12 -0
  67. package/dist/learning/pattern-grammar.js +148 -0
  68. package/dist/learning/pattern-learner.d.ts +10 -0
  69. package/dist/learning/pattern-learner.js +116 -0
  70. package/dist/learning/store.d.ts +51 -0
  71. package/dist/learning/store.js +84 -0
  72. package/dist/masking/partial-mask.d.ts +23 -0
  73. package/dist/masking/partial-mask.js +43 -0
  74. package/dist/masking/strategy.d.ts +10 -0
  75. package/dist/masking/strategy.js +1 -0
  76. package/dist/masking/type-label-mask.d.ts +17 -0
  77. package/dist/masking/type-label-mask.js +28 -0
  78. package/dist/mcp/index.d.ts +33 -0
  79. package/dist/mcp/index.js +146 -0
  80. package/dist/mcp/tools.d.ts +63 -0
  81. package/dist/mcp/tools.js +183 -0
  82. package/dist/model/chunks.d.ts +13 -0
  83. package/dist/model/chunks.js +74 -0
  84. package/dist/model/model-detector.d.ts +110 -0
  85. package/dist/model/model-detector.js +420 -0
  86. package/dist/model/prompt.d.ts +16 -0
  87. package/dist/model/prompt.js +192 -0
  88. package/dist/pii-masker.d.ts +27 -0
  89. package/dist/pii-masker.js +56 -0
  90. package/dist/pii-shield.d.ts +40 -0
  91. package/dist/pii-shield.js +142 -0
  92. package/dist/placeholder.d.ts +48 -0
  93. package/dist/placeholder.js +138 -0
  94. package/dist/redaction.d.ts +76 -0
  95. package/dist/redaction.js +52 -0
  96. package/dist/server/config.d.ts +23 -0
  97. package/dist/server/config.js +187 -0
  98. package/dist/server/http-server.d.ts +63 -0
  99. package/dist/server/http-server.js +241 -0
  100. package/dist/server/index.d.ts +9 -0
  101. package/dist/server/index.js +9 -0
  102. package/dist/server/model-providers.d.ts +31 -0
  103. package/dist/server/model-providers.js +158 -0
  104. package/dist/service/json-body.d.ts +14 -0
  105. package/dist/service/json-body.js +35 -0
  106. package/dist/service/local-peer.d.ts +16 -0
  107. package/dist/service/local-peer.js +83 -0
  108. package/dist/service/service-api.d.ts +75 -0
  109. package/dist/service/service-api.js +305 -0
  110. package/dist/validators/at-svnr.d.ts +8 -0
  111. package/dist/validators/at-svnr.js +21 -0
  112. package/dist/validators/de-tax-id.d.ts +8 -0
  113. package/dist/validators/de-tax-id.js +35 -0
  114. package/dist/validators/iban.d.ts +5 -0
  115. package/dist/validators/iban.js +24 -0
  116. package/dist/vault/encrypted-vault.d.ts +37 -0
  117. package/dist/vault/encrypted-vault.js +152 -0
  118. package/dist/vault/in-memory-vault.d.ts +17 -0
  119. package/dist/vault/in-memory-vault.js +39 -0
  120. package/dist/vault/memory-vault-storage.d.ts +16 -0
  121. package/dist/vault/memory-vault-storage.js +37 -0
  122. package/dist/vault/vault.d.ts +38 -0
  123. package/dist/vault/vault.js +16 -0
  124. package/dist/vault-redis/index.d.ts +28 -0
  125. package/dist/vault-redis/index.js +33 -0
  126. package/docs/openapi.yaml +422 -0
  127. package/package.json +122 -4
@@ -0,0 +1,150 @@
1
+ import { isEntityType } from '../entity-type.js';
2
+ import { LearningError } from '../errors.js';
3
+ import { codePointLength } from '../internal/pcre.js';
4
+ import { BACKTRACK_LIMIT, LearnedPattern } from './learned-pattern.js';
5
+ import { patternViolation } from './pattern-grammar.js';
6
+ /** Limits of a learned type; lengths count code points (PHP's mb_strlen). */
7
+ export const CUSTOM_ENTITY_TYPE_LIMITS = Object.freeze({
8
+ maxDescriptionLength: 300,
9
+ maxExamples: 20,
10
+ maxExampleLength: 100,
11
+ maxPatternLength: 200,
12
+ });
13
+ const compiledPatterns = new WeakMap();
14
+ /**
15
+ * Validates and freezes a learned type, with PHP's checks and messages.
16
+ *
17
+ * @throws LearningError
18
+ */
19
+ export function defineCustomEntityType(init) {
20
+ const { name, description, examples, counterExamples = [], pattern = null } = init;
21
+ // PHP's pattern has no /u and no D modifier: $ also matches before a final "\n".
22
+ if (!/^[A-Z][A-Z0-9_]{1,39}\n?$/.test(name)) {
23
+ throw new LearningError('The name must be UPPER_SNAKE_CASE, 2 to 40 characters, e.g. INSURANCE_NUMBER.');
24
+ }
25
+ if (isEntityType(name)) {
26
+ throw new LearningError(`"${name}" is a built-in type. Choose another name.`);
27
+ }
28
+ if (examples.length === 0) {
29
+ throw new LearningError('At least one example is needed.');
30
+ }
31
+ // Description and examples reach the detection model: keep them short, single-line data.
32
+ assertSingleLine(description, CUSTOM_ENTITY_TYPE_LIMITS.maxDescriptionLength, 'The description');
33
+ const max = CUSTOM_ENTITY_TYPE_LIMITS.maxExamples;
34
+ if (examples.length > max || counterExamples.length > max) {
35
+ throw new LearningError(`At most ${String(max)} examples and ${String(max)} counter-examples.`);
36
+ }
37
+ for (const example of [...examples, ...counterExamples]) {
38
+ assertSingleLine(example, CUSTOM_ENTITY_TYPE_LIMITS.maxExampleLength, 'An example');
39
+ }
40
+ let compiled = null;
41
+ if (pattern !== null) {
42
+ compiled = checkPattern(pattern, examples, counterExamples);
43
+ }
44
+ const type = Object.freeze({
45
+ name,
46
+ description,
47
+ examples: Object.freeze([...examples]),
48
+ counterExamples: Object.freeze([...counterExamples]),
49
+ pattern,
50
+ });
51
+ compiledPatterns.set(type, compiled);
52
+ return type;
53
+ }
54
+ /**
55
+ * Builds a type from stored data (JSON file, key-value store) like PHP's `fromArray()`: non-string
56
+ * 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.
58
+ *
59
+ * @throws LearningError
60
+ */
61
+ export function customEntityTypeFromJSON(data) {
62
+ const record = isPhpArray(data) ? data : {};
63
+ const strings = (list) => isPhpArray(list) ? Object.values(list).filter((v) => typeof v === 'string') : [];
64
+ const { name, description, examples, counterExamples, pattern } = record;
65
+ return defineCustomEntityType({
66
+ name: typeof name === 'string' ? name : '',
67
+ description: typeof description === 'string' ? description : '',
68
+ examples: strings(examples),
69
+ counterExamples: strings(counterExamples),
70
+ pattern: typeof pattern === 'string' && pattern !== '' ? pattern : null,
71
+ });
72
+ }
73
+ /** The compiled pattern of a type (validating it first if it did not come from defineCustomEntityType()). */
74
+ export function compiledPattern(type) {
75
+ let compiled = compiledPatterns.get(type);
76
+ if (compiled === undefined) {
77
+ compiled = compiledPatterns.get(defineCustomEntityType(type)) ?? null;
78
+ compiledPatterns.set(type, compiled);
79
+ }
80
+ return compiled;
81
+ }
82
+ /** JSON objects and arrays are both PHP arrays. */
83
+ function isPhpArray(value) {
84
+ return typeof value === 'object' && value !== null;
85
+ }
86
+ function assertSingleLine(value, maxLength, what) {
87
+ // No control characters (one line) and no angle brackets: they could end the model's data block.
88
+ // eslint-disable-next-line no-control-regex -- control characters are what this check is about
89
+ if (codePointLength(value) > maxLength || /[\x00-\x1F\x7F<>]/u.test(value)) {
90
+ throw new LearningError(`${what} must be one line of at most ${String(maxLength)} characters, without < and >.`);
91
+ }
92
+ }
93
+ function checkPattern(pattern, examples, counterExamples) {
94
+ const compiled = LearnedPattern.compile(pattern);
95
+ if (!(compiled instanceof LearnedPattern) && !compiled.compiles) {
96
+ throw new LearningError(`The pattern ${pattern} is not a valid regular expression.`);
97
+ }
98
+ // Patterns run on every text: no constructs that can backtrack catastrophically (ReDoS).
99
+ let reason = codePointLength(pattern) > CUSTOM_ENTITY_TYPE_LIMITS.maxPatternLength
100
+ ? `longer than ${String(CUSTOM_ENTITY_TYPE_LIMITS.maxPatternLength)} characters`
101
+ : patternViolation(pattern);
102
+ if (reason === null && !(compiled instanceof LearnedPattern)) {
103
+ // Cannot happen: everything the grammar allows is compiled or rejected as invalid above.
104
+ throw new LearningError(`The pattern ${pattern} is not a valid regular expression.`);
105
+ }
106
+ if (reason === null && compiled instanceof LearnedPattern && !runsInBoundedTime(compiled, examples)) {
107
+ reason = 'it takes too long on adversarial input';
108
+ }
109
+ if (reason !== null || !(compiled instanceof LearnedPattern)) {
110
+ throw new LearningError(`The pattern ${pattern} is not allowed: ${reason ?? ''}.`);
111
+ }
112
+ // Examples are personal data: messages name their position, never the value (they reach HTTP and MCP clients).
113
+ examples.forEach((example, i) => {
114
+ if (!compiled.matchesWhole(example)) {
115
+ throw new LearningError(`The pattern ${pattern} does not match example ${String(i + 1)}.`);
116
+ }
117
+ });
118
+ counterExamples.forEach((counter, i) => {
119
+ if (compiled.matchesWhole(counter)) {
120
+ throw new LearningError(`The pattern ${pattern} also matches counter-example ${String(i + 1)}.`);
121
+ }
122
+ });
123
+ return compiled;
124
+ }
125
+ /**
126
+ * Second line of defence, as in PHP: the whole-word search must finish on long near-miss inputs within
127
+ * the backtracking budget. Our engine counts like PCRE without its start-up optimisations, so it can be
128
+ * stricter than PHP (docs/DEVIATIONS.md).
129
+ */
130
+ /** Steps the bounded-time check may spend in total, across all adversarial inputs. */
131
+ const VALIDATION_BUDGET = 10_000_000;
132
+ function runsInBoundedTime(pattern, examples) {
133
+ const inputs = [
134
+ `${'a'.repeat(5000)}!`,
135
+ `${'A'.repeat(5000)}!`,
136
+ `${'1'.repeat(5000)}!`,
137
+ `${'A1-'.repeat(2000)}!`,
138
+ `${' '.repeat(5000)}x`,
139
+ ];
140
+ for (const example of examples) {
141
+ const times = Math.floor(5000 / Math.max(1, codePointLength(example)));
142
+ inputs.push(`${example.repeat(times)}!`, `${Array.from(example).slice(0, -1).join('').repeat(times)}!`);
143
+ }
144
+ // PHP limits each start position only, so a check can take 5000 × BACKTRACK_LIMIT steps per input (16 s
145
+ // for `.{0,45}.{0,45}.{0,45}X`). PHP spends that time in a request worker; Node would block its event loop,
146
+ // i.e. every request of an HTTP or MCP server. One budget across all inputs caps the check at well under a
147
+ // second; patterns that need more are rejected (docs/DEVIATIONS.md).
148
+ const total = { steps: 0, max: VALIDATION_BUDGET };
149
+ return inputs.every((input) => pattern.searchesWithin(input, BACKTRACK_LIMIT, total));
150
+ }
@@ -0,0 +1,50 @@
1
+ import type { Detector } from '../detector.js';
2
+ import { type CustomEntityType, type CustomEntityTypeInit } from './custom-entity-type.js';
3
+ import type { CustomEntityStore } from './store.js';
4
+ export interface LearningResult {
5
+ readonly type: CustomEntityType;
6
+ /** Why the type has no pattern (model-only), or null. */
7
+ readonly note: string | null;
8
+ }
9
+ export interface EntityLearnerOptions {
10
+ store: CustomEntityStore;
11
+ /** Derives a pattern from examples; default learnPattern(). */
12
+ learnPattern?: (examples: readonly string[], counterExamples: readonly string[]) => string;
13
+ }
14
+ /**
15
+ * Teach pii-shield new entity types from examples ("mask things like this too").
16
+ *
17
+ * A pattern is derived from the examples unless one is given. Values without a structure (plain words
18
+ * such as pet names) cannot become a safe pattern; they are learned as model-only types.
19
+ *
20
+ * Detection is synchronous, the store is not: the learner keeps a snapshot of the stored types. It is
21
+ * updated by learn() and forget() and reloaded by refresh(); `EntityLearner.create()` loads it once.
22
+ * Call refresh() (e.g. on a timer) to pick up types other processes learned.
23
+ */
24
+ export declare class EntityLearner {
25
+ #private;
26
+ constructor(options: EntityLearnerOptions);
27
+ /** A learner whose snapshot is already loaded from the store. */
28
+ static create(options: EntityLearnerOptions): Promise<EntityLearner>;
29
+ /**
30
+ * Learns and saves the type (replacing one with the same name).
31
+ *
32
+ * @throws LearningError
33
+ */
34
+ learn(init: CustomEntityTypeInit): Promise<LearningResult>;
35
+ /**
36
+ * Same as learn(), without saving: for trying out examples.
37
+ *
38
+ * @throws LearningError
39
+ */
40
+ preview(init: CustomEntityTypeInit): LearningResult;
41
+ forget(name: string): Promise<void>;
42
+ /** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
43
+ types(): Promise<CustomEntityType[]>;
44
+ /** Reloads the snapshot the detector uses. */
45
+ refresh(): Promise<void>;
46
+ /** The types in the current snapshot. */
47
+ get snapshot(): readonly CustomEntityType[];
48
+ /** A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take effect. */
49
+ detector(): Detector;
50
+ }
@@ -0,0 +1,87 @@
1
+ import { LearningError } from '../errors.js';
2
+ import { phpTrim } from '../internal/pcre.js';
3
+ import { LearnedTypesDetector } from './custom-entity-detector.js';
4
+ import { defineCustomEntityType } from './custom-entity-type.js';
5
+ import { learnPattern } from './pattern-learner.js';
6
+ const MODEL_ONLY_NOTE = 'No pattern: plain words would match ordinary text. Only model-based detection finds this type.';
7
+ /**
8
+ * Teach pii-shield new entity types from examples ("mask things like this too").
9
+ *
10
+ * A pattern is derived from the examples unless one is given. Values without a structure (plain words
11
+ * such as pet names) cannot become a safe pattern; they are learned as model-only types.
12
+ *
13
+ * Detection is synchronous, the store is not: the learner keeps a snapshot of the stored types. It is
14
+ * updated by learn() and forget() and reloaded by refresh(); `EntityLearner.create()` loads it once.
15
+ * Call refresh() (e.g. on a timer) to pick up types other processes learned.
16
+ */
17
+ export class EntityLearner {
18
+ #store;
19
+ #learnPattern;
20
+ #snapshot = [];
21
+ constructor(options) {
22
+ this.#store = options.store;
23
+ this.#learnPattern = options.learnPattern ?? learnPattern;
24
+ }
25
+ /** A learner whose snapshot is already loaded from the store. */
26
+ static async create(options) {
27
+ const learner = new EntityLearner(options);
28
+ await learner.refresh();
29
+ return learner;
30
+ }
31
+ /**
32
+ * Learns and saves the type (replacing one with the same name).
33
+ *
34
+ * @throws LearningError
35
+ */
36
+ async learn(init) {
37
+ const result = this.preview(init);
38
+ await this.#store.save(result.type);
39
+ await this.refresh();
40
+ return result;
41
+ }
42
+ /**
43
+ * Same as learn(), without saving: for trying out examples.
44
+ *
45
+ * @throws LearningError
46
+ */
47
+ preview(init) {
48
+ const { examples, counterExamples = [] } = init;
49
+ let { pattern = null } = init;
50
+ let note = null;
51
+ if (pattern === null || phpTrim(pattern) === '') {
52
+ try {
53
+ pattern = this.#learnPattern(examples, counterExamples);
54
+ }
55
+ catch (e) {
56
+ if (!(e instanceof LearningError) || e.code !== 'LEARNING_PLAIN_WORDS') {
57
+ throw e;
58
+ }
59
+ pattern = null;
60
+ note = MODEL_ONLY_NOTE;
61
+ }
62
+ }
63
+ return Object.freeze({ type: defineCustomEntityType({ ...init, counterExamples, pattern }), note });
64
+ }
65
+ async forget(name) {
66
+ await this.#store.remove(name);
67
+ await this.refresh();
68
+ }
69
+ /** All stored types, sorted by name (read from the store, also refreshing the snapshot). */
70
+ async types() {
71
+ const types = await this.#store.all();
72
+ this.#snapshot = Object.freeze([...types]);
73
+ return types;
74
+ }
75
+ /** Reloads the snapshot the detector uses. */
76
+ async refresh() {
77
+ await this.types();
78
+ }
79
+ /** The types in the current snapshot. */
80
+ get snapshot() {
81
+ return this.#snapshot;
82
+ }
83
+ /** A detector for all learned patterns; picks up the snapshot at each call, so later learn() calls take effect. */
84
+ detector() {
85
+ return new LearnedTypesDetector(() => this.#snapshot);
86
+ }
87
+ }
@@ -0,0 +1,36 @@
1
+ import type { CustomEntityType } from './custom-entity-type.js';
2
+ import { type CustomEntityStore } from './store.js';
3
+ export interface JsonFileCustomEntityStoreOptions {
4
+ /**
5
+ * Lock writes across processes with a lock file next to the store (`<path>.lock`, created exclusively).
6
+ * Default true. A lock older than `staleMs` (default 10000) is taken over; waiting longer than
7
+ * `timeoutMs` (default 5000) throws.
8
+ */
9
+ lock?: boolean | {
10
+ staleMs?: number;
11
+ timeoutMs?: number;
12
+ };
13
+ }
14
+ /**
15
+ * Learned types in one JSON file: readable, diffable, easy to review before deploying.
16
+ *
17
+ * The file is byte-identical to PHP's JsonFileCustomEntityStore (sorted by name, pretty-printed with
18
+ * four spaces, unescaped Unicode and slashes, trailing newline), so both can read each other's file.
19
+ * Writes are atomic (temporary file in the same directory + rename); the file gets mode 0600, a missing
20
+ * directory 0700. save() and remove() read, change and write the whole list under a lock file, which
21
+ * also serialises writers within one process. PHP's LockingCustomEntityStore uses symfony/lock instead:
22
+ * the two locks do not see each other.
23
+ */
24
+ export declare class JsonFileCustomEntityStore implements CustomEntityStore {
25
+ #private;
26
+ constructor(path: string, options?: JsonFileCustomEntityStoreOptions);
27
+ all(): Promise<CustomEntityType[]>;
28
+ get(name: string): Promise<CustomEntityType | null>;
29
+ save(type: CustomEntityType): Promise<void>;
30
+ remove(name: string): Promise<void>;
31
+ }
32
+ /**
33
+ * PHP's json_encode() with JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES:
34
+ * like JSON.stringify(…, null, 4), except that PHP still escapes U+2028 and U+2029.
35
+ */
36
+ export declare function encodeJson(value: unknown): string;
@@ -0,0 +1,132 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmod, mkdir, open, readFile, rename, stat, unlink } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
5
+ import { PiiShieldError } from '../errors.js';
6
+ import { sortByName, typesFromJSON } from './store.js';
7
+ /**
8
+ * Learned types in one JSON file: readable, diffable, easy to review before deploying.
9
+ *
10
+ * The file is byte-identical to PHP's JsonFileCustomEntityStore (sorted by name, pretty-printed with
11
+ * four spaces, unescaped Unicode and slashes, trailing newline), so both can read each other's file.
12
+ * Writes are atomic (temporary file in the same directory + rename); the file gets mode 0600, a missing
13
+ * directory 0700. save() and remove() read, change and write the whole list under a lock file, which
14
+ * also serialises writers within one process. PHP's LockingCustomEntityStore uses symfony/lock instead:
15
+ * the two locks do not see each other.
16
+ */
17
+ export class JsonFileCustomEntityStore {
18
+ #path;
19
+ #lock;
20
+ constructor(path, options = {}) {
21
+ this.#path = path;
22
+ const { lock = true } = options;
23
+ this.#lock =
24
+ lock === false
25
+ ? null
26
+ : {
27
+ staleMs: (lock === true ? undefined : lock.staleMs) ?? 10_000,
28
+ timeoutMs: (lock === true ? undefined : lock.timeoutMs) ?? 5_000,
29
+ };
30
+ }
31
+ async all() {
32
+ let raw;
33
+ try {
34
+ raw = await readFile(this.#path, 'utf8');
35
+ }
36
+ catch (e) {
37
+ if (e.code === 'ENOENT' || e.code === 'EISDIR') {
38
+ return [];
39
+ }
40
+ throw e;
41
+ }
42
+ let data = null;
43
+ try {
44
+ data = JSON.parse(raw);
45
+ }
46
+ catch {
47
+ // handled below, like PHP's json_decode() returning null
48
+ }
49
+ if (typeof data !== 'object' || data === null) {
50
+ throw new PiiShieldError(`"${this.#path}" does not contain a list of learned types.`, 'LEARNING_STORE_CORRUPT');
51
+ }
52
+ return typesFromJSON(data);
53
+ }
54
+ async get(name) {
55
+ return (await this.all()).find((t) => t.name === name) ?? null;
56
+ }
57
+ save(type) {
58
+ return this.#locked(async () => {
59
+ const types = (await this.all()).filter((t) => t.name !== type.name);
60
+ await this.#write([...types, type]);
61
+ });
62
+ }
63
+ remove(name) {
64
+ return this.#locked(async () => {
65
+ await this.#write((await this.all()).filter((t) => t.name !== name));
66
+ });
67
+ }
68
+ async #write(types) {
69
+ const json = `${encodeJson(sortByName(types))}\n`;
70
+ const dir = dirname(this.#path);
71
+ await mkdir(dir, { recursive: true, mode: 0o700 });
72
+ const tmp = join(dir, `.learned-${randomBytes(6).toString('hex')}`);
73
+ const file = await open(tmp, 'wx', 0o600);
74
+ try {
75
+ await file.writeFile(json, 'utf8');
76
+ }
77
+ finally {
78
+ await file.close();
79
+ }
80
+ try {
81
+ await chmod(tmp, 0o600);
82
+ await rename(tmp, this.#path);
83
+ }
84
+ catch (e) {
85
+ await unlink(tmp).catch(() => undefined);
86
+ throw e;
87
+ }
88
+ }
89
+ async #locked(write) {
90
+ if (this.#lock === null) {
91
+ return write();
92
+ }
93
+ const lockPath = `${this.#path}.lock`;
94
+ await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 });
95
+ const deadline = Date.now() + this.#lock.timeoutMs;
96
+ for (let wait = 5;; wait = Math.min(wait * 2, 25)) {
97
+ try {
98
+ const handle = await open(lockPath, 'wx', 0o600);
99
+ await handle.writeFile(`${String(process.pid)}\n`);
100
+ await handle.close();
101
+ break;
102
+ }
103
+ catch (e) {
104
+ if (e.code !== 'EEXIST') {
105
+ throw e;
106
+ }
107
+ }
108
+ const age = await stat(lockPath).then((s) => Date.now() - s.mtimeMs, () => 0);
109
+ if (age > this.#lock.staleMs) {
110
+ await unlink(lockPath).catch(() => undefined); // a crashed writer's lock
111
+ continue;
112
+ }
113
+ if (Date.now() > deadline) {
114
+ throw new PiiShieldError(`Timed out waiting for the lock "${lockPath}".`, 'LEARNING_STORE_LOCKED');
115
+ }
116
+ await sleep(wait);
117
+ }
118
+ try {
119
+ await write();
120
+ }
121
+ finally {
122
+ await unlink(lockPath).catch(() => undefined);
123
+ }
124
+ }
125
+ }
126
+ /**
127
+ * PHP's json_encode() with JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES:
128
+ * like JSON.stringify(…, null, 4), except that PHP still escapes U+2028 and U+2029.
129
+ */
130
+ export function encodeJson(value) {
131
+ return JSON.stringify(value, null, 4).replace(/[\u{2028}\u{2029}]/gu, (c) => `\\u${(c.codePointAt(0) ?? 0).toString(16)}`);
132
+ }
@@ -0,0 +1,48 @@
1
+ /** pcre.backtrack_limit used by PHP's CustomEntityType and CustomEntityDetector. */
2
+ export declare const BACKTRACK_LIMIT = 100000;
3
+ /** The search or match ran over its backtracking budget (PHP: preg_match() returns false). */
4
+ export declare class BacktrackLimitExceeded extends Error {
5
+ }
6
+ /** A text prepared for matching: code points plus their UTF-16 offsets. */
7
+ export declare class Subject {
8
+ readonly text: string;
9
+ readonly codePoints: Int32Array;
10
+ readonly offsets: Int32Array;
11
+ /** Run caches of the programs that searched this text. */
12
+ readonly runs: WeakMap<object, {
13
+ from: Int32Array;
14
+ end: Int32Array;
15
+ }>;
16
+ constructor(text: string);
17
+ }
18
+ /** A compiled learned pattern. */
19
+ export declare class LearnedPattern {
20
+ #private;
21
+ private constructor();
22
+ /**
23
+ * Compiles a pattern, or says why not: "invalid" (PCRE would not compile it either) or "unsupported"
24
+ * (outside the grammar subset; `compiles` then guesses what PCRE says).
25
+ */
26
+ static compile(pattern: string): LearnedPattern | {
27
+ error: 'invalid' | 'unsupported';
28
+ compiles: boolean;
29
+ };
30
+ /** `preg_match('~^(?:…)$~u', $text)`; false also when the budget runs out. */
31
+ matchesWhole(text: string, limit?: number): boolean;
32
+ /**
33
+ * `preg_match('~(?<![\p{L}\p{N}])(?:…)(?![\p{L}\p{N}])~u', $text)` within the budget: `limit` per start
34
+ * position like PCRE, and optionally a `total` shared across calls (see runsInBoundedTime()).
35
+ */
36
+ searchesWithin(text: string, limit: number, total?: {
37
+ steps: number;
38
+ readonly max: number;
39
+ }): boolean;
40
+ /**
41
+ * All whole-word matches like preg_match_all(), with UTF-16 offsets; empty matches are dropped (as
42
+ * RegexMatcher does). Throws BacktrackLimitExceeded when one search exceeds the budget.
43
+ */
44
+ matchAll(text: string, limit?: number): {
45
+ value: string;
46
+ offset: number;
47
+ }[];
48
+ }