Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 9 min read

Check passwords against breaches with the k-anonymity range API in Node.js

To check a password against known breaches in Node.js, SHA-1 hash it, send only the first 5 hex characters to the Pwned Passwords range endpoint (/range/{prefix} on api.pwnedpasswords.com), and look for the remaining 35

To check a password against known breaches in Node.js, SHA-1 hash it, send only the first 5 hex characters to the Pwned Passwords range endpoint (/range/{prefix} on api.pwnedpasswords.com), and look for the remaining 35 characters in the list that comes back. The password and its full hash never leave your server, the API needs no key, and the whole check is about 30 lines with no dependencies.

The lookup is the easy part. This post also covers the Add-Padding header, what to do when the API is slow or down (fail open or fail closed), and where in your auth flow to call it: sign-up, password change and login.

Disclosure: I work at Frontegg. Everything before the last section works with any Node.js stack.

Why check at all

NIST SP 800-63B (rev. 4, section 3.1.1.2) says that when a user sets or changes a password, you SHALL compare it against a blocklist of commonly used, expected or compromised passwords, and its first example is passwords from previous breach corpuses. If it matches, you SHALL make the user pick a different one and tell them why. The same guidance drops composition rules and forced periodic rotation, so a breach check plus a minimum length does more for you than "one uppercase, one symbol".

OWASP's Credential Stuffing Prevention Cheat Sheet points to Pwned Passwords as a well-known free source for this check. Credential-stuffing lists are built from breached credentials, so rejecting breached passwords makes your users much harder targets for one of the cheapest attacks there is.

How the range API keeps the password private

The Pwned Passwords range API uses k-anonymity:

password ──SHA-1──> 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
                    β””β”€β”¬β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   prefix (sent)      suffix (kept local)

GET /range/5BAA6  ──>  ~800-1,000 lines of "SUFFIX:COUNT"
                       compare locally: is our suffix in the list?

The API only ever sees a 5-character prefix. There are 1,048,576 possible prefixes and a typical one matches around 800 hashes in the dataset, so the prefix alone doesn't identify your password. A few details from the API docs that matter in code:

  • No API key, no rate limit, no attribution requirement for Pwned Passwords. A User-Agent isn't required but is recommended.
  • Every prefix returns HTTP 200. There is no 404 for "not found", so anything other than 200 is an error.
  • Add-Padding: true pads every response to between 800 and 1,000 rows. Padding rows have a count of 0. Without it, the response size can hint at which prefix you asked for.
  • Don't check as the user types. The HIBP docs warn that per-keystroke lookups can leak the password to an observer. Check on submit.

Step 1: The lookup

// src/pwned.js
import { createHash } from 'node:crypto';

const API = 'https://api.pwnedpasswords.com';

export function sha1Hex(password) {
  return createHash('sha1').update(password, 'utf8').digest('hex').toUpperCase();
}

// How many times the password appears in Pwned Passwords (0 = not found).
// Throws on network errors, timeouts and non-200 responses.
export async function pwnedCount(password, { baseUrl = API, timeoutMs = 1500 } = {}) {
  const hash = sha1Hex(password);
  const prefix = hash.slice(0, 5);
  const suffix = hash.slice(5);

  const res = await fetch(`${baseUrl}/range/${prefix}`, {
    headers: {
      'Add-Padding': 'true',
      'User-Agent': 'my-app-password-check',
    },
    signal: AbortSignal.timeout(timeoutMs),
  });
  if (res.status !== 200) {
    throw new Error(`Pwned Passwords returned HTTP ${res.status}`);
  }

  const body = await res.text();
  for (const line of body.split('\n')) {
    const [candidate, count] = line.trim().split(':');
    if (candidate === suffix) return Number(count); // padding rows have count 0
  }
  return 0;
}

Notes on the code:

  • SHA-1 is fine here. It's the lookup key the dataset uses, not how you store passwords. Store them with argon2id or bcrypt as usual.
  • Lines can end in CRLF (the downloadable dataset uses CRLF), so trim() each line before comparing.
  • The API's sample responses use uppercase hex, and sha1Hex uppercases too, so a plain === works.
  • AbortSignal.timeout keeps a slow lookup from hanging your sign-up form. Pick a timeout your users won't notice (1 to 2 seconds).
  • Don't log the password, the hash or the prefix.

