Skip to content

Accounts ​

Introduction ​

@plinthjs/accounts is a headless account backend. It gives you the actions every application ends up writing (register, log in, log out, reset a password, change a password, edit a profile, confirm a password) and a complete TOTP two-factor authentication flow with recovery codes. It has no routes, controllers, or views. Each action is a small class with one method, so you decide how it is called over HTTP and how its result is rendered.

The actions work over two small seams: a UserRepository that stores users, and a Hasher that hashes passwords. The Accounts class wires them together once so you can ask it for ready-to-run actions.

bash
pnpm add @plinthjs/accounts @plinthjs/auth @plinthjs/encryption

INFO

The actions do only required-field checks. Format rules, uniqueness, password strength, and confirmation matching are your application's job, typically with Validation before you call the action.

Setting up ​

Create one Accounts instance for your application. It needs a repository and a hasher; the real Hasher from @plinthjs/encryption satisfies the hasher seam.

ts
import { ArrayUserRepository, Accounts } from '@plinthjs/accounts'
import { Hasher } from '@plinthjs/encryption'

const hasher = new Hasher()
const repository = new ArrayUserRepository()

const accounts = new Accounts({ repository, hasher })

ArrayUserRepository keeps users in memory, which is perfect for tests and prototypes. For a real database, implement UserRepository (see below).

The options are:

OptionPurpose
repositoryThe storage seam. Required.
hasherThe password-hashing seam. Required.
passwordBrokerA PasswordBroker from @plinthjs/auth. Required only for resetting passwords.
twoFactorProviderA custom TwoFactorAuthenticationProvider (digits, period, secret size).
nowA clock in epoch milliseconds for the two-factor manager. Handy in tests.
recoveryCodeCountHow many recovery codes to issue when two-factor is confirmed. Default 8.

Every method on Accounts builds a fresh action, so nothing leaks between requests.

Registering users ​

createNewUser() requires name, email, and password, hashes the password, and stores the user. Extra attributes pass through to the repository as they are:

ts
const user = await accounts.createNewUser().handle({
  name: 'Ada',
  email: 'ada@example.com',
  password: 'secret-pass',
})

user.getAuthIdentifier() // => 1
user.getAttribute('name') // => 'Ada'

A missing field throws a ValidationError whose errors property maps each field to its messages:

ts
import { ValidationError } from '@plinthjs/accounts'

try {
  await accounts.createNewUser().handle({ name: 'Ada' })
} catch (error) {
  if (error instanceof ValidationError) {
    error.errors // => { email: ['The email field is required.'], password: ['The password field is required.'] }
  }
}

The action returns a AccountUser, an Authenticatable record wrapper, so you can log the user straight in with a guard from Authentication.

Logging in and out ​

attemptToAuthenticate() looks a user up by email (case-insensitively in the in-memory repository) and checks the password in constant time. It returns the user, or null for an unknown email or wrong password. A missing email or password throws a ValidationError.

ts
const user = await accounts
  .attemptToAuthenticate()
  .handle({ email: 'ada@example.com', password: 'secret-pass' })

if (user === null) {
  // respond with a 422 and a generic "credentials do not match" message
}

The action only verifies credentials. Persisting the login is the guard's job, so call the guard afterwards:

ts
if (user !== null) guard.login(user)

logoutUser() delegates to a StatefulGuard from @plinthjs/auth:

ts
await accounts.logoutUser().handle(guard)

Updating a password or profile ​

updateUserPassword() verifies the user's current_password, then hashes and stores the new password. A wrong current password throws a ValidationError keyed by current_password.

ts
await accounts.updateUserPassword().handle(user, {
  current_password: 'secret-pass',
  password: 'a-new-password',
})

updateUserProfileInformation() requires name and email and merges every supplied attribute onto the user:

ts
const updated = await accounts.updateUserProfileInformation().handle(user, {
  name: 'Ada Lovelace',
  email: 'ada@example.com',
})

updated.getAttribute('name') // => 'Ada Lovelace'

WARNING

The profile action does not hash anything. If a password key slips into the input it is stored as plain text. Pick the allowed fields in your controller before calling it, and use updateUserPassword() for credentials.

Confirming a password ​

confirmPassword() returns whether a supplied password matches the user's stored hash. It does not touch any session. Record the confirmation yourself on success, for example with confirmPassword() from @plinthjs/auth, which also stamps the session for the requirePassword middleware:

ts
accounts.confirmPassword().handle(user, { password: 'a-new-password' }) // => true
accounts.confirmPassword().handle(user, { password: 'wrong' }) // => false

Resetting a forgotten password ​

resetUserPassword() verifies a reset token through a PasswordBroker and stores the new hashed password. You must pass the broker when you build Accounts; otherwise calling resetUserPassword() throws Accounts: a passwordBroker is required to reset passwords.

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

const broker = new PasswordBroker(userProvider, new ArrayTokenRepository({ hasher }))
const accounts = new Accounts({ repository, hasher, passwordBroker: broker })

const status = await accounts.resetUserPassword().handle({
  email: 'ada@example.com',
  token: tokenFromTheEmailedLink,
  password: 'brand-new-password',
})

status // => 'passwords.reset' on success, 'passwords.token' for a bad or expired token

The result is a PasswordStatus string from the broker. Creating the reset token and sending the link is the broker's sendResetLink(); both are covered in Passwords and email verification. ArrayUserProvider from @plinthjs/auth accepts any Authenticatable, so the AccountUser objects of an ArrayUserRepository work with it directly:

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

const userProvider = new ArrayUserProvider(repository.all(), hasher)

With a database-backed repository, implement UserProvider over the same tables, as shown in Authentication.

Two-factor authentication ​

Two-factor authentication adds a one-time code from an authenticator app to the login. accounts.twoFactor() returns a TwoFactorManager that drives the whole lifecycle: enable, confirm, challenge, disable. The codes are standard RFC 6238 TOTP (SHA-1, 6 digits, 30 second steps), so any authenticator app works.

Enrolling a user ​

Enrollment has two steps so a user cannot lock themselves out with a mis-scanned code. enable() stores a fresh secret in an unconfirmed state and returns it. You show it as a QR code and ask for a code. confirm() verifies that code and only then turns two-factor on.

ts
const twoFactor = accounts.twoFactor()

const secret = await twoFactor.enable(user)

const url = twoFactor
  .getProvider()
  .qrCodeUrl('My App', user.getAttribute('email') as string, secret)
// => 'otpauth://totp/My%20App:ada%40example.com?secret=...&issuer=My+App&algorithm=SHA1&digits=6&period=30'

const confirmation = await twoFactor.confirm(user, codeFromTheUser)
if (confirmation === null) {
  // wrong code, or enable() was never called
} else {
  confirmation.recoveryCodes // => ['CCETU3QO-SF6WJPJ4', ...] show these once
}

twoFactor.isEnabled(user) // => true

qrCodeUrl() returns the otpauth:// provisioning URI that authenticator apps read from a QR code; render it with any QR library. confirm() returns the user and the plaintext recovery codes, eight by default. Only hashes of the codes are stored, so display them once and tell the user to save them.

Challenging at login ​

After the password check succeeds, ask the user for a code and pass it to challenge(). It accepts either a current TOTP or an unused recovery code:

ts
if (twoFactor.isEnabled(user)) {
  const ok = await twoFactor.challenge(user, request.string('code'))
  if (!ok) {
    // reject the login
  }
}

The TOTP check tolerates one time step of clock drift on either side. A matching recovery code is single use: it is consumed and replaced with a fresh one, so using the same code twice fails. challenge() returns false when two-factor is not confirmed for the user.

Turning it off ​

ts
await twoFactor.disable(user)
twoFactor.isEnabled(user) // => false

Testing two-factor flows ​

Inject a clock into both the provider and the manager and you can compute valid codes in tests:

ts
import { Accounts, TwoFactorAuthenticationProvider } from '@plinthjs/accounts'

let now = Date.UTC(2026, 0, 1)
const accounts = new Accounts({
  repository,
  hasher,
  now: () => now,
  twoFactorProvider: new TwoFactorAuthenticationProvider({ now: () => now }),
})

const twoFactor = accounts.twoFactor()
const secret = await twoFactor.enable(user)
const code = twoFactor.getProvider().getCurrentOtp(secret)

await twoFactor.confirm(user, code) // => { user, recoveryCodes: [...] }

TwoFactorAuthenticationProvider accepts secretBytes, digits, period, and now. verify(secret, code, window) takes an optional drift window in steps. The lower-level helpers generateRecoveryCodes({ count }), base32Encode(), and base32Decode() are exported too.

Storing users ​

UserRepository has four methods. Implement it over your database or ORM:

ts
import type { AccountUser, UserAttributes, UserRepository } from '@plinthjs/accounts'

class DatabaseUserRepository implements UserRepository {
  findByEmail(email: string): Promise<AccountUser | null> {
    // query by email, wrap the row in new AccountUser(row)
  }
  findById(id: string | number): Promise<AccountUser | null> {
    // query by primary key
  }
  create(attributes: UserAttributes): Promise<AccountUser> {
    // insert and return the stored user
  }
  update(id: string | number, attributes: UserAttributes): Promise<AccountUser | null> {
    // merge the attributes into the row and return the updated user
  }
}

The actions always hand the repository an already-hashed password. ArrayUserRepository also accepts users, nextId, and emailField options, and exposes all() for assertions.

The two-factor manager passes its state to repository.update(id, attributes) as three attributes: two_factor_secret (string or null), two_factor_recovery_codes (a JSON string of the hashed codes, or null) and two_factor_confirmed_at (epoch milliseconds or null). Their names are available as TWO_FACTOR_ATTRIBUTES. A database-backed repository only has to store every attribute it receives (add the three nullable columns) and return them in the attributes of the AccountUser it builds: new AccountUser(row) restores user.twoFactor from them.

Wiring it to routes ​

The actions are transport-agnostic, so a route is mostly validation and mapping results to responses. This is a minimal JSON login that supports two-factor:

ts
import { Response } from '@plinthjs/http'
import { validate } from '@plinthjs/validation'

router.post('/login', async (request) => {
  await validate(request, { email: 'required|email', password: 'required|string' })

  const user = await accounts.attemptToAuthenticate().handle({
    email: request.string('email'),
    password: request.string('password'),
  })
  if (user === null) {
    return Response.json({ message: 'These credentials do not match our records.' }, 422)
  }

  if (accounts.twoFactor().isEnabled(user)) {
    if (!(await accounts.twoFactor().challenge(user, request.string('code', '')))) {
      return Response.json({ message: 'A valid authentication code is required.' }, 422)
    }
  }

  guard(request).login(user) // also rotates the session id
  return Response.json({ ok: true })
})

Here guard(request) builds a SessionGuard as shown in Authentication. A ValidationError thrown by an action is a plain error with an errors map, not the HTTP validation error, so catch it in the route (or in your exception handler) and turn it into a 422 yourself.

Released under the MIT License.