# Validation rules

This guide covers the VineJS validation rules registered by the Persona provider. You will learn how to:

- Register the Persona provider
- Enforce a password policy and share it with your frontend
- Reject passwords that have appeared in data leaks
- Reject disposable email addresses
- Customize the validation error messages
- Fake the compromised passwords check during tests

## Overview

A password can satisfy every length and complexity requirement and still be unsafe, because it already appears in a public data leak and is part of the lists attackers try first. Similarly, an email address can be perfectly valid and still be useless to you, because it belongs to a disposable inbox that stops existing within minutes.

Persona ships three validation rules for these cases. The `passwordPolicy` rule enforces the length, composition, and strength requirements you define, the `uncompromised` rule checks a password against the [Have I Been Pwned](https://haveibeenpwned.com/Passwords) database, and the `nonDisposable` rule checks an email address against a bundled list of disposable email providers. The rules are chainable methods of the VineJS string schema, like `minLength` or `email`.

## Setup

The rules are registered by the Persona provider. It adds them when your app registers the VineJS provider of AdonisJS (`@adonisjs/core/providers/vinejs_provider` in `adonisrc.ts`).

[Installing Persona](/docs/packages/persona/introduction#installation) with `node ace add` registers its provider. If you installed the package another way, run `node ace configure @adonisplus/persona`. The `passwordPolicy`, `uncompromised`, and `nonDisposable` methods are then available on every `vine.string()` schema.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const signupValidator = vine.create({
  email: vine.string().email().nonDisposable(),
  password: vine.string().minLength(8).uncompromised(),
})
```

## Enforcing a password policy

A password policy describes the requirements a password must meet, like its minimum length or the kind of characters it must contain. You define the policy once using the `definePasswordPolicy` function and pass it to the `passwordPolicy` rule. The rule reports a separate error for every requirement the password does not meet.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'
import { definePasswordPolicy } from '@adonisplus/persona/password_policy'

export const passwordPolicy = definePasswordPolicy({
  minLength: 12,
  mixedCase: true,
  numbers: true,
})

export const signupValidator = vine.create({
  email: vine.string().email().nonDisposable(),
  // Run the cheap local checks first, and the network check last
  password: vine.string().passwordPolicy(passwordPolicy).uncompromised(),
})
```

A policy with no options only requires a minimum length of 8 characters. This is a deliberate default. Composition requirements, like forcing a symbol, push users towards predictable substitutions without making passwords harder to guess. Prefer a longer `minLength`, a `minScore` and the `uncompromised` rule over a long list of character requirements.

::::field-group

:::field{name="minLength" type="number"}
The minimum number of characters the password must have.

Defaults to `8`.
:::

:::field{name="maxLength" type="number | null"}
The maximum number of characters the password can have.

Defaults to `null`, which means there is no upper limit.
:::

:::field{name="letters" type="boolean"}
Require at least one letter.

Defaults to `false`.
:::

:::field{name="mixedCase" type="boolean"}
Require at least one uppercase and one lowercase letter.

Defaults to `false`.
:::

:::field{name="numbers" type="boolean"}
Require at least one number.

Defaults to `false`.
:::

:::field{name="symbols" type="boolean"}
Require at least one symbol. Spaces and punctuation marks are considered symbols.

Defaults to `false`.
:::

:::field{name="minScore" type="0 | 1 | 2 | 3 | 4"}
The minimum [strength score](#password-strength-score) the password must have.

Defaults to `0`, which disables the requirement.
:::

::::

### Password strength score

Alongside the requirements, every password is given a strength score between `0` (very weak) and `4` (very strong). The score is an estimate of the entropy of the password, computed from its length and the variety of characters used. It does not depend on the requirements of your policy. A long passphrase of lowercase words can score higher than a short password with symbols.

The score only looks at length and character variety. It does not recognize dictionary words, keyboard patterns, or sequences like `123`. A password such as `Password1!` gets a medium score. Use the `uncompromised` rule alongside `minScore` to reject the well-known ones.

You can enforce a minimum score using the `minScore` option. The following policy accepts any password that is at least 12 characters long and scores `2` (medium) or more.

```ts [app/validators/user.ts]
import { definePasswordPolicy } from '@adonisplus/persona/password_policy'

export const passwordPolicy = definePasswordPolicy({
  minLength: 12,
  minScore: 2,
})
```

### Building a password strength meter

The policy returned by `definePasswordPolicy` is a plain object. Send it to your frontend as JSON, and check passwords in the browser with the `checkPassword` function the validation rule uses on the server.

Start by sending the policy to the page that renders the password field. The following example uses Inertia, but an API response or a serialized value inside an Edge template works the same way.

```ts [app/controllers/signup_controller.ts]
import type { HttpContext } from '@adonisjs/core/http'
import { passwordPolicy } from '#validators/user'

export default class SignupController {
  async create({ inertia }: HttpContext) {
    return inertia.render('auth/signup', { passwordPolicy })
  }
}

```

Then, call the `checkPassword` function every time the value of the password field changes. The `@adonisplus/persona/password_policy` module has no dependencies and uses no Node.js APIs. You can import it in your frontend code.

```ts [inertia/lib/password_meter.ts]
import { checkPassword } from '@adonisplus/persona/password_policy'
import type { PasswordPolicy } from '@adonisplus/persona/password_policy/types'

export function getPasswordFeedback(password: string, policy: PasswordPolicy) {
  const result = checkPassword(password, policy)

  return {
    // True when the server will accept the password
    canSubmit: result.valid,
    // A value between 0 and 4 for the strength bar
    score: result.score,
    // One entry per requirement, for rendering a checklist
    checklist: result.requirements.map((requirement) => {
      return { name: requirement.rule, done: requirement.met }
    }),
  }
}
```

The `checkPassword` function returns an object with the following properties.

::::field-group

:::field{name="valid" type="boolean"}
True when the password meets all the requirements of the policy.
:::

:::field{name="score" type="0 | 1 | 2 | 3 | 4"}
The strength score of the password.
:::

:::field{name="requirements" type="PasswordRequirement[]"}
The state of every requirement enabled by the policy. Each requirement has the name of the `rule` and a `met` boolean. The `minLength` and `minScore` requirements also have a `min` property, and the `maxLength` requirement has a `max` property. You can use these values to display messages like "At least 12 characters".

```ts [inertia/lib/password_meter.ts]
import { checkPassword } from '@adonisplus/persona/password_policy'
import type { PasswordPolicy } from '@adonisplus/persona/password_policy/types'

export function getPasswordRequirements(password: string, policy: PasswordPolicy) {
  return checkPassword(password, policy).requirements
}
// [
//   { rule: 'minLength', met: false, min: 12 },
//   { rule: 'mixedCase', met: false },
//   { rule: 'numbers', met: false },
// ]
```

:::

::::

The `checkPassword` function does not check if the password has appeared in data leaks. That check requires a network request and is performed only on the server by the `uncompromised` rule.

### Helping password managers

Password managers generate passwords that satisfy your policy when the password field has a `passwordrules` attribute. You can create the value for this attribute using the `toPasswordRulesString` function.

```ts [app/controllers/signup_controller.ts]
import { passwordPolicy } from '#validators/user'
import { toPasswordRulesString } from '@adonisplus/persona/password_policy'

toPasswordRulesString(passwordPolicy)
// minlength: 12; required: lower; required: upper; required: digit;
```

## Rejecting compromised passwords

The `uncompromised` rule reports an error when the password has appeared in a known data leak. You should apply it wherever a user chooses a password, which is usually the signup, password reset, and change password forms.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const resetPasswordValidator = vine.create({
  token: vine.string(),
  password: vine.string().minLength(8).uncompromised(),
})
```

### How the check works

The rule never sends the password, or its complete hash, to a third party. Instead, it uses the k-anonymity model offered by the Have I Been Pwned API.

- The password is hashed using SHA-1 inside your application.
- The first five characters of the hash are sent to the API.
- The API responds with every leaked hash that starts with the same five characters, along with the number of times each one has been seen.
- The rule compares the rest of the hash against this list locally.

A single outgoing request is made for each validated password. The rule skips the request when the field has already failed an earlier rule, such as `minLength`. Chain `uncompromised` after your other password rules.

### Allowing a number of leaks

By default, a password is rejected when it has appeared in a data leak even once. You can relax the rule using the `threshold` option, which defines the number of times a password can appear in data leaks before it is considered compromised.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const signupValidator = vine.create({
  // Allow passwords seen in data leaks up to 3 times
  password: vine.string().minLength(8).uncompromised({ threshold: 3 }),
})
```

### When the API is unreachable

The rule waits for 5 seconds for the API to respond. If the request times out, fails, or the API responds with an error, the password is considered uncompromised and the validation passes. This is intentional, since an outage of a third-party service should not stop your users from signing up or resetting their passwords.

You can change the wait time using the `timeout` option. The value is defined in milliseconds.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const signupValidator = vine.create({
  // Wait for a maximum of 2 seconds
  password: vine.string().minLength(8).uncompromised({ timeout: 2000 }),
})
```

### Options

The `uncompromised` rule accepts the following options.

::::field-group

:::field{name="threshold" type="number"}
The number of times a password can appear in data leaks before being considered compromised.

Defaults to `0`.
:::

:::field{name="timeout" type="number"}
The number of milliseconds to wait for the API response. The password is considered uncompromised when the request times out.

Defaults to `5000`.
:::

::::

## Rejecting disposable emails

The `nonDisposable` rule reports an error when the email address belongs to a disposable (also known as temporary) email provider. Chain it after the `email` rule. The domain is then checked only for well-formed email addresses.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const signupValidator = vine.create({
  email: vine.string().email().nonDisposable(),
})
```

The rule does not make any outgoing requests. It looks up the domain of the email address inside a list of known disposable domains bundled with the [disposable-email-domains-js](https://www.npmjs.com/package/disposable-email-domains-js) package. Subdomains are rejected as well. For example, if `mailinator.com` is on the list, then `inbox.mailinator.com` is also considered disposable.

### Allowing and blocking domains

The bundled list will not always match your needs. You can use the `allow` option to accept a domain that is part of the list, and the `block` option to reject additional domains. Both options also apply to the subdomains of the given domains.

```ts [app/validators/user.ts]
import vine from '@vinejs/vine'

export const signupValidator = vine.create({
  email: vine
    .string()
    .email()
    .nonDisposable({
      // Accept this domain, even though it is on the list
      allow: ['mailinator.com'],
      // Reject these domains, in addition to the list
      block: ['example.org'],
    }),
})
```

::::field-group

:::field{name="allow" type="string[]"}
Domains to allow, even when they are part of the disposable domains list.
:::

:::field{name="block" type="string[]"}
Additional domains to treat as disposable.
:::

::::

## Customizing error messages

The `uncompromised` rule reports errors as `uncompromisedPassword`, the `nonDisposable` rule as `nonDisposableDomain`, and the `passwordPolicy` rule under a `passwordPolicy` prefix, with one name for every requirement. You can define custom messages for these rule names using the VineJS messages provider. The following example registers the default messages, which you can change as needed.

```ts [start/validator.ts]
import vine, { SimpleMessagesProvider } from '@vinejs/vine'

const messages = {
  'uncompromisedPassword':
    'The {{ field }} has appeared in a data leak. Please choose a different {{ field }}',
  'nonDisposableDomain': 'Disposable email addresses are not allowed',
  'passwordPolicy.minLength': 'The {{ field }} field must have at least {{ min }} characters',
  'passwordPolicy.maxLength': 'The {{ field }} field must not be greater than {{ max }} characters',
  'passwordPolicy.letters': 'The {{ field }} field must contain at least one letter',
  'passwordPolicy.mixedCase':
    'The {{ field }} field must contain at least one uppercase and one lowercase letter',
  'passwordPolicy.numbers': 'The {{ field }} field must contain at least one number',
  'passwordPolicy.symbols': 'The {{ field }} field must contain at least one symbol',
  'passwordPolicy.minScore': 'The {{ field }} field is not strong enough',
}

vine.messagesProvider = new SimpleMessagesProvider(messages)
```

## Testing

The `uncompromised` rule makes a network request, which makes your tests slower and dependent on a third-party service. You can replace the verifier with a fake implementation using the `fakePwnedPasswords` function. The function swaps the `PwnedPasswordsVerifier` binding inside the container and returns the fake, which you use to define the passwords that should be treated as leaked.

In the following example, the `using` keyword restores the original verifier automatically when the test finishes.

```ts [tests/functional/auth/signup.spec.ts]
import { test } from '@japa/runner'
import app from '@adonisjs/core/services/app'
import { fakePwnedPasswords } from '@adonisplus/persona/password'

test.group('Signup', () => {
  test('reject passwords that have appeared in data leaks', async ({ client }) => {
    // Treat "secret123" as leaked 12 times
    using pwned = fakePwnedPasswords(app.container).leaked('secret123', 12)

    const response = await client.post('/signup').json({
      email: 'virk@adonisjs.com',
      password: 'secret123',
    })

    response.assertStatus(422)
    pwned.assertVerified('secret123')
  })
})
```

When you cannot use the `using` keyword, call the `restore` method yourself after the test.

```ts [tests/functional/auth/signup.spec.ts]
import { test } from '@japa/runner'
import app from '@adonisjs/core/services/app'
import { fakePwnedPasswords } from '@adonisplus/persona/password'

test('reject passwords that have appeared in data leaks', async ({ cleanup }) => {
  const pwned = fakePwnedPasswords(app.container)
  cleanup(() => pwned.restore())

  pwned.leaked('secret123')
})
```

The fake never makes a network request. Every password is considered uncompromised, unless you mark it as leaked. The fake provides the following methods.

::::field-group

:::field{name="leaked" type="method"}
Marks a password as leaked. The second argument defines the number of times the password has appeared in data leaks (defaults to `1`), and is compared against the `threshold` option of the rule.

```ts
pwned.leaked('secret123')
pwned.leaked('secret123', 12)
```

:::

:::field{name="leakedAll" type="method"}
Marks every password as leaked. Passwords marked using the `leaked` method keep their own count.

```ts
pwned.leakedAll()
pwned.leakedAll(5)
```

:::

:::field{name="simulateOutage" type="method"}
Simulates the API being unreachable. Like the real verifier, every password is considered uncompromised during an outage, including the ones marked as leaked.

```ts
pwned.leaked('secret123').simulateOutage()
```

:::

:::field{name="assertVerified" type="method"}
Asserts the given password was checked against data leaks.

```ts
pwned.assertVerified('secret123')
```

:::

:::field{name="assertNoneVerified" type="method"}
Asserts no password was checked. This is helpful for verifying that the check is skipped when the password fails an earlier rule.

```ts
pwned.assertNoneVerified()
```

:::

:::field{name="restore" type="method"}
Restores the original verifier inside the container and clears the leaked passwords, the simulated outage, and the recorded checks.

```ts
pwned.restore()
```

:::

::::
