-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
589 lines (498 loc) · 19.7 KB
/
Copy pathscript.js
File metadata and controls
589 lines (498 loc) · 19.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
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
let masterKey = null;
let passwords = [];
let editingId = null;
let currentShareId = null;
let sharedPasswords = {};
document.addEventListener('DOMContentLoaded', () => {
loadPasswords();
checkForSharedPassword();
});
async function login() {
const masterPassword = document.getElementById('masterPassword').value;
const errorDiv = document.getElementById('loginError');
if (!masterPassword) {
showError(errorDiv, 'Bitte gib ein Master-Passwort ein');
return;
}
try {
masterKey = await deriveMasterKey(masterPassword);
const stored = localStorage.getItem('passwordData');
if (stored) {
const decrypted = await decryptData(stored, masterKey);
if (decrypted) {
passwords = JSON.parse(decrypted);
} else {
showError(errorDiv, 'Falsches Master-Passwort');
return;
}
}
document.getElementById('loginScreen').classList.remove('active');
document.getElementById('mainScreen').classList.add('active');
document.getElementById('masterPassword').value = '';
renderPasswords();
} catch (error) {
showError(errorDiv, 'Fehler beim Anmelden');
console.error(error);
}
}
function logout() {
masterKey = null;
passwords = [];
document.getElementById('mainScreen').classList.remove('active');
document.getElementById('loginScreen').classList.add('active');
}
function loadPasswords() {
const stored = localStorage.getItem('passwordData');
if (stored) {
}
}
// Passwörter rendern
function renderPasswords() {
const list = document.getElementById('passwordList');
const emptyState = document.getElementById('emptyState');
if (passwords.length === 0) {
list.innerHTML = '';
emptyState.classList.add('active');
return;
}
emptyState.classList.remove('active');
list.innerHTML = passwords.map(pwd => `
<div class="password-item">
<div class="password-header">
<div class="password-info">
<h3>${escapeHtml(pwd.service)}</h3>
<p>${escapeHtml(pwd.username)}</p>
</div>
<div class="password-actions">
<button class="icon-btn" onclick="copyToClipboard('${escapeHtml(pwd.password)}')" title="Passwort kopieren">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
</button>
<button class="icon-btn" onclick="editPassword('${pwd.id}')" title="Bearbeiten">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
</svg>
</button>
<button class="icon-btn delete" onclick="deletePassword('${pwd.id}')" title="Löschen">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
</div>
</div>
${pwd.notes ? `<div class="password-field" style="margin-top: 12px;">
<span style="color: var(--text-secondary); font-size: 13px;">${escapeHtml(pwd.notes)}</span>
</div>` : ''}
</div>
`).join('');
}
function filterPasswords() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
const items = document.querySelectorAll('.password-item');
items.forEach(item => {
const text = item.textContent.toLowerCase();
if (text.includes(searchTerm)) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
}
function showAddModal() {
editingId = null;
document.getElementById('modalTitle').textContent = 'Neues Passwort';
document.getElementById('serviceName').value = '';
document.getElementById('username').value = '';
document.getElementById('password').value = '';
document.getElementById('notes').value = '';
document.getElementById('passwordModal').classList.add('active');
}
function editPassword(id) {
const pwd = passwords.find(p => p.id === id);
if (!pwd) return;
editingId = id;
document.getElementById('modalTitle').textContent = 'Passwort bearbeiten';
document.getElementById('serviceName').value = pwd.service;
document.getElementById('username').value = pwd.username;
document.getElementById('password').value = pwd.password;
document.getElementById('notes').value = pwd.notes || '';
document.getElementById('passwordModal').classList.add('active');
}
function closeModal() {
document.getElementById('passwordModal').classList.remove('active');
editingId = null;
}
async function savePassword() {
const service = document.getElementById('serviceName').value.trim();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
const notes = document.getElementById('notes').value.trim();
if (!service || !username || !password) {
alert('Bitte fülle alle Pflichtfelder aus');
return;
}
if (editingId) {
const index = passwords.findIndex(p => p.id === editingId);
if (index !== -1) {
passwords[index] = {
...passwords[index],
service,
username,
password,
notes,
updated: new Date().toISOString()
};
}
} else {
passwords.push({
id: generateId(),
service,
username,
password,
notes,
created: new Date().toISOString()
});
}
await saveToStorage();
renderPasswords();
closeModal();
}
async function deletePassword(id) {
if (!confirm('Möchtest du dieses Passwort wirklich löschen?')) {
return;
}
passwords = passwords.filter(p => p.id !== id);
await saveToStorage();
renderPasswords();
}
function generatePassword() {
generatePasswordWithOptions();
}
function showGeneratorOptions() {
const options = document.getElementById('generatorOptions');
options.style.display = options.style.display === 'none' ? 'block' : 'none';
}
function updateLengthValue() {
const length = document.getElementById('pwdLength').value;
document.getElementById('lengthValue').textContent = length;
}
function generatePasswordWithOptions() {
const length = parseInt(document.getElementById('pwdLength').value);
const useUppercase = document.getElementById('useUppercase').checked;
const useLowercase = document.getElementById('useLowercase').checked;
const useNumbers = document.getElementById('useNumbers').checked;
const useSymbols = document.getElementById('useSymbols').checked;
const usePassphrase = document.getElementById('usePassphrase').checked;
let password = '';
if (usePassphrase) {
password = generatePassphrase();
} else {
let charset = '';
const lower = 'abcdefghijklmnopqrstuvwxyz';
const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
const symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
if (useLowercase) charset += lower;
if (useUppercase) charset += upper;
if (useNumbers) charset += numbers;
if (useSymbols) charset += symbols;
if (charset.length === 0) {
alert('Bitte wähle mindestens eine Zeichenart aus!');
return;
}
if (useLowercase) password += lower[Math.floor(Math.random() * lower.length)];
if (useUppercase) password += upper[Math.floor(Math.random() * upper.length)];
if (useNumbers) password += numbers[Math.floor(Math.random() * numbers.length)];
if (useSymbols) password += symbols[Math.floor(Math.random() * symbols.length)];
for (let i = password.length; i < length; i++) {
password += charset[Math.floor(Math.random() * charset.length)];
}
password = password.split('').sort(() => Math.random() - 0.5).join('');
}
document.getElementById('password').value = password;
document.getElementById('password').type = 'text';
checkPasswordStrength();
}
function generatePassphrase() {
const words = [
'korrekt', 'pferd', 'batterie', 'klammer', 'sonne', 'mond', 'stern', 'wolke',
'berg', 'fluss', 'baum', 'blume', 'vogel', 'fisch', 'katze', 'hund',
'haus', 'auto', 'fahrrad', 'tisch', 'stuhl', 'buch', 'stift', 'papier',
'fenster', 'tuer', 'schloss', 'schluessel', 'computer', 'telefon', 'musik', 'kunst',
'farbe', 'licht', 'schatten', 'feuer', 'wasser', 'erde', 'luft', 'wind',
'regen', 'schnee', 'sommer', 'winter', 'fruehling', 'herbst', 'morgen', 'abend'
];
const numWords = 4;
let passphrase = [];
for (let i = 0; i < numWords; i++) {
const word = words[Math.floor(Math.random() * words.length)];
if (Math.random() > 0.5) {
passphrase.push(word.charAt(0).toUpperCase() + word.slice(1));
} else {
passphrase.push(word);
}
}
passphrase.push(Math.floor(Math.random() * 100));
return passphrase.join('-');
}
function checkPasswordStrength() {
const password = document.getElementById('password').value;
const meter = document.getElementById('strengthMeter');
if (!password) {
meter.classList.remove('active', 'weak', 'medium', 'strong');
return;
}
let strength = 0;
// Länge
if (password.length >= 8) strength++;
if (password.length >= 12) strength++;
if (password.length >= 16) strength++;
// Zeichenvielfalt
if (/[a-z]/.test(password)) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[^a-zA-Z0-9]/.test(password)) strength++;
const uniqueChars = new Set(password).size;
if (uniqueChars >= password.length * 0.6) strength++;
meter.classList.add('active');
meter.classList.remove('weak', 'medium', 'strong');
if (strength <= 3) {
meter.classList.add('weak');
} else if (strength <= 6) {
meter.classList.add('medium');
} else {
meter.classList.add('strong');
}
}
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showToast('Passwort kopiert!');
} catch (error) {
console.error('Fehler beim Kopieren:', error);
}
}
function sharePassword(id) {
const pwd = passwords.find(p => p.id === id);
if (!pwd) return;
currentShareId = id;
document.getElementById('shareLink').style.display = 'none';
document.getElementById('generateShareBtn').style.display = 'block';
document.getElementById('shareModal').classList.add('active');
}
async function generateShareLink() {
const pwd = passwords.find(p => p.id === currentShareId);
if (!pwd) return;
const expiryMinutes = parseInt(document.getElementById('shareExpiry').value);
const expiryTime = Date.now() + (expiryMinutes * 60 * 1000);
const shareToken = generateId() + generateId();
const shareData = {
service: pwd.service,
username: pwd.username,
password: pwd.password,
expiresAt: expiryTime,
oneTimeUse: true
};
sharedPasswords[shareToken] = shareData;
localStorage.setItem('sharedPasswords', JSON.stringify(sharedPasswords));
// Erstelle Share-Link
const shareUrl = `${window.location.origin}${window.location.pathname}?share=${shareToken}`;
document.getElementById('shareLinkInput').value = shareUrl;
document.getElementById('shareLink').style.display = 'block';
document.getElementById('generateShareBtn').style.display = 'none';
showToast('Sicherer Link erstellt!');
}
async function copyShareLink() {
const linkInput = document.getElementById('shareLinkInput');
try {
await navigator.clipboard.writeText(linkInput.value);
showToast('Link kopiert!');
} catch (error) {
console.error('Fehler beim Kopieren:', error);
}
}
function closeShareModal() {
document.getElementById('shareModal').classList.remove('active');
currentShareId = null;
}
function checkForSharedPassword() {
const urlParams = new URLSearchParams(window.location.search);
const shareToken = urlParams.get('share');
if (shareToken) {
loadSharedPassword(shareToken);
}
}
function loadSharedPassword(token) {
const stored = localStorage.getItem('sharedPasswords');
if (!stored) {
alert('Dieser Link ist ungültig oder abgelaufen.');
return;
}
const sharedPasswords = JSON.parse(stored);
const shareData = sharedPasswords[token];
if (!shareData) {
alert('Dieser Link ist ungültig oder wurde bereits verwendet.');
return;
}
if (Date.now() > shareData.expiresAt) {
delete sharedPasswords[token];
localStorage.setItem('sharedPasswords', JSON.stringify(sharedPasswords));
alert('Dieser Link ist abgelaufen.');
return;
}
showSharedPasswordPopup(shareData);
if (shareData.oneTimeUse) {
delete sharedPasswords[token];
localStorage.setItem('sharedPasswords', JSON.stringify(sharedPasswords));
}
window.history.replaceState({}, document.title, window.location.pathname);
}
function showSharedPasswordPopup(data) {
const popup = document.createElement('div');
popup.className = 'modal active';
popup.innerHTML = `
<div class="modal-content">
<div class="modal-header">
<h2>Geteiltes Passwort</h2>
</div>
<div class="modal-body">
<div class="form-group">
<label>Dienst / Website</label>
<input type="text" value="${escapeHtml(data.service)}" readonly>
</div>
<div class="form-group">
<label>Benutzername</label>
<input type="text" value="${escapeHtml(data.username)}" readonly>
</div>
<div class="form-group">
<label>Passwort</label>
<div class="input-group">
<input type="text" id="sharedPassword" value="${escapeHtml(data.password)}" readonly>
<button class="toggle-password" onclick="copyToClipboard('${escapeHtml(data.password)}')">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
</button>
</div>
</div>
<p class="share-warning">⚠️ Dieser Link kann nur einmal verwendet werden!</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" onclick="this.closest('.modal').remove()">Schließen</button>
</div>
</div>
`;
document.body.appendChild(popup);
}
function togglePassword(inputId) {
const input = document.getElementById(inputId);
input.type = input.type === 'password' ? 'text' : 'password';
}
async function saveToStorage() {
try {
const data = JSON.stringify(passwords);
const encrypted = await encryptData(data, masterKey);
localStorage.setItem('passwordData', encrypted);
} catch (error) {
console.error('Fehler beim Speichern:', error);
alert('Fehler beim Speichern der Daten');
}
}
async function deriveMasterKey(password) {
const encoder = new TextEncoder();
const data = encoder.encode(password);
const keyMaterial = await crypto.subtle.importKey(
'raw',
data,
{ name: 'PBKDF2' },
false,
['deriveBits', 'deriveKey']
);
const salt = encoder.encode('password-manager-salt-2024');
return await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
async function encryptData(data, key) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv },
key,
dataBuffer
);
const result = new Uint8Array(iv.length + encrypted.byteLength);
result.set(iv, 0);
result.set(new Uint8Array(encrypted), iv.length);
return btoa(String.fromCharCode(...result));
}
async function decryptData(encryptedData, key) {
try {
const data = new Uint8Array(
atob(encryptedData).split('').map(char => char.charCodeAt(0))
);
const iv = data.slice(0, 12);
const encrypted = data.slice(12);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv },
key,
encrypted
);
const decoder = new TextDecoder();
return decoder.decode(decrypted);
} catch (error) {
console.error('Entschlüsselungsfehler:', error);
return null;
}
}
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function showError(element, message) {
element.textContent = message;
element.classList.add('active');
setTimeout(() => {
element.classList.remove('active');
}, 3000);
}
function showToast(message) {
const toast = document.createElement('div');
toast.textContent = message;
toast.style.cssText = `
position: fixed;
bottom: 24px;
right: 24px;
background: var(--success);
color: white;
padding: 12px 24px;
border-radius: 12px;
font-weight: 600;
z-index: 10000;
animation: slideIn 0.3s ease;
`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'fadeOut 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, 2000);
}