@plinthjs/accounts
Plinth's headless authentication backend. A set of framework-agnostic auth actions (register, log in, log out, reset, update password, update profile, confirm password) built on the @plinthjs/auth contracts and a small UserRepository / Hasher seam, plus RFC 6238 two-factor authentication (TOTP) with recovery codes. Accounts ties them together over one set of injected dependencies. There are no routes or views: wire the actions into your own controllers.
Install
npm install @plinthjs/accountsUsage
import { Hasher } from '@plinthjs/encryption'
import { ArrayUserRepository, Accounts, ValidationError } from '@plinthjs/accounts'
const accounts = new Accounts({
repository: new ArrayUserRepository(), // or your own UserRepository
hasher: new Hasher(), // anything with make(value) and check(value, hashed)
})
const user = await accounts.createNewUser().handle({
name: 'Ada',
email: 'ada@example.com',
password: 'secret',
}) // the password is stored hashed
const signedIn = await accounts.attemptToAuthenticate().handle({
email: 'ada@example.com',
password: 'secret',
}) // the AccountUser, or null on bad credentials
try {
await accounts.createNewUser().handle({ email: 'missing-fields@example.com' })
} catch (error) {
if (error instanceof ValidationError) error.errors // { name: [...], password: [...] }
}Actions
Each action is also exported as a class you can construct directly.
| Action | handle(...) |
|---|---|
createNewUser() | (input): requires name, email, password |
attemptToAuthenticate() | (input): email + password, returns user or null |
logoutUser() | (guard): logs out a @plinthjs/auth StatefulGuard |
updateUserPassword() | (user, { current_password, password }) |
updateUserProfileInformation() | (user, { name, email, ... }) |
confirmPassword() | (user, { password }): returns a boolean |
resetUserPassword() | ({ email, token, password }): returns a PasswordStatus |
resetUserPassword() needs a passwordBroker (a @plinthjs/auth PasswordBroker) in the Accounts options and throws without one. A wrong current_password raises a ValidationError.
Two-factor authentication
const twoFactor = accounts.twoFactor()
const secret = await twoFactor.enable(user) // pending, not yet active
const url = twoFactor.getProvider().qrCodeUrl('Plinth', 'ada@example.com', secret)
// otpauth://totp/Plinth:ada%40example.com?secret=... (render as a QR code)
const confirmed = await twoFactor.confirm(user, codeFromApp) // null if the code is wrong
confirmed?.recoveryCodes // plaintext codes to show once; only hashes are stored
twoFactor.isEnabled(user) // true
await twoFactor.challenge(user, codeOrRecoveryCode) // a used recovery code is replaced
await twoFactor.disable(user)Pass twoFactorProvider, now or recoveryCodeCount to Accounts to customize the flow. The manager writes two_factor_secret, two_factor_recovery_codes and two_factor_confirmed_at through UserRepository.update() (see TWO_FACTOR_ATTRIBUTES).
TOTP building blocks
import { generateRecoveryCodes, TwoFactorAuthenticationProvider } from '@plinthjs/accounts'
const totp = new TwoFactorAuthenticationProvider({ digits: 6, period: 30, now: () => Date.now() })
const key = totp.generateSecretKey() // base32
totp.getCurrentOtp(key) // '492039'
totp.verify(key, '492039') // allows one step of clock drift by default
generateRecoveryCodes({ count: 8 }) // ['XXXXXXXX-XXXXXXXX', ...]base32Encode, base32Decode and replaceRecoveryCode are exported as well.