Enjoying Blockend?

Give us a star on GitHub

Star on GitHub
blockend

Blockend

02 blocks

Password hash

Validated

Hash and verify passwords with Argon2id, a server-side pepper, and rehash detection.

The password hash block hashes passwords with Argon2id. It adds a server-side pepper with HMAC-SHA256, generates a random salt for every hash, and returns a standard PHC string.

The block has no root index.ts. Import the class from core, errors from errors, and types from types.

This block stores password hashes. It does not create users, authenticate requests, manage sessions, or rate limit login attempts. Those are application concerns.

Quick start

pnpm dlx blockend-cli init
pnpm dlx blockend-cli add password-hash

Generate a pepper and store it as an environment variable:

openssl rand -base64 32
export APP_PASSWORD_PEPPER="<the generated value>"
import { PasswordHasher } from "@/blocks/password-hash/core";

const hasher = new PasswordHasher();

const hash = await hasher.hashPassword("correct horse battery staple");
const valid = await hasher.verifyPassword("correct horse battery staple", hash);

console.log(valid); // true

Files

password-hash/
├── config.ts
├── core.ts
├── errors.ts
├── types.ts
└── *.test.ts

Installation

pnpm dlx blockend-cli add password-hash

The CLI copies the block and installs @node-rs/argon2. It does not create a pepper for you.

Copy all four source files into blocks/password-hash and install @node-rs/argon2.

Configuration

import type { PasswordHashConfig, PasswordHashConfigOverrides } from "./types";
import { InvalidPepperError, InvalidConfigError } from "./errors";

/**
 * Load configuration from environment variables, with optional overrides.
 * Environment variables:
 *   APP_PASSWORD_PEPPER       (required)
 *   ARGON2_MEMORY_COST        (default: 65536)
 *   ARGON2_TIME_COST          (default: 3)
 *   ARGON2_PARALLELISM        (default: 1)
 *   ARGON2_OUTPUT_LEN         (default: 32)
 *   PASSWORD_MAX_INPUT_BYTES  (default: 128)
 */

// RFC 4648 base64 (standard alphabet, optional padding). Node's decoder is
// lenient and silently skips invalid characters, so the format must be
// validated before decoding.
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;

const MAX_UINT32 = 4294967295;
const MAX_PARALLELISM = 255; // native binding limit

function resolveNumber(
  override: number | undefined,
  envValue: string | undefined,
  fallback: number,
  label: string,
  max: number = MAX_UINT32
): number {
  // Empty string is treated as unset so defaults still apply.
  const resolved =
    override ?? (envValue === undefined || envValue.trim() === "" ? fallback : Number(envValue));
  if (!Number.isInteger(resolved) || resolved < 1 || resolved > max) {
    const received = override !== undefined ? String(override) : (envValue ?? String(fallback));
    throw new InvalidConfigError(
      `${label} must be a positive integer between 1 and ${max}, but received "${received}"`
    );
  }
  return resolved;
}

export function loadConfig(overrides: PasswordHashConfigOverrides = {}): PasswordHashConfig {
  const pepper = overrides.pepper ?? process.env.APP_PASSWORD_PEPPER;
  if (!pepper) {
    throw new InvalidPepperError("APP_PASSWORD_PEPPER environment variable is required");
  }
  if (!BASE64_PATTERN.test(pepper)) {
    throw new InvalidPepperError();
  }

  const pepperBuffer = Buffer.from(pepper, "base64");
  if (pepperBuffer.length < 32) {
    throw new InvalidPepperError();
  }

  return {
    pepper,
    memoryCost: resolveNumber(
      overrides.memoryCost,
      process.env.ARGON2_MEMORY_COST,
      65536,
      "ARGON2_MEMORY_COST"
    ),
    timeCost: resolveNumber(
      overrides.timeCost,
      process.env.ARGON2_TIME_COST,
      3,
      "ARGON2_TIME_COST"
    ),
    parallelism: resolveNumber(
      overrides.parallelism,
      process.env.ARGON2_PARALLELISM,
      1,
      "ARGON2_PARALLELISM",
      MAX_PARALLELISM
    ),
    outputLen: resolveNumber(
      overrides.outputLen,
      process.env.ARGON2_OUTPUT_LEN,
      32,
      "ARGON2_OUTPUT_LEN"
    ),
    maxInputBytes: resolveNumber(
      overrides.maxInputBytes,
      process.env.PASSWORD_MAX_INPUT_BYTES,
      128,
      "PASSWORD_MAX_INPUT_BYTES"
    )
  };
}

