---
title: Passwords and tokens
description: "Store passwords as digests, check them, reset them, and give records random and signed tokens."
seo:
  description: "Keep Active Record passwords as salted digests with securePassword, check them with authenticate or authenticateBy, reset them with a signed token, and make random tokens, signed ids, and tokens for a purpose."
---

:::warning[The default hash is limited by Workers]
Passwords are hashed with PBKDF2-SHA256 at 100,000 iterations. That’s the most Cloudflare Workers allow, and about a sixth of the 600,000 that OWASP recommends. Each sign-up, sign-in, or password change also takes about 10–40 ms of CPU time. The Workers Free plan allows 10 ms per request, so an app that signs people in may need Workers Paid. Each digest records its iteration count, so a later default can raise it without breaking the passwords you’ve stored. For a stronger hash, [plug in your own](#choosing-the-hash).
:::

## At a glance

| To                                     | Write                                                                         |
| -------------------------------------- | ----------------------------------------------------------------------------- |
| keep a password as its digest          | `password: { securePassword: true }`, with a `password_digest` column         |
| check a record’s password              | `await user.authenticate(password)`: the record, or `false`                   |
| find a record and check its password   | `await User.authenticateBy({ email, password })`: the record, or `null`       |
| confirm a new password                 | `User.create({ password, passwordConfirmation })`                             |
| ask for the current password to change | `user.update({ password, passwordChallenge })`                                |
| hash with your own algorithm           | `password: { securePassword: { algorithm: bcryptPassword } }`                 |
| give each new record a random token    | `authToken: { secureToken: true }`                                            |
| save a new token                       | `await user.regenerateAuthToken()`                                            |
| make a token yourself                  | `generateSecureToken(32)`                                                     |
| send a password reset link             | `await user.passwordResetToken()`                                             |
| find the user a reset link is for      | `await User.findByPasswordResetToken(token)`: the record, or `null`           |
| declare a token for a purpose          | `this.generatesTokenFor("emailConfirmation", { expiresIn, dependsOn })`       |
| make and check one                     | `await user.generateTokenFor(purpose)`, `User.findByTokenFor(purpose, token)` |
| sign a record’s id                     | `await user.signedId({ purpose, expiresIn })`                                 |
| find the record a signed id is for     | `await User.findSigned(signedId, { purpose })`: the record, or `null`         |
| set the secret tokens are signed with  | `wrangler secret put SECRET_KEY_BASE`                                         |

| Prop | Type | Default | Description |
| - | - | - | - |
| `algorithm?` | `PasswordAlgorithm` | `PBKDF2-SHA256` | `securePassword`’s algorithm: `{ hash, verify, maxBytes? }`, which hashes a password and verifies one against its digest. |
| `validations?` | `boolean` | `true` | `securePassword`’s validations. `false` leaves them out. |
| `resetToken?` | `boolean \| { expiresIn }` | `true` | `securePassword`’s reset token, which lasts 15 minutes unless `expiresIn` says otherwise. `false` leaves it out. |
| `length?` | `number` | `24` | `secureToken`’s characters, after any prefix. At least 24. |
| `prefix?` | `true \| string` | - | Text before a `secureToken`’s characters. `true` uses the column’s name and `_`, as in `auth_token_…`. |
| `on?` | `"initialize" \| "create"` | `"initialize"` | When a new record without a token gets one: as it’s built, or as it’s created. |
| `expiresIn?` | `Duration` | - | How long a token lasts, such as `{ minutes: 15 }`: `seconds`, `minutes`, `hours`, or `days`. Without it, a signed id or a token for a purpose lasts until its secret changes. |
| `dependsOn?` | `(record) => unknown` | - | `generatesTokenFor`’s value, such as the user’s email. A token finds its record only while the value is the same as when it was made. |

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates:

```ts user.ts
import { ApplicationRecord } from "./application-record";

export class User extends ApplicationRecord {
  static override attributes = {
    password: { securePassword: true }, // kept in password_digest
    authToken: { secureToken: true }, // a random token for each new user
  } as const;

  static {
    this.normalizes("email", { with: (email) => email.trim().toLowerCase() });
    // A token that confirms the email it was sent to, for a day.
    this.generatesTokenFor("emailConfirmation", {
      expiresIn: { days: 1 },
      dependsOn: (user) => user.email,
    });
  }
}
```

```ts admin.ts
import { bcryptPassword } from "../bcrypt";
import { ApplicationRecord } from "./application-record";

export class Admin extends ApplicationRecord {
  static override attributes = {
    password: { securePassword: { algorithm: bcryptPassword } },
  } as const;
}
```

```ts application-record.ts
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;
}
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: d7a909d3f64f

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** admins — last changed by 0001_create_users.sql */
export const admins = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  passwordDigest: "string",
  createdAt: { type: "datetime", null: false },
  updatedAt: { type: "datetime", null: false },
} as const;

/** users — last changed by 0001_create_users.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  passwordDigest: "string",
  authToken: "string",
  createdAt: { type: "datetime", null: false },
  updatedAt: { type: "datetime", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    admins: { attributes: admins, primaryKey: "id" },
    users: { attributes: users, primaryKey: "id" },
  },
  models: { Admin: "admins", User: "users" },
});

declare module "../models/admin" {
  interface Admin extends TableAttributes<typeof admins, (typeof Admin)["attributes"]> {}
}

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL UNIQUE,
  password_digest TEXT,
  auth_token TEXT UNIQUE,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);

CREATE TABLE admins (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL UNIQUE,
  password_digest TEXT,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  password_digest TEXT,
  auth_token TEXT UNIQUE,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE TABLE admins (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  password_digest TEXT,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);
```

## Storing passwords

Declare `password: { securePassword: true }` in `static attributes`, as `User` does, and give the table a `password_digest` column. A sign-up form can then send the password and its confirmation:

```ts
import { User } from "./models/user";

export async function signUp(request: Request): Promise<Response> {
  const form = await request.formData();
  const permitted = User.permit(form, "email", "password", "passwordConfirmation");
  const user = await User.create(permitted);
  if (!user.isPersisted()) {
    return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
  }
  return Response.json(user, { status: 201 }); // no password, digest, or token in it
}
```

- **It adds three virtual attributes:** `password`, `passwordConfirmation`, and `passwordChallenge`. None of them is saved.
- **Responses and logs never show them.** `toJSON()` leaves out the password, its confirmation, its challenge, and its digest, without listing them in [`hiddenAttributes`](/serialization#hiding-attributes). `onQuery` listeners, error messages, and printed records show them as `[FILTERED]`, whatever [`filterAttributes`](/serialization#filtering-attributes) says. A secure token is treated the same way, and `attributes()` still has them all.
- **Another name works the same way.** `recoveryPassword: { securePassword: true }` keeps its digest in `recovery_password_digest`, and checks it with `authenticateRecoveryPassword`.

The password is hashed when the record is saved, so `passwordDigest` keeps its old value until then:

```ts
import { User } from "./models/user";

const user = User.build({ email: "jane@example.com", password: "correct horse battery" });
console.log(user.passwordDigest === null); // true, until the user is saved

await user.saveOrThrow();
const isHashed = user.passwordDigest?.startsWith("$pbkdf2-sha256$") === true;
console.log(isHashed); // true
```

Assigning `null` clears the digest. Assigning `""` is ignored, so a blank field in a form leaves the password as it was.

:::note
Without a string digest column, the Model throws `InvalidModel`, and `active-record schema` reports it. Declaring `passwordConfirmation` or `passwordChallenge` yourself throws `InvalidModel` too.
:::

## Checking a password

Call `authenticate` with a password to check it against the record’s digest:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });

const isSignedIn = (await user.authenticate("correct horse battery")) !== false;
console.log(isSignedIn); // true
```

- It resolves to the record, or `false` when the password isn’t the one, or the record has no digest.
- It checks the digest as it’s saved, so a password you’ve assigned since is checked once you save it.
- Each secure password gets its own method, named for it: `authenticatePassword`, `authenticateRecoveryPassword`. Only `password` gets `authenticate`.

## Signing in

Call `authenticateBy` with an email (or any other attributes) and a password to find a record and check its password in one step:

```ts
import { User } from "./models/user";

export async function signIn(request: Request): Promise<Response> {
  const form = await request.formData();
  const { email = "", password = "" } = User.permit(form, "email", "password");
  const user = await User.authenticateBy({ email, password });
  if (user === null) return new Response("Wrong email or password", { status: 401 });
  return Response.json({ token: user.authToken });
}
```

- **It resolves to the record, or `null`.** It’s `null` when no record matches, when the password is wrong, or when the password is blank.
- **It takes as long when no record matches.** It hashes the password anyway, as it does for a record with no digest. So how long a sign-in takes doesn’t tell anyone which emails have accounts.
- **Its other attributes find the record as `findBy` does.** Normalizations and default scopes apply.
- **It needs both.** Without a password, or without an attribute to find the record by, it throws `TypeError`.

## Confirming and challenging

A secure password adds these validations, unless it’s declared with `validations: false`:

| Fails when                                                                       | Error on               | Message                |
| -------------------------------------------------------------------------------- | ---------------------- | ---------------------- |
| there’s no digest, and no new password to hash                                   | `password`             | can’t be blank         |
| `passwordChallenge` isn’t the current password                                   | `passwordChallenge`    | is invalid             |
| the password is longer than the algorithm allows (72 bytes in UTF-8, by default) | `password`             | is too long            |
| `passwordConfirmation` is given and doesn’t match                                | `passwordConfirmation` | doesn’t match Password |

Set `passwordChallenge` to ask for the current password before a change:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });

const isChanged = await user.update({
  password: "staple battery horse",
  passwordConfirmation: "staple battery horse",
  passwordChallenge: "correct horse battery", // the current password
});
console.log(isChanged); // false if the challenge isn't the current password
```

