-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwebauthn-manage.js
More file actions
499 lines (438 loc) · 17.6 KB
/
webauthn-manage.js
File metadata and controls
499 lines (438 loc) · 17.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
/**
* WebAuthn credential management (list, rename, delete) for the user profile page.
*/
import { getCsrfToken, getCsrfHeaderName, isWebAuthnSupported, escapeHtml } from '/js/user/webauthn-utils.js';
import { registerPasskey } from '/js/user/webauthn-register.js';
import { showMessage } from '/js/shared.js';
import { getAuthMethods, invalidateAuthMethodsCache } from '/js/user/auth-methods.js';
const csrfHeader = getCsrfHeaderName();
const csrfToken = getCsrfToken();
let renameModalInstance;
let removePasswordModalInstance;
/**
* Load and display user's passkeys.
*/
export async function loadPasskeys() {
const container = document.getElementById('passkeys-list');
const globalMessage = document.getElementById('passkeyMessage');
if (!container) return;
try {
const response = await fetch('/user/webauthn/credentials', {
headers: { [csrfHeader]: csrfToken }
});
if (!response.ok) {
throw new Error('Failed to load passkeys');
}
const credentials = await response.json();
displayCredentials(container, credentials);
} catch (error) {
console.error('Failed to load passkeys:', error);
if (globalMessage) {
showMessage(globalMessage, 'Failed to load passkeys.', 'alert-danger');
}
}
}
/**
* Format a date string safely, returning 'Unknown' for invalid values.
*/
function formatDate(dateStr) {
if (!dateStr) return 'Unknown';
const date = new Date(dateStr);
return isNaN(date) ? 'Unknown' : date.toLocaleDateString();
}
/**
* Display credentials in UI.
*/
function displayCredentials(container, credentials) {
if (credentials.length === 0) {
container.innerHTML = '<p class="text-muted">No passkeys registered yet.</p>';
return;
}
container.innerHTML = credentials.map(cred => `
<div class="card mb-2" data-id="${escapeHtml(cred.id)}">
<div class="card-body d-flex justify-content-between align-items-center py-2">
<div class="me-3" style="min-width: 0;">
<strong class="d-inline-block text-truncate" style="max-width: 100%;">${escapeHtml(cred.label || 'Unnamed Passkey')}</strong>
<br>
<small class="text-muted">
Created: ${formatDate(cred.created)}
${cred.lastUsed ? ' | Last used: ' + formatDate(cred.lastUsed) : ' | Never used'}
</small>
<br>
${cred.backupEligible
? '<span class="badge bg-success">Synced</span>'
: '<span class="badge bg-warning text-dark">Device-bound</span>'}
</div>
<div class="flex-shrink-0">
<button class="btn btn-sm btn-outline-secondary me-1" data-action="rename" data-id="${escapeHtml(cred.id)}" data-label="${escapeHtml(cred.label || '')}">
<i class="bi bi-pencil"></i> Rename
</button>
<button class="btn btn-sm btn-outline-danger" data-action="delete" data-id="${escapeHtml(cred.id)}">
<i class="bi bi-trash"></i> Delete
</button>
</div>
</div>
</div>
`).join('');
}
/**
* Show the rename passkey modal.
*/
function renamePasskey(credentialId, currentLabel) {
const input = document.getElementById('renamePasskeyInput');
const counter = document.getElementById('renamePasskeyCount');
const errorEl = document.getElementById('renamePasskeyError');
const confirmBtn = document.getElementById('confirmRenameButton');
// Pre-fill with current label
input.value = currentLabel || '';
counter.textContent = `${input.value.length} / 64`;
errorEl.classList.add('d-none');
input.classList.remove('is-invalid');
// Show modal (reuse cached instance)
if (!renameModalInstance) {
renameModalInstance = new bootstrap.Modal(document.getElementById('renamePasskeyModal'));
}
renameModalInstance.show();
// Focus input when modal is shown
document.getElementById('renamePasskeyModal').addEventListener('shown.bs.modal', () => {
input.select();
}, { once: true });
// Character counter
const onInput = () => {
counter.textContent = `${input.value.length} / 64`;
if (input.value.trim()) {
errorEl.classList.add('d-none');
input.classList.remove('is-invalid');
}
};
input.addEventListener('input', onInput);
// Submit on Enter key
const onKeydown = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
confirmBtn.click();
}
};
input.addEventListener('keydown', onKeydown);
// Handle confirm click
const onConfirm = async () => {
const newLabel = input.value.trim();
if (!newLabel) {
errorEl.textContent = 'Please enter a name.';
errorEl.classList.remove('d-none');
input.classList.add('is-invalid');
return;
}
confirmBtn.disabled = true;
confirmBtn.textContent = 'Saving...';
const globalMessage = document.getElementById('passkeyMessage');
try {
const response = await fetch(`/user/webauthn/credentials/${credentialId}/label`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
[csrfHeader]: csrfToken
},
body: JSON.stringify({ label: newLabel })
});
if (!response.ok) {
let msg = 'Failed to rename passkey';
try {
const data = await response.json();
msg = data.message || msg;
} catch {
const text = await response.text();
if (text) msg = text;
}
throw new Error(msg);
}
renameModalInstance.hide();
if (globalMessage) {
showMessage(globalMessage, 'Passkey renamed successfully.', 'alert-success');
}
invalidateAuthMethodsCache();
loadPasskeys();
updateAuthMethodsUI();
} catch (error) {
console.error('Failed to rename passkey:', error);
errorEl.textContent = error.message;
errorEl.classList.remove('d-none');
input.classList.add('is-invalid');
} finally {
confirmBtn.disabled = false;
confirmBtn.textContent = 'Save';
}
};
confirmBtn.addEventListener('click', onConfirm);
// Clean up listeners when modal is hidden
document.getElementById('renamePasskeyModal').addEventListener('hidden.bs.modal', () => {
input.removeEventListener('input', onInput);
input.removeEventListener('keydown', onKeydown);
confirmBtn.removeEventListener('click', onConfirm);
}, { once: true });
}
/**
* Delete a passkey with confirmation.
*/
async function deletePasskey(credentialId) {
if (!confirm('Are you sure you want to delete this passkey? This action cannot be undone.')) {
return;
}
const globalMessage = document.getElementById('passkeyMessage');
try {
const response = await fetch(`/user/webauthn/credentials/${credentialId}`, {
method: 'DELETE',
headers: { [csrfHeader]: csrfToken }
});
if (!response.ok) {
let msg = 'Failed to delete passkey';
try {
const data = await response.json();
msg = data.message || msg;
} catch {
const text = await response.text();
if (text) msg = text;
}
throw new Error(msg);
}
if (globalMessage) {
showMessage(globalMessage, 'Passkey deleted successfully.', 'alert-success');
}
invalidateAuthMethodsCache();
loadPasskeys();
updateAuthMethodsUI();
} catch (error) {
console.error('Failed to delete passkey:', error);
if (globalMessage) {
showMessage(globalMessage, error.message || 'Failed to delete passkey. Please try again.', 'alert-danger');
}
}
}
/**
* Handle register passkey button click.
*/
async function handleRegisterPasskey() {
const globalMessage = document.getElementById('passkeyMessage');
const labelInput = document.getElementById('passkeyLabel');
const label = labelInput ? labelInput.value.trim() : '';
try {
await registerPasskey(label || 'My Passkey');
if (globalMessage) {
showMessage(globalMessage, 'Passkey registered successfully!', 'alert-success');
}
if (labelInput) labelInput.value = '';
invalidateAuthMethodsCache();
loadPasskeys();
updateAuthMethodsUI();
} catch (error) {
console.error('Registration error:', error);
if (globalMessage) {
showMessage(globalMessage, 'Failed to register passkey. Please try again.', 'alert-danger');
}
}
}
/**
* Update the MFA Status section in the auth-methods card.
* Hides the container if the MFA status endpoint returns 404 (MFA disabled).
* Logs a warning for other non-OK responses.
*/
async function updateMfaStatusUI() {
const container = document.getElementById('mfaStatusContainer');
const badgesEl = document.getElementById('mfaStatusBadges');
if (!container || !badgesEl) return;
try {
const response = await fetch('/user/mfa/status');
if (response.status === 404) {
// MFA feature disabled — silently hide
container.classList.add('d-none');
return;
}
if (!response.ok) {
console.warn('MFA status endpoint returned', response.status);
container.classList.add('d-none');
return;
}
const status = await response.json();
container.classList.remove('d-none');
// Build MFA badges using safe DOM methods
badgesEl.textContent = '';
if (status.mfaEnabled) {
badgesEl.appendChild(createBadge('MFA Active', 'bg-primary', 'bi-shield-lock'));
}
if (status.fullyAuthenticated) {
badgesEl.appendChild(createBadge('Fully Authenticated', 'bg-success', 'bi-shield-check'));
} else {
badgesEl.appendChild(createBadge('Additional Factor Required', 'bg-warning text-dark', 'bi-shield-exclamation'));
}
if (Array.isArray(status.satisfiedFactors)) {
status.satisfiedFactors.forEach(factor => {
badgesEl.appendChild(createBadge(factor, 'bg-secondary', 'bi-check-circle'));
});
}
if (Array.isArray(status.missingFactors) && status.missingFactors.length > 0) {
status.missingFactors.forEach(factor => {
badgesEl.appendChild(createBadge(factor + ' (pending)', 'bg-danger', 'bi-x-circle'));
});
}
} catch (error) {
console.error('Failed to fetch MFA status:', error);
container.classList.add('d-none');
}
}
/**
* Create a Bootstrap badge span element with an icon.
*/
function createBadge(text, bgClass, iconClass) {
const badge = document.createElement('span');
badge.className = `badge ${bgClass} me-2`;
const icon = document.createElement('i');
icon.className = `bi ${iconClass} me-1`;
badge.appendChild(icon);
badge.appendChild(document.createTextNode(text));
return badge;
}
/**
* Update the Authentication Methods UI card with current state.
*/
async function updateAuthMethodsUI() {
const section = document.getElementById('auth-methods-section');
if (!section) return;
try {
const auth = await getAuthMethods(true);
section.classList.remove('d-none');
// Build badges
const badgesContainer = document.getElementById('auth-method-badges');
let badges = '';
if (auth.hasPassword) {
badges += '<span class="badge bg-primary me-2"><i class="bi bi-lock me-1"></i>Password</span>';
} else {
badges += '<span class="badge bg-warning text-dark me-2"><i class="bi bi-unlock me-1"></i>No Password</span>';
}
if (auth.hasPasskeys) {
badges += `<span class="badge bg-success me-2"><i class="bi bi-key me-1"></i>Passkeys (${auth.passkeysCount})</span>`;
}
if (auth.provider && auth.provider !== 'LOCAL') {
badges += `<span class="badge bg-info me-2"><i class="bi bi-cloud me-1"></i>${escapeHtml(auth.provider)}</span>`;
}
badgesContainer.innerHTML = badges;
// Show/hide Remove Password button (only if has password AND passkeys)
const removeContainer = document.getElementById('removePasswordContainer');
if (removeContainer) {
removeContainer.classList.toggle('d-none', !(auth.hasPassword && auth.hasPasskeys));
}
// Show/hide Set Password link (only if no password)
const setContainer = document.getElementById('setPasswordContainer');
if (setContainer) {
setContainer.classList.toggle('d-none', auth.hasPassword);
}
// Update Change Password link text
const changePasswordLink = document.getElementById('changePasswordLink');
if (changePasswordLink) {
changePasswordLink.textContent = auth.hasPassword ? 'Change Password' : 'Set a Password';
}
// Update MFA status section
await updateMfaStatusUI();
} catch (error) {
console.error('Failed to update auth methods UI:', error);
const section = document.getElementById('auth-methods-section');
if (section) {
section.innerHTML = '<div class="alert alert-warning">Unable to load authentication methods.</div>';
}
}
}
/**
* Wire up the Remove Password button and modal.
*/
function initRemovePassword() {
const removeBtn = document.getElementById('removePasswordBtn');
const confirmInput = document.getElementById('removePasswordConfirmInput');
const confirmBtn = document.getElementById('confirmRemovePasswordBtn');
const errorEl = document.getElementById('removePasswordError');
if (!removeBtn) return;
removeBtn.addEventListener('click', () => {
if (!removePasswordModalInstance) {
removePasswordModalInstance = new bootstrap.Modal(document.getElementById('removePasswordModal'));
}
confirmInput.value = '';
confirmBtn.disabled = true;
errorEl.classList.add('d-none');
removePasswordModalInstance.show();
});
// Enable confirm button only when "REMOVE" is typed
confirmInput.addEventListener('input', () => {
confirmBtn.disabled = confirmInput.value.trim() !== 'REMOVE';
});
confirmBtn.addEventListener('click', async () => {
if (confirmInput.value.trim() !== 'REMOVE') return;
confirmBtn.disabled = true;
confirmBtn.textContent = 'Removing...';
errorEl.classList.add('d-none');
try {
const response = await fetch('/user/webauthn/password', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
[csrfHeader]: csrfToken
}
});
if (!response.ok) {
let msg = 'Failed to remove password';
try {
const data = await response.json();
msg = data.message || msg;
} catch {
const text = await response.text();
if (text) msg = text;
}
throw new Error(msg);
}
removePasswordModalInstance.hide();
const globalMessage = document.getElementById('globalMessage');
if (globalMessage) {
showMessage(globalMessage, 'Password removed successfully. You are now passwordless.', 'alert-success');
}
invalidateAuthMethodsCache();
updateAuthMethodsUI();
} catch (error) {
console.error('Failed to remove password:', error);
errorEl.textContent = error.message;
errorEl.classList.remove('d-none');
} finally {
confirmBtn.disabled = false;
confirmBtn.textContent = 'Remove Password';
}
});
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
const passkeySection = document.getElementById('passkey-section');
if (!passkeySection) return;
if (!isWebAuthnSupported()) {
passkeySection.innerHTML = '<div class="alert alert-warning">Your browser does not support passkeys.</div>';
return;
}
// Event delegation for credential list actions
const passkeysList = document.getElementById('passkeys-list');
if (passkeysList) {
passkeysList.addEventListener('click', (event) => {
const button = event.target.closest('button[data-action]');
if (!button) return;
const { action, id, label } = button.dataset;
if (action === 'rename') {
renamePasskey(id, label);
} else if (action === 'delete') {
deletePasskey(id);
}
});
}
// Wire up register button
const registerBtn = document.getElementById('registerPasskeyBtn');
if (registerBtn) {
registerBtn.addEventListener('click', handleRegisterPasskey);
}
// Initialize remove password functionality
initRemovePassword();
// Load existing passkeys and auth methods
loadPasskeys();
updateAuthMethodsUI();
});