> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# SaaS authentication

A multi-tenant API with every feature of `@dotpress/auth`, on Hono, over SQLite through `node:sqlite`, built in Node.js:

- sign-up with email verification, login with the tokens in the body or in `httpOnly` cookies, password reset and change, email change;
- [magic links](https://dotpress.dev/auth/magic-link.md); a client that sends a PKCE `codeChallenge` binds its link to the device that asked for it;
- [multi-factor authentication](https://dotpress.dev/auth/mfa.md): authenticator apps, codes by email, recovery codes, trusted devices, and the [step-up](https://dotpress.dev/auth/step-up.md) of a session;
- [passkeys](https://dotpress.dev/auth/passkeys.md): a login without password;
- [social login](https://dotpress.dev/auth/oauth.md) with Google and GitHub, and the [handoff codes](https://dotpress.dev/auth/magic-link.md#handoff-codes) of the apps;
- [enterprise SSO](https://dotpress.dev/auth/sso.md) per organization, over OpenID Connect or SAML 2.0, for a domain proven with a DNS record, with just-in-time provisioning, and enforcement once an owner logged in with the connection;
- impersonation by the administrators, an audit log of every [event](https://dotpress.dev/auth/events.md), rate limits counted in the database;
- organizations and their projects, reachable by their members only, invitations by email, with `requireMfa()` and `requireRecentAuth()` on the sensitive routes.

The SQL data provider implements every [store](https://dotpress.dev/auth/data-provider.md#the-stores), `transaction()` and `recordEvent()`, and passes the [conformance suite](https://dotpress.dev/auth/data-provider.md#conformance).

Source: [`examples/saas-auth`](https://github.com/dotpressjs/dotpress/tree/main/examples/saas-auth).

## Run it

```sh
npx degit dotpressjs/dotpress/examples/saas-auth my-api
cd my-api
npm install
ADMIN_PASSWORD='choose a long passphrase' npm run dev
```

`npm run dev` sets `NODE_ENV=development`: the missing `JWT_PRIVATE_KEY`, `JWT_PUBLIC_KEY`, `AUTH_SECRET_KEY`, `API_URL` and `APP_URL` get development defaults, with a warning. Without it (`npm start`), they are required, and the URLs must be https. Behind a reverse proxy, `TRUSTED_PROXIES` lists its addresses or CIDR ranges: `X-Forwarded-For` then gives the client address. A malformed entry (`10.0.0.0/`, a prefix beyond 32 or 128) stops the startup. The IP rate limits count an IPv6 client per /64 network. Google and GitHub sign-in turn on with `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`, `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`. The database is created in `data/saas-auth.db`. The README of the example lists every variable, and walks through the flows with `curl`.

The emails, with their links and codes, are printed in the console. The sign-up binds its verification link to the client with a PKCE pair: without the `codeVerifier` nor the password of the account, the link verifies the address but removes the password, which someone else may have chosen:

```sh
VERIFIER=$(openssl rand -base64 32 | tr '+/' '-_' | tr -d '=')
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=')
curl -X POST localhost:3000/auth/sign-up -H 'content-type: application/json' \
  -d '{"email":"ada@acme.com","password":"correct horse battery staple","codeChallenge":"'$CHALLENGE'"}'
curl -X POST localhost:3000/auth/email/verify -H 'content-type: application/json' \
  -d '{"token":"<token of the link>","codeVerifier":"'$VERIFIER'"}'
curl -X POST localhost:3000/auth/login -H 'content-type: application/json' \
  -d '{"username":"ada@acme.com","password":"correct horse battery staple"}'
curl -X POST localhost:3000/orgs -H 'authorization: Bearer <accessToken>' -H 'content-type: application/json' \
  -d '{"id":"acme","name":"Acme","domain":"acme.com"}'
```

## The service

`createAuth()` with every feature. The OAuth providers come from the environment; the tests give a fake provider instead.

```ts file="<root>/../examples/saas-auth/src/auth.ts"
import {
  createAuth,
  type Auth,
  type AuthEvent,
  type DataProvider,
  type KeyPairOptions,
  type MessagesOptions,
  type PasswordHasher,
  type SecretKey,
} from '@dotpress/auth'
import {
  createGitHubProvider,
  createGoogleProvider,
  createOAuth,
  type OAuthProvider,
} from '@dotpress/auth/oauth'
import { createPasskeys } from '@dotpress/auth/passkeys'
import type { Logger, RateLimitStore } from '@dotpress/core'
import type { Config } from './config.ts'
import type { TenantStore } from './db/tenants.ts'
import { createSafeFetch } from './safe-fetch.ts'
import { createTenantSso } from './sso.ts'

// Type of ctx.user: what dataProvider.findUserById() returns.
declare module '@dotpress/auth' {
  interface AuthUser {
    id: string
    email: string
    roles: string[]
  }
}

export interface AuthServiceOptions {
  keys: KeyPairOptions
  secretKey: SecretKey
  dataProvider: DataProvider
  tenants: TenantStore
  /** Rate limit counters, and the replay store of the SAML assertions. */
  rateLimitStore: RateLimitStore
  /** Public URL of the API. */
  apiUrl: string
  /** URL of the front-end. */
  appUrl: string
  /** Domain of the passkeys. */
  rpId: string
  /** Delivers the emails: verification, reset, magic links, MFA codes. */
  messages: MessagesOptions
  /** Social login: none turns the OAuth routes off. */
  oauthProviders: readonly OAuthProvider[]
  /**
   * The fetch of the requests to the SSO IdPs (OpenID Connect). Defaults
   * to `createSafeFetch()`: public https hosts only.
   */
  ssoFetch?: typeof fetch
  /** Password hasher. Defaults to bcrypt, cost 12. */
  passwordHasher?: PasswordHasher
  /** Receives the events, once their step is committed. */
  logger?: Logger
}

/** The social login providers whose client is configured. */
export const oauthProvidersOf = ({
  google,
  github,
}: Pick<Config, 'google' | 'github'>): OAuthProvider[] => [
  ...(google ? [createGoogleProvider(google)] : []),
  ...(github ? [createGitHubProvider(github)] : []),
]

/** One line per event in the log, besides the audit_events table. */
const logEvent = (logger: Logger | undefined) => (event: AuthEvent) => {
  logger?.info(
    { event: event.type, userId: event.userId, sessionId: event.sessionId },
    'auth event'
  )
}

/** Every feature of `@dotpress/auth`. */
export const createAuthService = (options: AuthServiceOptions): Auth =>
  createAuth({
    keys: options.keys,
    issuer: options.apiUrl,
    dataProvider: options.dataProvider,
    password: {
      ...(options.passwordHasher && { hasher: options.passwordHasher }),
      // Long passwords rather than complex ones.
      policy: { minLength: 12 },
    },
    // Encrypts the TOTP secrets, the state of the OAuth and SSO flows, and
    // keys the hashes of the recovery codes. The first key encrypts; the
    // others still decrypt, during a rotation.
    secrets: { keys: [options.secretKey] },
    // The flows that leave the API (OAuth, SSO, links) end on the front-end.
    redirects: { allowed: [options.appUrl] },
    links: { baseUrl: options.appUrl },
    messages: options.messages,
    // Clients choose at login: { mode: 'cookie' } for browsers (httpOnly
    // cookies), the body otherwise (mobile apps, other services). The
    // cookies authenticate the requests of the front-end only (CSRF).
    cookies: {
      enabled: true,
      accessTokenInCookie: true,
      trustedOrigins: [new URL(options.appUrl).origin],
    },
    // The SQL store: the counters are shared by every instance.
    rateLimits: { store: options.rateLimitStore },
    onEvent: logEvent(options.logger),

    // POST /auth/sign-up, with an optional name; the session starts at the
    // first login, once the address is verified.
    signUp: {
      mode: 'open',
      autoLogin: false,
      schema: (z) => ({ name: z.string().trim().min(1).max(100).optional() }),
    },
    emailVerification: { required: true },
    passwordReset: true,
    emailChange: true,
    // POST /auth/magic-link: a login link. A client that sends a PKCE
    // `codeChallenge` binds the link to its device: the `codeVerifier` is
    // then required to use it.
    magicLink: true,
    // POST /auth/token: the OAuth and SSO flows in body mode end with a
    // one-time code, exchanged with the PKCE verifier of the client.
    handoff: true,

    // Second factors: an authenticator app, a code by email, recovery codes,
    // and the devices that skip the second factor for 30 days.
    mfa: {
      totp: { issuer: 'SaaS example' },
      email: true,
      recoveryCodes: true,
      trustedDevices: true,
    },
    passkeys: createPasskeys({
      rpName: 'SaaS example',
      rpId: options.rpId,
      origins: [options.appUrl],
    }),
    ...(options.oauthProviders.length > 0 && {
      oauth: createOAuth({
        providers: options.oauthProviders,
        redirectBaseUrl: `${options.apiUrl}/auth`,
      }),
    }),
    sso: createTenantSso({
      tenants: options.tenants,
      apiUrl: options.apiUrl,
      replayStore: options.rateLimitStore,
      fetch: options.ssoFetch ?? createSafeFetch(),
    }),
  })

```

## The database

One SQLite connection serves every request. Its statements are synchronous: they never interleave with another request. A transaction of `@dotpress/auth` spans awaits instead: while it is open, the statements of the other requests wait, and nested transactions use savepoints.

```ts file="<root>/../examples/saas-auth/src/db/database.ts"
import { AsyncLocalStorage } from 'node:async_hooks'
import { mkdirSync, readFileSync } from 'node:fs'
import { dirname } from 'node:path'
import {
  DatabaseSync,
  type SQLInputValue,
  type StatementSync,
} from 'node:sqlite'

/**
 * The SQLite database of the app, over `node:sqlite` (built in Node.js).
 *
 * One connection serves every request. Its statements are synchronous: a
 * statement, or a few of them in `atomic()`, never interleave with another
 * request. A transaction of `transaction()` spans awaits instead: while it
 * is open, `run()` holds the statements of the other requests until it
 * ends, so that they neither see its writes nor get rolled back with it.
 * The code awaited inside the transaction, at any depth, runs at once.
 */
export interface Database {
  /** Rows of a query, typed by the caller. */
  all<T>(sql: string, ...params: SQLInputValue[]): T[]
  /** First row of a query, or undefined. */
  get<T>(sql: string, ...params: SQLInputValue[]): T | undefined
  /** Runs a statement, and returns the number of rows it changed. */
  write(sql: string, ...params: SQLInputValue[]): number
  /** Runs synchronous statements together: all of them, or none. */
  atomic<T>(fn: () => T): T
  /** Runs `fn` once no transaction of another request is open. */
  run<T>(fn: () => T): Promise<T>
  /**
   * Runs `fn` in a transaction: committed when it resolves, rolled back
   * when it throws. Nested calls use savepoints.
   */
  transaction<T>(fn: () => Promise<T>): Promise<T>
  close(): void
}

/** The transaction open in an async context, while it is. */
interface TransactionScope {
  active: boolean
}

/** A JSON value of a TEXT column. */
export const json = (value: unknown) => JSON.stringify(value)

/** A date of a TEXT column: ISO 8601, which sorts as text. */
export const iso = (date: Date) => date.toISOString()

export const isoOrNull = (date: Date | null | undefined) =>
  date ? date.toISOString() : null

export const dateOrNull = (value: string | null) =>
  value === null ? null : new Date(value)

export const dateOrUndefined = (value: string | null) =>
  value === null ? undefined : new Date(value)

/** A UNIQUE constraint failed (SQLITE_CONSTRAINT_UNIQUE, primary keys too). */
export const isUniqueViolation = (error: unknown) =>
  error instanceof Error &&
  'errcode' in error &&
  (error.errcode === 2067 || error.errcode === 1555)

const schema = readFileSync(new URL('schema.sql', import.meta.url), 'utf8')

/**
 * Opens the database (`:memory:` in the tests) and applies the schema.
 * Foreign keys are enforced.
 */
export const openDatabase = (path: string): Database => {
  if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
  const sqlite = new DatabaseSync(path, { enableForeignKeyConstraints: true })
  if (path !== ':memory:') {
    // Readers do not block the writer; a writer of another process waits
    // up to 5 seconds instead of failing at once.
    sqlite.exec('PRAGMA journal_mode = WAL')
    sqlite.exec('PRAGMA busy_timeout = 5000')
  }
  sqlite.exec(schema)

  // Each statement is compiled once.
  const statements = new Map<string, StatementSync>()
  const prepare = (sql: string) => {
    let statement = statements.get(sql)
    if (!statement) {
      statement = sqlite.prepare(sql)
      statements.set(sql, statement)
    }
    return statement
  }

  const scopes = new AsyncLocalStorage<TransactionScope>()
  /** Resolves when the open transaction ends. */
  let open: Promise<void> | undefined
  let savepoints = 0

  const inTransaction = () => scopes.getStore()?.active === true

  const withSavepoint = async <T>(fn: () => Promise<T>): Promise<T> => {
    const name = `nested_${++savepoints}`
    sqlite.exec(`SAVEPOINT ${name}`)
    try {
      const result = await fn()
      sqlite.exec(`RELEASE ${name}`)
      return result
    } catch (error) {
      sqlite.exec(`ROLLBACK TO ${name}`)
      sqlite.exec(`RELEASE ${name}`)
      throw error
    }
  }

  return {
    all: <T>(sql: string, ...params: SQLInputValue[]) =>
      prepare(sql).all(...params) as T[],

    get: <T>(sql: string, ...params: SQLInputValue[]) =>
      prepare(sql).get(...params) as T | undefined,

    write: (sql, ...params) => Number(prepare(sql).run(...params).changes),

    atomic: (fn) => {
      sqlite.exec('SAVEPOINT atomic')
      try {
        const result = fn()
        sqlite.exec('RELEASE atomic')
        return result
      } catch (error) {
        sqlite.exec('ROLLBACK TO atomic')
        sqlite.exec('RELEASE atomic')
        throw error
      }
    },

    run: async (fn) => {
      // No await between the last check and fn(): no transaction can
      // start in between.
      while (open && !inTransaction()) await open
      return fn()
    },

    transaction: async (fn) => {
      if (inTransaction()) return withSavepoint(fn)
      while (open) await open
      let end = () => {}
      open = new Promise((resolve) => {
        end = resolve
      })
      const scope: TransactionScope = { active: true }
      try {
        // IMMEDIATE takes the write lock at once: a transaction that reads,
        // then writes, never fails with SQLITE_BUSY when another process
        // wrote in between (it waits busy_timeout to start instead).
        sqlite.exec('BEGIN IMMEDIATE')
        const result = await scopes.run(scope, fn)
        sqlite.exec('COMMIT')
        return result
      } catch (error) {
        if (sqlite.isTransaction) sqlite.exec('ROLLBACK')
        throw error
      } finally {
        // Tasks started inside, still running, now wait like the others.
        scope.active = false
        open = undefined
        end()
      }
    },

    close: () => sqlite.close(),
  }
}

```

The data provider, in `src/db/provider.ts`, maps each method to one query, or a few in `db.atomic()`. The methods that must be atomic rely on SQL: a UNIQUE constraint refuses a second passkey or identity with the same key, and `UPDATE … WHERE <still valid>`, checked by its count of changed rows, lets one of two parallel calls win:

```ts
// tokens.consume(): of two parallel consumptions, one updates the row.
const row = db.get<TokenRow>(
  `UPDATE verification_tokens SET consumed_at = ?
   WHERE token_hash = ? AND purpose = ? AND consumed_at IS NULL
     AND expires_at > ? AND attempts < max_attempts
   RETURNING *`,
  iso(query.at), query.tokenHash, query.purpose, iso(query.at)
)
```

Its test runs the conformance suite on a fresh in-memory database, with real users for the foreign keys:

```ts file="<root>/../examples/saas-auth/test/conformance.test.ts"
import { describeDataProvider } from '@dotpress/auth/conformance'
import { openDatabase, type Database } from '../src/db/database.ts'
import { createSqlDataProvider } from '../src/db/provider.ts'
import { createTenantStore } from '../src/db/tenants.ts'
import { createSecretCipher } from '../src/secret-cipher.ts'

const cipher = createSecretCipher([
  { id: 'test', key: Buffer.alloc(32, 7).toString('base64') },
])

// The contract of @dotpress/auth over the SQL provider: every store and
// method, with the parallel calls that must leave one winner.
let db: Database | undefined

const database = () => {
  if (!db) throw new Error('reset() opens the database.')
  return db
}

describeDataProvider({
  name: 'SQL data provider',
  create: () => createSqlDataProvider(database()),
  // A fresh database per test.
  reset: () => {
    db?.close()
    db = openDatabase(':memory:')
  },
  // The foreign keys need real users.
  seedUser: async ({ email, status }) => {
    const { id } = await createTenantStore(database(), cipher).createUser({
      email,
      passwordHash: null,
      emailVerified: true,
    })
    if (status) {
      database().write('UPDATE users SET status = ? WHERE id = ?', status, id)
    }
    return { userId: id }
  },
  features: {
    sessions: true,
    users: true,
    tokens: true,
    mfa: true,
    trustedDevices: true,
    passkeys: true,
    identities: true,
    transaction: true,
    recordEvent: true,
    isSessionRevoked: true,
    updatePasswordHash: true,
  },
})

```

## SSO per organization

Each organization may have one connection, whose id is the id of the organization. `findConnection` loads it at each login, `discover` routes the addresses of its domain, and `resolveUser` decides who logs in:

```ts file="<root>/../examples/saas-auth/src/sso.ts"
import { createSamlProtocol } from '@dotpress/auth/saml'
import { createSso, ssoRejected, type SsoFeature } from '@dotpress/auth/sso'
import type { RateLimitStore } from '@dotpress/core'
import { domainOf, type TenantStore } from './db/tenants.ts'

export interface TenantSsoOptions {
  tenants: TenantStore
  /** Public URL of the API: the routes of a connection are under `<apiUrl>/auth/sso/<id>`. */
  apiUrl: string
  /** Remembers the SAML assertions already used, until their end. */
  replayStore: RateLimitStore
  /**
   * The fetch of the requests to the OpenID Connect IdPs: `createSafeFetch()`,
   * since their URLs come from the owners; the tests give a fake IdP.
   */
  fetch: typeof fetch
}

/**
 * Enterprise SSO per organization: each organization may have one
 * connection, OpenID Connect or SAML, whose id is the id of the
 * organization. Its owners set it with `PUT /orgs/:orgId/sso`, once they
 * proved the domain of the organization.
 */
export const createTenantSso = ({
  tenants,
  apiUrl,
  replayStore,
  fetch,
}: TenantSsoOptions): SsoFeature =>
  createSso({
    baseUrl: `${apiUrl}/auth`,
    protocols: [createSamlProtocol()],
    replayStore,
    fetch,

    // Loaded at each login: an edit of the owners applies at once.
    findConnection: async (connectionId) =>
      (await tenants.findOrganization(connectionId))?.sso?.connection,

    // The login page asks the connection of an address before asking a
    // password. With `enforced`, the domain has no other way in. Only a
    // proven domain routes its addresses.
    discover: async (email) => {
      const org = await tenants.findOrganizationByDomain(domainOf(email))
      return org?.sso?.connection.enabled
        ? { connectionId: org.id, enforced: org.sso.enforced }
        : undefined
    },

    // Who logs in: a member of the organization, an account of its domain
    // that joins it, or a new account (just-in-time provisioning).
    resolveUser: async ({ connection, profile, existingUserId }) => {
      const org = await tenants.findOrganization(connection.id)
      if (!org) throw ssoRejected('UNKNOWN_ORGANIZATION')
      // The IdP of an organization speaks for the domain it proved only.
      if (!org.domain || !org.domainVerifiedAt) {
        throw ssoRejected('DOMAIN_NOT_VERIFIED')
      }
      // A login of an owner proves the connection works: the owners may
      // then enforce it (`PUT /orgs/:orgId/sso`).
      const member = async (userId: string) => {
        if ((await tenants.findRole(org.id, userId)) === 'owner') {
          await tenants.markSsoTested(org.id)
        }
        return { userId }
      }
      if (existingUserId && (await tenants.findRole(org.id, existingUserId))) {
        return member(existingUserId)
      }

      // An IdP vouches for the addresses of its own domain only, that it
      // verified: `email_verified` of OpenID Connect (or, when the IdP
      // sends no such claim, the `trustEmail` of the connection), the
      // `trustEmail` of a SAML connection.
      const { email } = profile
      if (!email || domainOf(email) !== org.domain) {
        throw ssoRejected('FOREIGN_DOMAIN')
      }
      if (!profile.emailVerified) throw ssoRejected('EMAIL_NOT_VERIFIED')
      const account = existingUserId
        ? await tenants.findUserById(existingUserId)
        : await tenants.findUserByEmail(email)
      if (account && (await tenants.findRole(org.id, account.id))) {
        return member(account.id)
      }
      if (!org.sso?.jit) throw ssoRejected('NOT_A_MEMBER')
      if (account) {
        // An account that never proved its address may have been opened by
        // someone else: the IdP proves the address, so `@dotpress/auth`
        // claims the account at this login and removes what was set before
        // (password, sessions, passkeys, linked accounts, second factors).
        await tenants.addMember(org.id, account.id, 'member')
        return { userId: account.id }
      }
      const created = await tenants.createMember(org.id, {
        email,
        passwordHash: null,
        emailVerified: true,
        name: profile.name ?? null,
      })
      return { userId: created.id, created: true }
    },
  })

```

An organization speaks for the domain it proved only. `POST /orgs` stores the domain unverified, and answers the TXT record to publish (`_dotpress-challenge.<domain>`); `POST /orgs/:orgId/domain/verify` reads it with `resolveTxt()` of `node:dns/promises`. Until then, `discover` does not route the domain, `PUT /orgs/:orgId/sso` answers `403 DOMAIN_NOT_VERIFIED`, and `resolveUser` refuses every login. The domains of public mailbox providers are refused. `resolveUser` also refuses an address the IdP did not verify: `email_verified` of OpenID Connect, or `trustEmail` of the connection, for a SAML IdP and for an OpenID Connect IdP that sends no `email_verified` claim. An existing account of the domain that never verified its address joins the organization at the SSO login, and `@dotpress/auth` claims it: the password, sessions, passkeys, linked accounts and second factors set before are removed.

`PUT /orgs/:orgId/sso` checks the connection as `createSso()` does, and the SAML certificates, before storing it; the client secret is encrypted with `AUTH_SECRET_KEY` (`src/secret-cipher.ts`, AES-256-GCM bound to the organization). A client secret that no longer opens (its key left `AUTH_SECRET_KEY`) makes the connection unavailable, with an error in the log: no SSO login, no enforcement, until an owner sets it again; the other logins of the domain go on. `enforced: true` is refused (`409 SSO_NOT_TESTED`) until an owner logged in with the current connection: a broken connection would lock the whole domain out. Enforcing a connection ends the sessions the addresses of the domain opened another way (password, magic link, passkey, social login), refresh tokens included. When an enforced connection breaks anyway, `npm run cli -- sso:unenforce <orgId>`, run on the server, lifts the enforcement (`unenforceSso()` of `src/db/maintenance.ts`, recorded in the audit log).

The issuer of an OpenID Connect connection comes from the owners: the requests to the IdPs go through `createSafeFetch()`, which allows https only, to hosts whose every address is public, without redirects, within a timeout and a size limit. It resolves the host once, and connects to the address it checked (a `lookup` of `node:https` answering it): a DNS answer that changes in between (DNS rebinding) cannot reach the private networks, and TLS still checks the certificate of the host name:

```ts file="<root>/../examples/saas-auth/src/safe-fetch.ts"
import { lookup } from 'node:dns/promises'
import type { ClientRequest, IncomingMessage } from 'node:http'
import { request as httpsRequest, type RequestOptions } from 'node:https'
import { BlockList, isIP, type LookupFunction } from 'node:net'

/** The addresses of a host name, like `dns.lookup(host, { all: true })`. */
export type ResolveAddresses = (
  hostname: string
) => Promise<readonly { address: string }[]>

/** Sends a request, like `request()` of `node:https`. */
export type HttpsRequest = (
  url: URL,
  options: RequestOptions,
  onResponse: (response: IncomingMessage) => void
) => ClientRequest

export interface SafeFetchOptions {
  /** Resolves the host names. Defaults to `dns.lookup()` of `node:dns/promises`. */
  resolve?: ResolveAddresses
  /** Sends the checked requests. Defaults to `request()` of `node:https`. */
  request?: HttpsRequest
  /** Timeout of a request, body included. Defaults to 5 seconds. */
  timeoutMs?: number
  /** Largest body read. Defaults to 1 MiB. */
  maxBytes?: number
}

/**
 * The addresses an IdP of a tenant must not reach: this network, loopback,
 * private, shared (CGNAT), link-local (cloud metadata), benchmark,
 * documentation, multicast and reserved ranges, and their IPv6 forms.
 */
const BLOCKED = new BlockList()
for (const [network, prefix] of [
  ['0.0.0.0', 8],
  ['10.0.0.0', 8],
  ['100.64.0.0', 10],
  ['127.0.0.0', 8],
  ['169.254.0.0', 16],
  ['172.16.0.0', 12],
  ['192.0.0.0', 24],
  ['192.0.2.0', 24],
  ['192.88.99.0', 24],
  ['192.168.0.0', 16],
  ['198.18.0.0', 15],
  ['198.51.100.0', 24],
  ['203.0.113.0', 24],
  ['224.0.0.0', 4],
  ['240.0.0.0', 4],
] as const) {
  BLOCKED.addSubnet(network, prefix, 'ipv4')
}
for (const [network, prefix] of [
  ['::', 128],
  ['::1', 128],
  // IPv4-mapped addresses (::ffff:0:0/96) are checked against the IPv4
  // ranges by BlockList itself.
  ['64:ff9b::', 96],
  ['64:ff9b:1::', 48],
  ['100::', 64],
  ['2001::', 23],
  ['2001:db8::', 32],
  ['2002::', 16],
  ['fc00::', 7],
  ['fe80::', 10],
  ['fec0::', 10],
  ['ff00::', 8],
] as const) {
  BLOCKED.addSubnet(network, prefix, 'ipv6')
}

/** Whether an address is public: routable on the Internet. */
export const isPublicAddress = (address: string) => {
  const version = isIP(address)
  return (
    version !== 0 && !BLOCKED.check(address, version === 6 ? 'ipv6' : 'ipv4')
  )
}

const resolveWithDns: ResolveAddresses = (hostname) =>
  lookup(hostname, { all: true, verbatim: true })

/**
 * A `lookup` of `net.connect()` that answers the checked address: the
 * connection goes where the check looked, whatever the DNS answers now.
 * Node.js asks every address (`all`) when it tries both families.
 */
const pinnedLookup =
  (address: string): LookupFunction =>
  (_hostname, options, callback) => {
    const family = isIP(address)
    if (options.all) callback(null, [{ address, family }])
    else callback(null, address, family)
  }

/** Sends a request and waits for the head of its response. */
const send = (
  request: HttpsRequest,
  url: URL,
  options: RequestOptions,
  body: Buffer | undefined
) =>
  new Promise<IncomingMessage>((resolve, reject) => {
    const outgoing = request(url, options, resolve)
    outgoing.on('error', reject)
    outgoing.end(body)
  })

/** The body of a response, refused beyond `maxBytes`. */
const readCapped = async (response: IncomingMessage, maxBytes: number) => {
  const length = Number(response.headers['content-length'])
  if (length > maxBytes) {
    response.destroy()
    throw new TypeError('safeFetch: the response is too large.')
  }
  const chunks: Buffer[] = []
  let size = 0
  for await (const chunk of response) {
    const bytes = chunk as Buffer
    size += bytes.byteLength
    if (size > maxBytes) {
      response.destroy()
      throw new TypeError('safeFetch: the response is too large.')
    }
    chunks.push(bytes)
  }
  return Buffer.concat(chunks)
}

/**
 * A `fetch` for the requests to the IdPs of the tenants (`createSso({
 * fetch })`): their URLs come from the owners of the organizations, so a
 * request must not reach the network of the server (SSRF). It allows
 * https only, to a host whose every address is public, without following
 * redirects, within a timeout, and reads at most `maxBytes`.
 *
 * The host is resolved once: the connection goes to the address checked
 * (a `lookup` answering it), so a DNS server answering a public address
 * first and a private one next (DNS rebinding) reaches the public one.
 * The URL keeps the host name: TLS checks the certificate of that name
 * (SNI), and the `Host` header names it.
 */
export const createSafeFetch = ({
  resolve = resolveWithDns,
  request = httpsRequest,
  timeoutMs = 5000,
  maxBytes = 1024 * 1024,
}: SafeFetchOptions = {}): typeof fetch => {
  const safeFetch = async (
    input: string | URL | Request,
    init?: RequestInit
  ): Promise<Response> => {
    const outgoing = new Request(input, init)
    const url = new URL(outgoing.url)
    if (url.protocol !== 'https:') {
      throw new TypeError('safeFetch: only https URLs are allowed.')
    }
    // `[::1]` is the hostname of an IPv6 literal.
    const host = url.hostname.replace(/^\[(.*)\]$/, '$1')
    const addresses =
      isIP(host) === 0 ? await resolve(host) : [{ address: host }]
    const [checked] = addresses
    if (
      !checked ||
      !addresses.every(({ address }) => isPublicAddress(address))
    ) {
      throw new TypeError(`safeFetch: ${url.host} is not a public host.`)
    }

    const timeout = AbortSignal.timeout(timeoutMs)
    const signal = init?.signal
      ? AbortSignal.any([init.signal, timeout])
      : timeout
    const body = outgoing.body
      ? Buffer.from(await outgoing.arrayBuffer())
      : undefined
    const response = await send(
      request,
      url,
      {
        method: outgoing.method,
        headers: { ...Object.fromEntries(outgoing.headers), host: url.host },
        lookup: pinnedLookup(checked.address),
        ...(isIP(host) === 0 && { servername: host }),
        // A connection of its own: no socket of the pool, opened to
        // another address, is reused.
        agent: false,
        signal,
      },
      body
    )
    const status = response.statusCode ?? 0
    if (status >= 300 && status < 400) {
      response.destroy()
      throw new TypeError(`safeFetch: ${url.host} answered a redirect.`)
    }
    const content = await readCapped(response, maxBytes)
    const headers = new Headers()
    for (let i = 0; i + 1 < response.rawHeaders.length; i += 2) {
      headers.append(response.rawHeaders[i]!, response.rawHeaders[i + 1]!)
    }
    return new Response(content.byteLength > 0 ? content : null, {
      status,
      statusText: response.statusMessage ?? '',
      headers,
    })
  }
  return safeFetch
}

```

The tests play the identity providers: `createFakeOidcProvider()` of `@dotpress/auth/testing` for OpenID Connect, and a SAML IdP in memory (`test/support/fake-saml-idp.ts`) that signs its responses with `xml-crypto`.

## The routes

The organizations are reachable by their members only: the others get `404`, so that their existence is not revealed. A user owns 5 organizations at most. Members join by invitation: `POST /orgs/:orgId/invitations` answers `202` whether the address has an account or not (20 invitations per owner per day), and the invited address accepts with the token of its email (`POST /invitations/accept`). Deleting a project asks a recent login (`requireRecentAuth()`), changing the SSO connection a recent second factor (`requireMfa()`): the [step-up](https://dotpress.dev/auth/step-up.md) satisfies both without a new login. The impersonation records the request that started it (`meta`).

```ts file="<root>/../examples/saas-auth/src/routes.ts"
import { createHash, randomBytes, X509Certificate } from 'node:crypto'
import {
  forbidImpersonation,
  requireAuth,
  requireMfa,
  requireRecentAuth,
  requireRole,
  type Auth,
  type SessionsService,
  type SsoConnection,
} from '@dotpress/auth'
import { createSso, ssoRejected } from '@dotpress/auth/sso'
import {
  badRequestError,
  conflictError,
  createRouter,
  defineMiddleware,
  errorResponse,
  notFoundError,
  tooManyRequestsError,
  unauthorizedError,
  type RateLimitStore,
} from '@dotpress/core'
import {
  sameConnection,
  type Organization,
  type OrgRole,
  type TenantStore,
} from './db/tenants.ts'

const ORG_NOT_FOUND = 'Organization not found'

/** Organizations a user may own: creating them is not a way to spam. */
export const MAX_OWNED_ORGANIZATIONS = 5
/** Invitations an owner may send per day, every organization included. */
export const INVITATIONS_PER_DAY = 20
/** DNS checks of a domain per hour. */
const DOMAIN_CHECKS_PER_HOUR = 10
const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000

/**
 * Domains of public mailbox providers: their addresses belong to unrelated
 * people, so no organization may claim them. A short list: a real app
 * uses a maintained one.
 */
export const PUBLIC_EMAIL_DOMAINS: ReadonlySet<string> = new Set([
  'gmail.com',
  'googlemail.com',
  'outlook.com',
  'hotmail.com',
  'live.com',
  'msn.com',
  'yahoo.com',
  'icloud.com',
  'me.com',
  'mac.com',
  'aol.com',
  'proton.me',
  'protonmail.com',
  'gmx.com',
  'gmx.de',
  'web.de',
  'mail.com',
  'yandex.com',
  'yandex.ru',
  'zoho.com',
  'fastmail.com',
  'hey.com',
  'qq.com',
  '163.com',
  'orange.fr',
  'free.fr',
])

/** The TXT records of a host name, like `dns.resolveTxt()` of `node:dns/promises`. */
export type ResolveTxt = (hostname: string) => Promise<string[][]>

/** An invitation to send by email. */
export interface InvitationMessage {
  to: string
  organization: string
  role: OrgRole
  /** The page of the front-end that accepts it, with its token. */
  url: string
}

export interface OrgsRouterOptions {
  tenants: TenantStore
  /** Ends the sessions an enforcement no longer allows. */
  sessions: SessionsService
  /** Counters of the invitations and of the DNS checks. */
  rateLimits: RateLimitStore
  /** Reads the DNS records proving the domains. */
  resolveTxt: ResolveTxt
  /** Sends the email of an invitation. */
  sendInvitation: (message: InvitationMessage) => Promise<void>
  /** Public URL of the API: base of the SSO routes. */
  apiUrl: string
  /** URL of the front-end: the invitation links open it. */
  appUrl: string
}

/** The host name of the TXT record proving a domain. */
export const domainRecordOf = (domain: string) =>
  `_dotpress-challenge.${domain}`

const sha256 = (value: string) =>
  createHash('sha256').update(value).digest('hex')

/** What the API shows of an organization: never the client secret of its IdP. */
const toPublicOrganization = (org: Organization) => ({
  id: org.id,
  name: org.name,
  domain: org.domain,
  domainVerified: org.domainVerifiedAt !== null,
  sso: org.sso
    ? {
        protocol: org.sso.connection.protocol,
        enabled: org.sso.connection.enabled,
        enforced: org.sso.enforced,
        jit: org.sso.jit,
        tested: org.ssoTestedAt !== null,
      }
    : null,
  // The stored connection does not open: an owner sets it again.
  ssoUnavailable: org.ssoUnavailable,
})

/** For the owners: the TXT record to publish, until the domain is proven. */
const withDomainVerification = (org: Organization) => ({
  ...toPublicOrganization(org),
  domainVerification:
    org.domain && org.domainChallenge && !org.domainVerifiedAt
      ? {
          type: 'TXT',
          name: domainRecordOf(org.domain),
          value: org.domainChallenge,
        }
      : null,
})

/** Counts an attempt: false once `limit` is passed within the window. */
const allow = async (
  store: RateLimitStore,
  key: string,
  limit: number,
  windowSeconds: number
) => (await store.increment(key, windowSeconds)).count <= limit

/**
 * Checks a connection as `createSso()` does at login, and the SAML
 * certificates: a broken connection is refused before it is stored. The
 * error message names the field.
 */
const connectionError = (
  connection: SsoConnection,
  apiUrl: string
): string | undefined => {
  try {
    createSso({
      baseUrl: `${apiUrl}/auth`,
      connections: [connection],
      resolveUser: () => Promise.reject(ssoRejected('VALIDATION_ONLY')),
    })
  } catch (error) {
    if (error instanceof TypeError) return error.message
    throw error
  }
  if (connection.protocol === 'saml') {
    for (const certificate of connection.idpCertificates) {
      try {
        new X509Certificate(
          certificate.includes('-----BEGIN')
            ? certificate
            : `-----BEGIN CERTIFICATE-----\n${certificate}\n-----END CERTIFICATE-----`
        )
      } catch {
        return 'idpCertificates: a certificate is not a valid X.509 certificate.'
      }
    }
  }
  return undefined
}

/**
 * Members only: the organizations of others answer 404, not 403, so that
 * their existence is not revealed.
 */
const requireMember = (tenants: TenantStore) =>
  defineMiddleware(async (ctx) => {
    const { orgId } = ctx.req.params
    if (!ctx.user) return unauthorizedError()
    if (!orgId || !(await tenants.findRole(orgId, ctx.user.id))) {
      return notFoundError(ORG_NOT_FOUND)
    }
  })

/** The owners of the organization: its settings, the deletions. */
const requireOwner = (tenants: TenantStore) =>
  defineMiddleware(async (ctx) => {
    const { orgId } = ctx.req.params
    if (!ctx.user) return unauthorizedError()
    if (!orgId || (await tenants.findRole(orgId, ctx.user.id)) !== 'owner') {
      return errorResponse(403, 'OWNER_REQUIRED', 'Owners only.')
    }
  })

/** Organizations, their members, invitations, projects and SSO connection. */
export const orgsRouter = ({
  tenants,
  sessions,
  rateLimits,
  resolveTxt,
  sendInvitation,
  apiUrl,
  appUrl,
}: OrgsRouterOptions) => {
  const router = createRouter()
  const orgs = router.createGroup('/orgs', [requireAuth])

  orgs.defineRoute({
    path: '/',
    handler: async ({ user }) =>
      (await tenants.listOrganizations(user.id)).map((org) =>
        org.role === 'owner'
          ? { ...withDomainVerification(org), role: org.role }
          : { ...toPublicOrganization(org), role: org.role }
      ),
  })

  // The domain is a claim until a DNS TXT record proves it: the answer
  // gives the record to publish, then POST /orgs/:orgId/domain/verify.
  orgs.defineRoute({
    method: 'post',
    path: '/',
    status: 201,
    schema: (z) => ({
      body: z.object({
        id: z.string().regex(/^[a-z0-9][a-z0-9-]{1,62}$/),
        name: z.string().trim().min(1).max(100),
        domain: z
          .string()
          .trim()
          .toLowerCase()
          .regex(
            /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
          )
          .optional(),
      }),
    }),
    handler: async ({ req, user }) => {
      const { id, name, domain } = req.body
      if (domain !== undefined && PUBLIC_EMAIL_DOMAINS.has(domain)) {
        return errorResponse(
          403,
          'PUBLIC_EMAIL_DOMAIN',
          'The domain of a public mailbox provider belongs to no organization.'
        )
      }
      if (
        (await tenants.countOwnedOrganizations(user.id)) >=
        MAX_OWNED_ORGANIZATIONS
      ) {
        return errorResponse(
          403,
          'ORGANIZATION_LIMIT',
          `A user owns ${MAX_OWNED_ORGANIZATIONS} organizations at most.`
        )
      }
      const org = await tenants.createOrganization({
        id,
        name,
        domain: domain ?? null,
        domainChallenge:
          domain === undefined
            ? null
            : `dotpress-domain-verification=${randomBytes(24).toString('base64url')}`,
        ownerId: user.id,
      })
      if (org === 'taken') return conflictError('This id is taken.')
      return { ...withDomainVerification(org), role: 'owner' }
    },
  })

  // Accepts an invitation, with the token of its email: the invited
  // address only, once verified.
  router.defineRoute({
    method: 'post',
    path: '/invitations/accept',
    middlewares: [requireAuth, forbidImpersonation],
    schema: (z) => ({ body: z.object({ token: z.string().min(1).max(200) }) }),
    handler: async ({ req, user }) => {
      const account = await tenants.findUserById(user.id)
      if (account?.email_verified !== 1) {
        return errorResponse(
          403,
          'EMAIL_NOT_VERIFIED',
          'Verify your address before accepting an invitation.'
        )
      }
      const accepted = await tenants.acceptInvitation(sha256(req.body.token), {
        id: account.id,
        email: account.email,
      })
      if (!accepted) {
        return errorResponse(
          400,
          'INVALID_INVITATION',
          'This invitation is invalid, expired, used, or for another address.'
        )
      }
      return accepted
    },
  })

  const org = orgs.createGroup('/:orgId', [requireMember(tenants)])

  // Checks the TXT record of the domain: once found, the domain routes its
  // addresses to the SSO of the organization.
  org.defineRoute({
    method: 'post',
    path: '/domain/verify',
    middlewares: [requireOwner(tenants), forbidImpersonation],
    handler: async ({ req }) => {
      const { orgId } = req.params
      const found = await tenants.findOrganization(orgId)
      if (!found) return notFoundError(ORG_NOT_FOUND)
      if (!found.domain || !found.domainChallenge) {
        return badRequestError('The organization claims no domain.')
      }
      if (found.domainVerifiedAt) return withDomainVerification(found)
      if (
        !(await allow(
          rateLimits,
          `domain-verify:${orgId}`,
          DOMAIN_CHECKS_PER_HOUR,
          3600
        ))
      ) {
        return tooManyRequestsError('Too many checks: try again later.')
      }
      const records = await resolveTxt(domainRecordOf(found.domain)).catch(
        (): string[][] => []
      )
      // A long TXT record arrives in chunks of 255 characters.
      if (
        !records.some((chunks) => chunks.join('') === found.domainChallenge)
      ) {
        return errorResponse(
          422,
          'DOMAIN_NOT_VERIFIED',
          `No TXT record ${domainRecordOf(found.domain)} with the expected value.`
        )
      }
      if ((await tenants.markDomainVerified(orgId)) === 'taken') {
        return conflictError('Another organization proved this domain.')
      }
      const verified = await tenants.findOrganization(orgId)
      return verified
        ? withDomainVerification(verified)
        : notFoundError(ORG_NOT_FOUND)
    },
  })

  org.defineRoute({
    path: '/projects',
    handler: ({ req }) => tenants.listProjects(req.params.orgId),
  })

  org.defineRoute({
    method: 'post',
    path: '/projects',
    status: 201,
    schema: (z) => ({
      body: z.object({ name: z.string().trim().min(1).max(100) }),
    }),
    handler: ({ req, user }) =>
      tenants.createProject(req.params.orgId, req.body.name, user.id),
  })

  // A deletion asks a recent login, or a step-up (POST /auth/step-up).
  org.defineRoute({
    method: 'delete',
    path: '/projects/:projectId',
    middlewares: [requireOwner(tenants), requireRecentAuth({ maxAge: '10m' })],
    handler: async ({ req }) =>
      (await tenants.deleteProject(req.params.orgId, req.params.projectId))
        ? { status: 'deleted' }
        : notFoundError('Project not found'),
  })

  // Invites an address: the same answer whether it has an account, is
  // already a member, or neither (no account oracle). The invited person
  // accepts with the link of the email.
  org.defineRoute({
    method: 'post',
    path: '/invitations',
    status: 202,
    middlewares: [requireOwner(tenants), forbidImpersonation],
    schema: (z) => ({
      body: z.object({
        email: z.email(),
        role: z.enum(['owner', 'member']).default('member'),
      }),
    }),
    handler: async ({ req, user }) => {
      const { orgId } = req.params
      const { email, role } = req.body
      if (
        !(await allow(
          rateLimits,
          `invitations:${user.id}`,
          INVITATIONS_PER_DAY,
          24 * 3600
        ))
      ) {
        return tooManyRequestsError('Too many invitations: try again later.')
      }
      const found = await tenants.findOrganization(orgId)
      if (!found) return notFoundError(ORG_NOT_FOUND)
      const invited = await tenants.findUserByEmail(email)
      if (!invited || !(await tenants.findRole(orgId, invited.id))) {
        const token = randomBytes(32).toString('base64url')
        await tenants.createInvitation({
          orgId,
          email,
          role,
          tokenHash: sha256(token),
          invitedBy: user.id,
          expiresAt: new Date(Date.now() + INVITATION_TTL_MS),
        })
        const url = new URL('/invitations/accept', appUrl)
        url.searchParams.set('token', token)
        await sendInvitation({
          to: email,
          organization: found.name,
          role,
          url: url.href,
        })
      }
      return { status: 'invitation_sent' }
    },
  })

  // The SSO connection decides who logs in for the domain: changing it
  // asks a proven domain, and a second factor verified within 10 minutes.
  // Enforcing it ends the sessions the addresses of the domain opened
  // another way, their refresh tokens included.
  org.defineRoute({
    method: 'put',
    path: '/sso',
    middlewares: [
      requireOwner(tenants),
      forbidImpersonation,
      requireMfa({ maxAge: '10m' }),
    ],
    schema: (z) => ({
      body: z.object({
        connection: z.discriminatedUnion('protocol', [
          z.object({
            protocol: z.literal('oidc'),
            issuer: z.url({ protocol: /^https$/ }),
            clientId: z.string().min(1),
            clientSecret: z.string().min(1),
            scopes: z.array(z.string()).optional(),
            // The IdP verifies every address it sends, but sends no
            // `email_verified` claim (an explicit `false` still refuses).
            trustEmail: z.boolean().optional(),
            enabled: z.boolean().default(true),
          }),
          z.object({
            protocol: z.literal('saml'),
            idpEntityId: z.string().min(1),
            idpSsoUrl: z.url({ protocol: /^https$/ }),
            idpCertificates: z.array(z.string().min(1)).min(1),
            wantAssertionsSigned: z.boolean().optional(),
            allowIdpInitiated: z.boolean().optional(),
            // The IdP verifies the addresses it asserts: without it, a SAML
            // login never matches an account by its address.
            trustEmail: z.boolean().optional(),
            enabled: z.boolean().default(true),
          }),
        ]),
        enforced: z.boolean().default(false),
        jit: z.boolean().default(false),
      }),
    }),
    handler: async ({ req }) => {
      const { orgId } = req.params
      const { enforced, jit } = req.body
      const found = await tenants.findOrganization(orgId)
      if (!found) return notFoundError(ORG_NOT_FOUND)
      if (!found.domain || !found.domainVerifiedAt) {
        return errorResponse(
          403,
          'DOMAIN_NOT_VERIFIED',
          'Prove the domain of the organization first: POST /orgs/:orgId/domain/verify.'
        )
      }
      const connection: SsoConnection = { ...req.body.connection, id: orgId }
      const invalid = connectionError(connection, apiUrl)
      if (invalid) {
        return errorResponse(400, 'INVALID_SSO_CONNECTION', invalid)
      }
      // A broken connection, enforced, would lock the whole domain out:
      // an owner logs in with it first.
      if (
        enforced &&
        !(
          found.sso &&
          found.ssoTestedAt &&
          sameConnection(found.sso.connection, connection)
        )
      ) {
        return errorResponse(
          409,
          'SSO_NOT_TESTED',
          'Log in with this connection as an owner before enforcing it.'
        )
      }
      await tenants.configureSso(orgId, { connection, enforced, jit })
      if (enforced) {
        for (const userId of await tenants.listUserIdsByDomain(found.domain)) {
          for (const session of await sessions.list(userId)) {
            // An impersonation session belongs to the support staff.
            if (session.method !== 'sso' && !session.actor) {
              await sessions.revoke(session.id, 'sso_enforced')
            }
          }
        }
      }
      const updated = await tenants.findOrganization(orgId)
      return updated
        ? toPublicOrganization(updated)
        : notFoundError(ORG_NOT_FOUND)
    },
  })

  org.defineRoute({
    method: 'delete',
    path: '/sso',
    middlewares: [
      requireOwner(tenants),
      forbidImpersonation,
      requireMfa({ maxAge: '10m' }),
    ],
    handler: async ({ req }) => {
      await tenants.configureSso(req.params.orgId, null)
      return { status: 'removed' }
    },
  })

  return router
}

/** Support tools: the administrators (the `admin` role) only. */
export const adminRouter = (auth: Auth, tenants: TenantStore) => {
  const router = createRouter()
  const admin = router.createGroup('/admin', [requireRole('admin')])

  // A session as another user, to see what they see. The admin logged in
  // recently, as themselves; the session ends after 30 minutes, its
  // tokens carry the admin (`act` claim), and the routes guarded by
  // forbidImpersonation refuse it.
  admin.defineRoute({
    method: 'post',
    path: '/impersonate',
    middlewares: [forbidImpersonation, requireRecentAuth({ maxAge: '10m' })],
    schema: (z) => ({ body: z.object({ userId: z.string().min(1) }) }),
    handler: async ({ req, user, auth: session, requestId }) => {
      const target = await tenants.findUserById(req.body.userId)
      if (!target) return notFoundError('User not found')
      if (target.role === 'admin') {
        return errorResponse(
          403,
          'IMPERSONATION_FORBIDDEN',
          'Administrators cannot be impersonated.'
        )
      }
      const tokens = await auth.sessions.impersonate({
        actorId: user.id,
        userId: target.id,
        absoluteTimeout: '30m',
        ...(session.clientId && { clientId: session.clientId }),
        // The session record and the audit log keep where it came from.
        meta: {
          ipAddress: req.ip ?? '',
          userAgent: req.header('user-agent') ?? '',
          requestId,
          clientId: session.clientId,
        },
      })
      return {
        userId: target.id,
        accessToken: tokens.accessToken,
        refreshToken: tokens.refreshToken,
        sessionExpiresAt: tokens.sessionExpiresAt,
      }
    },
  })

  admin.defineRoute({
    path: '/audit-events',
    handler: () => tenants.listAuditEvents(50),
  })

  // Ends the impersonation of the current session, before its timeout.
  router.defineRoute({
    method: 'post',
    path: '/impersonation/end',
    middlewares: [requireAuth],
    handler: async ({ auth: session }) => {
      if (!session.actor) return badRequestError('Not an impersonation.')
      await auth.sessions.endImpersonation(session.sessionId)
      return { status: 'ended' }
    },
  })

  return router
}

```

## Before production

- Give the keys from the secrets of your platform, and replace the console provider of the mailer with the one of your email service.
- The rate limit counters and the SAML replay store live in the database: every instance shares them. With another store, keep it [shared](https://dotpress.dev/auth/passwords.md#a-shared-store). `src/db/maintenance.ts` deletes the expired rows every hour.
- The queries of `src/db/provider.ts` are SQLite SQL: on PostgreSQL, port `json_each()`, `IS ?` and `rowid`, and give each transaction its own connection of the pool; MySQL also lacks `RETURNING`. Run the conformance suite on the port.
- Go through the [security checklist](https://dotpress.dev/auth/security.md).

## Learn more

- [Data provider](https://dotpress.dev/auth/data-provider.md)
- [Enterprise SSO](https://dotpress.dev/auth/sso.md)
- [MFA](https://dotpress.dev/auth/mfa.md) and [step-up](https://dotpress.dev/auth/step-up.md)
- [Passkeys](https://dotpress.dev/auth/passkeys.md)
- [Social login](https://dotpress.dev/auth/oauth.md)
- [Sessions and impersonation](https://dotpress.dev/auth/sessions.md)