- The challenge is checked against the digest as it was last saved. A record with no saved digest fails any challenge.
- A `null` challenge or confirmation is skipped, so leave them out when you don’t ask for them.

## Choosing the hash

Give `securePassword` an `algorithm` to hash passwords your own way. An algorithm has `hash`, `verify`, and an optional `maxBytes`. This one uses bcrypt, from the `bcryptjs` package:

```ts title="src/bcrypt.ts"
import type { PasswordAlgorithm } from "@forestfuture/active-record";
import bcrypt from "bcryptjs";

/** bcrypt, at a cost of 10. It verifies digests another app made with bcrypt too. */
export const bcryptPassword: PasswordAlgorithm = {
  hash: (password) => bcrypt.hash(password, 10),
  verify: (password, digest) => bcrypt.compare(password, digest),
  maxBytes: 72, // bcrypt reads only a password's first 72 bytes
};
```

`Admin` declares it as its password’s algorithm, and its digests are bcrypt’s:

```ts
import { Admin } from "./models/admin";

const admin = await Admin.create({ email: "sam@example.com", password: "correct horse battery" });
const isBcrypt = admin.passwordDigest?.startsWith("$2b$10$") === true;
console.log(isBcrypt); // true
```

- **`hash`** resolves to a salted digest of the password, and **`verify`** to whether a password is the one a digest was made from.
- **`maxBytes`** sets the `is too long` validation. Without it, a password can be any length.
- **Each digest belongs to its algorithm.** The default throws `TypeError` for a digest it didn’t make, so give an algorithm that reads the digests you already have. bcrypt reads those made by another app’s bcrypt.

:::warning[A stronger hash costs more CPU time]
bcrypt in JavaScript at a cost of 10 takes about 100 ms of CPU time for each hash, well past the Free plan’s 10 ms. On Workers Paid, a request gets 30 seconds of CPU time by default. `bcryptjs` imports Node’s `crypto`, so turn on the `nodejs_compat` compatibility flag in `wrangler.jsonc`.
:::

## Generating tokens

Declare `secureToken: true` on a string column, as `User` does with `authToken`, to give each new record a random token:

```ts
import { User } from "./models/user";

const user = User.build({ email: "sam@example.com", password: "correct horse battery" });
console.log(user.authToken?.length); // 24, such as "pX27zsMN2ViQKta1bGfLmVJE"
await user.saveOrThrow();

const found = await User.findBy({ authToken: user.authToken });
```

- **It’s made as the record is built,** unless a value is given that isn’t `null` or `""`. With `on: "create"`, it’s made as the record is created instead. A bulk insert, such as `insertAll`, makes the first kind for a row that doesn’t give one, but not the second.
- **It’s 24 characters of base58:** letters and digits, without `0`, `O`, `I`, and `l`, which look alike. `length` makes it longer, and `prefix` puts text before it.
- **A record loaded from the database keeps the token it has,** even when it has none.
- **Nothing checks that a token is unique.** Two tokens matching is very unlikely, but give the column a UNIQUE index, as `users.auth_token` has.

`generateSecureToken(length)` makes a token the same way, for anything that isn’t an attribute.

:::note
A `length` under 24, a type other than `string`, or a `default` alongside it throws `InvalidModel`.
:::

## Regenerating tokens

Call `regenerateAuthToken()` to save a new token, so the old one stops working:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "sam@example.com" });

await user.regenerateAuthTokenOrThrow(); // saves a new token, so the old one stops working
```

- It saves the new token as `update` does. Validations and callbacks run, and it resolves to `false` when the record is invalid.
- `regenerateAuthTokenOrThrow()` throws `RecordInvalid` instead.
- Each token gets its own pair, named for it: `inviteCode` gets `regenerateInviteCode()`.

## Resetting passwords

Call `passwordResetToken()` to put a token in a reset link:

```ts
import { sendResetEmail } from "./email";
import { User } from "./models/user";

export async function requestReset(request: Request): Promise<Response> {
  const { email = "" } = User.permit(await request.formData(), "email");
  const user = await User.findBy({ email });
  if (user !== null) {
    const token = await user.passwordResetToken(); // lasts 15 minutes
    await sendResetEmail(email, `https://example.com/reset?token=${token}`);
  }
  return new Response("Check your email", { status: 202 }); // the same whether the email is known
}
```

When the link is followed, find the user it was sent to with `findByPasswordResetToken`, and set their new password:

```ts
import { User } from "./models/user";

export async function resetPassword(request: Request): Promise<Response> {
  const form = await request.formData();
  const user = await User.findByPasswordResetToken(form.get("token"));
  if (user === null) return new Response("That link has expired", { status: 400 });
  const isReset = await user.update(User.permit(form, "password", "passwordConfirmation"));
  if (!isReset) return Response.json({ errors: user.errors.fullMessages() }, { status: 422 });
  return new Response(null, { status: 204 }); // the link stops working: the password changed
}
```

- **A reset token lasts 15 minutes.** `resetToken: { expiresIn: { hours: 1 } }` makes it last longer, and `resetToken: false` leaves it out.
- **It works until the password changes.** Once the user resets their password, the link finds nobody, even if they choose the same password again.
- **It’s signed, not stored.** Nothing is saved for it, so there’s no column to add and nothing to clear.
- **`findByPasswordResetTokenOrThrow`** throws `InvalidToken` for a token that’s changed or expired, and `RecordNotFound` once the password has changed.

`recoveryPassword` gets `recoveryPasswordResetToken()`. Find the user it’s for with `User.findByTokenFor("recoveryPasswordReset", token)`.

## Making tokens for a purpose

Declare `generatesTokenFor` in `static {}` for a token your app sends for one purpose, as `User` does for confirming an email:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });
const token = await user.generateTokenFor("emailConfirmation");

const confirmed = await User.findByTokenFor("emailConfirmation", token);
console.log(confirmed?.email); // "jane@example.com", until the email changes or a day passes
```

