-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpassword-strength.js
More file actions
332 lines (285 loc) · 13.1 KB
/
Copy pathpassword-strength.js
File metadata and controls
332 lines (285 loc) · 13.1 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
/**
* Password strength meter with zxcvbn-ts scoring and HaveIBeenPwned breach advisory.
*
* Auto-initialises on any element with [data-password-field] in the page.
* Attributes:
* data-password-field — CSS selector for the password input (e.g. "#Input_Password")
* data-user-input-fields — Comma-separated CSS selectors for fields whose live values
* should penalise the strength score (e.g. "#Input_Email,#Input_UserName")
* data-min-length — Minimum password length enforced server-side (from PasswordRequirementOptions)
*/
import { zxcvbn, zxcvbnOptions } from '@zxcvbn-ts/core';
const SCORE_CONFIG = [
{ label: 'Very weak', barClass: 'bg-danger', width: 20, widthClass: 'password-strength-width-20' },
{ label: 'Weak', barClass: 'bg-warning text-dark', width: 40, widthClass: 'password-strength-width-40' },
{ label: 'Fair', barClass: 'bg-info text-dark', width: 60, widthClass: 'password-strength-width-60' },
{ label: 'Strong', barClass: 'bg-primary', width: 80, widthClass: 'password-strength-width-80' },
{ label: 'Very strong', barClass: 'bg-success', width: 100, widthClass: 'password-strength-width-100' },
];
let zxcvbnReady = false;
let zxcvbnLoadPromise = null;
async function ensureZxcvbn() {
if (zxcvbnReady) return;
if (!zxcvbnLoadPromise) {
zxcvbnLoadPromise = Promise.all([
import('@zxcvbn-ts/language-common'),
import('@zxcvbn-ts/language-en'),
]);
}
try {
const [zxcvbnCommon, zxcvbnEn] = await zxcvbnLoadPromise;
zxcvbnOptions.setOptions({
translations: zxcvbnEn.translations,
graphs: zxcvbnCommon.adjacencyGraphs,
dictionary: { ...zxcvbnCommon.dictionary, ...zxcvbnEn.dictionary },
useLevenshteinDistance: true,
});
zxcvbnReady = true;
} catch (err) {
zxcvbnLoadPromise = null; // Allow retry on next input
throw err;
}
}
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
function getUserInputValues(userInputFieldIds) {
if (!userInputFieldIds) return [];
const raw = userInputFieldIds
.split(',')
.map(sel => document.querySelector(sel.trim())?.value)
.filter(Boolean);
const parts = [];
for (const val of raw) {
parts.push(val);
// Split email addresses: "john.doe@gmail.com" → "john.doe", "john", "doe", "gmail"
if (val.includes('@')) {
const [local, domain] = val.split('@');
parts.push(local);
parts.push(...local.split(/[._+\-]/));
const domainBase = domain?.split('.')[0];
if (domainBase) parts.push(domainBase);
}
// Split on common word-separators: spaces, dots, underscores, hyphens
parts.push(...val.split(/[\s._@+\-]+/));
}
// Deduplicate and discard single-character fragments (too noisy)
return [...new Set(parts.filter(s => s.length >= 2))];
}
function updateMeter(container, score, feedback, crackTimesDisplay) {
const config = SCORE_CONFIG[score];
const bar = container.querySelector('.password-strength-bar');
const label = container.querySelector('.password-strength-label');
const warningEl = container.querySelector('.password-strength-warning');
const suggestionsEl = container.querySelector('.password-strength-suggestions');
const crackTimeEl = container.querySelector('.password-strength-cracktime');
// Reset bar classes
bar.className = `progress-bar password-strength-bar ${config.barClass} ${config.widthClass}`;
// Update aria
const progressEl = container.querySelector('.progress');
progressEl.setAttribute('aria-valuenow', config.width);
label.textContent = config.label;
// Suppress zxcvbn feedback while hard requirements (e.g. minimum length) are still unmet —
// the requirements checklist already tells the user what to fix; showing both is redundant.
const requirementsList = container.querySelector('.password-requirements');
const requirementsPending = requirementsList && !requirementsList.classList.contains('d-none');
// Warning: specific diagnosis of what pattern was detected (null for score >= 3)
const warning = requirementsPending ? '' : (feedback.warning ?? '');
if (warningEl) {
warningEl.textContent = warning;
warningEl.classList.toggle('d-none', !warning);
}
// Suggestions: generic improvement tips — only shown when there is no specific warning,
// since both would otherwise say the same thing in different words.
if (suggestionsEl) {
const tips = (!requirementsPending && !warning) ? (feedback.suggestions ?? []).filter(Boolean) : [];
suggestionsEl.textContent = tips.join(' ');
suggestionsEl.classList.toggle('d-none', tips.length === 0);
}
// Crack time estimate (online throttled — most relevant for web app context)
if (crackTimeEl) {
const display = crackTimesDisplay?.onlineThrottling100PerHour;
crackTimeEl.textContent = display ? `Time to crack: ${display}` : '';
crackTimeEl.classList.toggle('d-none', !display);
}
}
function clearMeter(container) {
const bar = container.querySelector('.password-strength-bar');
bar.className = 'progress-bar password-strength-bar password-strength-bar-initial';
container.querySelector('.progress').setAttribute('aria-valuenow', '0');
container.querySelector('.password-strength-label').textContent = '';
const warningEl = container.querySelector('.password-strength-warning');
if (warningEl) { warningEl.textContent = ''; warningEl.classList.add('d-none'); }
const suggestionsEl = container.querySelector('.password-strength-suggestions');
if (suggestionsEl) { suggestionsEl.textContent = ''; suggestionsEl.classList.add('d-none'); }
const crackTimeEl = container.querySelector('.password-strength-cracktime');
if (crackTimeEl) { crackTimeEl.textContent = ''; crackTimeEl.classList.add('d-none'); }
}
// --- Requirements checklist ---
function initRequirements(container, passwordInput) {
const minLength = parseInt(container.dataset.minLength, 10) || 8;
const listEl = container.querySelector('.password-requirements');
if (!listEl) return;
const rules = [
{
el: listEl.querySelector('[data-rule="minlength"]'),
label: `At least ${minLength} characters`,
test: pw => pw.length >= minLength,
},
];
// Set rule label text
for (const rule of rules) {
if (rule.el) rule.el.querySelector('.req-text').textContent = rule.label;
}
function updateRequirements() {
const pw = passwordInput.value;
let allMet = true;
for (const rule of rules) {
if (!rule.el) continue;
const met = rule.test(pw);
if (!met) allMet = false;
rule.el.classList.toggle('d-none', met);
const icon = rule.el.querySelector('.req-icon');
if (icon) icon.textContent = met ? '✓' : '○';
rule.el.classList.toggle('text-success', met);
}
// Hide entire checklist when all rules pass; show when any fail (and field has focus or value)
const hasValue = pw.length > 0;
listEl.classList.toggle('d-none', allMet || !hasValue);
}
passwordInput.addEventListener('focus', () => {
if (passwordInput.value.length === 0) {
// Show all rules unmet on first focus so user knows what to satisfy
for (const rule of rules) {
if (rule.el) {
rule.el.classList.remove('d-none');
const icon = rule.el.querySelector('.req-icon');
if (icon) icon.textContent = '○';
rule.el.classList.remove('text-success');
}
}
listEl.classList.remove('d-none');
} else {
updateRequirements();
}
});
passwordInput.addEventListener('blur', () => {
// Keep showing failures after blur so user knows what's still needed
updateRequirements();
if (passwordInput.value.length === 0) listEl.classList.add('d-none');
});
passwordInput.addEventListener('input', updateRequirements);
}
// --- Show/hide password toggle ---
function initShowToggle(container, passwordInput) {
const btn = container.querySelector('.password-show-toggle');
if (!btn) return btn;
btn.addEventListener('click', () => {
const isShowing = passwordInput.type === 'text';
passwordInput.type = isShowing ? 'password' : 'text';
const icon = btn.querySelector('i');
if (icon) {
icon.classList.toggle('bi-eye', isShowing);
icon.classList.toggle('bi-eye-slash', !isShowing);
}
btn.setAttribute('aria-label', isShowing ? 'Show password' : 'Hide password');
btn.setAttribute('aria-pressed', String(!isShowing));
});
return btn;
}
async function checkHibp(password) {
try {
const data = new TextEncoder().encode(password);
const hashBuf = await crypto.subtle.digest('SHA-1', data);
const hashHex = [...new Uint8Array(hashBuf)]
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const prefix = hashHex.slice(0, 5);
const suffix = hashHex.slice(5);
const resp = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {
headers: { 'Add-Padding': 'true' }
});
if (!resp.ok) return false;
const text = await resp.text();
for (const line of text.split(/\r?\n/)) {
const [hash, countStr] = line.trim().split(':');
// Padded responses include decoy entries with count=0; discard them per the HIBP spec.
if (hash === suffix && parseInt(countStr, 10) > 0) return true;
}
return false;
} catch {
// Network failure — fail silently, do not alarm the user
return false;
}
}
function initMeter(container) {
const passwordSelector = container.dataset.passwordField;
const userInputFieldIds = container.dataset.userInputFields || '';
const minLength = parseInt(container.dataset.minLength, 10) || 15;
const passwordInput = document.querySelector(passwordSelector);
if (!passwordInput) return;
initRequirements(container, passwordInput);
initShowToggle(container, passwordInput);
let hibpWarningActive = false;
let inputGeneration = 0;
const onInput = debounce(async () => {
const password = passwordInput.value;
if (!password) {
clearMeter(container);
hibpWarningActive = false;
return;
}
await ensureZxcvbn();
// Guard against stale result if the user kept typing during the initial load
if (password !== passwordInput.value) return;
const userInputs = getUserInputValues(userInputFieldIds);
const result = zxcvbn(password, userInputs);
// Render zxcvbn result immediately; HIBP check runs asynchronously below.
if (hibpWarningActive) {
updateMeter(container, 0, { warning: 'This password appeared in a data breach.' }, null);
} else {
updateMeter(container, result.score, result.feedback, result.crackTimesDisplay);
}
// Check HIBP while the user is still typing — no need to wait for blur.
// Only fires once the password meets minimum length; short passwords fail
// server-side validation before HIBP is relevant.
if (password.length >= minLength) {
const gen = inputGeneration;
const breached = await checkHibp(password);
// Discard if the user typed something new while the request was in flight.
if (passwordInput.value !== password || inputGeneration !== gen) return;
hibpWarningActive = breached;
if (breached) {
updateMeter(container, 0, { warning: 'This password appeared in a data breach.' }, null);
}
}
}, 300);
// Clear HIBP override immediately when user starts changing password again.
// Also clear the meter instantly when the field becomes empty (no 300 ms debounce delay).
passwordInput.addEventListener('input', () => {
hibpWarningActive = false;
inputGeneration++;
if (!passwordInput.value) {
clearMeter(container);
} else {
onInput();
}
});
// Catch autofill / password-manager injections which dispatch `change` but not `input`
passwordInput.addEventListener('change', onInput);
// Recompute strength score when related fields (email, username) change,
// since they are used as zxcvbn user inputs to penalise guessable passwords.
if (userInputFieldIds) {
for (const sel of userInputFieldIds.split(',')) {
const el = document.querySelector(sel.trim());
if (el) el.addEventListener('input', onInput);
}
}
}
// Auto-init all meters on the page
document.querySelectorAll('[data-password-field]').forEach(initMeter);