<!-- Source: README.md -->

# @codenhub/crypto

CryptoKit hashes and checks passwords with Argon2id, and gives the same bytes on Node.js, Bun, Deno, Cloudflare Workers and browsers, so a hash made on one runtime is checked on any other. It is written for apps that store password hashes in a database more than one runtime reads, which is how a table ends up with a column called `password_hash_v2`:

- **One algorithm everywhere.** Argon2id (RFC 9106) on every runtime, Workers included, using Node.js's own implementation where it has one and a small WebAssembly core everywhere else.
- **A stored hash cannot cost more than you allow.** Memory, passes, lanes, salt and hash lengths are checked against limits before any work starts, so a row someone tampered with cannot make a sign-in allocate gigabytes.
- **Bad input never throws.** A stored hash that is malformed, from another algorithm, or over the limits gives a failed result naming which check failed, never what the input said.
- **It tells you when to upgrade a hash.** Each successful check says whether the stored hash is weaker than what the hasher makes now, so you replace it at that sign-in.

> **Experimental:** the API may still change. Its first consumer, [Symbolon](https://github.com/codenhub/symbolon), hashes and checks passwords with the default options on Node.js and Cloudflare Workers, so far in its test suites rather than in production, and needed no change to the API. No real consumer has used custom options or limits, or run the package on Bun, Deno or in a browser, and one may still show that a function name, option name, issue code or its `params` must change. The stored hash format cannot change: it is the PHC string the reference implementation writes, with passwords normalized to Unicode NFKC.

## Installation

```sh
pnpm add @codenhub/crypto
```

## Usage

```ts
import { createPasswordHasher } from "@codenhub/crypto";

const passwords = createPasswordHasher(); // 19 MiB, 2 passes, 1 lane: OWASP's first configuration

// At sign-up, store the string it returns.
const hashed = await passwords.hash(password);
if (hashed.ok) {
  await db.users.insert({ email, passwordHash: hashed.value });
} else {
  // The only failure is a password longer than 1024 UTF-8 bytes: hashed.error.issues[0].code === "password_too_long"
}

// At sign-in, check the password against the stored string.
const check = await passwords.verify(password, user.passwordHash);
if (!check.ok) {
  // a stored hash it cannot read: check.error.issues says why
} else if (!check.value.isMatch) {
  // wrong password
} else {
  if (check.value.needsRehash) {
    const upgraded = await passwords.hash(password);
    // Only if the row still holds the hash just checked, so a password reset in between wins.
    if (upgraded.ok) await db.users.updateWhere({ id: user.id, passwordHash: user.passwordHash }, { passwordHash: upgraded.value });
  }
  // signed in
}
```

Create the hasher once, when your module loads, and use it for every call. Options it cannot accept, such as a cost below OWASP's recommendations, throw a `TypeError` there, at startup, rather than at somebody's first sign-in.

## Documentation

- [Documentation overview](docs/index.md)
- [Hashing passwords](docs/hashing.md)
- [Verifying passwords](docs/verifying.md)
- [Limits](docs/limits.md)
- [Issues](docs/errors.md)
- [Runtimes](docs/runtimes.md)
- [API reference](docs/reference/index.md)

## Requirements

- Node.js 26 or newer, where it uses `node:crypto`'s native Argon2id. Bun, Deno, Cloudflare Workers and browsers run the bundled WebAssembly core, which needs WebAssembly with SIMD: Chrome 91, Firefox 89, Safari 16.4.
- On Cloudflare Workers, a bundler that resolves the `workerd` export condition and loads `.wasm` imports as compiled modules, as Wrangler does. [Runtimes](docs/runtimes.md#cloudflare-workers) explains, and says why the Workers Free plan's CPU limit is too small.
- In browsers, a Content Security Policy that allows WebAssembly (`'wasm-unsafe-eval'` in `script-src`), when the page sets one.
- ESM-aware package resolution. The package is ESM only and marked `sideEffects: false`.

## Notes

- **Password hashing only.** Despite the grand name, 0.1 does Argon2id password hashing and nothing else: no encryption, no general-purpose hashing (Web Crypto's `crypto.subtle.digest` does that), no bcrypt, scrypt or PBKDF2. Other areas are added when a project needs them.
- **Off the main thread only on Node.js.** Node.js's native Argon2id runs on its thread pool. Everywhere else the WebAssembly core runs on the calling thread, about a tenth of a second per hash at the default cost, so a browser page that hashes should do it in a Web Worker.
- **No pepper and no associated data** in 0.1. Adding them later is not breaking.

## License

Licensed under [Apache-2.0](LICENSE).

<!-- Source: docs/index.md -->

# Hash passwords once, check them anywhere

`@codenhub/crypto` (CryptoKit) stores passwords the way they should be stored: as Argon2id hashes, the algorithm OWASP recommends first. It makes a hash when a user sets a password, checks a password against that hash when they sign in, and tells you when an old hash should be replaced with a stronger one.

The part it exists for is the word "anywhere". Node.js has Argon2id built in. Cloudflare Workers, browsers, Bun and Deno do not, and Web Crypto offers only PBKDF2, so an app that runs on more than one of them usually ends up with two kinds of hash in one table, and a database that can move in only one direction. Nobody plans that migration; it just happens. CryptoKit gives every runtime the same Argon2id: Node.js's own where it exists, and a small WebAssembly core everywhere else, tested to give the same bytes. A hash made by a Worker is checked by a Node.js server and the other way around, and a user does not have to reset a password because the code moved, short of a rare Unicode case between runtimes of very different ages that [Runtimes](docs/runtimes.md#unicode-versions) describes.

## A password hash in one paragraph

A password hash is a slow, salted, one-way function of the password. **One-way** means the stored string does not reveal the password. **Salted** means each hash mixes in 16 random bytes, so two users with the same password get different strings and an attacker cannot look passwords up in a precomputed table. **Slow** is the point, and it is the rare corner of software where "too fast" is a bug report: checking one guess costs about 19 MiB of memory and a few dozen milliseconds, which you pay once per sign-in and an attacker who stole your database pays once per guess per user. Argon2id's cost comes mostly from memory, which is what makes guessing on graphics cards expensive.

The stored string carries everything needed to check a password later, in the PHC string format the reference implementation also writes. Node.js returns only the key, so on Node.js too the package writes the string itself:

```text
$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
```

`m` is the memory in KiB, `t` the number of passes over it, and `p` the number of lanes. Because the cost is in the string, a hash made with old settings still checks after you raise them.

## Installation

```sh
pnpm add @codenhub/crypto
```

The package is ESM only and has no runtime dependencies. Everything is imported by name from `@codenhub/crypto`; the only other export is `@codenhub/crypto/package.json`, for tools that read the version. The right implementation for your runtime is picked by export conditions, so the import is the same everywhere; [Runtimes](docs/runtimes.md) explains how.

## Quick start

The running example in these pages is the sign-up and sign-in of a small app with a `users` table:

```ts
import { createPasswordHasher } from "@codenhub/crypto";

const passwords = createPasswordHasher();

// Sign-up: store the string.
const hashed = await passwords.hash("correct horse battery staple");
if (hashed.ok) {
  await db.users.insert({ email, passwordHash: hashed.value });
}

// Sign-in: check a password against it.
const check = await passwords.verify("correct horse battery staple", user.passwordHash);
if (check.ok && check.value.isMatch) {
  // signed in
}
```

`createPasswordHasher` is called once, when your module loads. It checks its options then and throws a `TypeError` for a mistake in them, so a typo in the configuration fails at startup instead of at someone's sign-in. Creating a hasher does no other work: the implementation loads on the first `hash` or `verify` call. The hasher it returns is frozen and is shared by every call.

## Reading the result

Both methods return a result rather than throwing, for anything that depends on input: a password a user typed or a string that came out of your database. A result is one of two frozen plain objects, so you branch on `ok`:

```ts
const check = await passwords.verify(password, user.passwordHash);

if (check.ok) {
  check.value; // { isMatch: boolean, needsRehash: boolean }
} else {
  check.error.issues; // e.g. [{ code: "malformed_hash", message: "…", params: { check: "salt" } }]
}
```

A wrong password is not a failure: it is `{ ok: true, value: { isMatch: false, needsRehash: false } }`. People mistype passwords all day; that is a typo, not an incident. A failure means the stored string is one the hasher cannot or will not check. No issue ever holds the password, the salt or the hash, so a failed result is safe to log. The shape is the same as `@codenhub/validation`'s and `@codenhub/jwt`'s results, so code that handles one handles the others. [Issues](docs/errors.md) lists every failure and the types for your own code.

## Reading path

1. [Hashing passwords](docs/hashing.md): making a hash at sign-up, what the cost options do, and how passwords are normalized and bounded.
2. [Verifying passwords](docs/verifying.md): checking a password at sign-in, hiding which emails have accounts, and replacing a weak hash when `needsRehash` says so.
3. [Limits](docs/limits.md): the upper bounds that keep a tampered stored hash from costing you gigabytes, and how to raise them with your cost.
4. [Issues](docs/errors.md): every failure code, its `params`, the exported types, and the `TypeError`s for mistakes in your own code.
5. [Runtimes](docs/runtimes.md): what runs where, Cloudflare Workers setup and its CPU limits, browsers, the event loop, and what the package cannot wipe from memory.

The [API reference](docs/reference/index.md) lists every export with its signature.

Start with [Hashing passwords](docs/hashing.md).

<!-- Source: docs/errors.md -->

# Issues

This page lists every way a call can fail, so you can decide what to do with each; keep it open while you write the `else` branches. Failures caused by input, a password or a stored hash, come back as a failed result. Mistakes in your own code, such as an invalid option, throw a `TypeError`.

## The failed result

```ts
{
  ok: false,
  error: {
    issues: [{ code: "hash_over_limit", message: "The stored hash's memory is above the limit of 65536.", params: { check: "memory", maximum: 65536 } }],
  },
}
```

`issues` is never empty, so `issues[0]` is always an issue, and its type says so. Today it holds exactly one: the checks run in order and stop at the first that fails. Each issue has:

- `code`: a stable string to branch on. A new code may be added in a minor release, so give a `switch` over it a default branch.
- `message`: an English sentence for logs. It may be reworded in any release; never parse it.
- `params`: the details of the code, listed below. Every `params` value comes from the package's own vocabulary or limits, never from the input.

The result, the `error` and each issue are frozen. No issue ever holds the password, the salt or the key, so a failed result is safe to log or to send to an error tracker.

## Codes

### `password_too_long`

From `hash`. The password is longer than `limits.maxPasswordBytes` UTF-8 bytes after normalization.

- `params`: `{ maximum }`, the limit.
- Handle it: tell the user the password is too long. `verify` never returns it; it answers `isMatch: false` for such a password instead.

### `malformed_hash`

From `verify`. The stored value is not a well-formed Argon2id PHC string. `params.check` names the first check that failed:

| `check`      | What was wrong                                                                                                                                                                          |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`       | It is not a string, such as `null` from an empty column.                                                                                                                                |
| `length`     | It is longer than 256 characters.                                                                                                                                                       |
| `format`     | It does not have the five `$`-separated fields, such as an empty string, a hash cut short, or one with an extra field.                                                                  |
| `algorithm`  | The algorithm field is not a PHC algorithm name, which is 1 to 32 lowercase letters, digits and hyphens. `Argon2id!` is one example.                                                    |
| `version`    | The string ends after the algorithm, or the version field is not `v=` and a number without leading zeros, such as `version=19`.                                                         |
| `parameters` | The cost is not exactly `m=<n>,t=<n>,p=<n>`, in that order, with whole numbers and no leading zeros, or a number is out of RFC 9106's range, such as `t=0` or less than 8 KiB per lane. |
| `salt`       | The salt is not canonical base64 without padding, or is shorter than 8 bytes.                                                                                                           |
| `hash`       | The key is not canonical base64 without padding, or is empty.                                                                                                                           |

Canonical means standard base64 (`+` and `/`, not the URL-safe `-` and `_`), no `=` padding, no whitespace, and no stray bits in the last character. The reference implementation, and this package on every runtime, write exactly that.

- `params`: `{ check }`.
- Handle it: the row is corrupt or was written by something else. Log the issue, which holds no input, and send the user through a password reset.

### `unsupported_hash`

From `verify`. The stored value is a well-formed PHC string, but not one this package checks. `params.check` says why:

| `check`     | What it is                                                                                                  |
| ----------- | ----------------------------------------------------------------------------------------------------------- |
| `algorithm` | Another algorithm, such as bcrypt (`$2b$`), scrypt, PBKDF2, Argon2i or Argon2d.                             |
| `version`   | An Argon2id version other than 19, such as `v=16`, or a hash with no version field, which means version 16. |
| `hash`      | An Argon2id key shorter than 16 bytes.                                                                      |

- `params`: `{ check }`.
- Handle it: these are hashes from another system. If you are migrating, check them with the library that wrote them, then hash the password with this package at that sign-in.

### `hash_over_limit`

From `verify`. The stored hash is well formed, but one of its settings is above a [limit](docs/limits.md), so checking it could cost more than you allow.

| `check`       | Limit                   |
| ------------- | ----------------------- |
| `memory`      | `limits.maxMemory`      |
| `passes`      | `limits.maxPasses`      |
| `parallelism` | `limits.maxParallelism` |
| `salt`        | 64 bytes, fixed         |
| `hash`        | 64 bytes, fixed         |

- `params`: `{ check, maximum }`.
- Handle it: if another hasher of yours wrote it with a higher cost, raise this hasher's limits to match. Otherwise treat it like `malformed_hash`: the row was tampered with.

## Types for your own code

Every type the package uses is exported by name, for annotating the code you write around the hasher:

| Type                    | What it is                                                                           |
| ----------------------- | ------------------------------------------------------------------------------------ |
| `PasswordHasher`        | What `createPasswordHasher` returns: `hash` and `verify`.                            |
| `PasswordHasherOptions` | Its options: `memory`, `passes`, `parallelism` and `limits`.                         |
| `PasswordLimits`        | The `limits` object: `maxMemory`, `maxPasses`, `maxParallelism`, `maxPasswordBytes`. |
| `PasswordCheck`         | What a successful `verify` holds: `{ isMatch, needsRehash }`.                        |
| `CryptoResult<T>`       | Either `CryptoOk<T>` or `CryptoErr`, as `hash` and `verify` return.                  |
| `CryptoOk<T>`           | `{ ok: true, value: T }`.                                                            |
| `CryptoErr`             | `{ ok: false, error: CryptoFailure }`.                                               |
| `CryptoFailure`         | `{ issues }`, a list with at least one `CryptoIssue`.                                |
| `CryptoIssue`           | One issue: `code`, `message`, and `params` when the code has details.                |
| `CryptoIssueCode`       | The union of the four codes above.                                                   |

For example, a function that picks the HTTP status your API answers a failed sign-in with:

```ts
import type { CryptoIssueCode } from "@codenhub/crypto";

function statusFor(code: CryptoIssueCode): number {
  switch (code) {
    case "password_too_long":
      return 400;
    case "malformed_hash":
    case "unsupported_hash":
    case "hash_over_limit":
      return 500;
    default:
      return 500; // a code added in a later minor release
  }
}
```

Everything but `createPasswordHasher` is a type, so `import type` keeps the import out of your bundle.

## What throws

A `TypeError` means the calling code is wrong, so it throws as early as possible.

`createPasswordHasher` throws when:

- an option is unknown, such as `memoryKib`, or `options` or `options.limits` is not an object;
- an option or limit is not a whole number from 1 up, or is above RFC 9106's maximum;
- `memory` and `passes` meet none of OWASP's configurations ([Hashing passwords](docs/hashing.md#owasps-floor));
- `memory` is below 8 KiB per lane;
- `memory`, `passes` or `parallelism` is above its limit.

`hash` and `verify` throw when the password is not a string.

Nothing throws for what a stored hash says. Two more failures come from the platform rather than from any input, and reject the call with the platform's or the core's `Error` instead of returning a result:

- The platform refuses WebAssembly, such as a browser page whose Content Security Policy forbids it. The next call tries again. [Runtimes](docs/runtimes.md#browsers) says what to allow.
- The runtime cannot give the hash the memory it needs, such as a Worker isolate near its 128 MB or a cost of 2 GiB or more on the WebAssembly core ([Limits](docs/limits.md#raising-the-limits)).

Next, [Runtimes](docs/runtimes.md) covers what runs where.

<!-- Source: docs/hashing.md -->

# Hashing passwords

This page covers the sign-up half of the running example: turning a password into the string you store. It also covers the three cost options, since they decide how expensive every later check is, and the two things done to a password before it is hashed: normalizing it and bounding its length.

## Making a hash

```ts
import { createPasswordHasher } from "@codenhub/crypto";

const passwords = createPasswordHasher();

const hashed = await passwords.hash(password);
if (!hashed.ok) {
  return { error: "Passwords can be at most 1024 bytes long." }; // password_too_long, the only failure
}
await db.users.insert({ email, passwordHash: hashed.value });
// hashed.value: "$argon2id$v=19$m=19456,t=2,p=1$x8n3…$Yq0E…"
```

Each call draws a fresh 16-byte salt from `crypto.getRandomValues`, derives a 32-byte key, and returns both with the cost in one PHC string, about 100 characters long. Hashing the same password twice gives two different strings, and both check. Store the string as it is: it is plain ASCII, and every part of it is needed to check a password later. Give the column room to spare, such as a `text` column: a hash cut short to fit a narrow one never checks again.

`hash` takes a string. Anything else, such as a `Buffer` or `undefined` from a missing form field, throws a `TypeError`, since that is a bug in the calling code rather than something a user typed. An empty string is a valid password as far as this package is concerned. The package hashes what it is given; rules about what makes a password acceptable, such as a minimum length or a check against breached passwords, are yours to apply before you call `hash`.

Calls can overlap. Each call is independent, and the WebAssembly core runs one derivation at a time and queues the rest, so a burst of sign-ups is slower, never wrong.

## Cost options

Three options set what each new hash costs. They apply only to hashes this hasher makes; checking a stored hash uses the cost written in that hash.

| Option        | Unit   | Default | What raising it does                                                       |
| ------------- | ------ | ------- | -------------------------------------------------------------------------- |
| `memory`      | KiB    | `19456` | Each check fills that much memory, which is what slows guessing on GPUs.   |
| `passes`      | passes | `2`     | Each check goes over the memory that many times: more time, same memory.   |
| `parallelism` | lanes  | `1`     | Splits the memory into lanes. More lanes do not make a hash stronger here. |

The defaults are OWASP's first recommended configuration for Argon2id: 19 MiB, two passes, one lane. Raise them when your servers can afford it; the graphics cards on the other side only get faster.

```ts
const passwords = createPasswordHasher({ memory: 47_104, passes: 1 }); // 46 MiB, one pass
```

### OWASP's floor

A hasher refuses to make hashes weaker than OWASP's recommendations. Its `memory` and `passes` must both meet or exceed at least one of the five configurations OWASP lists as equally strong:

| `memory` (KiB) | `passes` at least |
| -------------- | ----------------- |
| 47104 (46 MiB) | 1                 |
| 19456 (19 MiB) | 2                 |
| 12288 (12 MiB) | 3                 |
| 9216 (9 MiB)   | 4                 |
| 7168 (7 MiB)   | 5                 |

So `{ memory: 12_288, passes: 3 }` is accepted, trading memory for time, and `{ memory: 12_288, passes: 2 }` throws a `TypeError` that lists the configurations. There is no option to go lower, not even a scary-sounding one. If a platform cannot afford the floor, the platform is the problem, as [Runtimes](docs/runtimes.md#cloudflare-workers) discusses for the Workers Free plan.

Each option must be a whole number from 1 up. `memory` must also be at least 8 KiB per lane, which RFC 9106 requires, and every option must fit within the hasher's [limits](docs/limits.md), so the hasher can always check the hashes it makes. Each of these mistakes throws a `TypeError` when the hasher is created, naming the option.

### Lanes

Argon2id can split its memory into lanes that separate threads fill at once. Only Node.js's native implementation can use threads for them. The WebAssembly core fills lanes one after another, so on Bun, Deno, Workers and in browsers, a hash with four lanes takes as long as one with one lane and the same memory. Leave `parallelism` at 1 unless every runtime that checks your hashes is Node.js. A stored hash with any number of lanes up to the [limit](docs/limits.md) still checks everywhere.

### Changing the cost later

Raising the cost does not invalidate a single stored hash. Each hash carries its own cost, so old hashes keep checking, and [`verify`](docs/verifying.md#upgrading-a-weak-hash) reports them as needing a rehash, which you do at the user's next sign-in. No migration script, no maintenance window. Lowering the cost is possible too, down to the floor, but lowering it alone does not make `verify` ask you to downgrade the stronger hashes already stored. A stronger hash that needs a rehash for another reason, such as a salt shorter than 16 bytes, is rewritten at the current, lower cost.

## Normalization

Before hashing, and before checking, every password is normalized to Unicode NFKC. The same visible password can reach your server as different code points, depending on the keyboard, the operating system and the browser, and users have no way of knowing which ones they typed:

- `ä` typed as one code point (U+00E4) or as `a` plus a combining diaeresis (U+0061 U+0308);
- the ligature `ﬁ` (U+FB01) pasted from a document, where the user meant `fi`;
- full-width digits `１２３` from an East Asian input method, where the user meant `123`.

NFKC turns each pair into one spelling, so the user signs in whichever way they typed it. It is part of the stored format: a hash made by this package is of the normalized password, and that can never change. If your app already normalizes passwords to NFKC, nothing changes, since normalizing twice gives the same string. If it normalizes to NFC, or not at all, a password made only of characters NFKC leaves alone, such as plain ASCII, hashes the same either way; [Runtimes](docs/runtimes.md#unicode-versions) covers the rare case where it does not.

## Password length

A password can be at most 1024 bytes long once normalized and encoded as UTF-8. That is 1024 ASCII characters, or 512 characters such as `é` that take two bytes each. Longer passwords make `hash` return a `password_too_long` failure, with the limit in `params.maximum`. That is a long password even by password-manager standards, so a person is very unlikely to hit it, while a client that posts megabytes into a password field is turned away before the server spends any time on it: a string longer than eight times the limit is refused without being normalized at all.

The limit is counted after normalization, so two spellings of one password are counted alike. To allow longer passwords, raise `limits.maxPasswordBytes`, as [Limits](docs/limits.md#the-password-limit) shows.

Next, [Verifying passwords](docs/verifying.md) checks those hashes at sign-in.

<!-- Source: docs/limits.md -->

# Limits

This page covers the bounds a hasher checks before it does any work. They matter because the cost of a check is written in the stored hash, and a stored hash comes from your database, which is not as trustworthy as it feels. Anyone who can write one row, through an injection bug, a compromised admin tool, or a backup restored from somewhere odd, could set `m=4194304` and make the next sign-in for that user allocate 4 GiB. The limits refuse such a hash before allocating anything.

## The defaults

| Limit              | Default | Bounds                                         |
| ------------------ | ------- | ---------------------------------------------- |
| `maxMemory`        | `65536` | a stored hash's `m`, in KiB: 64 MiB            |
| `maxPasses`        | `10`    | a stored hash's `t`                            |
| `maxParallelism`   | `16`    | a stored hash's `p`                            |
| `maxPasswordBytes` | `1024`  | a password, in UTF-8 bytes after normalization |

The memory default leaves room above every OWASP configuration, the largest of which is 46 MiB, and stays well inside Cloudflare Workers' 128 MB per isolate. A stored hash over a limit gives a `hash_over_limit` failure that names the setting and the limit, such as `params: { check: "memory", maximum: 65536 }`.

Two more bounds are fixed, because no option needs to move them:

- The salt must be 8 to 64 bytes. RFC 9106 sets the 8; 64 is far above the 16 this package writes. A shorter salt is `malformed_hash`, a longer one `hash_over_limit`.
- The key must be 16 to 64 bytes. A key shorter than 16 bytes is refused as `unsupported_hash`, since it is too short to be safe; one longer than 64 as `hash_over_limit`.

And a stored hash longer than 256 characters is refused as `malformed_hash` before it is parsed at all, since no hash within the bounds above is that long.

## Raising the limits

Pass `limits` with only the bounds you want to change; the others keep their defaults:

```ts
const passwords = createPasswordHasher({
  memory: 131_072, // 128 MiB per hash
  limits: { maxMemory: 131_072 },
});
```

A hasher's own cost must fit within its limits, or it could not check the hashes it makes. `createPasswordHasher({ memory: 131_072 })` alone throws a `TypeError` saying `memory` is above `limits.maxMemory`. That keeps the limits and the cost from drifting apart: raising the cost means raising the limit in the same place, in the same commit.

Lowering a limit is allowed too, down to the hasher's own cost. Stored hashes above the new limit then fail with `hash_over_limit`, so lower a limit only after rehashing every stored hash above it.

Every hasher that checks your hashes needs limits at least as high as the cost of every hasher that writes them. If a Node.js server writes 128 MiB hashes and a Worker checks them, the Worker refuses them unless its `maxMemory` is raised too, and on Workers it cannot be raised that far, as [Runtimes](docs/runtimes.md#cloudflare-workers) explains. Give every hasher in an app the same options and this takes care of itself; a shared module that exports one `createPasswordHasher(...)` call is the easy way.

Outside Node.js, the WebAssembly core needs less than 2 GiB of memory (`2_097_152` KiB) per hash whatever the limit says: `hash` and `verify` reject with an `Error` for such a cost, rather than return a result.

## The password limit

`maxPasswordBytes` bounds the password, counted in UTF-8 bytes after NFKC normalization. Over it, `hash` returns `password_too_long` and `verify` answers `isMatch: false`, both without deriving anything.

```ts
const passwords = createPasswordHasher({ limits: { maxPasswordBytes: 4096 } });
```

Raise it if your users manage passwords with something that makes very long ones. Lowering it below the length of a password someone already set locks that person out, since `verify` then answers `isMatch: false` for their correct password.

Next, [Issues](docs/errors.md) lists every failure these checks produce.

<!-- Source: docs/runtimes.md -->

# Runtimes

This page covers what actually runs when you call `hash` or `verify` on each runtime, and what each one asks of you. The short version: the import is the same everywhere, the bytes are the same everywhere, and the differences are in setup, speed, and which thread does the work.

## What runs where

The package has three builds, and your runtime or bundler picks one through `package.json` export conditions. You never import them by path.

| Condition | Who picks it                                  | What it runs                                                                                        |
| --------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `workerd` | Cloudflare Workers bundlers, such as Wrangler | The WebAssembly core, imported as a separate `argon2.wasm` module.                                  |
| `node`    | Node.js, Bun, Deno                            | `node:crypto`'s native Argon2id when the runtime has a working one, the WebAssembly core otherwise. |
| default   | Browsers and their bundlers, everything else  | The WebAssembly core, compiled from bytes the JavaScript carries.                                   |

The WebAssembly core is about 26 KB, written for this package with no dependencies, and tested against RFC 9106's vectors, the reference implementation's, and Node.js's output for random inputs. Every build gives the same bytes for the same password, salt and cost, so where a hash was made does not matter, with one rare exception for runtimes of very different ages, covered under [Unicode versions](#unicode-versions).

The implementation is loaded on the first `hash` or `verify` call, not when the module is imported or the hasher is created, so that first call is a little slower than the rest: it compiles the WebAssembly core, or, on the `node` build when `node:crypto` has an `argon2`, runs the known-answer check described below instead. On Bun and Deno, which have none, the `node` build compiles the WebAssembly core without that check. Later calls reuse what it set up.

### Node.js

Node.js 26 has Argon2id in `node:crypto`, and the package uses it. It runs on Node.js's thread pool, so a sign-in does not block other requests while its hash is computed. On first use the package checks Node.js's implementation against a known answer, a tiny hash that takes well under a millisecond, and falls back to the WebAssembly core if the answer is wrong, which no released Node.js does. A function named `argon2` is only a claim; one known answer is a cheap way to catch a false one, though not proof that every other answer is right.

### Bun and Deno

Bun and Deno answer to the `node` condition, so they get the same build as Node.js, but neither has `argon2` in `node:crypto` at the time of writing: Bun 1.3 and Deno 2.9 do not. The package detects that and uses the WebAssembly core. If either adds a native Argon2id, the package starts using it once it passes the known-answer check, with no change on your side.

### Cloudflare Workers

Workers does not compile WebAssembly from bytes at run time; it runs only modules uploaded with the Worker. The `workerd` build therefore imports `argon2.wasm` as a module, and your bundler has to upload it as one. Wrangler does both by default: it resolves the `workerd` condition, and its default rules upload any imported `.wasm` file as a compiled module. A Worker needs no configuration beyond importing the package:

```ts
import { createPasswordHasher } from "@codenhub/crypto";

const passwords = createPasswordHasher();

export default {
  async fetch(request: Request): Promise<Response> {
    const { password } = await request.json<{ password: string }>();
    const hashed = await passwords.hash(password);
    return Response.json({ ok: hashed.ok });
  },
};
```

A bundler that ignores the `workerd` condition picks the default build instead, and the first `hash` or `verify` call rejects with a `CompileError` from Workers. If you see that, configure the bundler to resolve the `workerd` condition and to keep `.wasm` imports as modules.

> **CPU time.** On a deployed Worker, one hash takes about 50 to 75 ms of CPU time at the median and about 75 to 155 ms at the 95th percentile, depending on the configuration, and the slowest request seen took 211 ms, at the default cost and at every other cost OWASP recommends, since they all do about the same work. The Workers Free plan allows 10 ms of CPU time per request, so password hashing is expected not to fit on it, and the package will not go lower. Use a paid plan, whose default limit of 30 seconds per request leaves ample room. A request over its plan's CPU limit fails with Cloudflare's error 1102 rather than a result from this package.

Memory counts too. A Worker isolate has 128 MB, WebAssembly included. The core's memory grows to fit the largest hash it has computed and never shrinks, and it is shared by every request the isolate serves. With the default `maxMemory` of 64 MiB that is at most a little over 64 MiB for the core, whatever stored hash comes in. Raising `maxMemory` above that is possible but leaves less room for the rest of your Worker, and a limit near 128 MB lets a single stored hash run the isolate out of memory.

### Browsers

The default build compiles the WebAssembly core from bytes it carries, so it works with any bundler, or none, with no file to copy or serve. It needs WebAssembly with SIMD, which Chrome 91, Firefox 89 and Safari 16.4 and later have.

A page with a Content Security Policy must allow compiling WebAssembly with `'wasm-unsafe-eval'` in `script-src`. Without it, `hash` and `verify` reject with the browser's `CompileError`. A page keeps the policy it was loaded with, so fixing the policy takes effect when the page is loaded again. The package does not remember the failure: the next call on a page served with the fixed policy compiles the core.

Hashing in a browser is unusual, since the server must hash whatever it stores anyway; hashing on the client first does not replace that. It fits apps that run entirely in the browser, such as an offline app that guards local data with a password.

## The event loop

Outside Node.js, the WebAssembly core runs on the thread that calls it. At the default cost, a hash holds that thread for about a tenth of a second, during which nothing else on it runs:

- On a server, Bun or Deno, that is a tenth of a second during which other requests on the same process wait. Run more processes, or keep the cost in mind when sizing them.
- In a Worker, each request already has its own CPU time, so this is only the CPU cost above.
- In a browser page, it is a visible freeze, long enough for someone to click the button a second time. Call the hasher from a Web Worker instead of the page.

Calls never overlap inside the core: concurrent calls run one after another, each to completion.

## What the package cannot wipe

The WebAssembly core zeroes the password, every block of its working memory, and the stack it used before each call returns, and the package zeroes its own copies of the password's bytes and the derived key. It cannot do the same for JavaScript strings: the password you pass in is a string, strings cannot be overwritten, and the engine frees them whenever it chooses. The same holds for the request body it came from. This is true of every password-handling library in JavaScript, and is why the package's wiping is best effort, not a guarantee. If memory disclosure is in your threat model, keep the process that handles passwords small and short-lived.

## Unicode versions

Passwords are normalized to NFKC with the runtime's `String.prototype.normalize`, which follows the Unicode version the runtime was built with. Characters assigned in a newer Unicode version than a runtime knows are left as they are by that runtime, and a newer runtime may normalize them. In practice this concerns characters added to Unicode recently that also have a compatibility mapping, almost never found in passwords, and only when two runtimes of very different ages check the same hash. If a user reports that a password works on one of your runtimes and not on another, this is one cause to rule out, right after checking that both runtimes read the same database.

This is the end of the reading path. The [API reference](docs/reference/index.md) lists every export with its signature, and [Issues](docs/errors.md) is the page to keep open while you write the error handling.

<!-- Source: docs/verifying.md -->

# Verifying passwords

This page covers the sign-in half of the running example: checking what a user typed against the string you stored at sign-up, keeping that check from revealing who has an account, and using the same sign-in to upgrade a hash that has fallen behind your current settings.

## Checking a password

```ts
const user = await db.users.findByEmail(email);
const check = await passwords.verify(password, user.passwordHash);

if (!check.ok) {
  log.error("unreadable password hash", { issues: check.error.issues });
  return { error: "Sign-in failed." };
}
if (!check.value.isMatch) {
  return { error: "Wrong email or password." };
}
// signed in
```

`verify` reads the cost and salt from the stored string, derives a key from the password with them, and compares it to the stored key in constant time, so how long a comparison takes does not reveal how much of the key matched. It does not use the hasher's own cost options to check: a hash made with any cost within the [limits](docs/limits.md) checks, whichever hasher made it, on whichever runtime.

There are three answers:

| Result                                                        | Meaning                                                                    |
| ------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `{ ok: true, value: { isMatch: true, needsRehash } }`         | The password is right. `needsRehash` is covered below.                     |
| `{ ok: true, value: { isMatch: false, needsRehash: false } }` | The password is wrong.                                                     |
| `{ ok: false, error: { issues } }`                            | The stored string is not a hash this hasher checks. No password was tried. |

A wrong password is an ordinary answer, not a failure, because it is the expected outcome of a typo. A failure is about the stored string: it is malformed, it comes from another algorithm such as bcrypt, or its cost is above your limits. That usually means a bug, a migration that left old rows behind, or a row someone tampered with, which is why the example logs it. The issues never hold the password, the salt or the key, so logging them is safe. [Issues](docs/errors.md) lists each code.

A password longer than the [password limit](docs/limits.md#the-password-limit) is answered with `isMatch: false`, without deriving anything, since no hash this hasher makes can match it. The stored string is read first, so an unreadable hash is reported even when the password is also too long.

Like `hash`, `verify` throws a `TypeError` when the password is not a string. The stored hash can be anything: a `null` or `undefined` from an empty column gives a `malformed_hash` failure, not an exception.

## When there is no hash to check

The example above assumes the email belongs to a user with a password. When it does not, because nobody signed up with that email or the user signs in another way and has no hash, returning at once answers in well under a millisecond, while a real check takes tens of milliseconds. Anyone can time that difference and learn which emails have accounts. Check the password against a decoy instead, a hash made once at startup at the hasher's own cost, so a sign-in for an unknown email takes as long as one for an account whose hash is at that cost:

```ts
// Once, when the module loads: the hash of a random password nobody knows.
const decoy = await passwords.hash(crypto.randomUUID());
if (!decoy.ok) throw new Error("The decoy password is longer than limits.maxPasswordBytes.");

const user = await db.users.findByEmail(email);
const check = await passwords.verify(password, user?.passwordHash ?? decoy.value);
if (!check.ok) {
  log.error("unreadable password hash", { issues: check.error.issues });
  await passwords.verify(password, decoy.value); // take as long as a readable hash would
}
if (!user?.passwordHash || !check.ok || !check.value.isMatch) {
  return { error: "Wrong email or password." };
}
// signed in
```

The decoy never matches a password anyone types, and the check of `user?.passwordHash` makes sure it cannot sign anyone in even if it did. Give the same answer for an unknown email and a wrong password, as above, or the answer gives away what the decoy is there to hide.

Two details keep the timing even. A stored hash the hasher cannot read is refused before any work, so the example checks the decoy then too; otherwise a fast answer would mark that email as one with an account. And the decoy must exist: a random UUID is 36 bytes, far under the default password limit, but a hasher with `maxPasswordBytes` below that cannot hash it, so the example stops at startup rather than run without a decoy.

The decoy evens out the time only for hashes at the hasher's current cost. An account whose hash still has an older cost takes that cost's time until it is rehashed, so timing can still single out such accounts, and an even answer does not stop anyone from trying many emails. Limit sign-in attempts per address and per client as well.

## Upgrading a weak hash

`needsRehash` is `true` when the password matched and the stored hash is weaker than what this hasher makes now. The only time you hold the plain password is during a sign-in, so this is the one moment you can replace the hash. Skip it and the weak hash waits for the next sign-in, which for some accounts is next year.

```ts
if (check.value.needsRehash) {
  const upgraded = await passwords.hash(password);
  if (upgraded.ok) {
    // Only if the row still holds the hash just checked: a password reset in between must win.
    await db.users.updateWhere({ id: user.id, passwordHash: user.passwordHash }, { passwordHash: upgraded.value });
  }
}
```

Make the update conditional on the hash you verified, as above, or in SQL `UPDATE users SET password_hash = $new WHERE id = $id AND password_hash = $checked`. If the user resets their password while this sign-in is hashing, an unconditional update would write a hash of the old password over the new one, and the old password would work again.

The stored hash is compared setting by setting. It needs a rehash when any one of these is below the hasher's current value:

- its memory, below the hasher's `memory`;
- its passes, below the hasher's `passes`;
- its salt, shorter than 16 bytes;
- its key, shorter than 32 bytes.

A hash is kept when every one of them is at least the current value. A hash with more memory and fewer passes than the hasher's, such as 46 MiB and one pass against the default 19 MiB and two, is rehashed even though OWASP rates both equally strong: comparing each setting on its own keeps the rule simple to predict, and the price of that simplicity is one extra hash at one sign-in. Lanes are not compared, since a different lane count makes a hash neither stronger nor weaker.

`needsRehash` is always `false` when the password does not match, so a wrong password never triggers a write.

The rehash is a normal `hash` call, so it can fail only with `password_too_long`, which cannot happen for a password that just matched under the same limit. If the update to your database fails, nothing is lost: the old hash still checks, and the next sign-in tries again.

Next, [Limits](docs/limits.md) covers the bounds `verify` applies to a stored hash before it does any work.