- **`expiresIn`** sets how long a token lasts. Without it, a token lasts until its secret changes.
- **`dependsOn`** ties a token to a value of the record’s. A token finds its record only while the value is the same as when it was made, so a confirmation sent to an old email stops working once the email changes. The token holds a fingerprint of the value, never the value itself.
- **Changing `expiresIn` stops the tokens already sent,** since a token is signed for how long it lasts.
- **A purpose the Model doesn’t declare throws `TypeError`.** Declaring a purpose again replaces it, except a reset token’s, such as `passwordReset`, which throws `InvalidModel`.
- **`findByTokenForOrThrow`** throws `InvalidToken` for a token that’s changed or expired, and `RecordNotFound` when the record is gone or the value has changed.

## Signing ids

Call `signedId()` to sign a record’s id, and `findSigned` to find the record again:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });
const signedId = await user.signedId({ purpose: "unsubscribe", expiresIn: { days: 30 } });

const found = await User.findSigned(signedId, { purpose: "unsubscribe" });
console.log(found?.email); // "jane@example.com"
console.log(await User.findSigned(signedId)); // null: it was signed for unsubscribing
```

- **A purpose keeps a signed id to one use.** `findSigned` finds its record only given the same purpose.
- **`expiresIn` or `expiresAt`** makes it expire. Without either, it lasts until its secret changes.
- **Anyone can read the id in it, but nobody can change it.** A signed id that’s changed, made up, or signed with another secret finds nothing.
- **`findSignedOrThrow`** throws `InvalidToken` for a signed id that isn’t valid, and `RecordNotFound` when its record is gone.

`findSigned` and `findByTokenFor` are Relation methods too. `User.where({ isActive: true }).findSigned(signedId)` finds the user only if they’re active, and a default scope always applies.

:::note
A new record has no id to sign, so `signedId` and `generateTokenFor` throw `RecordNotSaved` for one.
:::

## Setting the signing secret

Reset tokens, tokens for a purpose, and signed ids are signed with the Worker’s `SECRET_KEY_BASE`. Set it as a secret, with at least 32 random bytes:

```sh
openssl rand -hex 32 | npx wrangler secret put SECRET_KEY_BASE
```

For local development, put one in `.dev.vars`. Tests and scripts that run outside a Worker read it from `process.env`. Without one, or with one shorter than 32 bytes, making or checking a token throws `InvalidModel`.

To change the secret without breaking the links you’ve sent, override `signingSecret` on `ApplicationRecord` and return both secrets, the new one first:

```ts
import { Model, type SigningEnv } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  static override signingSecret(env: SigningEnv) {
    return [env.SECRET_KEY_BASE, env.PREVIOUS_SECRET_KEY_BASE]; // the first signs, and both verify
  }
}
```

Once the tokens the old secret signed have expired, remove it.

:::note
A token isn’t tied to a database. If each tenant has a database of its own, put the tenant in a signed id’s purpose, as in ``signedId({ purpose: `${tenant}/unsubscribe` })``, and in what a token for a purpose `dependsOn`. Otherwise a token made in one tenant finds the record with the same id in another.
:::

> **Compared with Rails**
>
> Rails declares these with `has_secure_password` and `has_secure_token`. Here they go with the attributes, so their methods are typed from the same place. Rails hashes a password with bcrypt as it’s assigned; here PBKDF2 hashes it when the record is saved, since Workers have no bcrypt of their own and hashing is asynchronous. `authenticate_by`, `password_challenge`, `regenerate_<attribute>`, and base58 tokens work as in Rails. Rails’ `regenerate_token` raises on an invalid record; here `regenerateAuthToken()` resolves to `false`, and its `OrThrow` throws. Rails filters a password only when `filter_parameters` names it, and sends `password_digest` and a token in `as_json`; here a secure password, its digest, and a secure token are always filtered, and `toJSON()` leaves them out. `generates_token_for`, `signed_id`, and Rails 8’s reset tokens work as in Rails, with tokens of their own format, and each is asynchronous. Rails’ tokens carry the value a token depends on, readable by anyone who has one, and its reset token depends on part of bcrypt’s salt; here a token carries only a fingerprint, and a reset token depends on the whole digest, so there’s no `password_salt`. Rails reads `secret_key_base` and rotates through `message_verifiers`; here `signingSecret` reads `SECRET_KEY_BASE` from the Worker and returns a list to rotate.
