-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
346 lines (302 loc) · 9.39 KB
/
utils.js
File metadata and controls
346 lines (302 loc) · 9.39 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
/**
* Shared utilities for AutoFill Plugin
* Logger, Validator, and error handling utilities
*/
// ============================================================================
// LOGGER - Strukturert loggingssystem
// ============================================================================
const LogLevel = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
NONE: 4
};
const Logger = {
level: LogLevel.INFO, // Default level
prefix: '[AutoFill]',
/**
* Set log level
* @param {number} level - LogLevel value
*/
setLevel(level) {
this.level = level;
},
/**
* Enable debug mode
*/
enableDebug() {
this.level = LogLevel.DEBUG;
},
/**
* Format message with timestamp and context
*/
_format(level, context, message, ...args) {
const timestamp = new Date().toISOString().substr(11, 12);
const levelStr = ['DEBUG', 'INFO', 'WARN', 'ERROR'][level] || 'LOG';
const contextStr = context ? `[${context}]` : '';
return [`${this.prefix} ${timestamp} ${levelStr}${contextStr}:`, message, ...args];
},
/**
* Debug level logging
*/
debug(context, message, ...args) {
if (this.level <= LogLevel.DEBUG) {
console.log(...this._format(LogLevel.DEBUG, context, message, ...args));
}
},
/**
* Info level logging
*/
info(context, message, ...args) {
if (this.level <= LogLevel.INFO) {
console.info(...this._format(LogLevel.INFO, context, message, ...args));
}
},
/**
* Warning level logging
*/
warn(context, message, ...args) {
if (this.level <= LogLevel.WARN) {
console.warn(...this._format(LogLevel.WARN, context, message, ...args));
}
},
/**
* Error level logging
*/
error(context, message, ...args) {
if (this.level <= LogLevel.ERROR) {
console.error(...this._format(LogLevel.ERROR, context, message, ...args));
}
}
};
// ============================================================================
// VALIDATOR - Input validering
// ============================================================================
const Validator = {
/**
* Sjekk om en streng er en gyldig URL
* @param {string} url - URL å validere
* @returns {boolean}
*/
isValidUrl(url) {
if (!url || typeof url !== 'string') return false;
try {
new URL(url);
return true;
} catch {
return false;
}
},
/**
* Sjekk om en streng er et gyldig regex-mønster
* Inkluderer enkel ReDoS-deteksjon for farlige mønstre
* @param {string} pattern - Regex pattern å validere
* @returns {{valid: boolean, error?: string, warning?: string}}
*/
isValidRegex(pattern) {
if (!pattern || typeof pattern !== 'string') {
return { valid: false, error: 'Pattern must be a non-empty string' };
}
try {
new RegExp(pattern);
// Enkel ReDoS-deteksjon: Se etter nested quantifiers
const redosPatterns = [
/(\+|\*|\{[0-9,]+\})\s*(\+|\*|\{[0-9,]+\})/, // Nested quantifiers: a]++, a## , etc
/\([^)]*(\+|\*)\)[^)]*(\+|\*)/, // (a+)+ pattern
/(\.\*){2,}/, // Multiple .* in sequence
];
for (const dangerous of redosPatterns) {
if (dangerous.test(pattern)) {
return {
valid: true,
warning: 'Pattern may cause performance issues (potential ReDoS)'
};
}
}
return { valid: true };
} catch (e) {
return { valid: false, error: e.message };
}
},
/**
* Kjør regex med timeout for å unngå ReDoS
* @param {RegExp} regex - Regex å kjøre
* @param {string} text - Tekst å matche
* @param {number} timeoutMs - Timeout i millisekunder (default 100)
* @returns {{match: boolean, timedOut: boolean}}
*/
safeRegexTest(regex, text, timeoutMs = 100) {
// For korte strenger, kjør direkte
if (text.length < 1000) {
return { match: regex.test(text), timedOut: false };
}
// For lange strenger, bruk chunking som enkel timeout-mekanisme
const startTime = Date.now();
const chunkSize = 500;
for (let i = 0; i < text.length; i += chunkSize) {
if (Date.now() - startTime > timeoutMs) {
return { match: false, timedOut: true };
}
const chunk = text.slice(Math.max(0, i - 100), i + chunkSize);
if (regex.test(chunk)) {
return { match: true, timedOut: false };
}
}
return { match: false, timedOut: false };
},
/**
* Sjekk om en streng er en gyldig CSS-selector
* @param {string} selector - CSS selector å validere
* @returns {{valid: boolean, error?: string}}
*/
isValidSelector(selector) {
if (!selector || typeof selector !== 'string') {
return { valid: false, error: 'Selector must be a non-empty string' };
}
try {
document.querySelector(selector);
return { valid: true };
} catch (e) {
return { valid: false, error: e.message };
}
},
/**
* Sanitize en streng for sikker bruk (fjern potensielt farlige tegn)
* @param {string} str - Streng å sanitere
* @param {number} maxLength - Maks lengde (default 1000)
* @returns {string}
*/
sanitizeString(str, maxLength = 1000) {
if (!str || typeof str !== 'string') return '';
return str.slice(0, maxLength).trim();
},
/**
* Valider en regel-objekt
* @param {object} rule - Regel å validere
* @returns {{valid: boolean, errors: string[]}}
*/
validateRule(rule) {
const errors = [];
if (!rule || typeof rule !== 'object') {
return { valid: false, errors: ['Rule must be an object'] };
}
// Påkrevde felt
if (!rule.sitePattern) {
errors.push('sitePattern is required');
}
if (!rule.fieldPattern) {
errors.push('fieldPattern is required');
}
if (rule.value === undefined || rule.value === null) {
errors.push('value is required');
}
// Valider regex hvis brukt
if (rule.siteUseRegex && rule.sitePattern) {
const result = this.isValidRegex(rule.sitePattern);
if (!result.valid) {
errors.push(`Invalid site regex: ${result.error}`);
}
}
if (rule.fieldUseRegex && rule.fieldPattern) {
const result = this.isValidRegex(rule.fieldPattern);
if (!result.valid) {
errors.push(`Invalid field regex: ${result.error}`);
}
}
// Valider selector hvis brukt
if (rule.fieldType === 'selector' && rule.fieldPattern) {
const result = this.isValidSelector(rule.fieldPattern);
if (!result.valid) {
errors.push(`Invalid selector: ${result.error}`);
}
}
return { valid: errors.length === 0, errors };
},
/**
* Valider en profil-objekt
* @param {object} profile - Profil å validere
* @returns {{valid: boolean, errors: string[]}}
*/
validateProfile(profile) {
const errors = [];
if (!profile || typeof profile !== 'object') {
return { valid: false, errors: ['Profile must be an object'] };
}
if (!profile.id || typeof profile.id !== 'string') {
errors.push('Profile id is required and must be a string');
}
if (!profile.name || typeof profile.name !== 'string') {
errors.push('Profile name is required and must be a string');
}
return { valid: errors.length === 0, errors };
}
};
// ============================================================================
// ERROR HANDLER - Konsekvent feilhåndtering
// ============================================================================
const ErrorHandler = {
/**
* Wrap en async funksjon med feilhåndtering
* @param {Function} fn - Async funksjon å wrappe
* @param {string} context - Kontekst for logging
* @param {*} fallbackValue - Verdi å returnere ved feil
* @returns {Function}
*/
wrapAsync(fn, context, fallbackValue = null) {
return async function(...args) {
try {
return await fn.apply(this, args);
} catch (error) {
Logger.error(context, 'Async operation failed:', error.message || error);
return fallbackValue;
}
};
},
/**
* Wrap en sync funksjon med feilhåndtering
* @param {Function} fn - Funksjon å wrappe
* @param {string} context - Kontekst for logging
* @param {*} fallbackValue - Verdi å returnere ved feil
* @returns {Function}
*/
wrapSync(fn, context, fallbackValue = null) {
return function(...args) {
try {
return fn.apply(this, args);
} catch (error) {
Logger.error(context, 'Operation failed:', error.message || error);
return fallbackValue;
}
};
},
/**
* Håndter Chrome API-feil
* @param {Error} error - Feil å håndtere
* @param {string} context - Kontekst
* @returns {boolean} - true hvis feilen kan ignoreres
*/
handleChromeError(error, context) {
const ignorableErrors = [
'No tab with id',
'Extension context invalidated',
'The message port closed',
'Could not establish connection'
];
const errorMsg = error?.message || String(error);
const isIgnorable = ignorableErrors.some(msg => errorMsg.includes(msg));
if (isIgnorable) {
Logger.debug(context, 'Ignorable Chrome error:', errorMsg);
return true;
}
Logger.error(context, 'Chrome API error:', errorMsg);
return false;
}
};
// Export for use in other files (works with importScripts)
if (typeof window !== 'undefined') {
window.LogLevel = LogLevel;
window.Logger = Logger;
window.Validator = Validator;
window.ErrorHandler = ErrorHandler;
}