Skip to content

Passwords and Email Verification ​

Introduction ​

Two account flows are almost universal: letting a user who forgot their password choose a new one, and proving that an email address belongs to the person who registered it. @plinthjs/auth handles both without tying you to a mail transport or a database. A PasswordBroker runs the reset flow, an EmailVerifier mints and checks signed verification links, and a requirePassword middleware asks a signed-in user to re-enter their password before a sensitive action.

bash
pnpm add @plinthjs/auth @plinthjs/encryption

The examples assume a provider and hasher like the ones in Authentication:

ts
import { Hasher } from '@plinthjs/encryption'
import { ArrayUserProvider, GenericUser } from '@plinthjs/auth'

const hasher = new Hasher()
const user = new GenericUser({
  id: 1,
  email: 'ada@example.com',
  password: hasher.make('old-password'),
})
const provider = new ArrayUserProvider([user], hasher)

Resetting forgotten passwords ​

The reset flow has two halves. First you send the user a link containing a single-use token. Later, when they submit the new password, you verify the token and store the password. The PasswordBroker does the bookkeeping for both halves. It needs a UserProvider to find users and a TokenRepository to store tokens.

ts
import { ArrayTokenRepository, PasswordBroker } from '@plinthjs/auth'

const tokens = new ArrayTokenRepository({ hasher })
const broker = new PasswordBroker(provider, tokens)

ArrayTokenRepository keeps token hashes in memory and never stores the plaintext token. For production, implement the TokenRepository contract against a table (see below).

sendResetLink() looks the user up, refuses to send again if a token was issued recently, creates a token, and hands it to a callback you provide. The callback delivers the link however you like:

ts
import { PasswordStatus } from '@plinthjs/auth'

router.post('/forgot-password', async (request) => {
  const status = await broker.sendResetLink(
    { email: request.string('email') },
    async (user, token) => {
      const link = `https://app.test/reset-password/${token}?email=${encodeURIComponent(request.string('email'))}`
      // send `link` by mail, see the Mail page
    },
  )

  // Respond identically for every status so you do not reveal which emails exist.
  return Response.json({ message: 'If that address is registered, a reset link is on its way.' })
})

The method returns one of the PasswordStatus values:

StatusValueMeaning
PasswordStatus.ResetLinkSentpasswords.sentA token was created and the callback ran.
PasswordStatus.ResetThrottledpasswords.throttledA token was issued less than the throttle window ago.
PasswordStatus.InvalidUserpasswords.userNo user matched the credentials.
PasswordStatus.InvalidTokenpasswords.tokenThe token is wrong, expired, or already used.
PasswordStatus.InvalidPasswordpasswords.passwordThe new password was missing or empty.
PasswordStatus.PasswordResetpasswords.resetThe password was changed.

TIP

Showing a different message for "no such user" lets attackers discover which addresses have accounts. Return the same response for ResetLinkSent, InvalidUser, and ResetThrottled, and only use the status values for logging. See Mail for sending the message.

Resetting the password ​

reset() finds the user from the lookup fields, checks that the new password is not empty, verifies the token, and then calls your callback to persist the new password. Only after the callback succeeds does the broker delete the token and dispatch a PasswordReset event.

ts
router.post('/reset-password', async (request) => {
  const status = await broker.reset(
    {
      email: request.string('email'),
      token: request.string('token'),
      password: request.string('password'),
    },
    async (user, password) => {
      const target = user as GenericUser
      target.setAuthPassword(hasher.make(password))
    },
  )

  return status === PasswordStatus.PasswordReset
    ? Response.json({ ok: true })
    : Response.json({ message: 'This reset link is invalid or has expired.' }, 422)
})

The credentials you pass, minus token and password, are used to find the user, so { email, token, password } looks the user up by email. A token is single use: a second reset() with the same token returns PasswordStatus.InvalidToken.

Your callback does the actual persistence. Hash the password with your Hasher and write it through your user storage. With the actions from Accounts, accounts.resetUserPassword().handle(...) wraps this call for you and uses your repository.

Token lifetime and throttling ​

ArrayTokenRepository takes options for the lifetime and re-send window, plus an injectable clock and token generator for tests:

ts
const tokens = new ArrayTokenRepository({
  hasher,
  expireMinutes: 60, // default 60
  throttleSeconds: 60, // default 60
  now: () => new Date(),
})

deleteExpired() purges expired tokens; run it from a scheduled task when you store tokens in a table.

Storing tokens in your database ​

Implement TokenRepository to keep tokens in a table. It has five methods, and create() returns the plaintext token while only a hash is stored:

ts
import type { Authenticatable, TokenRepository } from '@plinthjs/auth'

class DatabaseTokenRepository implements TokenRepository {
  async create(user: Authenticatable): Promise<string> {
    // generate a random token, store hasher.make(token) with the user's email and a timestamp, return the token
  }
  async exists(user: Authenticatable, token: string): Promise<boolean> {
    // load the row, check it has not expired, then hasher.check(token, row.token)
  }
  async recentlyCreatedToken(user: Authenticatable): Promise<boolean> {
    // true when a row was created within the throttle window
  }
  async delete(user: Authenticatable): Promise<void> {
    // remove the user's row
  }
  async deleteExpired(): Promise<void> {
    // remove every row older than the lifetime
  }
}

