- main
- manifest
- deps
- main
- Install
- Run
const BACKEND_APP_SERVER = "origin_0";
const BACKEND_SECURITY_CHECK = "origin_1";
const PREFIX_LENGTH = 5;
const LOGIN_HTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Compromised password detection demo</title>
</head>
<body>
<form action="/post" method="post">
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required />
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required />
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
`;
async function handler(event) {
const req = event.request;
const url = new URL(req.url);
if (req.method === "GET" && url.pathname === "/") {
return new Response(LOGIN_HTML);
}
let body = await req.text();
let params = new URLSearchParams(body);
let plainCred = params.get("password");
if (plainCred) {
const hashedCred = Array.from(new Uint8Array(await crypto.subtle.digest({name:"sha-1"}, new TextEncoder().encode(plainCred)))).map(b => b.toString(16).padStart(2, "0")).join('').toUpperCase()
let hashLeft = hashedCred.slice(0, PREFIX_LENGTH);
let hashRight = hashedCred.slice(PREFIX_LENGTH);
let apiUrl = `https://api.pwnedpasswords.com/range/${hashLeft}`;
let apiReq = new Request(apiUrl);
let apiRes = await fetch(apiReq, { backend: BACKEND_SECURITY_CHECK });
let apiResBody = await apiRes.text();
let result = apiResBody.includes(hashRight) ? "compromised-credential" : "safe-credential";
req.headers.set("fastly-password-status", result);
}
return fetch(req, { backend: BACKEND_APP_SERVER, body: params });
}
addEventListener("fetch", (event) => event.respondWith(handler(event)));