Last active
April 2, 2019 21:34
-
-
Save tracker1/9d6ef79941ccaf89286bd01c3ff10d6e to your computer and use it in GitHub Desktop.
Check haveibeenpwned with JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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