Password Breach Checker — JavaScript source
Check if a password has appeared in known data breaches using k-anonymity. Only the first 5 characters of the SHA-1 hash are sent - your full password never leaves your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* breach-checker — password breach lookup via Have I Been Pwned's Pwned
* Passwords API, using k-anonymity: only the first 5 characters of the SHA-1
* hash ever leave the machine.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 15, Bun, Deno).
* CosmoDev polyglot showcase port of the `breach-checker` tool, ported from
* src/lib/breach-checker.ts.
*
* Why this file exists: it isolates the pure core of the k-anonymity protocol
* — hash locally, send only the 5-char prefix, match the suffix locally — so
* the service never learns which password was checked. The HTTP fetch half of
* checkBreach() is transport and stays out (as in every sibling port): a
* caller fetches rangeUrlFor(prefix) and hands status + body to checkRange().
*
* display source — part of CosmoDev's polyglot tool pages.
*/
/**
* Lookup outcome, mirroring the BreachResult interface in the TypeScript lib.
* @typedef {object} BreachResult
* @property {boolean} breached True when the exact hash suffix appeared.
* @property {number} count 0 = never seen, -1 = lookup failed.
* @property {string} hashPrefix First 5 chars of the uppercase SHA-1 hex.
* @property {string} hashSuffix Remaining 35 chars, matched locally.
* @property {string} [error] Set when the lookup failed.
* @property {number} [candidates] Candidate lines the API returned (all
* checked locally).
*/
// Free, no key, CORS-enabled. Returns one "SUFFIX:COUNT" line per hash
// sharing the requested prefix (~800 candidates).
export const HIBP_RANGE_URL = 'https://api.pwnedpasswords.com/range/';
/**
* SHA-1 of a UTF-8 string as uppercase hex (the format HIBP expects).
*
* Uses Web Crypto's crypto.subtle — the exact primitive the canonical lib
* uses — a global in every modern runtime, so no import is needed.
*/
export async function sha1Hex(input) {
const digest = await globalThis.crypto.subtle.digest('SHA-1', new TextEncoder().encode(input));
return [...new Uint8Array(digest)]
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
}
/**
* Split a 40-char hash into the 5-char k-anonymity prefix and the 35-char
* suffix. Uppercases first, so lowercase hashes are normalized.
*/
export function splitHash(hash) {
const h = String(hash).toUpperCase();
return { prefix: h.slice(0, 5), suffix: h.slice(5) };
}
/**
* Search an HIBP range response for a hash suffix and return its breach
* count. Never throws; returns 0 when the suffix is not present. Tolerates
* LF and CRLF line endings, blank lines, and per-line whitespace.
*/
export function parseRangeBody(body, suffix) {
if (typeof body !== 'string' || !suffix) return 0;
for (const line of body.split(/\r?\n/)) {
const idx = line.indexOf(':');
if (idx === -1) continue;
if (line.slice(0, idx).trim() === suffix) {
const count = Number.parseInt(line.slice(idx + 1).trim(), 10);
return Number.isNaN(count) || count < 0 ? 0 : count;
}
}
return 0;
}
/**
* Count the "SUFFIX:COUNT" candidate lines in a range response. Lines
* without a colon, or with an empty suffix field, don't count.
*/
export function countCandidates(body) {
if (typeof body !== 'string') return 0;
let n = 0;
for (const line of body.split(/\r?\n/)) {
const idx = line.indexOf(':');
if (idx !== -1 && line.slice(0, idx).trim() !== '') n++;
}
return n;
}
/** Build the range request URL for a prefix — only the 5-char prefix ever
* appears in it (the k-anonymity invariant). */
export function rangeUrlFor(prefix) {
return HIBP_RANGE_URL + prefix;
}
/**
* The pure half of checkBreach(): classify an already-fetched range response
* for a password. A non-2xx status mirrors the lib's !response.ok branch —
* count -1 with an HTTP error message; otherwise the suffix is matched
* locally and the breach count interpreted, with candidates counted.
*/
export async function checkRange(password, status, body) {
const { prefix, suffix } = splitHash(await sha1Hex(password));
if (status < 200 || status > 299) {
return {
breached: false,
count: -1,
hashPrefix: prefix,
hashSuffix: suffix,
error: `The breach database returned HTTP ${status}`,
};
}
const count = parseRangeBody(body, suffix);
return {
breached: count > 0,
count,
hashPrefix: prefix,
hashSuffix: suffix,
candidates: countCandidates(body),
};
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →