-
-
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.
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
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