forked from NomicFoundation/hardhat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanonymizer.ts
351 lines (297 loc) · 10.3 KB
/
anonymizer.ts
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
import { Event, Exception, StackFrame, Stacktrace } from "@sentry/node";
import findup from "find-up";
import { either } from "fp-ts";
import * as path from "path";
interface WordMatch {
index: number;
word: string;
}
const ANONYMIZED_FILE = "<user-file>";
const ANONYMIZED_MNEMONIC = "<mnemonic>";
const MNEMONIC_PHRASE_LENGTH_THRESHOLD = 7;
const MINIMUM_AMOUNT_OF_WORDS_TO_ANONYMIZE = 4;
export class Anonymizer {
constructor(private _configPath?: string) {}
/**
* Given a sentry serialized exception
* (https://develop.sentry.dev/sdk/event-payloads/exception/), return an
* anonymized version of the event.
*/
public anonymize(event: any): either.Either<string, Event> {
if (event === null || event === undefined) {
return either.left("event is null or undefined");
}
if (typeof event !== "object") {
return either.left("event is not an object");
}
const result: Event = {
event_id: event.event_id,
platform: event.platform,
timestamp: event.timestamp,
extra: event.extra,
};
if (event.exception !== undefined && event.exception.values !== undefined) {
const anonymizededExceptions = this._anonymizeExceptions(
event.exception.values
);
result.exception = {
values: anonymizededExceptions,
};
}
return either.right(result);
}
/**
* Return the anonymized filename and a boolean indicating if the content of
* the file should be anonymized
*/
public anonymizeFilename(filename: string): {
anonymizedFilename: string;
anonymizeContent: boolean;
} {
if (filename === this._configPath) {
const packageJsonPath = this._getFilePackageJsonPath(filename);
if (!packageJsonPath) {
// if we can't find a package.json, we just return the basename
return {
anonymizedFilename: path.basename(filename),
anonymizeContent: true,
};
}
return {
anonymizedFilename: path.relative(
path.dirname(packageJsonPath),
filename
),
anonymizeContent: true,
};
}
const parts = filename.split(path.sep);
const nodeModulesIndex = parts.indexOf("node_modules");
if (nodeModulesIndex === -1) {
if (filename.startsWith("internal")) {
// show internal parts of the stack trace
return {
anonymizedFilename: filename,
anonymizeContent: false,
};
}
// if the file isn't inside node_modules and it's a user file, we hide it completely
return {
anonymizedFilename: ANONYMIZED_FILE,
anonymizeContent: true,
};
}
return {
anonymizedFilename: parts.slice(nodeModulesIndex).join(path.sep),
anonymizeContent: false,
};
}
public anonymizeErrorMessage(errorMessage: string): string {
errorMessage = this._anonymizeMnemonic(errorMessage);
// the \\ before path.sep is necessary for this to work on windows
const pathRegex = new RegExp(`\\S+\\${path.sep}\\S+`, "g");
// for files that don't have a path separator
const fileRegex = new RegExp("\\S+\\.(js|ts)\\S*", "g");
// hide hex strings of 20 chars or more
const hexRegex = /(0x)?[0-9A-Fa-f]{20,}/g;
return errorMessage
.replace(pathRegex, ANONYMIZED_FILE)
.replace(fileRegex, ANONYMIZED_FILE)
.replace(hexRegex, (match) => match.replace(/./g, "x"));
}
public raisedByHardhat(event: Event): boolean {
const exceptions = event?.exception?.values;
if (exceptions === undefined) {
// if we can't prove that the exception doesn't come from hardhat,
// we err on the side of reporting the error
return true;
}
const originalException = exceptions[exceptions.length - 1];
const frames = originalException?.stacktrace?.frames;
if (frames === undefined) {
return true;
}
for (const frame of frames.slice().reverse()) {
if (frame.filename === undefined) {
continue;
}
// we stop after finding either a hardhat file or a file from the user's
// project
if (this._isHardhatFile(frame.filename)) {
return true;
}
if (frame.filename === ANONYMIZED_FILE) {
return false;
}
if (
this._configPath !== undefined &&
this._configPath.includes(frame.filename)
) {
return false;
}
}
// if we didn't find any hardhat frame, we don't report the error
return false;
}
protected _getFilePackageJsonPath(filename: string): string | undefined {
return findup.sync("package.json", {
cwd: path.dirname(filename),
});
}
private _isHardhatFile(filename: string): boolean {
const nomiclabsPath = path.join("node_modules", "@nomiclabs");
const nomicFoundationPath = path.join("node_modules", "@nomicfoundation");
const truffleContractPath = path.join(nomiclabsPath, "truffle-contract");
const isHardhatFile =
(filename.startsWith(nomiclabsPath) ||
filename.startsWith(nomicFoundationPath)) &&
!filename.startsWith(truffleContractPath);
return isHardhatFile;
}
private _anonymizeExceptions(exceptions: Exception[]): Exception[] {
return exceptions.map((exception) => this._anonymizeException(exception));
}
private _anonymizeException(value: Exception): Exception {
const result: Exception = {
type: value.type,
};
if (value.value !== undefined) {
result.value = this.anonymizeErrorMessage(value.value);
}
if (value.stacktrace !== undefined) {
result.stacktrace = this._anonymizeStacktrace(value.stacktrace);
}
return result;
}
private _anonymizeStacktrace(stacktrace: Stacktrace): Stacktrace {
if (stacktrace.frames !== undefined) {
const anonymizededFrames = this._anonymizeFrames(stacktrace.frames);
return {
frames: anonymizededFrames,
};
}
return {};
}
private _anonymizeFrames(frames: StackFrame[]): StackFrame[] {
return frames.map((frame) => this._anonymizeFrame(frame));
}
private _anonymizeFrame(frame: StackFrame): StackFrame {
const result: StackFrame = {
lineno: frame.lineno,
colno: frame.colno,
function: frame.function,
};
let anonymizeContent = true;
if (frame.filename !== undefined) {
const anonymizationResult = this.anonymizeFilename(frame.filename);
result.filename = anonymizationResult.anonymizedFilename;
anonymizeContent = anonymizationResult.anonymizeContent;
}
if (!anonymizeContent) {
result.context_line = frame.context_line;
result.pre_context = frame.pre_context;
result.post_context = frame.post_context;
result.vars = frame.vars;
}
return result;
}
private _anonymizeMnemonic(errorMessage: string): string {
const matches = getAllWordMatches(errorMessage);
// If there are enough consecutive words, there's a good chance of there being a mnemonic phrase
if (matches.length < MNEMONIC_PHRASE_LENGTH_THRESHOLD) {
return errorMessage;
}
const mnemonicWordlist = ([] as string[]).concat(
...[
require("ethereum-cryptography/bip39/wordlists/czech"),
require("ethereum-cryptography/bip39/wordlists/english"),
require("ethereum-cryptography/bip39/wordlists/french"),
require("ethereum-cryptography/bip39/wordlists/italian"),
require("ethereum-cryptography/bip39/wordlists/japanese"),
require("ethereum-cryptography/bip39/wordlists/korean"),
require("ethereum-cryptography/bip39/wordlists/simplified-chinese"),
require("ethereum-cryptography/bip39/wordlists/spanish"),
require("ethereum-cryptography/bip39/wordlists/traditional-chinese"),
].map((wordlistModule) => wordlistModule.wordlist)
);
let anonymizedMessage = errorMessage.slice(0, matches[0].index);
// Determine all mnemonic phrase maximal fragments.
// We check sequences of n consecutive words just in case there is a typo
let wordIndex = 0;
while (wordIndex < matches.length) {
const maximalPhrase = getMaximalMnemonicPhrase(
matches,
errorMessage,
wordIndex,
mnemonicWordlist
);
if (maximalPhrase.length >= MINIMUM_AMOUNT_OF_WORDS_TO_ANONYMIZE) {
const lastAnonymizedWord = maximalPhrase[maximalPhrase.length - 1];
const nextWordIndex =
wordIndex + maximalPhrase.length < matches.length
? matches[wordIndex + maximalPhrase.length].index
: errorMessage.length;
const sliceUntilNextWord = errorMessage.slice(
lastAnonymizedWord.index + lastAnonymizedWord.word.length,
nextWordIndex
);
anonymizedMessage += `${ANONYMIZED_MNEMONIC}${sliceUntilNextWord}`;
wordIndex += maximalPhrase.length;
} else {
const thisWord = matches[wordIndex];
const nextWordIndex =
wordIndex + 1 < matches.length
? matches[wordIndex + 1].index
: errorMessage.length;
const sliceUntilNextWord = errorMessage.slice(
thisWord.index,
nextWordIndex
);
anonymizedMessage += sliceUntilNextWord;
wordIndex++;
}
}
return anonymizedMessage;
}
}
function getMaximalMnemonicPhrase(
matches: WordMatch[],
originalMessage: string,
startIndex: number,
mnemonicWordlist: string[]
): WordMatch[] {
const maximalPhrase: WordMatch[] = [];
for (let i = startIndex; i < matches.length; i++) {
const thisMatch = matches[i];
if (!mnemonicWordlist.includes(thisMatch.word)) {
break;
}
if (maximalPhrase.length > 0) {
// Check that there's only whitespace until this word.
const lastMatch = maximalPhrase[maximalPhrase.length - 1];
const lastIndex = lastMatch.index + lastMatch.word.length;
const sliceBetweenWords = originalMessage.slice(
lastIndex,
thisMatch.index
);
if (!/\s+/u.test(sliceBetweenWords)) {
break;
}
}
maximalPhrase.push(thisMatch);
}
return maximalPhrase;
}
function getAllWordMatches(errorMessage: string) {
const matches: WordMatch[] = [];
const re = /\p{Letter}+/gu;
let match = re.exec(errorMessage);
while (match !== null) {
matches.push({
word: match[0],
index: match.index,
});
match = re.exec(errorMessage);
}
return matches;
}