Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check haveibeenpwned with JS
import crypto from 'crypto';
import fetch from 'node-fetch';
const PREFIX_LENGTH = 5;
export function hash(passphrase) {
const shaSum = crypto.createHash('sha1');
shaSum.update(String(passphrase).normalize('NFKC'));
return shaSum.digest('hex');
}
export async function passwordBreached(
passphrase,
passcheckUrl = 'https://api.pwnedpasswords.com/range/'
) {
const hashedPass = hash(passphrase);
const hashedPrefix = hashedPass.substr(0, PREFIX_LENGTH);
const hashedPasswordSub = hashedPass.substr(PREFIX_LENGTH);
const response = await fetch(`${passcheckUrl}${hashedPrefix}`, {
method: 'GET',
headers: {
'User-Agent': 'YOURAPP (APP DETAIL; APP_URL) <CONTACT_EMAIL>',
},
});
if (!response.ok)
throw Object.assign(new Error('Unexpected result from passcheck api.'), { response });
const result = await response.text();
return (
result
.split('\n')
.map(line => line.split(':'))
.filter(([suffix]) => hashedPasswordSuffix === suffix.toLowerCase())
.map(([_, count]) => Number(count))
.shift() || 0
);
}
export default passwordBreached;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment