Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Passwords and tokens

Store passwords as digests, check them, reset them, and give records random and signed tokens.

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
PropType
algorithm?PasswordAlgorithm

`securePassword`’s algorithm: `{ hash, verify, maxBytes? }`, which hashes a password and verifies one against its digest.

TypePasswordAlgorithm
DefaultPBKDF2-SHA256
validations?boolean

`securePassword`’s validations. `false` leaves them out.

Typeboolean
Defaulttrue
resetToken?boolean | { expiresIn }

`securePassword`’s reset token, which lasts 15 minutes unless `expiresIn` says otherwise. `false` leaves it out.

Typeboolean | { expiresIn }
Defaulttrue
length?number

`secureToken`’s characters, after any prefix. At least 24.

Typenumber
Default24
prefix?true | string

Text before a `secureToken`’s characters. `true` uses the column’s name and `_`, as in `auth_token_…`.

Typetrue | string
on?"initialize" | "create"

When a new record without a token gets one: as it’s built, or as it’s created.

Type"initialize" | "create"
Default"initialize"
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.

TypeDuration
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.

Type(record) => unknown

The Models

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

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,
    });
  }
}
import { bcryptPassword } from "../bcrypt";
import { ApplicationRecord } from "./application-record";

export class Admin extends ApplicationRecord {
  static override attributes = {
    password: { securePassword: { algorithm: bcryptPassword } },
  } as const;
}
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;
}
// 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"]> {}
}
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
);
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:

import { class UserUser } from "./models/user";

export async function function signUp(request: Request): Promise<Response>signUp(request: Requestrequest: Request): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<Response> {
const const form: FormDataform = await request: Requestrequest.Body.formData(): Promise<FormData>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)
formData
();
const
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>, "email" | ... 1 more ... | "passwordConfirmation">>
permitted
= class UserUser.
Model.permit<typeof User, "email" | "password" | "passwordConfirmation">(this: typeof User, input: unknown, ...names: ("email" | "password" | "passwordConfirmation")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        ...;
    };
}>>, "email" | ... 1 more ... | "passwordConfirmation">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(const form: FormDataform, "email", "password", "passwordConfirmation");
const const user: Useruser = await class UserUser.
create<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>> | undefined, init?: Init<...> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
(
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>, "email" | ... 1 more ... | "passwordConfirmation">>
permitted
);
if (!const user: Useruser.Model.isPersisted(): boolean
Backed by a row: loaded, or saved successfully.
isPersisted
()) {
return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
({ errors: string[]errors: const user: Useruser.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
() }, { ResponseInit.status?: number | undefinedstatus: 422 });
} return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
(const user: Useruser, { ResponseInit.status?: number | undefinedstatus: 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. onQuery listeners, error messages, and printed records show them as [FILTERED], whatever filterAttributes 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:

import { class UserUser } from "./models/user";

const const user: Useruser = class UserUser.
build<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>> | undefined, init?: ((record: User) => void) | undefined): User
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ email?: string | undefinedemail: "jane@example.com", password?: string | null | undefinedpassword: "correct horse battery" });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const user: Useruser.passwordDigest: string | nullpasswordDigest === null); // true, until the user is saved
await const user: Useruser.Model.saveOrThrow(options?: SaveOptions): Promise<true>
Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a record marked for destruction refused) instead of returning `false`.
saveOrThrow
();
const const isHashed: booleanisHashed = const user: Useruser.passwordDigest: string | nullpasswordDigest?.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.
startsWith
("$pbkdf2-sha256$") === true;
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const isHashed: booleanisHashed); // true

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

Checking a password

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

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const isSignedIn: booleanisSignedIn = (await const user: Useruser.authenticate: <User>(this: User, password: string) => Promise<false | User>authenticate("correct horse battery")) !== false; var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const isSignedIn: booleanisSignedIn); // 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:

import { class UserUser } from "./models/user";

export async function function signIn(request: Request): Promise<Response>signIn(request: Requestrequest: Request): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<Response> {
const const form: FormDataform = await request: Requestrequest.Body.formData(): Promise<FormData>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)
formData
();
const { const email: stringemail = "", const password: string | nullpassword = "" } = class UserUser.
Model.permit<typeof User, "email" | "password">(this: typeof User, input: unknown, ...names: ("email" | "password")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>, "email" | "password">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(const form: FormDataform, "email", "password");
const const user: User | nulluser = await class UserUser.
Model.authenticateBy<typeof User>(this: typeof User, attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>>): Promise<...>
The record its other attributes find, if each secure password given is its own (#355): `User.authenticateBy({ email, password })`, or null. When none is found, the password is hashed anyway, so how long it takes doesn't say whether one exists. Without a secure password, or an attribute to find the record by, it throws `TypeError`.
authenticateBy
({ email?: string | undefinedemail, password?: string | null | undefinedpassword });
if (const user: User | nulluser === null) return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
("Wrong email or password", { ResponseInit.status?: number | undefinedstatus: 401 });
return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
({ token: string | nulltoken: const user: Useruser.authToken: string | nullauthToken });
}
  • 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:

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const isChanged: booleanisChanged = await const user: Useruser.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>>): Promise<boolean>
`assign` then `save`.
update
({
password?: string | null | undefinedpassword: "staple battery horse", passwordConfirmation?: string | null | undefinedpasswordConfirmation: "staple battery horse", passwordChallenge?: string | null | undefinedpasswordChallenge: "correct horse battery", // the current password }); var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const isChanged: booleanisChanged); // 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:

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:

import { class AdminAdmin } from "./models/admin";

const const admin: Adminadmin = await class AdminAdmin.
create<typeof Admin>(this: typeof Admin, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: {
            readonly algorithm: PasswordAlgorithm;
        };
    };
}>>> | undefined, init?: Init<...> | undefined): Promise<...>
Builds a record, awaits `init` with it if it's given, and saves it; resolves to it whether or not it was saved (check `isPersisted()`).
create
({ email?: string | undefinedemail: "sam@example.com", password?: string | null | undefinedpassword: "correct horse battery" });
const const isBcrypt: booleanisBcrypt = const admin: Adminadmin.passwordDigest: string | nullpasswordDigest?.String.startsWith(searchString: string, position?: number): boolean
Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.
startsWith
("$2b$10$") === true;
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const isBcrypt: booleanisBcrypt); // 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.

Generating tokens

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

import { class UserUser } from "./models/user";

const const user: Useruser = class UserUser.
build<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>> | undefined, init?: ((record: User) => void) | undefined): User
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ email?: string | undefinedemail: "sam@example.com", password?: string | null | undefinedpassword: "correct horse battery" });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const user: Useruser.authToken: string | nullauthToken?.String.length: number | undefined
Returns the length of a String object.
length
); // 24, such as "pX27zsMN2ViQKta1bGfLmVJE"
await const user: Useruser.Model.saveOrThrow(options?: SaveOptions): Promise<true>
Like `save()`, but throws `RecordInvalid`, `RecordNotSaved`, or `RecordNotDestroyed` (a record marked for destruction refused) instead of returning `false`.
saveOrThrow
();
const const found: User | nullfound = await class UserUser.findBy<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User | null>
The first record matching `conditions` (in no particular order), or null.
findBy
({ authToken?: string | readonly (string | null)[] | Comparison<string> | null | undefinedauthToken: const user: Useruser.authToken: string | nullauthToken });
  • 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.

Regenerating tokens

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

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "sam@example.com" });
await const user: Useruser.regenerateAuthTokenOrThrow: () => Promise<true>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:

import { function sendResetEmail(_email: string, _link: string): Promise<void>
Sends `link` to `email`.
sendResetEmail
} from "./email";
import { class UserUser } from "./models/user"; export async function function requestReset(request: Request): Promise<Response>requestReset(request: Requestrequest: Request): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<Response> {
const { const email: stringemail = "" } = class UserUser.
Model.permit<typeof User, "email">(this: typeof User, input: unknown, ...names: "email"[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>, "email">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(await request: Requestrequest.Body.formData(): Promise<FormData>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)
formData
(), "email");
const const user: User | nulluser = await class UserUser.findBy<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User | null>
The first record matching `conditions` (in no particular order), or null.
findBy
({ email?: string | readonly string[] | Comparison<string> | undefinedemail });
if (const user: User | nulluser !== null) { const const token: stringtoken = await const user: Useruser.passwordResetToken: () => Promise<string>passwordResetToken(); // lasts 15 minutes await function sendResetEmail(_email: string, _link: string): Promise<void>
Sends `link` to `email`.
sendResetEmail
(const email: stringemail, `https://example.com/reset?token=${const token: stringtoken}`);
} return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
("Check your email", { ResponseInit.status?: number | undefinedstatus: 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:

import { class UserUser } from "./models/user";

export async function function resetPassword(request: Request): Promise<Response>resetPassword(request: Requestrequest: Request): interface Promise<T>
Represents the completion of an asynchronous operation
Promise
<Response> {
const const form: FormDataform = await request: Requestrequest.Body.formData(): Promise<FormData>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData)
formData
();
const const user: User | nulluser = await class UserUser.ResetTokenStatics.findByPasswordResetToken: <typeof User>(this: typeof User, token: unknown) => Promise<User | null>findByPasswordResetToken(const form: FormDataform.FormData.get(name: string): FormDataEntryValue | null
The **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead. [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)
get
("token"));
if (const user: User | nulluser === null) return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
("That link has expired", { ResponseInit.status?: number | undefinedstatus: 400 });
const const isReset: booleanisReset = await const user: Useruser.
Model.update(attributes: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        readonly secureToken: true;
    };
}>>>): Promise<boolean>
`assign` then `save`.
update
(class UserUser.
Model.permit<typeof User, "password" | "passwordConfirmation">(this: typeof User, input: unknown, ...names: ("password" | "passwordConfirmation")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly passwordDigest: "string";
    readonly authToken: "string";
    readonly createdAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly updatedAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, {
    readonly password: {
        readonly securePassword: true;
    };
    readonly authToken: {
        ...;
    };
}>>, "password" | "passwordConfirmation">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(const form: FormDataform, "password", "passwordConfirmation"));
if (!const isReset: booleanisReset) return
var Response: {
    new (body?: BodyInit | null, init?: ResponseInit): Response;
    prototype: Response;
    error(): Response;
    json(data: any, init?: ResponseInit): Response;
    redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
.function json(data: any, init?: ResponseInit): Response
The **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)
json
({ errors: string[]errors: const user: Useruser.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
() }, { ResponseInit.status?: number | undefinedstatus: 422 });
return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => Response
The **`Response`** interface of the Fetch API represents the response to a request. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
Response
(null, { ResponseInit.status?: number | undefinedstatus: 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:

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const token: stringtoken = await const user: Useruser.RecordTokens.generateTokenFor(purpose: string): Promise<string>
A token for `purpose`, which its Model declares with `generatesTokenFor`, for `findByTokenFor` to find this saved record by. `RecordNotSaved` for a new record.
generateTokenFor
("emailConfirmation");
const const confirmed: User | nullconfirmed = await class UserUser.findByTokenFor<typeof User>(this: typeof User, purpose: string, token: unknown): Promise<User | null>
The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
findByTokenFor
("emailConfirmation", const token: stringtoken);
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const confirmed: User | nullconfirmed?.email: string | undefinedemail); // "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:

import { class UserUser } from "./models/user";

const const user: Useruser = await class UserUser.findByOrThrow<typeof User>(this: typeof User, conditions: SafeSql | Conditions<User>): Promise<User>
Like `findBy`, but throws `RecordNotFound` instead of returning null.
findByOrThrow
({ email?: string | readonly string[] | Comparison<string> | undefinedemail: "jane@example.com" });
const const signedId: stringsignedId = await const user: Useruser.RecordTokens.signedId(options?: SignedIdOptions): Promise<string>
This saved record's primary key, signed with its Model's secret, for `findSigned` to find it by: for a purpose, if given, and until it expires, if given. `RecordNotSaved` for a new record.
signedId
({ SignedIdOptions.purpose?: string | undefined
What it's for (`"login"`): `findSigned` finds its record only given the same.
purpose
: "unsubscribe", SignedIdOptions.expiresIn?: Duration | undefined
How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`.
expiresIn
: { Duration.days?: number | undefineddays: 30 } });
const const found: User | nullfound = await class UserUser.findSigned<typeof User>(this: typeof User, signedId: unknown, options?: FindSignedOptions | undefined): Promise<User | null>
The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for the same `purpose` and it hasn't expired, and this Relation matches it; or null.
findSigned
(const signedId: stringsignedId, { FindSignedOptions.purpose?: string | undefinedpurpose: "unsubscribe" });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const found: User | nullfound?.email: string | undefinedemail); // "jane@example.com"
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(await class UserUser.findSigned<typeof User>(this: typeof User, signedId: unknown, options?: FindSignedOptions | undefined): Promise<User | null>
The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for the same `purpose` and it hasn't expired, and this Relation matches it; or null.
findSigned
(const signedId: stringsignedId)); // 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.

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:

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:

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.

Last updated on