-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanonymizer.js
More file actions
401 lines (357 loc) · 13.7 KB
/
Copy pathanonymizer.js
File metadata and controls
401 lines (357 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"use strict";
(function (window) {
// Simple text wrapper with change notification.
class TextWrapper {
constructor(initialText = "") {
this.text = initialText;
this._onTextChange = null;
}
get() {
return this.text;
}
set(newText) {
this.text = newText;
if (this._onTextChange) {
this._onTextChange(newText);
}
}
setOnTextChange(callback) {
this._onTextChange = callback;
}
}
class Anonymizer {
constructor(initialText = "") {
// Updated placeholder types with new EmailPlaceholder integration.
this.placeholderTypes = [
new NumberPlaceholder(), // placeholder for numbers
new NamePlaceholder(), // placeholder for names
new EmailPlaceholder() // placeholder for emails
];
this.whitelist = [];
this._wlMapping = {};
this._wlCounter = 1;
this.scanCompleted = false;
// Mapping entries: [original, token, placeholder, rank]
this.mapping = [];
this._abortController = null;
// Callback properties
this._onProgress = null;
this._onMappingChange = null;
this._onComplete = null;
this._onAbort = null;
this._onTextChange = null;
this.textWrapper = new TextWrapper(initialText);
this.textWrapper.setOnTextChange(() => this._triggerTextChange());
}
// Callback setters
setOnProgress(callback) { this._onProgress = callback; }
setOnMappingChange(callback) { this._onMappingChange = callback; }
setOnComplete(callback) { this._onComplete = callback; }
setOnAbort(callback) { this._onAbort = callback; }
setOnTextChange(callback) { this._onTextChange = callback; }
// Trigger progress callback
_triggerProgress(percent, message) {
if (this._onProgress) this._onProgress(percent, message);
}
_triggerMappingChange() {
if (this._onMappingChange) this._onMappingChange();
}
_triggerComplete(mapping) {
if (this._onComplete) this._onComplete(mapping);
}
_triggerAbort() {
if (this._onAbort) this._onAbort();
}
_triggerTextChange() {
if (this._onTextChange) this._onTextChange();
}
// Set text and apply whitelist, then clean mapping list.
setText(newText = "") {
const processedText = this._applyWhitelist(newText);
this.textWrapper.set(processedText);
this.cleanMappingList();
}
// Replace whitelist items with tokens.
_applyWhitelist(newText) {
this._wlMapping = {};
this._wlCounter = 1;
// Sort whitelist items by length descending.
const sortedWL = [...this.whitelist].sort((a, b) => b.length - a.length);
sortedWL.forEach(wl => {
const token = `[!WL!${this._wlCounter++}]`;
const escaped = window.Utils.escapeRegExp(wl);
newText = newText.replace(new RegExp(escaped, "g"), token);
this._wlMapping[token] = wl;
});
return newText;
}
// Restore whitelist tokens.
_restoreWhitelist(text) {
for (const token in this._wlMapping) {
const wlValue = this._wlMapping[token];
text = text.replace(new RegExp(window.Utils.escapeRegExp(token), "g"), wlValue);
}
return text;
}
// Scan text for sensitive data using new detection strategies.
async identifyPII() {
if (this._abortController) {
this._abortController.abort();
this._triggerAbort();
}
this._abortController = new AbortController();
const signal = this._abortController.signal;
this.scanCompleted = false;
const originalText = this.textWrapper.get();
// Filter active placeholders; assume each has an 'enabled' property (default true).
const activePlaceholders = this.placeholderTypes.filter(ph => ph.enabled !== false)
.sort((a, b) => (a.rank || 0) - (b.rank || 0));
for (let i = 0; i < activePlaceholders.length; i++) {
if (signal.aborted) return;
const ph = activePlaceholders[i];
const percent = Math.round(((i + 1) / activePlaceholders.length) * 100);
this._triggerProgress(percent, `Scanning for ${ph.placeholderPrefix}...`);
// Use the new detect method from the placeholder.
const results = ph.detect(originalText, this.mapping) || [];
results.forEach(result => {
// Add detection result to mapping list.
this.addToMappingList(result.original, result.token, ph, ph.rank);
});
}
this.cleanMappingList();
this._triggerComplete(this.mapping);
this.scanCompleted = true;
this._abortController = null;
console.log("PII identification completed.");
}
// Add a new mapping entry. Removes entries with the same original text.
addToMappingList(original, token, placeholder, rank) {
this.mapping = this.mapping.filter(entry => entry[0] !== original);
this.mapping.push([original, token, placeholder, rank]);
this._triggerMappingChange();
}
// Apply anonymization by assigning tokens and replacing sensitive data.
_applyAnonymization(text, mappingList) {
let modifiedText = text;
const updatedMappingList = mappingList.map(entry => [...entry]);
updatedMappingList.sort((a, b) => {
if (a[3] === b[3]) {
return b[0].length - a[0].length;
}
return a[3] - b[3];
});
updatedMappingList.forEach(entry => {
const [original, token, placeholder] = entry;
const regex = new RegExp(window.Utils.escapeRegExp(original), "g");
if (regex.test(modifiedText)) {
if (token === null) {
entry[1] = placeholder.getNextTokenName(updatedMappingList);
}
modifiedText = modifiedText.replace(regex, entry[1]);
}
});
return { modifiedText, updatedMappingList };
}
// Replace sensitive data with tokens.
async anonymize() {
if (!this.scanCompleted) {
await this.identifyPII();
}
const { modifiedText, updatedMappingList } =
this._applyAnonymization(this.textWrapper.get(), this.mapping);
this.mapping = updatedMappingList;
this.setText(modifiedText);
return this.textWrapper.get();
}
// Replace tokens with original sensitive data.
deanonymize() {
let text = this.textWrapper.get();
this.mapping.forEach(entry => {
if (entry[1] !== null) {
text = text.replace(new RegExp(window.Utils.escapeRegExp(entry[1]), "g"), entry[0]);
}
});
this.setText(text);
return this.textWrapper.get();
}
// Return final text with whitelist restored.
getText() {
return this._restoreWhitelist(this.textWrapper.get());
}
clearMapping() {
this.mapping = [];
this._triggerMappingChange();
}
getMapping() {
return this.mapping;
}
// Clean mapping list by removing invalid or duplicate entries.
cleanMappingList() {
const { updatedMappingList } = this._applyAnonymization(this.textWrapper.get(), this.mapping);
this.mapping = this.mapping.filter(entry => {
if (!entry[2].enabled) return false;
if (entry[1] !== null) return true;
return updatedMappingList.some(simEntry =>
simEntry[0] === entry[0] &&
simEntry[2] === entry[2] &&
simEntry[1] !== null
);
});
this._triggerMappingChange();
}
// Add item to whitelist and re-run detection.
addToWhitelist(item) {
if (!this.whitelist.includes(item)) {
let currentText = this.textWrapper.get();
const regex = new RegExp(window.Utils.escapeRegExp(item), "g");
const matches = currentText.match(regex);
if (matches) {
matches.forEach(match => {
const regex = new RegExp(window.Utils.escapeRegExp(match), "g");
const mappingEntry = this.mapping.find(entry => entry[1] === match);
if (mappingEntry) {
const originalText = mappingEntry[0];
currentText = currentText.replace(regex, originalText);
item = currentText;
}
});
}
this.textWrapper.set(currentText);
this.whitelist.push(item);
this.setText(this.getText());
this.identifyPII();
}
}
removeFromWhitelist(item) {
this.whitelist = this.whitelist.filter(wl => wl !== item);
this.setText(this.getText());
this.identifyPII();
}
addCustomPlaceholder(label, pattern, direct = false) {
let uniqueLabel;
if (this.placeholderTypes.some(ph => ph.placeholderPrefix === label)) {
let counter = 1;
uniqueLabel = label + counter;
while (this.placeholderTypes.some(ph => ph.placeholderPrefix === uniqueLabel)) {
counter++;
uniqueLabel = label + counter;
}
} else {
uniqueLabel = label;
}
const customPlaceholder = new CustomPlaceholderType(pattern, uniqueLabel);
this.placeholderTypes.push(customPlaceholder);
const currentText = this.textWrapper.get();
const results = customPlaceholder.detect(currentText, this.mapping) || [];
results.forEach(entry => {
// Verwende entry.original statt entry[0] und entry.token statt entry[1]
this.addToMappingList(entry.original, entry.token, customPlaceholder, customPlaceholder.rank);
});
if (direct && typeof customPlaceholder.apply === 'function') {
customPlaceholder.apply();
}
}
getUniqueSecretLabel() {
let maxNum = 0;
this.placeholderTypes.forEach(ph => {
if (ph.placeholderPrefix.startsWith("Secret")) {
const num = parseInt(ph.placeholderPrefix.slice(6), 10);
if (!isNaN(num) && num > maxNum) maxNum = num;
}
});
return "Secret" + (maxNum + 1);
}
getPlaceholderByID(id) {
return this.placeholderTypes.find(ph => ph.id === id);
}
removePlaceholder(id) {
const ph = this.getPlaceholderByID(id);
if (!ph) return;
// Deanonymize: Replace all tokens belonging to the placeholder with their original text
let currentText = this.textWrapper.get();
this.mapping.forEach(entry => {
if (entry[2].id === ph.id && entry[1] !== null) {
const token = entry[1];
const original = entry[0];
const regex = new RegExp(window.Utils.escapeRegExp(token), "g");
currentText = currentText.replace(regex, original);
}
});
// Update the text with deanonymized content
this.textWrapper.set(currentText);
// Remove mapping entries related to the placeholder
this.mapping = this.mapping.filter(entry => entry[2].id !== ph.id);
// Remove the placeholder if it is custom, otherwise disable it
if (ph.isCustom) {
const index = this.placeholderTypes.findIndex(item => item.id === ph.id);
if (index !== -1) {
this.placeholderTypes.splice(index, 1);
}
} else {
ph.enabled = false;
}
// Trigger callbacks to notify mapping and text changes
this._triggerMappingChange();
this._triggerTextChange();
// Re-identify PII in the updated text
this.identifyPII();
}
setPlaceholderStatus(id, status) {
const ph = this.getPlaceholderByID(id);
if (ph) {
// If disabling, first deanonymize all tokens associated with this placeholder
if (!status) {
let currentText = this.textWrapper.get();
this.mapping.forEach(entry => {
if (entry[2].id === ph.id && entry[1] !== null) {
const token = entry[1];
const original = entry[0];
const regex = new RegExp(window.Utils.escapeRegExp(token), "g");
currentText = currentText.replace(regex, original);
}
});
// Update the text with deanonymized content
this.textWrapper.set(currentText);
// Remove mapping entries related to this placeholder
this.mapping = this.mapping.filter(entry => entry[2].id !== ph.id);
// Trigger mapping and text change callbacks
this._triggerMappingChange();
this._triggerTextChange();
}
// Set placeholder enabled status
ph.enabled = status;
// Re-run PII identification after changes
this.identifyPII();
}
}
// Singular anonymization: replace all occurrences of a specific original text.
anonymizeSingleText(originalText) {
let mappingEntry = this.mapping.find(entry => entry[0] === originalText);
if (!mappingEntry) return;
const regex = new RegExp(window.Utils.escapeRegExp(originalText), "g");
let currentText = this.textWrapper.get();
if (mappingEntry[1] === null) {
mappingEntry[1] = mappingEntry[2].getNextTokenName(this.mapping);
}
currentText = currentText.replace(regex, mappingEntry[1]);
this.setText(currentText);
this._triggerTextChange();
}
// Singular deanonymization: replace a specific token with its original text.
deanonymizeSingleToken(token) {
let mappingEntry = this.mapping.find(entry => entry[1] === token);
if (!mappingEntry) return;
let currentText = this.textWrapper.get();
const regex = new RegExp(window.Utils.escapeRegExp(token), "g");
currentText = currentText.replace(regex, mappingEntry[0]);
this.setText(currentText);
this._triggerTextChange();
}
}
window.Anonymizer = Anonymizer;
window.TextWrapper = TextWrapper;
// Compatibility alias for existing calls.
Anonymizer.prototype.deanonymize_singleToken = Anonymizer.prototype.deanonymizeSingleToken;
Anonymizer.prototype.anonymize_singleText = Anonymizer.prototype.anonymizeSingleText;
})(window);
window.anonymizer = new Anonymizer();