-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
609 lines (514 loc) · 21.4 KB
/
Copy pathapp.js
File metadata and controls
609 lines (514 loc) · 21.4 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
class NexiumApp {
constructor() {
this.cryptoManager = new CryptoManager();
this.masterPassword = null;
this.masterKeyHash = null;
this.encryptionKey = null;
this.passwords = [];
this.notes = [];
this.isFirstTime = false;
this.failedAttempts = 0;
this.maxAttempts = 3;
this.lockoutTime = 5 * 60 * 1000; // 5 minutes
this.init();
}
init() {
this.checkFirstTimeSetup();
this.loadData();
if (this.isFirstTime) {
this.showSetupModal();
} else {
this.showAuthModal();
}
}
checkFirstTimeSetup() {
const masterHash = localStorage.getItem('nexium_master_hash');
this.isFirstTime = !masterHash;
}
showSetupModal() {
document.getElementById('setup-modal').style.display = 'flex';
document.getElementById('auth-modal').style.display = 'none';
}
showAuthModal() {
if (this.isLocked()) {
this.showLockoutMessage();
return;
}
document.getElementById('auth-modal').style.display = 'flex';
document.getElementById('setup-modal').style.display = 'none';
}
isLocked() {
const lockoutEnd = localStorage.getItem('nexium_lockout_end');
if (lockoutEnd && Date.now() < parseInt(lockoutEnd)) {
return true;
}
return false;
}
showLockoutMessage() {
const lockoutEnd = localStorage.getItem('nexium_lockout_end');
const remainingTime = Math.ceil((parseInt(lockoutEnd) - Date.now()) / 1000 / 60);
alert(`Account locked. Try again in ${remainingTime} minutes.`);
}
async setupMasterPassword() {
const password = document.getElementById('setup-password').value;
const confirmPassword = document.getElementById('confirm-password').value;
if (password !== confirmPassword) {
alert('Passwords do not match!');
return;
}
const strength = this.checkPasswordStrength(password);
if (strength.score < 70) {
alert('Password is too weak. Please use a stronger password.');
return;
}
try {
this.masterKeyHash = await this.cryptoManager.hashPassword(password);
this.encryptionKey = this.cryptoManager.generateSecureKey();
localStorage.setItem('nexium_master_hash', this.masterKeyHash);
localStorage.setItem('nexium_encryption_key', await this.cryptoManager.encryptData(this.encryptionKey, password));
this.masterPassword = password;
this.isFirstTime = false;
document.getElementById('setup-modal').style.display = 'none';
this.showSuccessMessage('Master password created successfully!');
} catch (error) {
alert('Error setting up master password: ' + error.message);
}
}
async authenticate() {
const password = document.getElementById('master-password').value;
if (!password) {
alert('Please enter your master password');
return;
}
try {
const storedHash = localStorage.getItem('nexium_master_hash');
const inputHash = await this.cryptoManager.hashPassword(password);
if (storedHash !== inputHash) {
this.failedAttempts++;
if (this.failedAttempts >= this.maxAttempts) {
const lockoutEnd = Date.now() + this.lockoutTime;
localStorage.setItem('nexium_lockout_end', lockoutEnd.toString());
alert('Too many failed attempts. Account locked for 5 minutes.');
document.getElementById('auth-modal').style.display = 'none';
return;
}
alert(`Invalid password. ${this.maxAttempts - this.failedAttempts} attempts remaining.`);
document.getElementById('master-password').value = '';
return;
}
// Successful authentication
this.masterPassword = password;
this.failedAttempts = 0;
localStorage.removeItem('nexium_lockout_end');
// Decrypt the encryption key
const encryptedKey = localStorage.getItem('nexium_encryption_key');
this.encryptionKey = await this.cryptoManager.decryptData(encryptedKey, password);
document.getElementById('auth-modal').style.display = 'none';
await this.loadPasswords();
await this.loadNotes();
this.showSuccessMessage('Welcome back!');
} catch (error) {
alert('Authentication failed: ' + error.message);
}
}
checkPasswordStrength(password) {
let score = 0;
const feedback = [];
// Length check
if (password.length >= 12) score += 25;
else if (password.length >= 8) score += 15;
else feedback.push("Use at least 8 characters");
// Character variety
if (/[a-z]/.test(password)) score += 15;
else feedback.push("Add lowercase letters");
if (/[A-Z]/.test(password)) score += 15;
else feedback.push("Add uppercase letters");
if (/\d/.test(password)) score += 15;
else feedback.push("Add numbers");
if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score += 20;
else feedback.push("Add special characters");
// Common passwords
const common = ['password', '123456', 'qwerty', 'admin'];
if (common.includes(password.toLowerCase())) {
score -= 30;
feedback.push("Avoid common passwords");
}
let strength = 'Weak';
if (score >= 80) strength = 'Strong';
else if (score >= 60) strength = 'Medium';
return { score: Math.max(0, score), strength, feedback };
}
generateStrongPassword(length = 16) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
let password = '';
for (let i = 0; i < length; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
return password;
}
async savePassword() {
if (!this.masterPassword || !this.encryptionKey) {
this.showAuthModal();
return;
}
const title = document.getElementById('site-title').value;
const username = document.getElementById('username').value;
const password = document.getElementById('site-password').value;
const category = document.getElementById('category').value;
const url = document.getElementById('site-url').value;
if (!title || !password) {
alert('Title and password are required!');
return;
}
try {
const passwordData = {
id: Date.now(),
title: await this.cryptoManager.encryptData(title, this.encryptionKey),
username: await this.cryptoManager.encryptData(username, this.encryptionKey),
password: await this.cryptoManager.encryptData(password, this.encryptionKey),
url: await this.cryptoManager.encryptData(url, this.encryptionKey),
category: await this.cryptoManager.encryptData(category, this.encryptionKey),
createdAt: new Date().toISOString()
};
this.passwords.push(passwordData);
await this.saveDataToFile();
await this.displayPasswords();
this.clearPasswordForm();
this.showSuccessMessage('Password saved successfully!');
} catch (error) {
alert('Error saving password: ' + error.message);
}
}
async saveNote() {
if (!this.masterPassword || !this.encryptionKey) {
this.showAuthModal();
return;
}
const title = document.getElementById('note-title').value;
const content = document.getElementById('note-content').value;
const category = document.getElementById('note-category').value;
const tags = document.getElementById('note-tags').value;
if (!title || !content) {
alert('Title and content are required!');
return;
}
try {
const noteData = {
id: Date.now(),
title: await this.cryptoManager.encryptData(title, this.encryptionKey),
content: await this.cryptoManager.encryptData(content, this.encryptionKey),
category: await this.cryptoManager.encryptData(category, this.encryptionKey),
tags: await this.cryptoManager.encryptData(tags, this.encryptionKey),
createdAt: new Date().toISOString()
};
this.notes.push(noteData);
await this.saveDataToFile();
await this.displayNotes();
this.clearNoteForm();
this.showSuccessMessage('Note saved successfully!');
} catch (error) {
alert('Error saving note: ' + error.message);
}
}
async displayPasswords() {
const container = document.getElementById('passwords-container');
container.innerHTML = '';
if (this.passwords.length === 0) {
container.innerHTML = '<p class="empty-state">No passwords saved yet. Add your first password above!</p>';
return;
}
for (const pwd of this.passwords) {
try {
const title = await this.cryptoManager.decryptData(pwd.title, this.encryptionKey);
const username = await this.cryptoManager.decryptData(pwd.username, this.encryptionKey);
const category = await this.cryptoManager.decryptData(pwd.category, this.encryptionKey);
const url = await this.cryptoManager.decryptData(pwd.url, this.encryptionKey);
const div = document.createElement('div');
div.className = 'password-item glass-card';
div.innerHTML = `
<div class="password-header">
<h4>${title}</h4>
<span class="category-tag">${category}</span>
</div>
<p><strong>Username:</strong> ${username}</p>
<p><strong>URL:</strong> ${url}</p>
<p><strong>Password:</strong> <span id="pwd-${pwd.id}">••••••••</span></p>
<div class="password-actions">
<button class="btn-show" onclick="app.togglePassword(${pwd.id})">👁️ Show</button>
<button class="btn-copy" onclick="app.copyPassword(${pwd.id})">📋 Copy</button>
<button class="btn-delete" onclick="app.deletePassword(${pwd.id})">🗑️ Delete</button>
</div>
`;
container.appendChild(div);
} catch (e) {
console.error('Failed to decrypt password:', e);
}
}
}
async displayNotes() {
const container = document.getElementById('notes-container');
container.innerHTML = '';
if (this.notes.length === 0) {
container.innerHTML = '<p class="empty-state">No notes saved yet. Create your first secure note above!</p>';
return;
}
for (const note of this.notes) {
try {
const title = await this.cryptoManager.decryptData(note.title, this.encryptionKey);
const category = await this.cryptoManager.decryptData(note.category, this.encryptionKey);
const content = await this.cryptoManager.decryptData(note.content, this.encryptionKey);
const div = document.createElement('div');
div.className = 'note-item glass-card';
div.innerHTML = `
<div class="note-header">
<h4>${title}</h4>
<span class="category-tag">${category}</span>
</div>
<p class="note-preview">${content.substring(0, 100)}${content.length > 100 ? '...' : ''}</p>
<div class="note-actions">
<button class="btn-view" onclick="app.viewNote(${note.id})">👁️ View</button>
<button class="btn-edit" onclick="app.editNote(${note.id})">✏️ Edit</button>
<button class="btn-delete" onclick="app.deleteNote(${note.id})">🗑️ Delete</button>
</div>
`;
container.appendChild(div);
} catch (e) {
console.error('Failed to decrypt note:', e);
}
}
}
async saveDataToFile() {
const data = {
passwords: this.passwords,
notes: this.notes,
timestamp: new Date().toISOString(),
version: '1.0.0'
};
// Save to localStorage as backup
localStorage.setItem('nexium_vault_data', JSON.stringify(data));
// Create downloadable JSON file
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
// Auto-save to downloads (if supported)
if ('showSaveFilePicker' in window) {
try {
const fileHandle = await window.showSaveFilePicker({
suggestedName: `nexium-vault-${new Date().toISOString().split('T')[0]}.json`,
types: [{
description: 'JSON files',
accept: { 'application/json': ['.json'] }
}]
});
const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
} catch (e) {
// User cancelled or error occurred
}
}
}
loadData() {
const data = localStorage.getItem('nexium_vault_data');
if (data) {
const parsed = JSON.parse(data);
this.passwords = parsed.passwords || [];
this.notes = parsed.notes || [];
} else {
this.passwords = [];
this.notes = [];
}
}
async togglePassword(id) {
const element = document.getElementById(`pwd-${id}`);
const password = this.passwords.find(p => p.id === id);
if (element.textContent === '••••••••') {
try {
const decrypted = await this.cryptoManager.decryptData(password.password, this.encryptionKey);
element.textContent = decrypted;
setTimeout(() => {
element.textContent = '••••••••';
}, 10000); // Hide after 10 seconds
} catch (e) {
alert('Failed to decrypt password');
}
} else {
element.textContent = '••••••••';
}
}
async copyPassword(id) {
const password = this.passwords.find(p => p.id === id);
try {
const decrypted = await this.cryptoManager.decryptData(password.password, this.encryptionKey);
await navigator.clipboard.writeText(decrypted);
this.showSuccessMessage('Password copied to clipboard!');
} catch (e) {
alert('Failed to copy password');
}
}
deletePassword(id) {
if (confirm('Are you sure you want to delete this password?')) {
this.passwords = this.passwords.filter(p => p.id !== id);
this.saveDataToFile();
this.displayPasswords();
this.showSuccessMessage('Password deleted successfully!');
}
}
deleteNote(id) {
if (confirm('Are you sure you want to delete this note?')) {
this.notes = this.notes.filter(n => n.id !== id);
this.saveDataToFile();
this.displayNotes();
this.showSuccessMessage('Note deleted successfully!');
}
}
showSuccessMessage(message) {
const toast = document.createElement('div');
toast.className = 'toast success';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.classList.add('show');
}, 100);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => document.body.removeChild(toast), 300);
}, 3000);
}
clearPasswordForm() {
document.getElementById('site-title').value = '';
document.getElementById('username').value = '';
document.getElementById('site-password').value = '';
document.getElementById('site-url').value = '';
document.getElementById('category').value = '';
}
clearNoteForm() {
document.getElementById('note-title').value = '';
document.getElementById('note-content').value = '';
document.getElementById('note-category').value = '';
document.getElementById('note-tags').value = '';
}
async loadPasswords() {
await this.displayPasswords();
}
async loadNotes() {
await this.displayNotes();
}
logout() {
this.masterPassword = null;
this.encryptionKey = null;
this.cryptoManager.clearCache();
this.passwords = [];
this.notes = [];
this.showAuthModal();
this.showSuccessMessage('Logged out successfully!');
}
async exportData() {
if (!this.masterPassword) {
this.showAuthModal();
return;
}
const data = {
passwords: this.passwords,
notes: this.notes,
exportDate: new Date().toISOString(),
version: '1.0.0'
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `nexium-vault-backup-${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.showSuccessMessage('Data exported successfully!');
}
async importData() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
if (data.passwords && data.notes) {
if (confirm('This will replace all current data. Continue?')) {
this.passwords = data.passwords;
this.notes = data.notes;
await this.saveDataToFile();
await this.displayPasswords();
await this.displayNotes();
this.showSuccessMessage('Data imported successfully!');
}
} else {
alert('Invalid backup file format');
}
} catch (error) {
alert('Error importing data: ' + error.message);
}
};
input.click();
}
}
// Global functions
function showTab(tabName) {
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
});
document.getElementById(tabName).classList.add('active');
event.target.classList.add('active');
}
function checkPassword() {
const password = document.getElementById('password-input').value;
const result = app.checkPasswordStrength(password);
document.getElementById('strength-text').textContent =
`Strength: ${result.strength} (${result.score}/100)`;
const strengthBar = document.getElementById('strength-bar');
strengthBar.className = `strength-bar strength-${result.strength.toLowerCase()}`;
const feedbackList = document.getElementById('feedback-list');
feedbackList.innerHTML = '';
result.feedback.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
feedbackList.appendChild(li);
});
}
function generatePassword() {
const password = app.generateStrongPassword();
document.getElementById('password-input').value = password;
checkPassword();
}
function togglePasswordVisibility(inputId) {
const input = document.getElementById(inputId);
input.type = input.type === 'password' ? 'text' : 'password';
}
function authenticate() {
app.authenticate();
}
function setupMasterPassword() {
app.setupMasterPassword();
}
function savePassword() {
app.savePassword();
}
function saveNote() {
app.saveNote();
}
function logout() {
app.logout();
}
function exportData() {
app.exportData();
}
function importData() {
app.importData();
}
// This script is made by Nexium Team. john pork/ skull
// do not change anything that can make the script broken
const app = new NexiumApp();