@waswrongassembled/pii-shield 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +29 -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,56 @@
1
+ import { typeName } from './entity.js';
2
+ import { EntityExtractor } from './entity-extractor.js';
3
+ import { EntityType } from './entity-type.js';
4
+ import { replaceSpans } from './internal/text-spans.js';
5
+ import { PartialMask } from './masking/partial-mask.js';
6
+ import { TypeLabelMask } from './masking/type-label-mask.js';
7
+ /** IBAN keeps first and last 4 characters, phone keeps the last 2. */
8
+ export function defaultMaskingStrategies() {
9
+ return {
10
+ [EntityType.Iban]: new PartialMask({ keepStart: 4, keepEnd: 4 }),
11
+ [EntityType.Phone]: new PartialMask({ keepEnd: 2 }),
12
+ };
13
+ }
14
+ /**
15
+ * Same detection as PiiShield, but replaces entities irreversibly. No mapping, no way back.
16
+ *
17
+ * A strategy is looked up by the entity's type name (learned types), then by its type; everything else
18
+ * goes to the fallback, which turns it into a type label.
19
+ */
20
+ export class PiiMasker {
21
+ #extractor;
22
+ #strategies;
23
+ #fallback;
24
+ constructor(options = {}) {
25
+ const { detectors, allowlist, strategies = {}, fallback = new TypeLabelMask() } = options;
26
+ this.#extractor = new EntityExtractor({
27
+ ...(detectors === undefined ? {} : { detectors }),
28
+ ...(allowlist === undefined ? {} : { allowlist }),
29
+ });
30
+ const merged = new Map();
31
+ for (const [type, strategy] of [...Object.entries(defaultMaskingStrategies()), ...Object.entries(strategies)]) {
32
+ if (strategy !== undefined) {
33
+ merged.set(type, toFunction(strategy));
34
+ }
35
+ }
36
+ this.#strategies = merged;
37
+ this.#fallback = toFunction(fallback);
38
+ }
39
+ /**
40
+ * @throws TypeError when an async detector (e.g. ModelDetector) is configured; use maskAsync()
41
+ */
42
+ mask(text) {
43
+ return replaceSpans(text, this.#extractor.extract(text), (entity) => this.#strategyFor(entity)(entity));
44
+ }
45
+ /** Like mask(), and works with async detectors such as ModelDetector. */
46
+ async maskAsync(text, options = {}) {
47
+ const entities = await this.#extractor.extractAsync(text, options);
48
+ return replaceSpans(text, entities, (entity) => this.#strategyFor(entity)(entity));
49
+ }
50
+ #strategyFor(entity) {
51
+ return this.#strategies.get(typeName(entity)) ?? this.#strategies.get(entity.type) ?? this.#fallback;
52
+ }
53
+ }
54
+ function toFunction(strategy) {
55
+ return typeof strategy === 'function' ? strategy : (entity) => strategy.mask(entity);
56
+ }
@@ -0,0 +1,40 @@
1
+ import type { DetectOptions } from './detector.js';
2
+ import { type EntityExtractorOptions } from './entity-extractor.js';
3
+ import { type PlaceholderMapping, type RedactionResult, type Redactor, type RestoreResult, type VaultRedactionResult, type VaultRedactor } from './redaction.js';
4
+ import { type Vault } from './vault/vault.js';
5
+ export interface PiiShieldOptions extends EntityExtractorOptions {
6
+ /** Optional; enables redactToVault(), restoreFromVault() and forget() across requests. */
7
+ vault?: Vault;
8
+ /** Seconds a stored mapping lives, a positive integer. Default: PiiShield.DEFAULT_VAULT_TTL (3600). */
9
+ vaultTtl?: number;
10
+ }
11
+ /**
12
+ * Replaces each detected entity with a consistent, typed placeholder (see EntityExtractor for detection rules).
13
+ *
14
+ * - Consistency: the same value always gets the same placeholder within one text.
15
+ * - Person aliases: a surname that also occurs as last part of a full name maps to the
16
+ * full name's placeholder. Restore yields the full name.
17
+ */
18
+ export declare class PiiShield implements VaultRedactor {
19
+ #private;
20
+ static readonly DEFAULT_VAULT_TTL = 3600;
21
+ constructor(options?: PiiShieldOptions);
22
+ /**
23
+ * @throws TypeError when an async detector (e.g. ModelDetector) is configured; use redactAsync()
24
+ */
25
+ redact(text: string): RedactionResult;
26
+ /** Like redact(), and works with async detectors such as ModelDetector. */
27
+ redactAsync(text: string, options?: DetectOptions): Promise<RedactionResult>;
28
+ restore(text: string, source: RedactionResult | PlaceholderMapping): RestoreResult;
29
+ redactToVault(text: string, options?: DetectOptions): Promise<VaultRedactionResult>;
30
+ restoreFromVault(text: string, vaultId: string): Promise<RestoreResult>;
31
+ forget(vaultId: string): Promise<void>;
32
+ }
33
+ /**
34
+ * Pass-through implementation, e.g. to build an app before the real shield is wired up. Redacts nothing.
35
+ */
36
+ export declare class NullPiiShield implements Redactor {
37
+ redact(text: string): RedactionResult;
38
+ redactAsync(text: string, options?: DetectOptions): Promise<RedactionResult>;
39
+ restore(text: string, source?: RedactionResult | PlaceholderMapping): RestoreResult;
40
+ }
@@ -0,0 +1,142 @@
1
+ import { typeName } from './entity.js';
2
+ import { EntityExtractor, surname } from './entity-extractor.js';
3
+ import { EntityType } from './entity-type.js';
4
+ import { VaultError } from './errors.js';
5
+ import { replaceSpans } from './internal/text-spans.js';
6
+ import { formatPlaceholder } from './placeholder.js';
7
+ import { createRedactionResult, restorePlaceholders, withVaultId, } from './redaction.js';
8
+ import { assertTtl } from './vault/vault.js';
9
+ /**
10
+ * Replaces each detected entity with a consistent, typed placeholder (see EntityExtractor for detection rules).
11
+ *
12
+ * - Consistency: the same value always gets the same placeholder within one text.
13
+ * - Person aliases: a surname that also occurs as last part of a full name maps to the
14
+ * full name's placeholder. Restore yields the full name.
15
+ */
16
+ export class PiiShield {
17
+ static DEFAULT_VAULT_TTL = 3600;
18
+ #extractor;
19
+ #vault;
20
+ #vaultTtl;
21
+ constructor(options = {}) {
22
+ const { detectors, allowlist, vault, vaultTtl = PiiShield.DEFAULT_VAULT_TTL } = options;
23
+ assertTtl(vaultTtl, 'The vault TTL must be positive.');
24
+ this.#vault = vault;
25
+ this.#vaultTtl = vaultTtl;
26
+ this.#extractor = new EntityExtractor({
27
+ ...(detectors === undefined ? {} : { detectors }),
28
+ ...(allowlist === undefined ? {} : { allowlist }),
29
+ });
30
+ }
31
+ /**
32
+ * @throws TypeError when an async detector (e.g. ModelDetector) is configured; use redactAsync()
33
+ */
34
+ redact(text) {
35
+ return redactEntities(text, this.#extractor.extract(text));
36
+ }
37
+ /** Like redact(), and works with async detectors such as ModelDetector. */
38
+ async redactAsync(text, options = {}) {
39
+ return redactEntities(text, await this.#extractor.extractAsync(text, options));
40
+ }
41
+ restore(text, source) {
42
+ return restorePlaceholders(text, source);
43
+ }
44
+ async redactToVault(text, options = {}) {
45
+ const vault = this.#requireVault();
46
+ const result = await this.redactAsync(text, options);
47
+ const vaultId = Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(16))).toString('hex');
48
+ await vault.store(vaultId, result.mapping, this.#vaultTtl);
49
+ return withVaultId(result, vaultId);
50
+ }
51
+ async restoreFromVault(text, vaultId) {
52
+ const mapping = await this.#requireVault().fetch(vaultId);
53
+ if (mapping === null) {
54
+ throw new VaultError('Unknown or expired vault id.', 'VAULT_UNKNOWN_ID');
55
+ }
56
+ return restorePlaceholders(text, mapping);
57
+ }
58
+ async forget(vaultId) {
59
+ await this.#requireVault().delete(vaultId);
60
+ }
61
+ #requireVault() {
62
+ if (this.#vault === undefined) {
63
+ throw new Error('No vault configured. Pass a Vault to PiiShield to restore across requests.');
64
+ }
65
+ return this.#vault;
66
+ }
67
+ }
68
+ /**
69
+ * Pass-through implementation, e.g. to build an app before the real shield is wired up. Redacts nothing.
70
+ */
71
+ export class NullPiiShield {
72
+ redact(text) {
73
+ return createRedactionResult(text, {}, []);
74
+ }
75
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- same signature as Redactor
76
+ redactAsync(text, options) {
77
+ return Promise.resolve(this.redact(text));
78
+ }
79
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- same signature as Redactor
80
+ restore(text, source) {
81
+ return Object.freeze({
82
+ text,
83
+ unknownPlaceholders: Object.freeze([]),
84
+ unusedPlaceholders: Object.freeze([]),
85
+ isClean: true,
86
+ });
87
+ }
88
+ }
89
+ function redactEntities(text, entities) {
90
+ if (entities.length === 0) {
91
+ return createRedactionResult(text, {}, entities);
92
+ }
93
+ const { mapping, byValue } = assignPlaceholders(entities);
94
+ const redacted = replaceSpans(text, entities, (e) => byValue.get(typeName(e))?.get(e.value) ?? e.value);
95
+ return createRedactionResult(redacted, mapping, entities);
96
+ }
97
+ /**
98
+ * Numbers placeholders per type name in order of appearance. Full names come first, so a surname
99
+ * that appears before its full name still links to it.
100
+ *
101
+ * @param entities sorted by offset
102
+ */
103
+ function assignPlaceholders(entities) {
104
+ const mapping = {};
105
+ // type name → value → placeholder
106
+ const byValue = new Map();
107
+ const counters = new Map();
108
+ const fullNames = entities.filter((e) => e.type === EntityType.Person && surname(e.value) !== null);
109
+ for (const entity of [...fullNames, ...entities]) {
110
+ const type = typeName(entity);
111
+ let placeholders = byValue.get(type);
112
+ if (placeholders === undefined) {
113
+ placeholders = new Map();
114
+ byValue.set(type, placeholders);
115
+ }
116
+ if (placeholders.has(entity.value)) {
117
+ continue;
118
+ }
119
+ if (entity.type === EntityType.Person && surname(entity.value) === null) {
120
+ const alias = fullNameFor(entity.value, placeholders);
121
+ if (alias !== null) {
122
+ placeholders.set(entity.value, alias);
123
+ continue;
124
+ }
125
+ }
126
+ const counter = (counters.get(type) ?? 0) + 1;
127
+ counters.set(type, counter);
128
+ const placeholder = formatPlaceholder(type, counter);
129
+ placeholders.set(entity.value, placeholder);
130
+ mapping[placeholder] = entity.value;
131
+ }
132
+ return { mapping, byValue };
133
+ }
134
+ /** The placeholder of the first full name (in assignment order) whose surname is `name`. */
135
+ function fullNameFor(name, placeholders) {
136
+ for (const [fullName, placeholder] of placeholders) {
137
+ if (surname(fullName) === name) {
138
+ return placeholder;
139
+ }
140
+ }
141
+ return null;
142
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Canonical placeholder "⟦TYPE_N⟧" (wire format, identical to PHP).
3
+ *
4
+ * @param type an EntityType value or the name of a learned type (see typeName())
5
+ * @param number counter per type, starting at 1
6
+ */
7
+ export declare function formatPlaceholder(type: string, number: number): string;
8
+ /**
9
+ * Calls `replace` for every placeholder in `text` and returns the text with the return values in place.
10
+ *
11
+ * Parsing tolerates what models do to placeholders: case changes, inner whitespace, a space instead of
12
+ * an underscore, markdown-escaped underscores (`\_`) and ASCII `[[...]]` brackets. Type names may contain
13
+ * digits (learned types such as "VN2_NUMBER"); the last number is the counter.
14
+ *
15
+ * @param replace receives the canonical form (e.g. "⟦TAX_NUMBER_1⟧") and the text as found (e.g. "[[tax number 1]]")
16
+ */
17
+ export declare function replacePlaceholders(text: string, replace: (canonical: string, original: string) => string): string;
18
+ /**
19
+ * Length of the (tolerant) placeholder that starts exactly at `index`, or -1.
20
+ *
21
+ * @internal
22
+ */
23
+ export declare function placeholderLengthAt(text: string, index: number): number;
24
+ /**
25
+ * Incremental check whether a text can still grow into a placeholder that TOLERANT matches at its start.
26
+ * Start with `PLACEHOLDER_PREFIX_START` and feed one code point at a time to `stepPlaceholderPrefix()`;
27
+ * the result is 0 when it can no longer become one and has `PLACEHOLDER_PREFIX_DONE` set when it is complete.
28
+ *
29
+ * @internal
30
+ */
31
+ export declare const PLACEHOLDER_PREFIX_START = 1;
32
+ /** @internal */
33
+ export declare const PLACEHOLDER_PREFIX_DONE = 1024;
34
+ /** @internal */
35
+ export declare function stepPlaceholderPrefix(states: number, c: string): number;
36
+ /**
37
+ * Automaton state after reading `text` from `index` to its end (0: it cannot become a placeholder).
38
+ *
39
+ * @internal
40
+ */
41
+ export declare function placeholderPrefixState(text: string, index: number): number;
42
+ /**
43
+ * Whether `text` from `index` to its end is an unfinished placeholder: it starts with an opening bracket
44
+ * and nothing so far rules it out. Used to hold back stream chunks.
45
+ *
46
+ * @internal
47
+ */
48
+ export declare function isPlaceholderPrefix(text: string, index: number): boolean;
@@ -0,0 +1,138 @@
1
+ import { DIGIT, SPACE } from './internal/pcre.js';
2
+ const OPEN = '⟦';
3
+ const CLOSE = '⟧';
4
+ /**
5
+ * PHP's Placeholder::TOLERANT_PATTERN. It is a /u pattern, so \s and \d are Unicode-aware (PCRE2_UCP):
6
+ * "⟦PERSON\u{A0}1⟧" is found, and the number may contain non-ASCII digits (kept as they are).
7
+ * Letters stay ASCII ([A-Za-z], no i flag), so "K" (U+212A) or "ſ" never start a type.
8
+ */
9
+ const TOLERANT = new RegExp(String.raw `(?:⟦|\[\[)${SPACE}*(?<type>[A-Za-z][A-Za-z0-9]*(?:(?:\\?_|${SPACE}+)[A-Za-z0-9]+)*)(?:\\?_|${SPACE}+)(?<number>${DIGIT}+)${SPACE}*(?:⟧|\]\])`, 'gu');
10
+ /**
11
+ * PHP replaces the separators inside the type with a pattern *without* /u, so only ASCII whitespace
12
+ * (\t \n \v \f \r and space) becomes "_"; a no-break space inside the type stays and the placeholder is unknown.
13
+ */
14
+ const TYPE_SEPARATOR = /\\?_|[\t\n\v\f\r ]+/g;
15
+ /**
16
+ * Canonical placeholder "⟦TYPE_N⟧" (wire format, identical to PHP).
17
+ *
18
+ * @param type an EntityType value or the name of a learned type (see typeName())
19
+ * @param number counter per type, starting at 1
20
+ */
21
+ export function formatPlaceholder(type, number) {
22
+ return `${OPEN}${type}_${String(number)}${CLOSE}`;
23
+ }
24
+ /**
25
+ * Calls `replace` for every placeholder in `text` and returns the text with the return values in place.
26
+ *
27
+ * Parsing tolerates what models do to placeholders: case changes, inner whitespace, a space instead of
28
+ * an underscore, markdown-escaped underscores (`\_`) and ASCII `[[...]]` brackets. Type names may contain
29
+ * digits (learned types such as "VN2_NUMBER"); the last number is the counter.
30
+ *
31
+ * @param replace receives the canonical form (e.g. "⟦TAX_NUMBER_1⟧") and the text as found (e.g. "[[tax number 1]]")
32
+ */
33
+ export function replacePlaceholders(text, replace) {
34
+ return text.replace(TOLERANT, (original, ...rest) => {
35
+ const groups = rest.at(-1);
36
+ const type = asciiUpper(groups.type.replace(TYPE_SEPARATOR, '_'));
37
+ return replace(`${OPEN}${type}_${groups.number}${CLOSE}`, original);
38
+ });
39
+ }
40
+ const TOLERANT_AT = new RegExp(TOLERANT.source, 'uy');
41
+ /**
42
+ * Length of the (tolerant) placeholder that starts exactly at `index`, or -1.
43
+ *
44
+ * @internal
45
+ */
46
+ export function placeholderLengthAt(text, index) {
47
+ TOLERANT_AT.lastIndex = index;
48
+ const match = TOLERANT_AT.exec(text);
49
+ return match === null ? -1 : match[0].length;
50
+ }
51
+ const IS_SPACE = new RegExp(`^${SPACE}$`, 'u');
52
+ const IS_DIGIT = new RegExp(`^${DIGIT}$`, 'u');
53
+ const IS_LETTER = /^[A-Za-z]$/;
54
+ const IS_ALNUM = /^[A-Za-z0-9]$/;
55
+ // States of an automaton that follows TOLERANT from its start (a bit set: the pattern is ambiguous).
56
+ const START = 1; // nothing read yet
57
+ const HALF_OPEN = 2; // the first [ of [[
58
+ const AFTER_OPEN = 4; // ⟦ or [[ and optional spaces
59
+ const IN_TYPE = 8; // inside a type token [A-Za-z0-9]+
60
+ const AFTER_BACKSLASH = 16; // \ of an escaped underscore
61
+ const AFTER_UNDERSCORE = 32; // _ separator
62
+ const AFTER_SPACE = 64; // whitespace separator
63
+ const IN_NUMBER = 128; // counter digits
64
+ const AFTER_NUMBER = 256; // spaces before the closing bracket
65
+ const AFTER_FIRST_CLOSE = 512; // first ] of ]]
66
+ const DONE = 1024; // closing bracket read: TOLERANT matches
67
+ /**
68
+ * Incremental check whether a text can still grow into a placeholder that TOLERANT matches at its start.
69
+ * Start with `PLACEHOLDER_PREFIX_START` and feed one code point at a time to `stepPlaceholderPrefix()`;
70
+ * the result is 0 when it can no longer become one and has `PLACEHOLDER_PREFIX_DONE` set when it is complete.
71
+ *
72
+ * @internal
73
+ */
74
+ export const PLACEHOLDER_PREFIX_START = START;
75
+ /** @internal */
76
+ export const PLACEHOLDER_PREFIX_DONE = DONE;
77
+ /** @internal */
78
+ export function stepPlaceholderPrefix(states, c) {
79
+ const space = IS_SPACE.test(c);
80
+ const digit = IS_DIGIT.test(c);
81
+ const alnum = IS_ALNUM.test(c);
82
+ let next = 0;
83
+ if (states & START)
84
+ next |= c === OPEN ? AFTER_OPEN : c === '[' ? HALF_OPEN : 0;
85
+ if (states & HALF_OPEN && c === '[')
86
+ next |= AFTER_OPEN;
87
+ if (states & AFTER_OPEN)
88
+ next |= (space ? AFTER_OPEN : 0) | (IS_LETTER.test(c) ? IN_TYPE : 0);
89
+ if (states & IN_TYPE) {
90
+ next |= (alnum ? IN_TYPE : 0) | (space ? AFTER_SPACE : 0);
91
+ next |= c === '\\' ? AFTER_BACKSLASH : c === '_' ? AFTER_UNDERSCORE : 0;
92
+ }
93
+ if (states & AFTER_BACKSLASH && c === '_')
94
+ next |= AFTER_UNDERSCORE;
95
+ if (states & AFTER_UNDERSCORE)
96
+ next |= (alnum ? IN_TYPE : 0) | (digit ? IN_NUMBER : 0);
97
+ if (states & AFTER_SPACE)
98
+ next |= (space ? AFTER_SPACE : 0) | (alnum ? IN_TYPE : 0) | (digit ? IN_NUMBER : 0);
99
+ if (states & IN_NUMBER)
100
+ next |= (digit ? IN_NUMBER : 0) | (space ? AFTER_NUMBER : 0);
101
+ if (states & AFTER_NUMBER && space)
102
+ next |= AFTER_NUMBER;
103
+ if (states & (IN_NUMBER | AFTER_NUMBER))
104
+ next |= c === ']' ? AFTER_FIRST_CLOSE : c === CLOSE ? DONE : 0;
105
+ if (states & AFTER_FIRST_CLOSE && c === ']')
106
+ next |= DONE;
107
+ return next;
108
+ }
109
+ /**
110
+ * Automaton state after reading `text` from `index` to its end (0: it cannot become a placeholder).
111
+ *
112
+ * @internal
113
+ */
114
+ export function placeholderPrefixState(text, index) {
115
+ let states = START;
116
+ for (let i = index; i < text.length;) {
117
+ const c = String.fromCodePoint(text.codePointAt(i) ?? 0);
118
+ states = stepPlaceholderPrefix(states, c);
119
+ if (states === 0) {
120
+ return 0;
121
+ }
122
+ i += c.length;
123
+ }
124
+ return states;
125
+ }
126
+ /**
127
+ * Whether `text` from `index` to its end is an unfinished placeholder: it starts with an opening bracket
128
+ * and nothing so far rules it out. Used to hold back stream chunks.
129
+ *
130
+ * @internal
131
+ */
132
+ export function isPlaceholderPrefix(text, index) {
133
+ return (placeholderPrefixState(text, index) & ~DONE) !== 0;
134
+ }
135
+ /** PHP's strtoupper(): ASCII only. */
136
+ function asciiUpper(text) {
137
+ return text.replace(/[a-z]+/g, (s) => s.toUpperCase());
138
+ }
@@ -0,0 +1,76 @@
1
+ import type { DetectOptions } from './detector.js';
2
+ import type { Entity } from './entity.js';
3
+ import type { EntityType } from './entity-type.js';
4
+ /**
5
+ * Placeholder → original value, e.g. `{ '⟦PERSON_1⟧': 'Maria Muster' }`, in order of assignment.
6
+ * A plain object, so it serializes as the JSON object the PHP package stores in its vault.
7
+ */
8
+ export type PlaceholderMapping = Readonly<Record<string, string>>;
9
+ /**
10
+ * Result of a redaction. Holds the original values: never log it, persist it or send it to a model provider
11
+ * (send `redactedText` only).
12
+ *
13
+ * A frozen plain object. `JSON.stringify` includes the mapping (it is the data you restore from);
14
+ * only `util.inspect` / `console.log` in Node hide it, like PHP's `__debugInfo()`.
15
+ *
16
+ * `PiiShield.redactToVault()` returns a VaultRedactionResult, which adds the `vaultId`.
17
+ */
18
+ export interface RedactionResult {
19
+ readonly redactedText: string;
20
+ readonly mapping: PlaceholderMapping;
21
+ /** All detected entities (offsets into the original text), for diagnostics and tests. */
22
+ readonly entities: readonly Entity[];
23
+ }
24
+ /** Result of `PiiShield.redactToVault()`: the mapping is also stored in the vault under `vaultId`. */
25
+ export interface VaultRedactionResult extends RedactionResult {
26
+ /** 32 lowercase hex characters (16 random bytes). Pass it to restoreFromVault() and forget(). */
27
+ readonly vaultId: string;
28
+ }
29
+ export interface RestoreResult {
30
+ readonly text: string;
31
+ /** Placeholders found in the text that are not in the mapping (the model invented them), in order of appearance. */
32
+ readonly unknownPlaceholders: readonly string[];
33
+ /** Mapping entries that did not appear in the text (informational), in mapping order. */
34
+ readonly unusedPlaceholders: readonly string[];
35
+ /** True when there are no unknown placeholders. */
36
+ readonly isClean: boolean;
37
+ }
38
+ /** Reversible redaction (PHP's PiiShieldInterface). */
39
+ export interface Redactor {
40
+ /** Replaces detected personal data with consistent, typed placeholders. */
41
+ redact(text: string): RedactionResult;
42
+ /** Like redact(), also with async detectors (model-based detection). */
43
+ redactAsync(text: string, options?: DetectOptions): Promise<RedactionResult>;
44
+ /** Replaces placeholders in a (model-generated) text with the original values. */
45
+ restore(text: string, source: RedactionResult | PlaceholderMapping): RestoreResult;
46
+ }
47
+ /**
48
+ * Unmasking across requests (PHP's VaultAwarePiiShieldInterface): the mapping is stored in a vault, a later
49
+ * request restores by id.
50
+ */
51
+ export interface VaultRedactor extends Redactor {
52
+ /** Redacts like redactAsync() and stores the mapping in the vault under a new random id. */
53
+ redactToVault(text: string, options?: DetectOptions): Promise<VaultRedactionResult>;
54
+ /**
55
+ * @throws VaultError if the id is unknown or expired, or the entry cannot be read
56
+ * @throws Error if no vault is configured
57
+ */
58
+ restoreFromVault(text: string, vaultId: string): Promise<RestoreResult>;
59
+ /**
60
+ * Deletes the mapping immediately (end of conversation, right to erasure).
61
+ *
62
+ * @throws Error if no vault is configured
63
+ */
64
+ forget(vaultId: string): Promise<void>;
65
+ }
66
+ /** @internal */
67
+ export declare function createRedactionResult(redactedText: string, mapping: Record<string, string>, entities: Entity[]): RedactionResult;
68
+ /** @internal */
69
+ export declare function withVaultId(result: RedactionResult, vaultId: string): VaultRedactionResult;
70
+ /**
71
+ * Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
72
+ * Placeholders that are not in the mapping stay as they were found.
73
+ */
74
+ export declare function restorePlaceholders(text: string, source: RedactionResult | PlaceholderMapping): RestoreResult;
75
+ /** The distinct entity types of a redaction, in order of first appearance (PHP's foundTypes()). */
76
+ export declare function foundTypes(result: Pick<RedactionResult, 'entities'>): EntityType[];
@@ -0,0 +1,52 @@
1
+ import { replacePlaceholders } from './placeholder.js';
2
+ const INSPECT = Symbol.for('nodejs.util.inspect.custom');
3
+ /** @internal */
4
+ export function createRedactionResult(redactedText, mapping, entities) {
5
+ const result = { redactedText, mapping: Object.freeze(mapping), entities: Object.freeze(entities) };
6
+ Object.defineProperty(result, INSPECT, {
7
+ value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length }),
8
+ });
9
+ return Object.freeze(result);
10
+ }
11
+ /** @internal */
12
+ export function withVaultId(result, vaultId) {
13
+ const { redactedText, mapping, entities } = result;
14
+ const withId = { redactedText, mapping, entities, vaultId };
15
+ Object.defineProperty(withId, INSPECT, {
16
+ value: () => ({ redactedText, mapping: '[hidden]', entityCount: entities.length, vaultId }),
17
+ });
18
+ return Object.freeze(withId);
19
+ }
20
+ /**
21
+ * Replaces placeholders (tolerant to model mangling, see replacePlaceholders()) with their original values.
22
+ * Placeholders that are not in the mapping stay as they were found.
23
+ */
24
+ export function restorePlaceholders(text, source) {
25
+ const mapping = isRedactionResult(source) ? source.mapping : source;
26
+ const seen = new Set();
27
+ const unknown = new Set();
28
+ const restored = replacePlaceholders(text, (canonical, original) => {
29
+ const value = Object.hasOwn(mapping, canonical) ? mapping[canonical] : undefined;
30
+ if (value === undefined) {
31
+ unknown.add(canonical);
32
+ return original;
33
+ }
34
+ seen.add(canonical);
35
+ return value;
36
+ });
37
+ return Object.freeze({
38
+ text: restored,
39
+ unknownPlaceholders: Object.freeze([...unknown]),
40
+ unusedPlaceholders: Object.freeze(Object.keys(mapping).filter((placeholder) => !seen.has(placeholder))),
41
+ isClean: unknown.size === 0,
42
+ });
43
+ }
44
+ /** The distinct entity types of a redaction, in order of first appearance (PHP's foundTypes()). */
45
+ export function foundTypes(result) {
46
+ return [...new Set(result.entities.map((e) => e.type))];
47
+ }
48
+ function isRedactionResult(source) {
49
+ // A mapping only holds strings, so an object-valued "mapping" property marks a RedactionResult.
50
+ const mapping = source.mapping;
51
+ return typeof mapping === 'object' && mapping !== null;
52
+ }
@@ -0,0 +1,23 @@
1
+ import { ServiceApi } from '../service/service-api.js';
2
+ /** A configuration problem; the message names the variable, never a secret. */
3
+ export declare class ConfigError extends Error {
4
+ readonly name = "ConfigError";
5
+ }
6
+ export interface EnvService {
7
+ api: ServiceApi;
8
+ allowedHosts: string[];
9
+ maxBodyBytes: number;
10
+ host: string;
11
+ port: number;
12
+ /** Notes for the operator (stderr), e.g. that mappings do not survive a restart. Never secrets. */
13
+ notes: string[];
14
+ /** Closes connections the configuration opened (Redis). */
15
+ close(): Promise<void>;
16
+ }
17
+ /**
18
+ * Builds the service from environment variables (names as in the PHP service where they exist; see
19
+ * docs/server.md). Used by the `pii-shield` CLI.
20
+ *
21
+ * @throws ConfigError
22
+ */
23
+ export declare function serviceFromEnv(env?: Readonly<Record<string, string | undefined>>): Promise<EnvService>;