Step 2: Decide what happens when the API is down

pwnedCount throws when the lookup fails. Your policy decides what that means. Wrap it once so the rest of the app gets a clear answer:

// src/policy.js
import { pwnedCount } from './pwned.js';

// Result: { breached: true | false | null, count }
// breached === null means the check could not run (timeout, outage).
export async function checkPassword(password, options) {
  try {
    const count = await pwnedCount(password, options);
    return { breached: count > 0, count };
  } catch (err) {
    console.warn('breached-password check unavailable:', err.message);
    return { breached: null, count: null };
  }
}

// Sign-up and password change: reject known-breached passwords.
// failClosed decides what happens when the check can't run.
export async function canSetPassword(password, { failClosed = false, ...options } = {}) {
  const { breached, count } = await checkPassword(password, options);
  if (breached) {
    return {
      ok: false,
      reason: `This password has appeared in ${count.toLocaleString('en-US')} data breaches. Choose a different one.`,
    };
  }
  if (breached === null && failClosed) {
    return { ok: false, reason: 'We could not check this password right now. Try again in a minute.' };
  }
  return { ok: true, unchecked: breached === null };
}

// Login: call only AFTER the password was verified. Never blocks login on its own.
export async function afterLogin(password, options) {
  const { breached } = await checkPassword(password, options);
  return breached ? 'require-password-change' : 'continue';
}

Fail open or fail closed?

Fail open (default here) Fail closed
API down at sign-up Accept the password, flag it for a re-check Reject with "try again"
Risk A breached password gets in until the next check Sign-ups and password changes stop during an outage
Good fit Most consumer and B2B apps High-assurance apps that can tolerate the friction

Failing open is reasonable if you close the gap later. The unchecked flag records the gap. In the app below, /login checks on every successful login, so the password gets checked the next time the user signs in. If you only check at login for flagged accounts, read recheckPassword there. At login, always fail open. A third-party outage shouldn't lock every user out.

Step 3: Call it from sign-up, password change and login

Here is an Express 5 app with both routes. Password change and reset use the same canSetPassword call as sign-up.

// src/app.js
import express from 'express';
import { canSetPassword, afterLogin } from './policy.js';

export function createApp({
  checkOptions = {},
  saveUser = async () => {},
  verifyUser = async () => null, // returns the user if email + password match
} = {}) {
  const app = express();
  app.use(express.json());

  app.post('/signup', async (req, res) => {
    const { email, password } = req.body ?? {};
    if (typeof email !== 'string' || typeof password !== 'string') {
      return res.status(400).json({ error: 'email and password are required' });
    }
    if ([...password].length < 15) {
      return res.status(400).json({ error: 'Use at least 15 characters.' });
    }

    const verdict = await canSetPassword(password, checkOptions);
    if (!verdict.ok) {
      return res.status(400).json({ error: verdict.reason });
    }

    // saveUser hashes the password (argon2id, bcrypt...) before storing it.
    // recheckPassword: the breach check didn't run (API down). /login below
    // checks on every successful login, which closes the gap.
    await saveUser({ email, password, recheckPassword: verdict.unchecked });
    res.status(201).json({ ok: true });
  });

  app.post('/login', async (req, res) => {
    const { email, password } = req.body ?? {};
    if (typeof email !== 'string' || typeof password !== 'string') {
      return res.status(400).json({ error: 'email and password are required' });
    }
    const user = await verifyUser(email, password);
    if (!user) return res.status(401).json({ error: 'Invalid email or password' });

    // Only now, with a verified password, check it against breaches.
    const next = await afterLogin(password, checkOptions);
    if (next === 'require-password-change') {
      return res.status(200).json({ next: 'change-password' });
    }
    res.status(200).json({ next: 'app' });
  });

  return app;
}

Where each call belongs:

  • Sign-up, password change, password reset: reject a breached password and show the reason. NIST requires both.
  • Login: check only after the password is verified, so a wrong guess never triggers a lookup. If the password is breached, send the user to a password change instead of the app, and keep that session limited to the change screen (session handling is out of scope for this sketch). NIST says to force a change when there's evidence a password is compromised.
  • The 15-character minimum (counted in Unicode code points, hence [...password]) is NIST's floor for passwords used as a single factor. If the password is always paired with MFA, NIST allows 8.

Step 4: Test it without calling the real API

You don't want unit tests to depend on a third-party service. A small node:http server that mimics the API (HTTP 200, uppercase SUFFIX:COUNT lines, CRLF endings, count-0 padding rows) is enough:

// test/mock.js (excerpt)
const lines = [];
for (const [pw, count] of Object.entries(breached)) {
  const h = sha1Hex(pw);
  if (h.startsWith(prefix)) lines.push(`${h.slice(5)}:${count}`);
}
if (req.headers['add-padding'] === 'true') {
  while (lines.length < 800) {
    lines.push(`${randomBytes(18).toString('hex').slice(0, 35).toUpperCase()}:0`);
  }
}
res.writeHead(200, { 'content-type': 'text/plain' }).end(lines.sort().join('\r\n'));

Then point baseUrl at it and test the parts that matter, including that only the prefix leaves the process:

test('sends only the 5-char prefix, with Add-Padding and a User-Agent', async (t) => {
  const mock = await startMock({ breached: { [LEAKED]: 3 } });
  t.after(mock.close);
  await pwnedCount(LEAKED, { baseUrl: mock.baseUrl });
  const [req] = mock.requests;
  const hash = sha1Hex(LEAKED);
  assert.equal(req.url, `/range/${hash.slice(0, 5)}`);
  assert.ok(!JSON.stringify(req).includes(hash.slice(5)), 'suffix never leaves the process');
  assert.ok(!JSON.stringify(req).includes(LEAKED), 'password never leaves the process');
  assert.equal(req.headers['add-padding'], 'true');
  assert.equal(req.headers['user-agent'], 'my-app-password-check');
});
$ npm test   # node --test --test-reporter=spec, durations trimmed
βœ” sha1Hex returns uppercase SHA-1 hex
βœ” sends only the 5-char prefix, with Add-Padding and a User-Agent
βœ” returns the breach count for a leaked password (CRLF, padded body)
βœ” returns 0 when only padding rows come back
βœ” throws on non-200 and on timeout
βœ” checkPassword reports breached: null when the API is unavailable
βœ” canSetPassword: rejects breached, fail-open vs fail-closed on outage
βœ” afterLogin: breached -> require-password-change; outage -> continue
βœ” Express /signup: 400 for breached, 201 for fresh, flags unchecked on outage
βœ” Express /login: checks only after the password is verified
β„Ή tests 10
β„Ή pass 10

Tested with Node.js 22.23.4 and Express 5.3.0. The first test pins the SHA-1 of password to 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8, so you know the hashing matches what the API expects. For a manual smoke test against the real API, request /range/5BAA6 on api.pwnedpasswords.com and look for the line starting with 1E4C9B93F3F0682250B6CF8331B7EE68FD8. It should come back with a large count.

The same check with Frontegg

If you use Frontegg for authentication, you don't have to write this yourself. Frontegg has a Breached password security rule (Security management β†’ Security rules β†’ Breached password) that runs the same kind of check: the password is hashed locally and only a small part of the hash is sent to a third-party breached-password database.

  • It's off by default in every environment. You turn it on and pick an action: Allow, Challenge or Block.
  • With Challenge or Block, a breached password is rejected at sign-up, password change and password reset, and the user is asked to choose another one.
  • The affected user is notified by email when a breach is detected.

The breached password docs cover login-time checks, per-user and per-tenant overrides, and how the events show up in Security Events. For the bigger picture of where breach checks sit among other defenses, see this guide to credential stuffing and how to stop it.

Checklist

  • [ ] Hash with SHA-1, uppercase, send only the first 5 characters to /range/{prefix}.
  • [ ] Send Add-Padding: true and ignore count-0 rows.
  • [ ] Treat anything but HTTP 200 as an error, and set a short timeout.
  • [ ] Check on submit, never per keystroke.
  • [ ] Reject breached passwords at sign-up, password change and reset, and say why.
  • [ ] At login, check only after the password is verified, then force a password change.
  • [ ] Decide fail open vs fail closed on purpose. If you fail open, re-check later.
  • [ ] Never log the password, its hash or the prefix.
  • [ ] Test against a local mock, not the live API.

Sources: Pwned Passwords API docs, NIST SP 800-63B, OWASP Credential Stuffing Prevention Cheat Sheet.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.