Core

import crypto from "node:crypto";
import { hash, verify } from "@node-rs/argon2";
import type { PasswordHashConfig, PasswordHashConfigOverrides } from "./types";
import { loadConfig } from "./config";
import { PasswordTooLongError } from "./errors";

/**
 * Framework-agnostic password hashing service using Argon2id.
 * Can be used in Express, Fastify, Hono, or any Node.js environment.
 */
export class PasswordHasher {
  private readonly config: PasswordHashConfig;
  private readonly pepperBuffer: Buffer;

  constructor(overrides: PasswordHashConfigOverrides = {}) {
    this.config = loadConfig(overrides);
    this.pepperBuffer = Buffer.from(this.config.pepper, "base64");
  }

  /**
   * Apply pepper using HMAC-SHA256.
   * The result is always 32 bytes.
   * Enforces maximum input byte length.
   */
  private applyPepper(password: string): Buffer {
    if (typeof password !== "string") {
      throw new TypeError("password must be a string");
    }

    const byteLength = Buffer.byteLength(password, "utf8");
    if (byteLength > this.config.maxInputBytes) {
      throw new PasswordTooLongError(this.config.maxInputBytes);
    }

    return crypto.createHmac("sha256", this.pepperBuffer).update(password, "utf8").digest();
  }

  /**
   * Hash a plaintext password and return a PHC string.
   * The peppered digest is passed as base64 because @node-rs/argon2's
   * verify() rejects raw binary buffers ("invalid utf-8 sequence"), while
   * a fixed-width ASCII encoding stays byte-stable across hash and verify.
   */
  async hashPassword(password: string): Promise<string> {
    const peppered = this.applyPepper(password).toString("base64");
    const salt = crypto.randomBytes(16); // 128-bit salt

    return hash(peppered, {
      algorithm: 2, // Argon2id
      memoryCost: this.config.memoryCost,
      timeCost: this.config.timeCost,
      parallelism: this.config.parallelism,
      outputLen: this.config.outputLen,
      salt
    });
  }

  /**
   * Verify a plaintext password against a stored Argon2id PHC string.
   * Returns false if the hash is not Argon2id or verification fails.
   * Throws PasswordTooLongError / TypeError for caller mistakes
   * (same policy as hashing).
   */
  async verifyPassword(password: string, storedHash: string): Promise<boolean> {
    if (typeof storedHash !== "string" || !storedHash.startsWith("$argon2id$")) {
      return false;
    }

    // Deliberately outside try/catch: caller mistakes such as oversized
    // passwords or non-string input must propagate instead of being
    // masked as a failed login.
    const peppered = this.applyPepper(password).toString("base64");

    try {
      return await verify(storedHash, peppered);
    } catch {
      // Malformed hash, unsupported parameters, or native binding error.
      // Treat as verification failure — never throw for corrupt stored data.
      return false;
    }
  }

  /**
   * Check if a stored hash was created with weaker or different parameters
   * and should be rehashed.
   */
  needsRehash(storedHash: string): boolean {
    if (typeof storedHash !== "string" || !storedHash.startsWith("$argon2id$")) {
      return true;
    }

    const params = this.extractPhcParams(storedHash);
    if (!params) return true;

    // Force rehash on version mismatch or any parameter that is weaker
    // or different from the current configuration.
    return (
      params.version !== 19 ||
      params.memoryCost < this.config.memoryCost ||
      params.timeCost < this.config.timeCost ||
      params.parallelism !== this.config.parallelism ||
      params.outputLen !== this.config.outputLen
    );
  }

  /**
   * Expose current configuration (read-only).
   */
  get currentConfig(): Readonly<PasswordHashConfig> {
    return { ...this.config };
  }

  /**
   * Parse the parameter section of a PHC string.
   * Returns null on any parse failure.
   *
   * Expected form: $argon2id$v=19$m=65536,t=3,p=1$salt$hash
   * (outputLen is not always present in the PHC string produced by
   * @node-rs/argon2; we treat a missing value as the library default of 32)
   */
  private extractPhcParams(storedHash: string): {
    version: number;
    memoryCost: number;
    timeCost: number;
    parallelism: number;
    outputLen: number;
  } | null {
    // Split: ["", "argon2id", "v=19", "m=65536,t=3,p=1", "salt", "hash"]
    const parts = storedHash.split("$");
    if (parts.length < 5 || parts[1] !== "argon2id") {
      return null;
    }

    const versionPart = parts[2];
    const paramPart = parts[3];

    // Explicit guards — TypeScript cannot always narrow array access
    if (!versionPart || !paramPart || !versionPart.startsWith("v=")) {
      return null;
    }

    const version = parseInt(versionPart.slice(2), 10);
    if (Number.isNaN(version)) return null;

    const paramMap = new Map<string, number>();
    for (const pair of paramPart.split(",")) {
      const [key, value] = pair.split("=");
      if (!key || value === undefined) continue;
      const num = parseInt(value, 10);
      if (!Number.isNaN(num)) {
        paramMap.set(key, num);
      }
    }

    const memoryCost = paramMap.get("m");
    const timeCost = paramMap.get("t");
    const parallelism = paramMap.get("p");

    if (memoryCost === undefined || timeCost === undefined || parallelism === undefined) {
      return null;
    }

    // @node-rs/argon2 does not always emit "l=" (output length).
    // Fall back to the common default of 32 when absent.
    const outputLen = paramMap.get("l") ?? 32;

    return {
      version,
      memoryCost,
      timeCost,
      parallelism,
      outputLen
    };
  }
}

Errors

export class PasswordHashError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "PasswordHashError";
  }
}

export class InvalidPepperError extends PasswordHashError {
  constructor(message = "Pepper must be a base64-encoded string of at least 32 bytes") {
    super(message);
    this.name = "InvalidPepperError";
  }
}

export class InvalidConfigError extends PasswordHashError {
  constructor(message = "Invalid password-hash configuration parameters") {
    super(message);
    this.name = "InvalidConfigError";
  }
}

export class PasswordTooLongError extends PasswordHashError {
  constructor(maxBytes: number) {
    super(`Password exceeds maximum allowed byte length (${maxBytes} bytes)`);
    this.name = "PasswordTooLongError";
  }
}

Types

/**
 * Core configuration for Argon2id hashing.
 */
export interface Argon2Params {
  /** Memory cost in KiB (e.g., 65536 for 64 MiB) */
  memoryCost: number;
  /** Number of iterations */
  timeCost: number;
  /** Degree of parallelism (use 1 for web apps) */
  parallelism: number;
  /** Length of the hash output in bytes */
  outputLen: number;
}

/**
 * Full configuration including pepper and input limits.
 */
export interface PasswordHashConfig extends Argon2Params {
  /** Base64-encoded pepper (must decode to ≥32 bytes) */
  pepper: string;
  /** Maximum allowed password byte length (prevent DoS) */
  maxInputBytes: number;
}

/**
 * Options that can be overridden when instantiating PasswordHasher.
 */
export type PasswordHashConfigOverrides = Partial<PasswordHashConfig>;

Pepper setup

The pepper is a secret mixed into every password before Argon2 runs. It is not stored with the hash. An attacker who steals the database still cannot test password guesses without the pepper.

APP_PASSWORD_PEPPER must be valid base64 and decode to at least 32 bytes. The openssl command above produces a suitable value. Keep it in a secret manager, not in source control or a public environment file.

If the pepper is missing, invalid, or shorter than 32 bytes, new PasswordHasher() throws InvalidPepperError.

Usage

Hash a password

import { PasswordHasher } from "@/blocks/password-hash/core";

const hasher = new PasswordHasher();

app.post("/users", async (req, res) => {
  const hash = await hasher.hashPassword(req.body.password);

  const user = await db.user.create({
    data: {
      email: req.body.email,
      passwordHash: hash
    }
  });

  res.status(201).json({ id: user.id });
});

The stored string looks like this:

$argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>

Store it in a text column long enough for future parameter changes. Do not split or parse it in application code.

Verify a password

app.post("/login", async (req, res) => {
  const user = await db.user.findUnique({
    where: { email: req.body.email }
  });

  if (!user) {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  const valid = await hasher.verifyPassword(req.body.password, user.passwordHash);

  if (!valid) {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  if (hasher.needsRehash(user.passwordHash)) {
    const newHash = await hasher.hashPassword(req.body.password);
    await db.user.update({
      where: { id: user.id },
      data: { passwordHash: newHash }
    });
  }

  // Create a session or return a token.
  res.json({ ok: true });
});

Return the same error for an unknown email and a wrong password. Do not reveal which one failed.

Configuration overrides

The constructor accepts overrides for tests and for apps that do not use environment variables:

const hasher = new PasswordHasher({
  pepper: process.env.APP_PASSWORD_PEPPER!,
  memoryCost: 65_536,
  timeCost: 3,
  parallelism: 1,
  outputLen: 32,
  maxInputBytes: 128
});
SettingEnvironment variableDefault
pepperAPP_PASSWORD_PEPPERRequired
memoryCostARGON2_MEMORY_COST65536 KiB
timeCostARGON2_TIME_COST3
parallelismARGON2_PARALLELISM1
outputLenARGON2_OUTPUT_LEN32
maxInputBytesPASSWORD_MAX_INPUT_BYTES128

Numbers must be positive integers. parallelism is capped at 255 by the native binding.

Parameter guidance

Argon2id cost parameters are a tradeoff between resistance to guessing and memory use. Start with the defaults and measure on production hardware.

ScenariomemoryCosttimeCostparallelismNotes
Default web app655363164 MiB per hash. Start here.
High-traffic API471041146 MiB, one pass. Measure latency.
Memory-constrained container1638431Lower memory, more iterations.
Desktop or CLI tool13107231128 MiB if memory allows.

Two rules matter more than the table:

  1. Measure hash and verify latency on the hardware you deploy. A verify that takes seconds will hurt login and invite abuse.
  2. Budget total memory, not per-hash memory. Each concurrent hash holds memoryCost of RAM. Twenty logins at 64 MiB can use 1.25 GiB.

Use the rate limiter on credential endpoints and queue bursts if your login traffic is spiky.

Rehashing

needsRehash(hash) returns true when:

  • The hash is not Argon2id.
  • The version is not 19.
  • memoryCost is lower than the current config.
  • timeCost is lower than the current config.
  • parallelism differs from the current config.
  • outputLen differs from the current config.

If the other parameters match, a hash with higher memory or time cost than the current config does not need a rehash. It is already at least as strong.

Call needsRehash after a successful verify, then rehash with the plaintext password you already have. Do not rehash without the plaintext.

Changing the pepper makes every old hash fail verification. needsRehash cannot detect a pepper change because the pepper is not in the stored string. Pepper rotation needs a planned migration, not a silent swap.

Errors

import {
  InvalidConfigError,
  InvalidPepperError,
  PasswordHashError,
  PasswordTooLongError
} from "@/blocks/password-hash/errors";
ErrorWhen it is thrown
InvalidPepperErrorThe pepper is missing, not base64, or shorter than 32 bytes.
InvalidConfigErrorA numeric parameter is out of range.
PasswordTooLongErrorThe password exceeds maxInputBytes.
TypeErrorThe password is not a string.
PasswordHashErrorBase class for the block's errors.

verifyPassword returns false for a malformed or non-Argon2id stored hash. It still throws PasswordTooLongError and TypeError for caller mistakes. Oversized input is a bad request, not a failed login.

try {
  const valid = await hasher.verifyPassword(password, storedHash);
} catch (error) {
  if (error instanceof PasswordTooLongError) {
    return res.status(400).json({ error: "Password is too long" });
  }

  throw error;
}

API reference

PasswordHasher

class PasswordHasher {
  constructor(overrides?: PasswordHashConfigOverrides);

  hashPassword(password: string): Promise<string>;
  verifyPassword(password: string, storedHash: string): Promise<boolean>;
  needsRehash(storedHash: string): boolean;

  readonly currentConfig: Readonly<PasswordHashConfig>;
}

currentConfig includes the pepper. Do not log it or expose it through an admin endpoint.

PasswordHashConfig

interface PasswordHashConfig {
  pepper: string;
  memoryCost: number;
  timeCost: number;
  parallelism: number;
  outputLen: number;
  maxInputBytes: number;
}

loadConfig

function loadConfig(overrides?: PasswordHashConfigOverrides): PasswordHashConfig;

Reads environment variables and applies overrides. PasswordHasher calls this in its constructor.

Security notes

  • Use a unique pepper per environment. Do not reuse production secrets in staging.
  • Keep the pepper out of logs, error reports, and client bundles.
  • Enforce a minimum password length in your application. The block has no minimum; it only enforces a maximum byte length.
  • Normalize Unicode only if your product requires it. Changing normalization later changes the password.
  • Do not compare password hashes in application code. Use verifyPassword.
  • For unknown accounts, verify against a dummy hash with the same parameters to reduce timing differences.
  • Argon2 is memory-hard by design. Set container memory limits above memoryCost times your expected concurrency.

When not to use it

  • You need a managed identity provider that already stores credentials.
  • You need passwordless authentication, OAuth, or passkeys. Use a dedicated flow.
  • You run on a runtime without Node native bindings. @node-rs/argon2 requires a runtime that supports them.

On this page