Reacting to resets ​

Pass an AuthEvents dispatcher as the broker's third argument to receive a PasswordReset event after each successful reset. A common use is to sign the user out of all other devices. See the events section of Authentication.

ts
const broker = new PasswordBroker(provider, tokens, events)

Verifying email addresses ​

To verify an address, you send the user a link that only your server could have produced, and confirm it when they click. The EmailVerifier produces an expiring HMAC signature that binds the user's id, their current email address, and an expiry time. It cannot be forged without your secret, and it stops working if the user changes their email.

Making a user verifiable ​

The user must also implement the MustVerifyEmail contract: how to read the address, whether it is already verified, and how to mark it verified. Extending GenericUser is the quickest way:

ts
import { GenericUser } from '@plinthjs/auth'
import type { MustVerifyEmail } from '@plinthjs/auth'

class AppUser extends GenericUser implements MustVerifyEmail {
  getEmailForVerification(): string {
    return String(this.attributes['email'])
  }

  hasVerifiedEmail(): boolean {
    return this.attributes['email_verified_at'] != null
  }

  markEmailAsVerified(): void {
    this.attributes['email_verified_at'] = new Date().toISOString()
    // persist the change to your database here
  }
}

Create one verifier for the application with a secret key, then sign for a user and embed the signature in a URL:

ts
import { EmailVerifier } from '@plinthjs/auth'

const verifier = new EmailVerifier({
  secret: process.env['APP_KEY'] ?? '',
  expireMinutes: 60, // default 60
})

const user = new AppUser({ id: 1, email: 'ada@example.com', password: '' })
const { expires, signature } = verifier.sign(user)

const link = `https://app.test/email/verify/${user.getAuthIdentifier()}?expires=${expires}&signature=${signature}`
// send `link` to the user

The signature object has two fields: expires (epoch milliseconds) and signature (a hex HMAC). When the user clicks the link, load the user from the id in the path and check the payload from the query string:

ts
router.get('/email/verify/{id}', async (request) => {
  const user = (await provider.retrieveById(Number(request.param('id')))) as AppUser | null
  if (user === null) return Response.make('Not found.', 404)

  const ok = await verifier.verify(user, {
    expires: Number(request.query('expires')),
    signature: request.query('signature') ?? '',
  })

  return ok ? Response.redirectTo('/dashboard') : Response.make('Invalid or expired link.', 403)
})

verify() returns false for a bad signature or an expired link. On success it calls markEmailAsVerified() and dispatches a Verified event, but only when the address was not already verified, so clicking the link twice is harmless and returns true both times. isValid(user, payload) performs the same check without marking anything.

ts
verifier.isValid(user, { expires, signature }) // => true
verifier.isValid(user, { expires, signature: 'forged' }) // => false

user.attributes['email'] = 'new@example.com'
verifier.isValid(user, { expires, signature }) // => false (the link was for the old address)

WARNING

Use a secret that is long and private, such as your application key, and keep it out of source control. Anyone who knows it can sign links for any user.

Requiring verified addresses ​

The package gives you the contract and the signing; the gate on your routes is your own middleware. Check hasVerifiedEmail() on the user the authentication middleware attached:

ts
import { getUser } from '@plinthjs/auth'
import type { Middleware } from '@plinthjs/http'

export const verified = (): Middleware => async (request, next) => {
  const user = getUser(request) as AppUser | undefined
  if (user === undefined || !user.hasVerifiedEmail()) {
    return Response.redirectTo('/email/verify')
  }
  return next(request)
}

Pass an events dispatcher in the verifier options to receive Verified, and dispatch Registered yourself after creating the account if you want a listener to send the first verification email.

Confirming passwords ​

Some actions deserve a second password prompt even for a signed-in user. The requirePassword() middleware blocks a route until the session carries a recent confirmation, and confirmPassword() records one after checking the password. Both live in @plinthjs/auth:

ts
import { authenticateSession, confirmPassword, getUser, requirePassword } from '@plinthjs/auth'

router
  .get('/settings/delete-account', showDeleteForm)
  .middleware(authenticateSession(provider), requirePassword('/confirm-password', 900))

router
  .post('/confirm-password', async (request) => {
    const confirmed = await confirmPassword(
      provider,
      session(request),
      getUser(request)!,
      request.string('password'),
    )
    return confirmed
      ? Response.redirectTo('/settings/delete-account')
      : Response.json({ message: 'Wrong password.' }, 422)
  })
  .middleware(authenticateSession(provider))

requirePassword(redirectTo, timeoutSeconds) defaults to /confirm-password and three hours (10800 seconds). Without a fresh confirmation, browsers are redirected and JSON clients get a 423 response with {"message":"Password confirmation required."}. The full walkthrough, including the session keys, is in Authentication.

  • Accounts offers ready-made actions for the same flows.
  • Hashing explains the Hasher used to protect stored tokens and passwords.
  • Authentication covers guards, sessions, and the AuthEvents seam.

Released under the MIT License.