Skip to content

Instantly share code, notes, and snippets.

@hrshadhin
Forked from jgrahamc/pwnd.js
Created February 27, 2018 17:29
Show Gist options
  • Save hrshadhin/471cb9b85962cfe3b8683ef74f069325 to your computer and use it in GitHub Desktop.
Save hrshadhin/471cb9b85962cfe3b8683ef74f069325 to your computer and use it in GitHub Desktop.
Cloudflare Workers that adds an "Cf-Password-Pwnd" header to a POST request indicating whether the 'password' field appears in Troy Hunt's database of pwned passwords.
addEventListener('fetch', event => {
event.respondWith(fetchAndCheckPassword(event.request))
})
async function fetchAndCheckPassword(req) {
if (req.method == "POST") {
try {
const post = await req.formData();
const pwd = post.get('password')
const enc = new TextEncoder("utf-8").encode(pwd)
let hash = await crypto.subtle.digest("SHA-1", enc)
let hashStr = hex(hash).toUpperCase()
const prefix = hashStr.substring(0, 5)
const suffix = hashStr.substring(5)
const pwndpwds = await fetch('https://api.pwnedpasswords.com/range/' + prefix)
const t = await pwndpwds.text()
const pwnd = t.includes(suffix)
let newHdrs = new Headers(req.headers)
newHdrs.set('Cf-Password-Pwnd', pwnd?'YES':'NO')
const init = {
method: 'POST',
headers: newHdrs,
body: post
}
return await fetch(req.url, init)
} catch (err) {
return new Response('Internal Error')
}
}
return await fetch(req)
}
function hex(a) {
var h = "";
var b = new Uint8Array(a);
for(var i = 0; i < b.length; i++){
var hi = b[i].toString(16);
h += hi.length === 1?"0"+hi:hi;
}
return h;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment