-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
731 lines (636 loc) · 21.6 KB
/
storage.js
File metadata and controls
731 lines (636 loc) · 21.6 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/**
* Storage API Wrapper for AutoFill Plugin
* Håndterer all interaksjon med chrome.storage.local og chrome.storage.sync
*/
const Storage = {
STORAGE_KEY: 'autofill_rules',
SYNC_KEY: 'autofill_rules_sync',
PROFILES_KEY: 'autofill_profiles',
// Settings that sync across Chrome profiles
SYNC_SETTINGS_KEYS: [
'autofillEnabled',
'autofillDelay',
'autofillTrigger',
'blacklist',
'whitelist',
'fieldBlacklist',
'notificationsEnabled',
'scanToastEnabled',
'language',
'userVariables',
'debugMode'
],
/**
* Get settings (from sync storage)
*/
async getSettings() {
try {
const result = await chrome.storage.sync.get(this.SYNC_SETTINGS_KEYS);
return result;
} catch (error) {
console.error('Error fetching settings from sync:', error);
// Fallback to local storage
return await chrome.storage.local.get(this.SYNC_SETTINGS_KEYS);
}
},
/**
* Save settings (to sync storage)
*/
async saveSettings(settings) {
try {
// Filter only valid settings keys
const validSettings = {};
for (const key of this.SYNC_SETTINGS_KEYS) {
if (key in settings) {
validSettings[key] = settings[key];
}
}
await chrome.storage.sync.set(validSettings);
return true;
} catch (error) {
console.error('Error saving settings to sync:', error);
// Fallback to local storage
await chrome.storage.local.set(settings);
return false;
}
},
/**
* Migrate settings from local to sync storage (one-time migration)
*/
async migrateSettingsToSync() {
try {
const migrated = await chrome.storage.local.get('_settingsMigrated');
if (migrated._settingsMigrated) return false;
const localSettings = await chrome.storage.local.get(this.SYNC_SETTINGS_KEYS);
const hasSettings = Object.keys(localSettings).some(k => localSettings[k] !== undefined);
if (hasSettings) {
await chrome.storage.sync.set(localSettings);
console.log('Settings migrated to sync storage');
}
await chrome.storage.local.set({ _settingsMigrated: true });
return true;
} catch (error) {
console.error('Error migrating settings:', error);
return false;
}
},
/**
* Export all settings to JSON
*/
async exportSettings() {
const settings = await this.getSettings();
return JSON.stringify(settings, null, 2);
},
/**
* Import settings from JSON
*/
async importSettings(jsonString) {
try {
const settings = JSON.parse(jsonString);
await this.saveSettings(settings);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
},
/**
* Henter alle profiler
*/
async getProfiles() {
try {
const result = await chrome.storage.local.get(this.PROFILES_KEY);
let profiles = result[this.PROFILES_KEY] || [];
// Migration: Create default profile if none exists
if (profiles.length === 0) {
profiles = [{
id: 'default',
name: 'Default',
enabled: true,
created: Date.now()
}];
await this.saveProfiles(profiles);
}
return profiles;
} catch (error) {
console.error('Error fetching profiles:', error);
return [];
}
},
/**
* Lagre profiler
*/
async saveProfiles(profiles) {
await chrome.storage.local.set({ [this.PROFILES_KEY]: profiles });
},
async addProfile(name) {
const profiles = await this.getProfiles();
const newProfile = {
id: this.generateId(),
name: name,
enabled: true,
created: Date.now()
};
profiles.push(newProfile);
await this.saveProfiles(profiles);
return newProfile;
},
async deleteProfile(id) {
const profiles = await this.getProfiles();
// Kan ikke slette siste profil
if (profiles.length <= 1) return false;
const filtered = profiles.filter(p => p.id !== id);
await this.saveProfiles(filtered);
// Slett tilhørende regler? Eller flytt til default?
// For nå: Slett regler
const rules = await this.getRules();
const rulesToKeep = rules.filter(r => r.profileId !== id);
await this.saveRules(rulesToKeep);
return true;
},
async toggleProfile(id, enabled) {
const profiles = await this.getProfiles();
const p = profiles.find(p => p.id === id);
if (p) {
p.enabled = enabled;
await this.saveProfiles(profiles);
}
},
/**
* Henter alle regler fra storage
* @returns {Promise<Array>} Array av regler
*/
async getRules() {
try {
const result = await chrome.storage.local.get(this.STORAGE_KEY);
const rules = result[this.STORAGE_KEY] || [];
return this.normalizeRules(rules);
} catch (error) {
console.error('Error fetching rules:', error);
return [];
}
},
/**
* Push alle regler til chrome.storage.sync (manuell sync)
*/
async pushToSync() {
const rules = await this.getRules();
await chrome.storage.sync.set({ [this.SYNC_KEY]: rules });
return { success: true, count: rules.length };
},
/**
* Pull regler fra chrome.storage.sync og erstatt lokale
*/
async pullFromSync() {
const result = await chrome.storage.sync.get(this.SYNC_KEY);
const rules = result[this.SYNC_KEY] || [];
await this.saveRules(rules);
return { success: true, count: rules.length };
},
/**
* Lagrer alle regler til storage
* @param {Array} rules - Array av regler
* @returns {Promise<boolean>} Om lagring var vellykket
*/
async saveRules(rules) {
try {
await chrome.storage.local.set({ [this.STORAGE_KEY]: rules });
return true;
} catch (error) {
console.error('Error saving rules:', error);
return false;
}
},
/**
* Legger til en ny regel
* @param {Object} rule - Regelobjekt
* @returns {Promise<Object>} Den nye regelen med ID
*/
async addRule(rule) {
const rules = await this.getRules();
const newRule = {
id: this.generateId(),
created: Date.now(),
lastUsed: null,
enabled: true,
elementType: 'text',
sortOrder: this.getNextSortOrder(rules),
priority: 0,
conditionType: 'none',
conditionValue: '',
...rule
};
rules.push(newRule);
await this.saveRules(rules);
return newRule;
},
/**
* Oppdaterer en eksisterende regel
* @param {string} ruleId - ID til regelen som skal oppdateres
* @param {Object} updates - Oppdateringer
* @returns {Promise<Object|null>} Oppdatert regel eller null
*/
async updateRule(ruleId, updates) {
const rules = await this.getRules();
const index = rules.findIndex(r => r.id === ruleId);
if (index === -1) {
return null;
}
rules[index] = { ...rules[index], ...updates };
await this.saveRules(rules);
return rules[index];
},
/**
* Oppdater rekkefolge (drag-and-drop)
* @param {Array<{id: string, sortOrder: number}>} orderUpdates
* @returns {Promise<Array>} Oppdaterte regler
*/
async reorderRules(orderUpdates) {
const rules = await this.getRules();
const orderMap = new Map(orderUpdates.map(o => [o.id, o.sortOrder]));
const updated = rules.map(rule => {
if (orderMap.has(rule.id)) {
return { ...rule, sortOrder: orderMap.get(rule.id) };
}
return rule;
});
await this.saveRules(updated);
return updated;
},
/**
* Sletter en regel
* @param {string} ruleId - ID til regelen som skal slettes
* @returns {Promise<boolean>} Om sletting var vellykket
*/
async deleteRule(ruleId) {
const rules = await this.getRules();
const filtered = rules.filter(r => r.id !== ruleId);
if (filtered.length === rules.length) {
return false; // Ingen regel ble slettet
}
await this.saveRules(filtered);
return true;
},
/**
* Oppdaterer lastUsed timestamp for en regel
* @param {string} ruleId - ID til regelen
* @returns {Promise<void>}
*/
async markRuleUsed(ruleId) {
await this.updateRule(ruleId, { lastUsed: Date.now() });
},
/**
* Henter regler som matcher en gitt side
* @param {string} url - URL til siden
* @param {string|null} profileId - Optional profile ID to filter by
* @returns {Promise<Array>} Matchende regler
*/
async getRulesForSite(url, profileId = null) {
const rules = await this.getRules();
const profiles = await this.getProfiles();
const enabledProfileIds = new Set(profiles.filter(p => p.enabled).map(p => p.id));
const hostname = new URL(url).hostname;
const domain = this.extractDomain(hostname);
const matched = rules.filter(rule => {
if (!rule.enabled) return false;
// Treat rules without profileId (or empty string) as belonging to 'default'
const ruleProfile = (typeof rule.profileId === 'string' && rule.profileId.trim()) || 'default';
// Check profile status
if (profileId) {
// When a specific profile is requested, match that profile (treat missing as default)
if (ruleProfile !== profileId) return false;
} else {
// Standard autofill: only use rules from enabled profiles
if (!enabledProfileIds.has(ruleProfile)) return false;
}
return this.matchSite(url, hostname, domain, rule);
});
return matched.sort((a, b) => {
const specA = this.computeSpecificityScore(a);
const specB = this.computeSpecificityScore(b);
if (specA !== specB) return specB - specA;
const priA = typeof a.priority === 'number' ? a.priority : 0;
const priB = typeof b.priority === 'number' ? b.priority : 0;
if (priA !== priB) return priB - priA;
const sortA = typeof a.sortOrder === 'number' ? a.sortOrder : a.created || 0;
const sortB = typeof b.sortOrder === 'number' ? b.sortOrder : b.created || 0;
return sortA - sortB;
});
},
/**
* Matcher en URL mot en regel
* @param {string} url - Full URL
* @param {string} hostname - Hostname
* @param {string} domain - Domene
* @param {Object} rule - Regel å matche mot
* @returns {boolean} Om regelen matcher
*/
matchSite(url, hostname, domain, rule) {
const pattern = rule.sitePattern;
const matchType = rule.siteMatchType || 'host';
switch (matchType) {
case 'host':
return PatternMatcher.match(hostname, pattern, false);
case 'domain':
return PatternMatcher.match(domain, pattern, false);
case 'url':
return PatternMatcher.match(url, pattern, false);
case 'regex':
return PatternMatcher.match(url, pattern, true);
default:
return false;
}
},
computeSpecificityScore(rule) {
const pattern = rule.sitePattern || '';
const matchType = rule.siteMatchType || 'host';
const matchWeight = {
url: 4,
host: 3,
domain: 2,
regex: 1
};
const wildcardCount = (pattern.match(/[\*\?]/g) || []).length;
const base = matchWeight[matchType] || 0;
return base * 1000 + (pattern.length - wildcardCount * 10);
},
/**
* Trekker ut domene fra hostname
* @param {string} hostname - Hostname (f.eks. "sub.example.com")
* @returns {string} Domene (f.eks. "example.com")
*/
extractDomain(hostname) {
const parts = hostname.split('.');
if (parts.length <= 2) {
return hostname;
}
return parts.slice(-2).join('.');
},
/**
* Genererer en unik ID
* @returns {string} Unik ID
*/
generateId() {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
},
/**
* Hent neste sorteringsnummer
*/
getNextSortOrder(rules) {
const maxOrder = rules.reduce((max, rule) => {
return Math.max(max, typeof rule.sortOrder === 'number' ? rule.sortOrder : -Infinity);
}, -Infinity);
return maxOrder === -Infinity ? 0 : maxOrder + 1;
},
/**
* Sikre at regler har alle nye felter og sortOrder
*/
normalizeRules(rules) {
let nextOrder = this.getNextSortOrder(rules);
const normalized = rules.map(rule => {
const merged = {
elementType: 'text',
priority: 0,
conditionType: 'none',
conditionValue: '',
profileId: 'default', // Default profile ID
...rule
};
if (!merged.created) {
merged.created = Date.now();
}
if (merged.sortOrder === undefined || merged.sortOrder === null || Number.isNaN(merged.sortOrder)) {
merged.sortOrder = nextOrder++;
}
return merged;
});
// Sorter på sortOrder som default rekkefolge
normalized.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
return normalized;
},
/**
* Eksporterer alle regler til CSV-format
* @returns {Promise<string>} CSV-streng
*/
async exportToCSV() {
const rules = await this.getRules();
const headers = 'id;sitePattern;siteMatchType;elementType;fieldType;fieldPattern;fieldUseRegex;value;enabled;created;lastUsed;sortOrder;priority;conditionType;conditionValue';
const rows = rules.map(rule => {
return [
rule.id,
rule.sitePattern,
rule.siteMatchType,
rule.elementType || 'text',
rule.fieldType,
rule.fieldPattern,
rule.fieldUseRegex,
this.escapeCSV(rule.value),
rule.enabled,
rule.created,
rule.lastUsed || '',
rule.sortOrder ?? '',
rule.priority ?? 0,
rule.conditionType || 'none',
this.escapeCSV(rule.conditionValue || '')
].join(';');
});
return [headers, ...rows].join('\n');
},
// CSV validation constants
CSV_MAX_SIZE_BYTES: 10 * 1024 * 1024, // 10MB max
CSV_MAX_RULES: 10000, // Max rules per import
VALID_MATCH_TYPES: ['host', 'domain', 'url', 'regex'],
VALID_FIELD_TYPES: ['name', 'id', 'data-name', 'data-id', 'placeholder', 'selector'],
VALID_ELEMENT_TYPES: ['text', 'select', 'checkbox', 'radio', 'textarea', 'date', 'email', 'password', 'number', 'tel', 'url', 'macro'],
VALID_CONDITION_TYPES: ['none', 'urlContains', 'urlRegex', 'selectorExists'],
/**
* Importerer regler fra CSV-format med utvidet validering
* @param {string} csvContent - CSV-innhold
* @param {boolean} merge - Om regler skal merges eller overskrive
* @returns {Promise<Object>} Resultat med success, antall, og eventuelle valideringsfeil
*/
async importFromCSV(csvContent, merge = true) {
const validationErrors = [];
const skippedRows = [];
try {
// Pre-validation: Sjekk filstørrelse
const contentSize = new Blob([csvContent]).size;
if (contentSize > this.CSV_MAX_SIZE_BYTES) {
throw new Error(`CSV-fil for stor: ${Math.round(contentSize / 1024 / 1024)}MB (maks ${this.CSV_MAX_SIZE_BYTES / 1024 / 1024}MB)`);
}
if (!csvContent || typeof csvContent !== 'string' || csvContent.trim().length === 0) {
throw new Error('Tom eller ugyldig CSV-innhold');
}
const lines = csvContent.trim().split('\n');
if (lines.length < 2) {
throw new Error('CSV må inneholde header og minst én rad med data');
}
if (lines.length - 1 > this.CSV_MAX_RULES) {
throw new Error(`For mange regler: ${lines.length - 1} (maks ${this.CSV_MAX_RULES})`);
}
const headers = lines[0].split(';');
if (!this.validateCSVHeaders(headers)) {
throw new Error('Ugyldig CSV-format: Manglende påkrevde kolonner');
}
const headerIndex = {};
headers.forEach((h, i) => { headerIndex[h] = i; });
const newRules = [];
for (let i = 1; i < lines.length; i++) {
const lineNum = i + 1;
const values = this.parseCSVLine(lines[i]);
// Skip empty lines
if (values.length === 1 && values[0].trim() === '') {
continue;
}
if (values.length !== headers.length) {
skippedRows.push({ line: lineNum, reason: `Feil antall kolonner (${values.length} vs ${headers.length})` });
continue;
}
const get = (name) => headerIndex[name] !== undefined ? values[headerIndex[name]] : undefined;
// Valider påkrevde felt
const sitePattern = get('sitePattern');
const fieldPattern = get('fieldPattern');
if (!sitePattern || sitePattern.trim() === '') {
skippedRows.push({ line: lineNum, reason: 'Mangler sitePattern' });
continue;
}
if (!fieldPattern || fieldPattern.trim() === '') {
skippedRows.push({ line: lineNum, reason: 'Mangler fieldPattern' });
continue;
}
// Valider enum-felt
const siteMatchType = get('siteMatchType');
if (siteMatchType && !this.VALID_MATCH_TYPES.includes(siteMatchType)) {
validationErrors.push({ line: lineNum, field: 'siteMatchType', value: siteMatchType, reason: 'Ugyldig verdi' });
}
const fieldType = get('fieldType');
if (fieldType && !this.VALID_FIELD_TYPES.includes(fieldType)) {
validationErrors.push({ line: lineNum, field: 'fieldType', value: fieldType, reason: 'Ugyldig verdi' });
}
const elementType = get('elementType') || 'text';
if (!this.VALID_ELEMENT_TYPES.includes(elementType)) {
validationErrors.push({ line: lineNum, field: 'elementType', value: elementType, reason: 'Ugyldig verdi' });
}
const conditionType = get('conditionType') || 'none';
if (!this.VALID_CONDITION_TYPES.includes(conditionType)) {
validationErrors.push({ line: lineNum, field: 'conditionType', value: conditionType, reason: 'Ugyldig verdi' });
}
// Valider regex hvis brukt
if (get('fieldUseRegex') === 'true') {
try {
new RegExp(fieldPattern);
} catch (e) {
validationErrors.push({ line: lineNum, field: 'fieldPattern', value: fieldPattern, reason: 'Ugyldig regex: ' + e.message });
}
}
const lastRaw = get('lastUsed');
const lastUsedVal = (lastRaw !== undefined && lastRaw !== null && `${lastRaw}`.trim() !== '')
? parseInt(lastRaw)
: null;
const rule = {
id: get('id') || this.generateId(),
sitePattern: sitePattern,
siteMatchType: siteMatchType || 'host',
elementType: elementType,
fieldType: fieldType || 'name',
fieldPattern: fieldPattern,
fieldUseRegex: get('fieldUseRegex') === 'true',
value: this.unescapeCSV(get('value') || ''),
enabled: get('enabled') !== 'false', // Default true
created: parseInt(get('created')) || Date.now(),
lastUsed: Number.isFinite(lastUsedVal) ? lastUsedVal : null,
sortOrder: get('sortOrder') !== undefined ? parseInt(get('sortOrder')) : null,
priority: get('priority') !== undefined ? parseInt(get('priority')) : 0,
conditionType: conditionType,
conditionValue: this.unescapeCSV(get('conditionValue') || '')
};
newRules.push(rule);
}
if (newRules.length === 0) {
throw new Error('Ingen gyldige regler funnet i CSV');
}
if (merge) {
const existingRules = await this.getRules();
const mergedRules = this.normalizeRules([...existingRules, ...newRules]);
await this.saveRules(mergedRules);
} else {
await this.saveRules(this.normalizeRules(newRules));
}
return {
success: true,
imported: newRules.length,
total: newRules.length,
skipped: skippedRows.length,
skippedRows: skippedRows.length > 0 ? skippedRows : undefined,
warnings: validationErrors.length,
validationErrors: validationErrors.length > 0 ? validationErrors : undefined
};
} catch (error) {
console.error('Error importing CSV:', error);
return {
success: false,
error: error.message,
skipped: skippedRows.length,
skippedRows: skippedRows.length > 0 ? skippedRows : undefined,
validationErrors: validationErrors.length > 0 ? validationErrors : undefined
};
}
},
/**
* Validerer CSV-headers
* @param {Array} headers - Headers fra CSV
* @returns {boolean} Om headers er gyldige
*/
validateCSVHeaders(headers) {
const required = ['id', 'sitePattern', 'siteMatchType', 'fieldType', 'fieldPattern', 'fieldUseRegex', 'value', 'enabled', 'created', 'lastUsed'];
return required.every(h => headers.includes(h));
},
/**
* Parser en CSV-linje med støtte for quoted values
* @param {string} line - CSV-linje
* @returns {Array} Array av verdier
*/
parseCSVLine(line) {
const result = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ';' && !inQuotes) {
result.push(current);
current = '';
} else {
current += char;
}
}
result.push(current);
return result;
},
/**
* Escaper spesialtegn for CSV
* @param {string} value - Verdi å escape
* @returns {string} Escaped verdi
*/
escapeCSV(value) {
if (value.includes(';') || value.includes('"') || value.includes('\n')) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
},
/**
* Unescaper CSV-verdi
* @param {string} value - Escaped verdi
* @returns {string} Unescape verdi
*/
unescapeCSV(value) {
if (value.startsWith('"') && value.endsWith('"')) {
return value.slice(1, -1).replace(/""/g, '"');
}
return value;
}
};
// Eksporter for bruk i andre moduler
if (typeof module !== 'undefined' && module.exports) {
module.exports = Storage;
}