> **Can't find what you're looking for?** Use `search_docs` on the docs MCP server at `https://mpp.dev/api/mcp` to find what you need.

# Identity \[Verify agents and clients]

Require a verified identity before payment, check the payer before settlement, or use the MPP Credential itself as identity.

## Options

| Option | Verifies | Use it for |
|---|---|---|
| [**Link**](/extensions/identity#link) | Link-issued agent tokens or disclosed identity claims | Recognize Link agents or require a verified email |
| [**Email OTP**](/extensions/identity#email-otp) | An email inbox, or any fact a trusted issuer attests | Verified-address access without your own login |
| [**Agent signatures**](/extensions/identity#agent-signatures) | The agent or bot that signed the request | Bot recognition and agent-specific policy |
| [**Your own identity provider**](/extensions/identity#your-own-identity-provider) | Your identity provider's API keys, sessions, or SSO, or your own protocol | Existing customer access policy |
| [**Persona KYC**](/extensions/identity#persona-kyc) | An accepted Persona inquiry for an authenticated reference ID | KYC-gated paid access with wallet binding |
| [**Payer identity**](/extensions/identity#payer-identity) | The payer named in the MPP Credential | Ownership, zero-dollar auth, and payer allowlists |

## How identity checks run

Pass verifiers in a route's `identity` option. `mppx` runs each verifier at most once per request, before it issues a Challenge, so rejected callers never see payment terms.

```mermaid
sequenceDiagram
  participant Client
  participant Server
  Client->>Server: Request + identity proof
  Note over Server: Run request verifiers
  alt Rejected
      Server-->>Client: 401, 403, or 503
  else Valid
      Server-->>Client: 402 + Challenge
      Client->>Server: Credential + identity proof
      Note over Server: Run verifiers and payer check
      Server-->>Client: 200 + Receipt
  end

```

Every verifier returns one fixed status:

| Status        | Response             | Meaning                                                                   |
| ------------- | -------------------- | ------------------------------------------------------------------------- |
| `valid`       | Continues to payment | The proof verified. Read its value with `result.identity?.get(verifier)`. |
| `missing`     | 401                  | No proof was presented                                                    |
| `invalid`     | 401                  | A proof was presented but didn't verify                                   |
| `forbidden`   | 403                  | The proof verified, but your policy rejects the identity                  |
| `unavailable` | 503                  | The proof couldn't be checked, such as during an issuer outage            |

* When several verifiers reject, the highest-precedence status decides: `forbidden`, then `unavailable`, `invalid`, and `missing`. The headers of every rejection are merged. See [`Identity.Status`](/sdk/typescript/core/Identity.Status).
* A rejection arrives on the same branch as a Challenge, so `if (result.status === 402) return result.challenge` sends the rejection response. Read `result.rejection` (`stage`, `status`, `reason`) to log why.
* Routes without `identity` skip identity checks, not payment checks.

## Combine verifiers

Every verifier in a route's `identity` list must be valid. To accept any one of several, wrap them in [`Identity.anyOf`](/sdk/typescript/core/Identity.anyOf):

```ts twoslash [server.ts]
import type * as Tap from 'mppx/extensions/identity/tap'
import type * as WebBotAuth from 'mppx/extensions/identity/web-bot-auth'
import * as Identity from 'mppx/identity'
import { Mppx, tempo } from 'mppx/server'

declare const tap: ReturnType<typeof Tap.Server.verifier>
declare const webBotAuth: ReturnType<typeof WebBotAuth.Server.verifier>

const payment = Mppx.create({ methods: [tempo.charge({ testnet: true })] })

export const handler = payment.charge({
  amount: '12.50',
  identity: [Identity.anyOf(tap, webBotAuth)], // [!code hl]
})
```

* Every `anyOf` member runs, so each presented proof's nonce is consumed. The first valid member wins.
* If a verifier reads `Authorization`, set [`authorization: true`](/sdk/typescript/core/Identity.Verifier#authorization-optional) on its verifier object and create the server with `requiresAuth: true`. Payment Credentials then use `Payment-Authorization`, leaving the identity proof intact. This also applies inside nested `anyOf` groups; configuring the route without it throws a `TypeError`.
* When every member rejects, the highest-precedence status decides and the headers of every rejection are merged.
* Attestation members are listed as one group of alternatives, such as `Identity-Attestation-Required: (email;issuer="https://identity.mpp.tempo.xyz" email;issuer="https://identity.example.com")`. The client meets the group with one attestation it holds, or acquires the first that succeeds, so accepting several issuers costs the caller one code.

## Link

[Link Agent Identity](https://docs.link.com/concepts/agent-identity) provides agent tokens without personal details and presentations of signed claims, such as a verified email. Use agent attestation for the former and claims verification for the latter. Neither proves that the identity owns the paying wallet.

### Recognize a Link agent

[`Link.Server.attestation`](/sdk/typescript/server/Link.attestation) verifies an Agent Attestation Token from `Authorization: PrivateToken`. Set `requiresAuth: true` so Payment Credentials use `Payment-Authorization` instead.

```ts twoslash [server.ts]
import * as Link from 'mppx/extensions/identity/link'
import { Mppx, tempo } from 'mppx/server'

// [!code hl:start]
const agent = Link.Server.attestation()
const mppx = Mppx.create({
  methods: [tempo.charge({ testnet: true })],
  requiresAuth: true,
})
// [!code hl:end]
export const handler = mppx.charge({ amount: '0.05', identity: [agent] })
```

Configure [`Link.Client.attestation`](/sdk/typescript/client/Link.attestation) to obtain a token from your Link CLI integration. `getLinkToken` below is application code that returns the CLI's `authorization` value or a bare token.

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as Link from 'mppx/extensions/identity/link'
import type { Account } from 'viem'

declare const account: Account
declare function getLinkToken(): Promise<string | undefined>

const client = Mppx.create({
  // [!code hl:start]
  identity: [Link.Client.attestation({
    scope: ['https://api.example.com'],
    token: () => getLinkToken(),
  })],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})

const response = await client.fetch('https://api.example.com/report')
console.log(response.status)
// @log: 200
```

* A missing token gets `401` with a `PrivateToken` challenge. The prover obtains a token and retries the unpaid request, then reuses it for that origin, including on the paid retry.
* The token only establishes that Link issued it; it discloses no personal details and isn't single-use. Existing caller-supplied `Authorization` is left untouched.
* Use [`Link.Server.tokenVerifier`](/sdk/typescript/server/Link.tokenVerifier) to configure the built-in Web Crypto verifier, or pass an `@stripe/agent-identity` verifier.

### Require verified claims

Install `@stripe/agent-identity` 0.3.0 or later for claims verification. Agent attestation alone uses Web Crypto and doesn't need this package.

:::code-group
```bash [npm]
$ npm install @stripe/agent-identity
```

```bash [pnpm]
$ pnpm add @stripe/agent-identity
```

```bash [bun]
$ bun add @stripe/agent-identity
```
:::

[`Link.Server.claims`](/sdk/typescript/server/Link.claims) verifies a presentation of claims signed by Link. Request both `email` and `email_verified` for a verified email; read it through `result.identity?.get(email)?.email` after success.

```ts twoslash [server.ts]
import * as Link from 'mppx/extensions/identity/link'
import { Mppx, tempo } from 'mppx/server'

// [!code hl:start]
const email = Link.Server.claims({
  audience: 'https://api.example.com',
  claims: ['email', 'email_verified'],
  purpose: 'Send your purchased report',
  secretKey: process.env.MPP_SECRET_KEY!,
})
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })
export const handler = mppx.charge({ amount: '0.05', identity: [email] })
```

Configure [`Link.Client.claims`](/sdk/typescript/client/Link.claims) with the claims you permit and a callback that obtains a presentation, for example through `link-cli identity credentials present`.

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as Link from 'mppx/extensions/identity/link'
import type { Account } from 'viem'

declare const account: Account
declare const present: Link.Present

const client = Mppx.create({
  // [!code hl:start]
  identity: [Link.Client.claims({
    claims: ['email', 'email_verified'],
    present,
    scope: ['https://api.example.com'],
  })],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})

const response = await client.fetch('https://api.example.com/report')
console.log(response.status)
// @log: 200
```

* A missing presentation gets `401` with `WWW-Authenticate: Identity-Presentation` and a claims challenge in the response body. The prover checks the audience, trusted issuer, format, and allowed claims before calling `present`.
* The presentation travels in `Identity-Presentation`, bound to the configured API origin and a nonce signed by the server with `secretKey`. It remains reusable until the nonce expires (300 seconds by default), including on the paid retry.
* Put the claims verifier first to retain its challenge body when other verifiers also return `missing`. Use a fixed public origin for `audience`, not a caller-controlled host.
* Claims alone don't need `requiresAuth`. Add it if you also require agent attestation. Neither prover retries an already-paid attempt for identity recovery.
* See [`Link.Client.claimsChallenge`](/sdk/typescript/client/Link.claimsChallenge) to parse the challenge yourself and [`Link.Server.presentationVerifier`](/sdk/typescript/server/Link.presentationVerifier) for verification options.

Keep proofs at their intended origin. The client strips sensitive identity headers on cross-origin redirects, and the [proxy](/sdk/typescript/proxy) removes them before forwarding upstream. See [`Identity.Headers`](/sdk/typescript/core/Identity.Headers).

## Email OTP

Use the email OTP extension when callers need a verified address and you don't have your own identity provider. An issuer is the service that emails codes and signs attestations: bearer tokens confirming inbox access for a specific API origin. The server checks this token before issuing a payment Challenge or settling a Credential.

The examples use Tempo's hosted issuer; you can also self-host it.

```mermaid
sequenceDiagram
  participant Client
  participant Issuer
  participant API
  Client->>API: Request without attestation
  API-->>Client: 401 + Identity-Attestation-Required
  Client->>Issuer: Request code for email and API origin
  Issuer-->>Client: Email code
  Client->>Issuer: Exchange code
  Issuer-->>Client: Origin-bound attestation
  Client->>API: Request + Identity-Attestation
  API-->>Client: 402 + Challenge
  Client->>API: Credential + Identity-Attestation
  API-->>Client: 200 + Receipt

```

### Set it up

```ts twoslash [server.ts]
import * as EmailOtp from 'mppx/extensions/identity/email-otp'
import { Mppx, tempo } from 'mppx/server'

// [!code hl:start]
const email = EmailOtp.Server.verifier({
  allow: (address) => address.endsWith('@example.com'),
  audience: 'https://api.example.com',
  issuer: 'https://identity.mpp.tempo.xyz',
})
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })

export async function handler(request: Request) {
  const result = await mppx.charge({ amount: '0.05', identity: [email] })(request)
  if (result.status === 402) return result.challenge
  return result.withReceipt(Response.json({ email: result.identity?.get(email)?.email }))
}
```

Configure the matching client prover. Use your terminal or form to return the emailed code from `code`:

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as EmailOtp from 'mppx/extensions/identity/email-otp'
import type { Account } from 'viem'

declare const account: Account
declare function promptForCode(message: string): Promise<string | undefined>

const client = Mppx.create({
  // [!code hl:start]
  identity: [EmailOtp.Client.prover({
    code: ({ audience, email, issuer }) =>
      promptForCode(`Code from ${issuer} for ${email} at ${audience}:`),
    email: 'you@example.com',
    issuers: ['https://identity.mpp.tempo.xyz'],
    scope: ['https://api.example.com'],
  })],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})

const response = await client.fetch('https://api.example.com/report')
console.log(response.status)
// @log: 200
```

#### Email OTP details

* The prover only contacts allowlisted `issuers` and only sends attestations to in-scope origins matching their audience. Never trust an issuer supplied only by a server—it could relay your code to another issuer.
* The server returns `401` for missing or invalid attestations, `403` for a verified address rejected by `allow`, and `503` when issuer keys are unavailable. Only identity success reaches payment.
* Cached attestations are reused in memory and refreshed near expiry before payment. The prover prompts at most three times for rejected codes; paid attempts aren't resent by identity recovery.
* Issuer calls explicitly disable automatic payment, including through `Identity.Client.wrapFetch`. Custom fetch forwarding layers must preserve the request init's symbol properties so the opt-out reaches the payment wrapper; forwarding only a reconstructed `Request` drops it. An issuer `402` is an OTP error, not a payment to approve.
* For your own send/verify form, use [`sendCode`](/sdk/typescript/client/EmailOtp.sendCode), [`verifyCode`](/sdk/typescript/client/EmailOtp.verifyCode), and [pre-obtained attestations](/sdk/typescript/client/EmailOtp.prover#use-a-custom-email-form).

:::warning[Keep attestations at their audience]
An attestation is a reusable bearer token, not a per-request signature. Use HTTPS and configure `audience` as your fixed public API origin. Derive it from the request only when the platform guarantees the host; a caller-controlled `Host` header can bypass isolation.

Don't forward `Identity-Attestation` to upstream services. `mppx` strips it from cross-origin payment preparation, and its proxy strips both this request header and upstream `Identity-Attestation-Required` responses. Authenticate each hop independently.
:::

See [`EmailOtp.Server.verifier`](/sdk/typescript/server/EmailOtp.verifier) for key resolution and rejection rules, and [`EmailOtp.Client.prover`](/sdk/typescript/client/EmailOtp.prover) for callbacks, expiry handling, and errors. The [Cloudflare Worker example](https://github.com/wevm/mppx/tree/main/examples/email-otp) includes a terminal prompt, a domain allowlist, and a self-hosted issuer option.

### Other attestation types

An attestation is a short-lived token an issuer signs after checking one fact about the caller, bound to your API's origin. Email OTP is one attestation type. Use the attestation module directly for another type, such as a phone number, or for your own issuer.

```ts twoslash [server.ts]
import * as Attestation from 'mppx/extensions/identity/attestation'
import { Mppx, tempo } from 'mppx/server'

// [!code hl:start]
const phone = Attestation.Server.verifier({
  audience: 'https://api.example.com',
  issuer: 'https://phone.example.com',
  type: 'phone',
  validate: (claims) =>
    claims.sub.startsWith('+1') ? undefined : 'Only US numbers are allowed.',
})
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })
export const handler = mppx.charge({ amount: '0.05', identity: [phone] })
```

A request without a matching attestation gets `401` with `Identity-Attestation-Required: phone;issuer="https://phone.example.com"`. A `validate` rejection gets `403`, and unreachable issuer keys get `503`.

On the client, the prover sends cached attestations to in-scope origins and calls `acquire` when a server asks for one from a trusted issuer:

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as Attestation from 'mppx/extensions/identity/attestation'
import type { Account } from 'viem'

declare const account: Account
declare function obtainPhoneAttestation(parameters: {
  audience: string
  issuer: string
}): Promise<string | undefined>

const client = Mppx.create({
  // [!code hl:start]
  identity: [Attestation.Client.prover({
    acquire: ({ audience, issuer }) => obtainPhoneAttestation({ audience, issuer }),
    issuers: ['https://phone.example.com'],
    scope: ['https://api.example.com'],
    types: ['phone'],
  })],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})
```

* The audience is always the request's own origin, never one a server names, so a server can't obtain an attestation it could replay elsewhere.
* `acquire` only runs for `issuers` you list. Never trust an issuer named only by a server.
* To run an issuer, sign claims with [`Attestation.sign`](/sdk/typescript/core/Attestation.sign) and publish your Ed25519 keys at `/.well-known/jwks.json`. Servers read them with [`Attestation.Jwks.resolver`](/sdk/typescript/core/Attestation.Jwks.resolver).

See [`Attestation.Server.verifier`](/sdk/typescript/server/Attestation.verifier) and [`Attestation.Client.prover`](/sdk/typescript/client/Attestation.prover) for every option.

## Persona KYC

Use Persona when a buyer needs an approved KYC inquiry linked to a wallet or customer in your system. Start an inquiry after authenticating that identity, then check its approval on paid requests. Keep the Persona API key on the server.

### Bind the wallet before KYC

1. Authenticate the person and issue a short-lived, single-use nonce for their session.
2. Ask their wallet to sign a message containing that nonce, your domain, and its [`Persona.did`](/sdk/typescript/core/Persona.did).
3. Retrieve the session's nonce and expected message on the server, verify the signature, and atomically consume the nonce. Don't accept a caller's nonce as the server-issued value.
4. Start the inquiry with the returned DID and store it in that authenticated session.

```ts twoslash [onboarding.ts]
import * as Persona from 'mppx/extensions/identity/persona'
import type { Address, Hex } from 'viem'

declare const address: Address
declare const message: string // Server-expected message containing the nonce and wallet DID.
declare const nonce: string // Retrieved from the authenticated person's server-side session.
declare const signature: Hex
declare function consumeNonce(nonce: string): Promise<void>
declare function saveWallet(referenceId: string): Promise<void>

const persona = Persona.Server.create({
  apiKey: process.env.PERSONA_API_KEY!,
  templateId: 'itmpl_example',
})
// [!code hl:start]
const referenceId = await Persona.Server.verifyWallet({
  address,
  chainId: 42431,
  message,
  nonce,
  signature,
})
// [!code hl:end]
await consumeNonce(nonce) // Atomically reject an already-consumed nonce.
await saveWallet(referenceId)
const { url } = await persona.startInquiry({ referenceId })
```

Send the one-time `url` to the person to complete Persona's hosted flow. `consumeNonce` and `saveWallet` are application code. Without wallet verification, anyone can complete KYC for another wallet. The default signature check supports EOAs; use a chain-pinned verifier for [smart accounts](/sdk/typescript/server/Persona.verifyWallet#verify-smart-accounts).

### Require approval before settlement

[`persona.paymentCheck`](/sdk/typescript/server/Persona.paymentCheck) advertises KYC on the initial `402` and checks the inquiry on the paid retry, before settlement:

```ts twoslash [server.ts]
import { Store } from 'mppx'
import * as Persona from 'mppx/extensions/identity/persona'
import { Mppx, tempo } from 'mppx/server'

declare function authenticatedWallet(request: Request): Promise<string | undefined>

const persona = Persona.Server.create({
  apiKey: process.env.PERSONA_API_KEY!,
  templateId: 'itmpl_example',
})
// [!code hl:start]
const kyc = persona.paymentCheck({
  cache: Store.memory(),
  onboarding: 'https://api.example.com/kyc',
  referenceId: ({ request }) => authenticatedWallet(request),
})
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })

export async function handler(request: Request) {
  const result = await mppx.charge({ amount: '0.05', identity: { payment: kyc } })(request)
  if (result.status === 402) return result.challenge
  return result.withReceipt(Response.json({ inquiry: result.identity?.get(kyc)?.inquiryId }))
}
```

`authenticatedWallet` reads the verified DID stored in your session. It must not read an unauthenticated header or return `credential.source` unchecked. A session authenticates its own identity; separately authenticate and compare the payer if your policy requires that exact wallet to pay. See [payer checks](/extensions/identity#check-the-payer-before-settlement).

* The route's `402` advertises `Identity-Required: kyc;issuer="https://api.withpersona.com"`. No Persona client prover or automatic hosted-flow completion is provided.
* Missing identity gets `401`; no accepted inquiry gets `403`. Both include the configured onboarding `Link`. Persona lookup failures get `503`, without an onboarding link or provider response details.
* Only `approved` is accepted by default. Completing the flow isn't approval. A configured cache retains accepted results for 300 seconds; no cache is enabled by default.
* Set `templateId` when creating the client to accept only that inquiry template. See the reference for [freshness, caching, and lookup limits](/sdk/typescript/server/Persona.paymentCheck#parameters).

### Advanced options

Use [`persona.verifier`](/sdk/typescript/server/Persona.verifier) with a session-derived customer reference ID to require KYC before any payment Challenge: `identity: [kyc]`. Unlike `paymentCheck`, it runs on the initial unpaid request too and doesn't receive a payment Credential. For non-wallet identities, start the inquiry with your authenticated customer's identifier instead of a DID.

## Agent signatures

Agent signatures use [RFC 9421 HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421) to bind an agent identity to an HTTP request. `mppx` supports Ed25519 and RSA-PSS SHA-512 signatures through two profiles:

| Profile | Trust source | Signed request data | Recommended use |
|---|---|---|---|
| [**Web Bot Auth**](/extensions/identity#use-web-bot-auth) | Public key associated with a trusted HTTPS directory | Authority and `Signature-Agent` | General bot and agent identification |
| [**Trusted Agent Protocol**](/extensions/identity#use-trusted-agent-protocol) | Public key provisioned by a trusted agent provider | Authority and path | Commerce agents with explicit browse or payment intent |

Each client prover signs the initial request and every automatic MPP retry to the origins in its `scope`, with a fresh nonce and timestamp per attempt. Requests that carry proofs don't follow redirects. An unsigned request or a signature that doesn't verify gets `401`, and a key your resolver doesn't trust gets `403`.

### Use Web Bot Auth

[Web Bot Auth](https://datatracker.ietf.org/doc/html/draft-meunier-web-bot-auth-architecture) identifies automated HTTP clients through a signed `Signature-Agent` header. Use the HTTPS-directory profile when the agent publishes its keys through a directory origin that your server trusts.

Configure the prover on the MPP client. `keyId` must be the RFC 7638 SHA-256 thumbprint of the public key registered for the bot, and `scope` lists the origins that receive the signature.

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as WebBotAuth from 'mppx/extensions/identity/web-bot-auth'
import type { Account } from 'viem'

declare const account: Account
declare const botPrivateKey: CryptoKey

const botIdentity = {
  keyId: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U',
  signatureAgent: 'https://bot.example',
} as const

const client = Mppx.create({
  // [!code hl:start]
  identity: [
    WebBotAuth.Client.prover({
      key: botPrivateKey,
      keyId: botIdentity.keyId,
      scope: ['https://api.example.com'],
      signatureAgent: botIdentity.signatureAgent,
    }),
  ],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})

const response = await client.fetch('https://api.example.com/resource')
console.log(response.status)
// @log: 200
```

Create the verifier on the MPP server and require it on each protected route. The resolver receives the signed directory origin and key ID. Apply your trust policy before you return a key.

```ts twoslash [server.ts]
import * as WebBotAuth from 'mppx/extensions/identity/web-bot-auth'
import { Mppx, Store, tempo } from 'mppx/server'

declare const botPublicKey: CryptoKey

const botIdentity = {
  keyId: 'poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U',
  signatureAgent: 'https://bot.example',
} as const

// [!code hl:start]
const webBotAuth = WebBotAuth.Server.verifier({
  keyResolver({ keyId, signatureAgent }) {
    if (
      keyId !== botIdentity.keyId ||
      signatureAgent !== botIdentity.signatureAgent
    ) return undefined
    return botPublicKey
  },
  maxAge: 60,
  nonceStore: Store.memory(),
})
// [!code hl:end]

const payment = Mppx.create({ methods: [tempo.charge({ testnet: true })] })

export const handler = payment.charge({ amount: '0.05', identity: [webBotAuth] }) // [!code hl]
```

:::warning[Trust the directory before fetching]
The verifier doesn't fetch the caller-provided `Signature-Agent` URL. Allowlist the origin before a directory lookup, prevent redirects to untrusted origins, and return an extractable public key so `mppx` can verify its JWK thumbprint.
:::

### Use Trusted Agent Protocol

[Trusted Agent Protocol](https://developer.visa.com/capabilities/trusted-agent-protocol/trusted-agent-protocol-specifications/) (TAP) identifies an agent that a merchant or payment network trusts. TAP signatures include an intent: `browse` for discovery and `payment` for payment-related requests.

Use `payment` for an MPP client that accesses paid routes. The prover uses an eight-minute lifetime by default, which is TAP's maximum.

```ts twoslash [client.ts]
import { Mppx, tempo } from 'mppx/client'
import * as Tap from 'mppx/extensions/identity/tap'
import type { Account } from 'viem'

declare const account: Account
declare const agentPrivateKey: CryptoKey

const client = Mppx.create({
  // [!code hl:start]
  identity: [
    Tap.Client.prover({
      intent: 'payment',
      key: agentPrivateKey,
      keyId: 'agent-provider-key-1',
      scope: ['https://merchant.example'],
    }),
  ],
  // [!code hl:end]
  methods: [tempo({ account })],
  polyfill: false,
})

const response = await client.fetch('https://merchant.example/checkout')
console.log(response.status)
// @log: 200
```

On the server, resolve `keyId` only from agent providers you trust. The verifier checks the signature, request authority and path, lifetime, intent tag, and nonce. Read the verified key ID and intent with `result.identity?.get(tap)`.

```ts twoslash [server.ts]
import * as Tap from 'mppx/extensions/identity/tap'
import { Mppx, Store, tempo } from 'mppx/server'

declare const trustedAgentKeys: ReadonlyMap<string, CryptoKey>

// [!code hl:start]
const tap = Tap.Server.verifier({
  keyResolver({ keyId }) {
    return trustedAgentKeys.get(keyId)
  },
  nonceStore: Store.memory(),
})
// [!code hl:end]

const payment = Mppx.create({ methods: [tempo.charge({ testnet: true })] })
const charge = payment.charge({ amount: '12.50', identity: [tap] }) // [!code hl]

export async function handler(request: Request) {
  const result = await charge(request)
  if (result.status === 402) return result.challenge

  console.log(result.identity?.get(tap)?.intent)
  // @log: payment
  return result.withReceipt(new Response('Accepted'))
}
```

### Store nonces

Web Bot Auth and TAP verifiers use the core `Store.AtomicStore` to retain consumed nonces and block replay. `Store.memory()` is limited to one long-lived server process. In a multi-instance deployment, provide a shared atomic store so every instance claims nonces through their expiration time.

```ts [nonce-store.ts]
import type { Store } from 'mppx'

declare const nonceDatabase: {
  insertIfAbsent(value: { expires: number; key: string }): Promise<boolean>
}
declare const sharedStore: Store.AtomicStore

export const nonceStore = {
  ...sharedStore,
  async tryClaim(key: string, expires: number) {
    return nonceDatabase.insertIfAbsent({ expires, key })
  },
} satisfies Store.AtomicStore
```

Adapt `tryClaim` to your storage client's atomic insert-if-absent operation. It returns `true` when it records a new claim and `false` when an unexpired claim already exists. If your `AtomicStore` omits this optimized method, `mppx` falls back to its atomic `update` operation. See [`Store.tryClaim`](/sdk/typescript/core/Store.tryClaim).

### IETF Specification

[HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421) — Read RFC 9421

[Web Bot Auth](https://datatracker.ietf.org/doc/html/draft-meunier-web-bot-auth-architecture) — Read the IETF draft

## Your own identity provider

Use your own identity provider in one of two ways:

* **Connect your identity provider** when callers already have an API key, session, or SSO login from you. The server checks it before payment.
* **Build a protocol** when the client must prove something new. You write both sides: what the client sends and how the server checks it.

### Connect your identity provider

Wrap your existing check in [`Identity.from`](/sdk/typescript/core/Identity.from). Callers your identity provider accepts continue to payment; everyone else is rejected before they see a price.

```ts twoslash [server.ts]
import * as Identity from 'mppx/identity'
import { Mppx, tempo } from 'mppx/server'

declare const customers: ReadonlyMap<string, { customerId: string }>

// [!code hl:start]
const customer = Identity.from({
  challenge: { 'WWW-Authenticate': 'ApiKey' },
  verify(request) {
    const key = request.headers.get('X-Api-Key')
    if (!key) return undefined
    const identity = customers.get(key)
    if (!identity) throw new Identity.Rejection('Unknown API key.', { status: 'forbidden' })
    return identity
  },
})
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })
export const handler = mppx.charge({ amount: '0.05', identity: [customer] })
```

#### Identity provider details

* **No credential:** return `undefined` or `null`. The caller gets a `401`.
* **Rejected credential:** throw [`Identity.Rejection`](/sdk/typescript/core/Identity.Rejection) with `status` `invalid` (`401`), `forbidden` (`403`), or `unavailable` (`503`). Other errors propagate.
* **Reading the identity:** use `result.identity?.get(customer)` in a successful handler.
* **Combining with email:** `identity: [Identity.anyOf(email, customer)]` accepts either; a plain list requires both.

### Build your own protocol

Third-party identity protocols implement the `Identity.Verifier` and `Identity.Prover` types from `mppx/identity`.

* **Verifier:** set `authorization: true` if it reads `Authorization`, and create the server with `requiresAuth: true`. `verify(request)` returns `{ status: 'valid', value }` or a [rejection status](/extensions/identity#how-identity-checks-run) with a `reason` and optional `headers`.
* **Prover:** `prove(request, context)` returns the proved request for origins in `scope`. `context` has a fresh nonce, a timestamp, and on a paid retry the Challenge.
* **`prepare`** (optional): runs on a `402` before the paid retry. Its `requirements` list the 402's `Identity-Required` entries.
* **`retry`** (optional): returns headers to resend a rejected non-402 request once. Paid attempts are never resent.
* **`headers`** (optional): sensitive request headers stripped on cross-origin redirects. Remove custom proof headers yourself when forwarding upstream.

```ts twoslash [identity.ts]
import type * as Identity from 'mppx/identity'

declare function signRequest(request: Request, context: Identity.ProveContext): Promise<Request>

export const prover: Identity.Prover = {
  // [!code hl:start]
  prove: (request, context) => signRequest(request, context),
  scope: ['https://api.example.com'],
  // [!code hl:end]
}
```

Outside `Mppx.create`, wrap any Fetch implementation with `Identity.Client.wrapFetch`. Prefer `Mppx.create({ identity })`, which also passes the payment Challenge to provers.

```ts twoslash [client.ts]
import * as Identity from 'mppx/identity'

declare const prover: Identity.Prover

const fetch = Identity.Client.wrapFetch(
  globalThis.fetch,
  Identity.Client.from([prover]),
)

await fetch('https://api.example.com/resource')
```

## Payer identity

The Credential's optional `source` is a DID naming the payer's key, not a raw public key. Tempo verifies the Credential's signature or transaction against this identity. After the payment method verifies it, read `source` with `Credential.fromRequest`. Parsing alone doesn't verify identity. [Zone payments](/guides/private-payments) use a private payment environment whose Credentials omit `source`, so they require separate request authentication:

```ts twoslash [server.ts]
// @noEmit
declare const request: Request
// ---cut---
import { Credential } from 'mppx'

const credential = Credential.fromRequest(request)
const clientIdentity = credential.source
// @log: "did:pkh:eip155:42431:0x1234..."
```

The examples below use a Tempo method that authenticates `source`, with Zone payments disabled. Unresolved job, dataset, and pipeline helpers are application code, not SDK functions.

### Zero-dollar auth

Zero-dollar auth uses the standard Challenge → Credential flow with the amount set to `0`. The client signs the Challenge to prove key ownership. No funds move on-chain, and no additional protocol extensions are required.

For Tempo charge, zero-dollar auth uses a `proof` Credential payload instead of a real transaction. The client signs a proof message over the Challenge ID, and the server verifies that signature against the `source` DID. Set the server `realm` to its public hostname. If it differs, clients must pin the realm to that origin with `trustedTempoProofRealms` before signing.

:::warning[Replay protection]
By default, a valid zero-dollar proof remains reusable until the Challenge expires. Pass a `store` to `tempo.charge()` when you want single-use proof auth. In a multi-instance deployment, use a shared store so every instance sees consumed proofs.
:::

```mermaid
sequenceDiagram
  participant Client
  participant Server
  Client->>Server: (1) GET /resource
  Server-->>Client: (2) 402 + Challenge (amount: 0)
  Note over Client: (3) Sign proof message
  Client->>Server: (4) GET /resource + Credential
  Note over Server: (5) Verify proof
  Server-->>Client: (6) 200 OK

```

The proof Credential contains the client's `source` DID and a signature, giving the server a verified payer identity to associate with the request.

For Tempo, the server rejects `transaction` and `hash` payloads for zero-amount Challenges and requires `proof`.

The client refuses to sign a zero-amount proof when the Challenge realm differs from the hostname of the server that sent it, so another origin can't relay the Challenge and replay the proof. Set the server's `realm` to its public hostname, or pin a different realm on the client with [`trustedTempoProofRealms`](/sdk/typescript/client/Mppx.create#trustedtempoproofrealms-optional).

#### Case study: long-running jobs

A service accepts a paid request to start work, then lets the client poll for results using zero-dollar auth. The server keys workloads on the client's verified `source` DID.

:::steps
##### Client submits a job (paid)

The client sends a request with payment to create a new job. The Credential includes payment proof and the client's `source` DID.

```ts twoslash [client.ts]
// @noEmit
declare const fetch: (url: string) => Promise<{ json(): Promise<any> }>
// ---cut---
const response = await fetch('https://api.example.com/v1/jobs')
const { jobId } = await response.json()
// @log: { jobId: "abc123" }
```

The server records the job and associates it with the verified `source` DID from the Credential.

##### Server stores the payer identity

After the payment middleware verifies the Credential, extract the client's verified payer identity from the request:

```ts [server.ts]
import { Credential } from 'mppx'

export async function handler(request: Request) {
  const result = await mppx.charge({ amount: '1.00' })(request)
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  // [!code hl:start]
  const payer = credential.source
  const jobId = createJob({ owner: payer })
  // [!code hl:end]

  return result.withReceipt(Response.json({ jobId }))
}
```

##### Client polls for status (zero-dollar auth)

The client polls the job endpoint. The server issues a zero-dollar Challenge—the client signs it to prove they own the same key.

```ts [server.ts]
export async function statusHandler(request: Request) {
  const result = await mppx.charge({ amount: '0' })(request) // [!code hl]
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  const job = getJob(jobIdFromUrl(request))

  if (job.owner !== credential.source) {
    return Response.json({ error: 'Not your job' }, { status: 403 })
  }

  return result.withReceipt(Response.json({ result: job.result, status: job.status }))
}
```
:::

#### Case study: paid unlock with free access

A service charges once to unlock a resource, then grants repeated free access tied to the client's identity. This replaces API keys with cryptographic ownership.

:::steps
##### Client pays to unlock

The client pays once to gain access. The server records the verified payer DID as an authorized user.

```ts [server.ts]
export async function unlockHandler(request: Request) {
  const result = await mppx.charge({ amount: '50.00' })(request)
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  grantAccess({ dataset: 'premium', owner: credential.source }) // [!code hl]

  return result.withReceipt(Response.json({ status: 'unlocked' }))
}
```

##### Client accesses the resource (zero-dollar auth)

Subsequent requests use zero-dollar auth. The server checks the client's identity against the access list.

```ts [server.ts]
export async function accessHandler(request: Request) {
  const result = await mppx.charge({ amount: '0' })(request) // [!code hl]
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  if (!hasAccess({ dataset: 'premium', owner: credential.source })) {
    return Response.json({ error: 'Not unlocked' }, { status: 403 })
  }

  return result.withReceipt(Response.json({ data: getDataset('premium') }))
}
```
:::

#### Case study: multi-step agent workflow

An agent orchestrates a pipeline where one paid step kicks off several follow-up steps that only need identity. Each step verifies the same payer DID to maintain continuity across the workflow.

:::steps
##### Agent starts the pipeline (paid)

The agent pays to kick off generation. The server returns a pipeline ID tied to the agent's verified payer DID.

```ts [server.ts]
export async function createPipelineHandler(request: Request) {
  const result = await mppx.charge({ amount: '5.00' })(request)
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  const pipelineId = createPipeline({ owner: credential.source }) // [!code hl]

  return result.withReceipt(Response.json({ pipelineId }))
}
```

##### Agent retrieves intermediate results (zero-dollar auth)

The agent polls each stage of the pipeline. Every request proves the same identity without additional payment.

```ts [server.ts]
export async function stageHandler(request: Request) {
  const result = await mppx.charge({ amount: '0' })(request) // [!code hl]
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  const pipeline = getPipeline(pipelineIdFromUrl(request))

  if (pipeline.owner !== credential.source) {
    return Response.json({ error: 'Not your pipeline' }, { status: 403 })
  }

  const stage = pipeline.stages[stageFromUrl(request)]
  return result.withReceipt(Response.json({ output: stage.output, status: stage.status }))
}
```

##### Agent downloads the final artifact (zero-dollar auth)

The final download also uses zero-dollar auth—the server already collected payment at the start.

```ts [server.ts]
export async function resultHandler(request: Request) {
  const result = await mppx.charge({ amount: '0' })(request) // [!code hl]
  if (result.status === 402) return result.challenge

  const credential = Credential.fromRequest(request)
  const pipeline = getPipeline(pipelineIdFromUrl(request))

  if (pipeline.owner !== credential.source) {
    return Response.json({ error: 'Not your pipeline' }, { status: 403 })
  }

  return result.withReceipt(Response.json({ result: pipeline.finalResult }))
}
```
:::

### Check the payer before settlement

Experimental

A payment check verifies the payer on the paid retry, after the Credential is checked and before it settles. Pass it as `identity: { payment }`; request verifiers go under `request`.

```ts twoslash [server.ts]
import type * as Identity from 'mppx/identity'
import { Mppx, tempo } from 'mppx/server'

declare const allowedPayers: ReadonlySet<string>

// [!code hl:start]
const allowlist: Identity.PaymentCheck<{ payer: string }> = {
  requires: [{ issuer: 'https://kyc.example.com', type: 'kyc' }],
  verify({ credential }) {
    const payer = credential?.source
    if (!payer) return { reason: 'The Credential names no payer.', status: 'missing' }
    if (!allowedPayers.has(payer))
      return { reason: 'This payer is not allowed.', status: 'forbidden' }
    return { status: 'valid', value: { payer } }
  },
}
// [!code hl:end]
const mppx = Mppx.create({ methods: [tempo.charge({ testnet: true })] })
export const handler = mppx.charge({ amount: '0.05', identity: { payment: allowlist } }) // [!code hl]
```

* Every `402` for the route lists `requires` in an `Identity-Required` header, such as `kyc;issuer="https://kyc.example.com"`.
* `verify` runs once on the paid retry. A rejection gets its fixed status code with no fresh Challenge, because the client may already have pushed the payment.
* `credential.source` is the client's claim. Tempo transaction and hash Credentials reject a `source` that doesn't match the payer, unless [`validateSender`](/sdk/typescript/server/Method.tempo.charge#validatesender-optional) accepts another sender; Zone Credentials don't check it. Don't allowlist by `source` on routes that accept `zones` or set `validateSender`.
* Routes with a payment check reject x402 Credentials and don't offer x402. Composed offers must share the same check.
* The API may change in any release.
