---
title: "Verifier code"
description: "The whole runnable verifier, with its tests: copy it, run it, and compare your output."
url: https://app.visacli.sh/docs/verifier-code
updated: 2026-11-20
---

# Verifier code

> The whole runnable verifier, with its tests: copy it, run it, and compare your output.

Canonical: https://app.visacli.sh/docs/verifier-code. Updated: 2026-11-20. Full index: /llms.txt.

All the code behind [Verify a signed request](/docs/verify-a-signed-request.md), in Node 22 with no dependencies. This is Visa CLI's example verifier, published by the Visa CLI team for Visa CLI's profile of TAP. It isn't a verifier Visa publishes, so call it Visa CLI's example verifier in your own docs and code. There's no installable package, so you copy these files. The verifier passes every case in the [test vectors](/docs/conformance.md).

<a id="the-example"></a>

## Copy the verifier

Each file on this page is also a download, so you can fetch it with one `curl` instead of copying it: [verify-agent.mjs](/examples/verify-agent.mjs), [accepted-trids.mjs](/examples/accepted-trids.mjs), [sign.mjs](/examples/sign.mjs) and, for Python, [verify_agent.py](/examples/verify_agent.py), [accepted_trids.py](/examples/accepted_trids.py) and [sign.py](/examples/sign.py). [verify-example.zip](/examples/verify-example.zip) has all of them with their tests.

The runnable verifier is three files. Save them in one folder, with Node 22.

```js title="verify-agent.mjs"
import { createHash, createPublicKey, verify } from 'node:crypto'

const REASONS = {
  no_signature_headers: ['tap_missing', 'The request has no Signature-Input and Signature headers.'],
  signature_input_format: ['tap_malformed', 'Signature-Input must be label sig2, then the covered components, created, expires, keyid, alg, nonce and tag="agent-browser-auth", in that order. The nonce is 32 bytes of base64.'],
  signature_header_format: ['tap_malformed', 'Signature must be sig2=:<base64>:.'],
  components_invalid: ['tap_malformed', 'The covered components are unreadable or repeated.'],
  directory_components_missing: ['tap_malformed', 'A key named by directory ID must also cover @query, accept and content-type when sent.'],
  required_components_missing: ['tap_malformed', 'The signature must cover @method, @scheme, @authority, @path, @query and content-digest first, in that order.'],
  credential_header_present: ['tap_malformed', 'Authorization, Cookie, X-Payment and Payment-Signature are refused. Authenticate first and remove them before this check.'],
  method_not_allowed: ['tap_malformed', 'Only GET, HEAD and POST can be signed.'],
  signed_header_invalid: ['tap_malformed', 'A covered header is out of order, absent, starts or ends with a space, is not printable ASCII, is over 4096 characters, or is one this profile never signs, such as Origin, Host or X-Forwarded-For. At most 38 components and 16384 characters of signed headers.'],
  uncovered_header: ['tap_malformed', 'The request carries a header the signature does not cover. Only transport headers may go unsigned.'],
  nonce_format: ['tap_malformed', 'The nonce must be exactly 32 bytes of canonical base64.'],
  body_too_large: ['tap_malformed', 'The body is over 1 MiB.'],
  digest_format: ['tap_malformed', 'Content-Digest must be sha-256=:<base64>:.'],
  not_yet_valid: ['tap_expired', 'The signature was created in the future. Check the clock.'],
  expired: ['tap_expired', 'The signature has expired. Sign a new request.'],
  lifetime_too_long: ['tap_expired', 'The signature lives longer than 60 seconds.'],
  nonce_reused: ['tap_replayed', 'This key and nonce were already used. Sign a new request.'],
  key_not_listed: ['tap_key_unknown', 'This key has no live listing. It may be unknown, paused or revoked; the registry does not say which.'],
  agent_not_live: ['tap_key_inactive', 'The registry reports this agent as not live.'],
  key_not_live: ['tap_key_inactive', "This key is not one of the agent's live keys: it was replaced, or its expirationDate has passed."],
  body_digest_mismatch: ['tap_signature_invalid', 'The body does not match the signed Content-Digest. Digest the raw bytes, before anything parses them.'],
  signature_mismatch: ['tap_signature_invalid', 'The signature does not verify for this exact request. Check that your pinned origin is what the agent signed for.'],
  algorithm_mismatch: ['tap_signature_invalid', "The signature's alg is not the algorithm of the listed key."],
  signature_agent_not_accepted: ['tap_signature_agent_not_accepted', 'Signature-Agent is not on your allowlist.'],
  signature_agent_other_directory: ['tap_signature_agent_not_accepted', 'Signature-Agent names a different directory from the one this verifier reads.'],
  key_not_in_directory: ['tap_key_unknown', "Visa's directory names keys by UUID, and this keyid is a thumbprint."],
  simulated_listing: ['tap_simulated_not_accepted', 'This key belongs to a simulated test listing, which this verifier does not accept.'],
  listing_unusable: ['tap_trust_invalid', 'The registry returned an unusable answer. The agent has not been judged.'],
  registry_unavailable: ['tap_trust_unavailable', 'The registry could not be reached. The agent has not been judged; retry later.'],
  nonce_store_unavailable: ['tap_trust_unavailable', 'The nonce store could not be reached. The agent has not been judged; retry later.'],
  request_target_invalid: ['tap_malformed', 'The request target is not in normal form: it does not start with a single /, or it has dot segments, encoded dots, slashes or backslashes, a fragment, or does not parse. The signature covers the host and path exactly, so it is refused rather than normalized.'],
  request_unreadable: ['tap_malformed', 'The request could not be read.'],
  origin_not_https: ['tap_malformed', 'The pinned public origin is not https. Agents only sign https URLs, so pin an https origin.'],
  origin_not_normal: ['tap_malformed', 'The pinned public origin is not in normal form: write the host in lowercase, as plain DNS labels or an IP address, with no default port, trailing dot or trailing slash, such as https://market.example. pinnedOrigin() does this for you.'],
}
const COULD_NOT_CHECK = new Set(['tap_trust_invalid', 'tap_trust_unavailable'])

function refusal(reason, retryAfterSeconds = null, header = null) {
  const [code, message] = REASONS[reason]
  const judged = !COULD_NOT_CHECK.has(code)
  return { ok: false, code, reason, message: header ? `${message} Header: ${header}.` : message, judged, status: judged ? 403 : 503, retryAfterSeconds, ...(header ? { header } : {}) }
}

export function pinnedOrigin(value) {
  let url = null
  try {
    url = new URL(value)
  } catch {}
  if (!url || /[^\x21-\x7e]|[?#]$/.test(value) || url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password || !HOST.test(url.host)) {
    throw new Error(`The public origin must be an https origin with a plain host name and no path, such as https://market.example. Got: ${value}`)
  }
  return url.origin
}

export function registryOriginFrom(value) {
  let url = null
  try {
    url = new URL(value)
  } catch {}
  const loopback = url && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
  if (!url || /[^\x21-\x7e]/.test(value) || !(url.protocol === 'https:' || (url.protocol === 'http:' && loopback)) || url.pathname !== '/' || url.search || url.hash || url.username || url.password) {
    throw new Error(`The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1]. Got: ${value}`)
  }
  return url.origin
}

const INPUT = /^sig2=\(([^)]+)\);created=(\d+);expires=(\d+);keyid="([A-Za-z0-9_-]{43}|[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})";alg="(ed25519|Ed25519|ecdsa-p256-sha256)";nonce="([A-Za-z0-9+/]{43}=)";tag="agent-browser-auth"$/
const SIGNATURE = /^sig2=:((?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=):$/
const CORE = ['@method', '@scheme', '@authority', '@path', '@query', 'content-digest']
export const TRANSPORT_HEADERS = new Set([
  'host', 'content-length', 'connection', 'transfer-encoding', 'keep-alive', 'accept', 'accept-language', 'accept-encoding', 'user-agent',
  'forwarded', 'via', 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-ssl', 'x-real-ip',
  'true-client-ip', 'cdn-loop', 'traceparent', 'tracestate', 'x-request-id', 'x-amzn-trace-id', 'x-cloud-trace-context',
  'b3', 'x-b3-traceid', 'x-b3-spanid', 'x-b3-parentspanid', 'x-b3-sampled',
  'cf-ray', 'cf-connecting-ip', 'cf-connecting-ipv6', 'cf-pseudo-ipv4', 'cf-connecting-o2o', 'cf-ew-via', 'cf-worker', 'cf-visitor',
  'cf-ipcountry', 'cf-ipcity', 'cf-ipcontinent', 'cf-iplatitude', 'cf-iplongitude', 'cf-region', 'cf-region-code', 'cf-metro-code',
  'cf-postal-code', 'cf-timezone',
  'x-vercel-id', 'x-vercel-forwarded-for', 'x-vercel-deployment-url', 'x-vercel-ip-continent', 'x-vercel-ip-country',
  'x-vercel-ip-country-region', 'x-vercel-ip-city', 'x-vercel-ip-latitude', 'x-vercel-ip-longitude', 'x-vercel-ip-timezone',
  'x-vercel-ip-postal-code',
  'fly-client-ip', 'fly-forwarded-port', 'fly-region', 'fly-request-id',
  'signature', 'signature-input', 'content-digest',
])
const CREDENTIALS = ['authorization', 'cookie', 'x-payment', 'payment-signature']
const NEVER_SIGNED = new Set([
  'authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'host', 'connection', 'content-length', 'transfer-encoding', 'te',
  'trailer', 'upgrade', 'keep-alive', 'expect', 'via', 'forwarded', 'origin', 'referer', 'content-digest', 'signature', 'signature-input',
  'agent-payer-auth', 'payment', 'payment-signature', 'payment-required', 'payment-receipt', 'payment-response',
])
const NEVER_SIGNED_PREFIX = /^(?:proxy-|sec-|x-forwarded-|x-visa(?:$|-)|x-stamp(?:$|-)|x-payment(?:$|-))/
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]{1,128}$/
const HOST = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:]+\])(?::[1-9][0-9]{0,4})?$/
const DIGEST = /^sha-256=:[A-Za-z0-9+/]+={0,2}:$/
const MAX_LIFETIME_SECONDS = 60
const CLOCK_SKEW_SECONDS = 30
export const MAX_BODY_BYTES = 1024 * 1024

function originIsNormal(publicOrigin) {
  try {
    return new URL(publicOrigin).origin === publicOrigin && HOST.test(publicOrigin.slice('https://'.length))
  } catch {
    return false
  }
}

const EXPIRY = /^([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:[Zz]|([+-])([0-9]{2}):([0-9]{2}))$/

function expirySeconds(value) {
  const found = typeof value === 'string' ? EXPIRY.exec(value) : null
  if (!found) return null
  const [year, month, day, hour, minute, second] = found.slice(1, 7).map(Number)
  const [offsetHours, offsetMinutes] = [Number(found[9] ?? 0), Number(found[10] ?? 0)]
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
  const monthDays = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
  if (!monthDays || day < 1 || day > monthDays || hour > 23 || minute > 59 || second > 59 || offsetHours > 23 || offsetMinutes > 59) return null
  const y = month <= 2 ? year - 1 : year
  const era = Math.floor(y / 400)
  const yearOfEra = y - era * 400
  const dayOfYear = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1
  const days = era * 146097 + yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear - 719468
  const offset = (found[8] === '-' ? -1 : 1) * (offsetHours * 3600 + offsetMinutes * 60)
  return days * 86400 + hour * 3600 + minute * 60 + second - offset + Number((found[7] ?? '').slice(0, 3).padEnd(3, '0')) / 1000
}

function normalTarget(publicOrigin, target) {
  if (typeof target !== 'string' || !target.startsWith('/') || target.startsWith('//') || target.split('?')[0].includes('^')) return null
  if (target.split('?')[0].split('/').some((segment) => segment === '.' || segment === '..')) return null
  let url
  try {
    url = new URL(`${publicOrigin}${target}`)
  } catch {
    return null
  }
  if (url.origin !== publicOrigin || `${url.pathname}${url.search}` !== target) return null
  if (/%2e|%2f|%5c/i.test(url.pathname)) return null
  return url
}

export function readBody(req, maxBytes = MAX_BODY_BYTES) {
  return new Promise((resolve) => {
    const chunks = []
    let size = 0
    let tooLarge = Number(req.headers['content-length']) > maxBytes
    let done = false
    const finish = (answer) => {
      if (done) return
      done = true
      resolve(answer)
    }
    req.on('data', (chunk) => {
      size += chunk.length
      if (size > maxBytes) tooLarge = true
      if (size > maxBytes * 4) {
        req.pause()
        return finish({ tooLarge: true })
      }
      if (!tooLarge) chunks.push(chunk)
    })
    req.on('end', () => finish(tooLarge ? { tooLarge: true } : { body: Buffer.concat(chunks) }))
    req.on('error', () => finish({ aborted: true }))
    req.on('close', () => finish({ aborted: true }))
  })
}

export function requestHeaders(req) {
  return Object.fromEntries(Object.entries(req.headersDistinct).map(([name, values]) => [name, values.join(', ')]))
}

function thumbprint(publicKey) {
  const { kty, crv, x, y } = publicKey.export({ format: 'jwk' })
  const members = kty === 'EC' ? { crv, kty, x, y } : { crv: 'Ed25519', kty: 'OKP', x }
  return createHash('sha256').update(JSON.stringify(members)).digest('base64url')
}

function readListing(keyId, doc) {
  if (typeof doc?.id !== 'string' || typeof doc.name !== 'string' || typeof doc.isActive !== 'boolean' || !Array.isArray(doc.keys)) return null
  for (const key of doc.keys) {
    if (typeof key?.publicKey !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(key.jkt) || key.agentId !== doc.id) return null
    if (key.status !== 'active' || key.algorithm !== 'ed25519') return null
    if (key.expirationDate != null && expirySeconds(key.expirationDate) === null) return null
  }
  const key = keyId === undefined ? null : doc.keys.find((k) => k.id === keyId || k.jkt === keyId)
  if (!key) return { agent: doc }
  const publicKey = createPublicKey(Buffer.from(key.publicKey, 'base64').toString('utf8'))
  if (publicKey.asymmetricKeyType !== 'ed25519') return null
  const { kty, crv } = publicKey.export({ format: 'jwk' })
  if (kty !== 'OKP' || crv !== 'Ed25519') return null
  return { agent: doc, key, publicKey, algorithm: 'ed25519', thumbprint: thumbprint(publicKey) }
}

const P256_ALGORITHMS = ['ecdsa-p256', 'ecdsa-p256-sha256', 'es256', 'p-256']

function directoryJwk(algorithm, jwk) {
  const coordinate = (value) => typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value)
  if (['ed25519', 'Ed25519'].includes(algorithm) && jwk?.kty === 'OKP' && jwk.crv === 'Ed25519' && coordinate(jwk.x)) return ['ed25519', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }]
  if (typeof algorithm === 'string' && P256_ALGORITHMS.includes(algorithm.toLowerCase()) && jwk?.kty === 'EC' && jwk.crv === 'P-256' && coordinate(jwk.x) && coordinate(jwk.y)) return ['ecdsa-p256-sha256', { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y }]
  return null
}

function readDirectoryEntry(keyId, doc) {
  const key = doc?.key
  if (typeof doc?.agent?.name !== 'string' || typeof key?.id !== 'string' || key.status !== 'active') return null
  const usable = directoryJwk(key.algorithm, key.publicKeyJwk)
  if (!usable) return null
  if (key.id !== keyId || (key.expirationDate != null && expirySeconds(key.expirationDate) === null)) return null
  const publicKey = createPublicKey({ key: usable[1], format: 'jwk' })
  const computed = thumbprint(publicKey)
  const agent = { id: null, name: doc.agent.name, isActive: true, tokenRequestorId: typeof doc.agent.tokenRequestorId === 'string' ? doc.agent.tokenRequestorId : null }
  return { agent, key: { id: key.id, jkt: computed, expirationDate: key.expirationDate ?? null }, publicKey, algorithm: usable[0], thumbprint: computed }
}

function signatureVerifies(found, base, signature) {
  if (found.algorithm === 'ecdsa-p256-sha256') return signature.length === 64 && verify('sha256', base, { key: found.publicKey, dsaEncoding: 'ieee-p1363' }, signature)
  return verify(null, base, found.publicKey, signature)
}

export async function readKey(registryOrigin, keyId, fetchImpl = fetch) {
  return readRegistry(`${registryOriginFrom(registryOrigin)}/v1/tap/registry/keys/${encodeURIComponent(keyId)}`, (doc) => readListing(keyId, doc), fetchImpl)
}

export async function readAgent(registryOrigin, agentId, fetchImpl = fetch) {
  return readRegistry(`${registryOriginFrom(registryOrigin)}/v1/tap/registry/agents/${encodeURIComponent(agentId)}`, (doc) => readListing(undefined, doc), fetchImpl)
}

export async function readDirectoryKey(directoryOrigin, keyId, fetchImpl = fetch) {
  return readRegistry(`${registryOriginFrom(directoryOrigin)}/.well-known/jwks/keys/${encodeURIComponent(keyId)}`, (doc) => readDirectoryEntry(keyId, doc), fetchImpl)
}

export async function readOwnKey(keyId, lookupKey) {
  let found
  try {
    found = await lookupKey(keyId)
  } catch {
    return { unavailable: true, retryAfterSeconds: null }
  }
  if (found == null) return { notListed: true }
  if (found.unavailable === true) return { unavailable: true, retryAfterSeconds: null }
  const usable = typeof found.name === 'string' ? directoryJwk(found.algorithm, found.publicKeyJwk) : null
  if (!usable) return { invalid: true }
  let publicKey
  let computed
  try {
    publicKey = createPublicKey({ key: usable[1], format: 'jwk' })
    computed = thumbprint(publicKey)
  } catch {
    return { invalid: true }
  }
  return { listed: true, agent: { id: null, name: found.name, isActive: true, tokenRequestorId: null }, key: { id: keyId, jkt: computed, expirationDate: null }, publicKey, algorithm: usable[0], thumbprint: computed }
}

export function judgeKey(keyId, answer, { acceptSimulated = false, now = Math.floor(Date.now() / 1000) } = {}) {
  if (answer.unavailable) return refusal('registry_unavailable', answer.retryAfterSeconds)
  if (answer.invalid) return refusal('listing_unusable')
  if (answer.notListed) return refusal('key_not_listed')
  if (answer.agent.simulated === true && !acceptSimulated) return refusal('simulated_listing')
  if (!answer.agent.isActive) return refusal('agent_not_live')
  if (!answer.key) return refusal('key_not_live')
  const computed = answer.thumbprint
  if (computed !== keyId && (keyId.length !== 36 || answer.key.id !== keyId || answer.key.jkt !== computed)) return refusal('key_not_live')
  if (answer.key.expirationDate != null && expirySeconds(answer.key.expirationDate) <= now) return refusal('key_not_live')
  return null
}

async function readRegistry(url, parse, fetchImpl) {
  let response
  try {
    response = await fetchImpl(url, { redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(5000) })
  } catch {
    return { unavailable: true, retryAfterSeconds: null }
  }
  if (response.status === 404) return { notListed: true }
  if (!response.ok) {
    const retry = response.headers.get('retry-after') ?? ''
    return { unavailable: true, retryAfterSeconds: /^[0-9]+$/.test(retry) && Number(retry) > 0 ? Number(retry) : null }
  }
  try {
    const listing = parse(await response.json())
    return listing ? { listed: true, ...listing } : { invalid: true }
  } catch {
    return { invalid: true }
  }
}

export function createVerifier({
  registryOrigin,
  directoryOrigin,
  allowedSignatureAgents = ['"https://sbx.agenticdirectory.visa.com"', '"https://agenticdirectory.visa.com"'],
  acceptSimulated = false,
  reserveNonce,
  now = () => Math.floor(Date.now() / 1000),
  fetchImpl = fetch,
  cacheSeconds = 60,
  extraTransportHeaders = [],
  lookupKey,
}) {
  const directory = !lookupKey && directoryOrigin ? registryOriginFrom(directoryOrigin) : null
  const registry = directory || lookupKey ? null : registryOriginFrom(registryOrigin)
  const cache = new Map()

  async function lookup(keyId, { fresh = false } = {}) {
    const hit = cache.get(keyId)
    if (!fresh && hit && hit.until > now()) return hit.answer
    const answer = lookupKey ? await readOwnKey(keyId, lookupKey) : directory ? await readDirectoryKey(directory, keyId, fetchImpl) : await readKey(registry, keyId, fetchImpl)
    if (answer.unavailable || answer.invalid) return answer
    cache.delete(keyId)
    if (answer.listed && answer.agent.isActive && answer.key) cache.set(keyId, { answer, until: now() + cacheSeconds })
    return answer
  }

  const judge = (keyId, answer) => judgeKey(keyId, answer, { acceptSimulated, now: now() })
  const transportHeaders = new Set([...TRANSPORT_HEADERS, ...extraTransportHeaders.map((name) => name.toLowerCase())])

  return async function verifyRequest(request) {
    try {
      return await check(request)
    } catch {
      return refusal('request_unreadable')
    }
  }

  async function check({ method, publicOrigin, target, headers, rawBody }) {
    const input = headers['signature-input']
    const signatureHeader = headers['signature']
    if (!input || !signatureHeader) return refusal('no_signature_headers')
    const parsed = INPUT.exec(input)
    if (!parsed) return refusal('signature_input_format')
    const signed = SIGNATURE.exec(signatureHeader)
    if (!signed) return refusal('signature_header_format')

    const parts = parsed[1].trim().split(/\s+/)
    if (!parts.every((part) => /^"[^"]+"$/.test(part))) return refusal('components_invalid')
    const components = parts.map((part) => part.slice(1, -1).toLowerCase())
    if (new Set(components).size !== components.length) return refusal('components_invalid')

    const created = Number(parsed[2])
    const expires = Number(parsed[3])
    const keyId = parsed[4]
    const alg = parsed[5] === 'ecdsa-p256-sha256' ? 'ecdsa-p256-sha256' : 'ed25519'
    const nonce = parsed[6]
    if (!String(publicOrigin).startsWith('https://')) return refusal('origin_not_https')
    if (!originIsNormal(publicOrigin)) return refusal('origin_not_normal')
    const url = normalTarget(publicOrigin, target)
    if (!url) return refusal('request_target_invalid')
    if (keyId.length === 36) {
      const needed = [...(url.search ? ['@query'] : []), ...['accept', 'content-type'].filter((name) => headers[name] !== undefined)]
      if (needed.some((name) => !components.includes(name))) return refusal('directory_components_missing')
    }

    const t = now()
    if (created > t + CLOCK_SKEW_SECONDS) return refusal('not_yet_valid')
    if (expires <= t || expires <= created) return refusal('expired')
    if (expires - created > MAX_LIFETIME_SECONDS) return refusal('lifetime_too_long')

    if (JSON.stringify(components.slice(0, CORE.length)) !== JSON.stringify(CORE)) return refusal('required_components_missing')
    if (!['GET', 'HEAD', 'POST'].includes(method)) return refusal('method_not_allowed')
    if (CREDENTIALS.some((name) => headers[name] !== undefined)) return refusal('credential_header_present')

    if (components.length > 38) return refusal('signed_header_invalid')
    let previous = ''
    let size = 0
    for (const name of components.slice(CORE.length)) {
      const value = headers[name]
      if (!HEADER_NAME.test(name) || name <= previous || typeof value !== 'string' || value.trim() !== value || value.length > 4096 || /[^\x20-\x7e]/.test(value)) return refusal('signed_header_invalid')
      if (NEVER_SIGNED.has(name) || NEVER_SIGNED_PREFIX.test(name)) return refusal('signed_header_invalid')
      previous = name
      size += name.length + value.length
    }
    if (size > 16384) return refusal('signed_header_invalid')
    for (const name of Object.keys(headers)) {
      const transport = transportHeaders.has(name) || name.startsWith('sec-fetch-')
      if (!components.includes(name) && !transport) return refusal('uncovered_header', null, name)
    }
    if (Buffer.from(nonce, 'base64').toString('base64') !== nonce) return refusal('nonce_format')

    if (rawBody.length > MAX_BODY_BYTES) return refusal('body_too_large')
    if (!DIGEST.test(headers['content-digest'] ?? '')) return refusal('digest_format')
    const digest = `sha-256=:${createHash('sha256').update(rawBody).digest('base64')}:`
    if (headers['content-digest'] !== digest) return refusal('body_digest_mismatch')

    const signatureAgent = headers['signature-agent']
    if (signatureAgent !== undefined && !allowedSignatureAgents.includes(signatureAgent)) return refusal('signature_agent_not_accepted')
    if (directory && keyId.length !== 36) return refusal('key_not_in_directory')
    if (directory && signatureAgent !== undefined && signatureAgent !== `"${directory}"`) return refusal('signature_agent_other_directory')

    let found = await lookup(keyId)
    let refused = judge(keyId, found)
    if (refused) return refused

    const derived = { '@method': method, '@scheme': 'https', '@authority': url.host, '@path': url.pathname || '/', '@query': url.search || '?' }
    const lines = components.map((name) => `"${name}": ${name.startsWith('@') ? derived[name] : headers[name]}`)
    lines.push(`"@signature-params": ${input.slice('sig2='.length)}`)
    const base = Buffer.from(lines.join('\n'), 'utf8')
    const signature = Buffer.from(signed[1], 'base64')

    if (found.algorithm !== alg || !signatureVerifies(found, base, signature)) {
      found = await lookup(keyId, { fresh: true })
      refused = judge(keyId, found)
      if (refused) return refused
      if (found.algorithm !== alg) return refusal('algorithm_mismatch')
      if (!signatureVerifies(found, base, signature)) return refusal('signature_mismatch')
    }

    let reserved
    try {
      reserved = await reserveNonce(`${keyId}:${nonce}`, expires)
    } catch {
      return refusal('nonce_store_unavailable')
    }
    if (!reserved) return refusal('nonce_reused')

    return { ok: true, keyId, jkt: found.key.jkt, agentId: found.agent.id, agentName: found.agent.name, simulated: found.agent.simulated === true, covered: components, expires, ...(directory ? { tokenRequestorId: found.agent.tokenRequestorId } : {}), ...(lookupKey ? { selfKey: true } : {}) }
  }
}

export function memoryNonceStore(now = () => Math.floor(Date.now() / 1000)) {
  const seen = new Map()
  return async (id, expires) => {
    for (const [key, until] of seen) if (until <= now()) seen.delete(key)
    if (seen.has(id)) return false
    seen.set(id, expires)
    return true
  }
}
```

The second is a small endpoint that uses it. It passes the headers through `requestHeaders(req)`, which keeps every value of a repeated header, joined with commas. Node's own `req.headers` keeps only the first `Content-Type` and drops the rest, so a second, unsigned value would never reach the check. With every value kept, the joined value no longer matches what the agent signed, and the request is refused, as `server.py` does.

```js title="server.mjs"
import { createServer } from 'node:http'
import { createVerifier, memoryNonceStore, pinnedOrigin, readBody, requestHeaders } from './verify-agent.mjs'

export function startMarketplace({ registryOrigin, directoryOrigin, publicOrigin: configured, port = 0, extraTransportHeaders }) {
  const publicOrigin = pinnedOrigin(configured)
  const verifyRequest = createVerifier({ registryOrigin, directoryOrigin, reserveNonce: memoryNonceStore(), extraTransportHeaders })

  const answer = (res, status, body, headers = {}) => {
    if (res.headersSent || res.destroyed) return
    res.writeHead(status, { 'content-type': 'application/json', ...headers })
    res.end(JSON.stringify(body))
  }

  async function handle(req, res) {
    const read = await readBody(req)
    if (read.aborted) return
    if (read.tooLarge) return answer(res, 413, { ok: false, code: 'body_too_large' }, { connection: 'close' })
    const result = await verifyRequest({
      method: req.method,
      publicOrigin,
      target: req.url,
      headers: requestHeaders(req),
      rawBody: read.body,
    })
    const retry = result.judged === false ? { 'retry-after': String(result.retryAfterSeconds ?? 5) } : {}
    answer(res, result.ok ? 200 : result.status, result, retry)
  }

  const server = createServer((req, res) => {
    handle(req, res).catch(() => answer(res, 500, { ok: false, code: 'internal_error' }))
  })

  return new Promise((resolve) => {
    server.listen(port, '127.0.0.1', () => resolve(server))
  })
}

if (process.argv[1]?.endsWith('server.mjs')) {
  const server = await startMarketplace({
    registryOrigin: process.env.REGISTRY_ORIGIN ?? 'https://auth.visacli.sh',
    directoryOrigin: process.env.DIRECTORY_ORIGIN,
    publicOrigin: process.env.PUBLIC_ORIGIN,
    port: Number(process.env.PORT ?? 8080),
  })
  console.log(`listening on http://127.0.0.1:${server.address().port}`)
}
```

<a id="types"></a>

### Types for TypeScript

`verify-agent.mjs` is plain JavaScript. To use it from TypeScript, save this beside it as `verify-agent.d.mts`, and TypeScript picks it up for imports of `verify-agent.mjs`. It's in [verify-example.zip](/examples/verify-example.zip) too.

```ts title="verify-agent.d.mts"
import type { IncomingMessage } from 'node:http'

export type Refusal = {
  ok: false
  code: string
  reason: string
  message: string
  judged: boolean
  status: 403 | 503
  retryAfterSeconds: number | null
  header?: string
}

export type Verified = {
  ok: true
  keyId: string
  jkt: string
  agentId: string | null
  agentName: string
  simulated: boolean
  covered: string[]
  expires: number
  tokenRequestorId?: string | null
  selfKey?: true
}

export type CheckRequest = {
  method: string
  publicOrigin: string
  target: string
  headers: Record<string, string>
  rawBody: Uint8Array
}

export type ReserveNonce = (id: string, expires: number) => boolean | Promise<boolean>

export type VerifierOptions = {
  registryOrigin?: string
  directoryOrigin?: string
  allowedSignatureAgents?: string[]
  acceptSimulated?: boolean
  reserveNonce: ReserveNonce
  now?: () => number
  fetchImpl?: typeof fetch
  cacheSeconds?: number
  extraTransportHeaders?: string[]
  lookupKey?: (keyId: string) => Promise<OwnKey | { unavailable: true } | null>
}

export type OwnKey = {
  name: string
  algorithm: 'ed25519' | 'ecdsa-p256'
  publicKeyJwk: { kty: 'OKP'; crv: 'Ed25519'; x: string } | { kty: 'EC'; crv: 'P-256'; x: string; y: string }
}

export type Answer = {
  listed?: true
  notListed?: true
  invalid?: true
  unavailable?: true
  retryAfterSeconds?: number | null
  agent?: { id: string | null; name: string; isActive: boolean; simulated?: boolean; tokenRequestorId?: string | null }
  key?: { id: string; jkt: string; expirationDate?: string | null }
  algorithm?: 'ed25519' | 'ecdsa-p256-sha256'
  thumbprint?: string
}

export const TRANSPORT_HEADERS: Set<string>
export const MAX_BODY_BYTES: number
export function pinnedOrigin(value: string): string
export function registryOriginFrom(value: string): string
export function readBody(req: IncomingMessage, maxBytes?: number): Promise<{ body: Buffer } | { tooLarge: true } | { aborted: true }>
export function requestHeaders(req: IncomingMessage): Record<string, string>
export function readKey(registryOrigin: string, keyId: string, fetchImpl?: typeof fetch): Promise<Answer>
export function readAgent(registryOrigin: string, agentId: string, fetchImpl?: typeof fetch): Promise<Answer>
export function readDirectoryKey(directoryOrigin: string, keyId: string, fetchImpl?: typeof fetch): Promise<Answer>
export function readOwnKey(keyId: string, lookupKey: NonNullable<VerifierOptions['lookupKey']>): Promise<Answer>
export function judgeKey(keyId: string, answer: Answer, options?: { acceptSimulated?: boolean; now?: number }): Refusal | null
export function createVerifier(options: VerifierOptions): (request: CheckRequest) => Promise<Verified | Refusal>
export function memoryNonceStore(now?: () => number): ReserveNonce
```

<a id="enabler-agents"></a>

## Read the Visa Agent Directory instead

Visa CLI's agents are listed in Visa CLI's registry, which is what `registryOrigin` reads. Agents that an integrator registers through an enabler, such as Basis Theory, are listed in the Visa Agent Directory instead, so for those, create the verifier with `directoryOrigin` in place of `registryOrigin`:

```js title="Directory mode"
const verifyRequest = createVerifier({
  directoryOrigin: 'https://sbx.agenticdirectory.visa.com',
  reserveNonce: memoryNonceStore(),
})
```

Use `https://sbx.agenticdirectory.visa.com` for the Visa Agent Directory sandbox and `https://agenticdirectory.visa.com` for the Visa Agent Directory (production). No credentials are needed. In Python it's `create_verifier(directory_origin=..., reserve_nonce=...)`, and both servers read `DIRECTORY_ORIGIN`. The verifier reads `GET {directory}/.well-known/jwks/keys/{keyid}`, and every other check stays the same. Reading the Visa Agent Directory, it also:

- refuses a thumbprint `keyid` as `tap_key_unknown`, because the Visa Agent Directory names keys by UUID;
- accepts a request without `Signature-Agent`. When the header is sent, it must be signed and be the quoted origin the verifier reads, so a verifier reading the Visa Agent Directory sandbox refuses an agent that names the Visa Agent Directory, as `tap_signature_agent_not_accepted`;
- takes the key only when `key.id` equals the `keyid` and the key is one of two kinds: `algorithm` is `ed25519` or `Ed25519` with an Ed25519 `publicKeyJwk`, or `algorithm` names P-256, as `ecdsa-p256`, `ecdsa-p256-sha256`, `es256` or `p-256` in any case, with a `publicKeyJwk` of `{"kty":"EC","crv":"P-256","x":...,"y":...}`. Anything else is couldn't check, `tap_trust_invalid`. Agents registered through Basis Theory may sign with P-256 keys, as Basis Theory documents. Basis Theory's guide shows the Visa Agent Directory listing a P-256 key's `algorithm` as `ecdsa-p256-sha256`, and the verifier accepts the other three spellings too;
- verifies a P-256 key's signature as RFC 9421's `ecdsa-p256-sha256`: the signature is the 64 bytes of `r` then `s`, over the SHA-256 of the signature base, and the signature's `alg` is `ecdsa-p256-sha256`. The `alg` has to match the key: a P-256 key with `alg="Ed25519"`, or an Ed25519 key with `alg="ecdsa-p256-sha256"`, is refused as `tap_signature_invalid` with the reason `algorithm_mismatch`. Visa CLI's registry lists only Ed25519 keys, so reading it, an `ecdsa-p256-sha256` signature is always refused that way;
- refuses a key whose RFC 3339 `expirationDate` has passed, as `tap_key_inactive`, and treats a key whose `status` isn't `active` as couldn't check, `tap_trust_invalid`, as registry mode does. The Visa Agent Directory answers `404` for a revoked key, so a `200` that says otherwise is a broken answer, not a judgement on the agent;
- treats `404` as not listed, `tap_key_unknown`, and `5xx`, a timeout or a redirect as couldn't check, `tap_trust_unavailable`.

It doesn't look at `agentType`. Don't gate on it: the check is that the key resolves, which means a registered, active agent. A pass returns `agentId: null`, because the Visa Agent Directory answer has no agent ID, and adds `tokenRequestorId`, the integrator's TRID, which many agents share. This mode accepts a key from any integrator listed in the Visa Agent Directory, and in sandbox anyone can register one. If you accept only some integrators, filter on `tokenRequestorId`, as [Accept only some integrators](#accepted-trids) shows. Bind to the `keyId`. If you accept Visa CLI's agents as well, don't fall back from one source to the other: [Two lookup sources](/docs/marketplace-code.md#two-sources) shows how to choose per request. To test against a local stand-in for the Visa Agent Directory, add its quoted address to `allowedSignatureAgents` in the test only. `directory-fixture.mjs`, printed on [Marketplace code](/docs/marketplace-code.md) and in [marketplace-example.zip](/examples/marketplace-example.zip), does this. This goes for `directoryOrigin` too: a stand-in's origin belongs in test configuration, never in the default. [Where to look up a key](/docs/keys-and-directories.md#enabler-lookup) shows the answer, and the [test vectors](/docs/conformance.md) include cases that read the Visa Agent Directory.

<a id="accepted-trids"></a>

### Accept only some integrators

Reading the Visa Agent Directory, a pass means the key is listed under some integrator's TRID. Which TRID a key carries depends on who registered it: a company's agents carry the TRID its enabler created for it, every Basis Theory test tenant's agents share one sandbox TRID, and Visa CLI's agents each carry a label of their own. So list the TRIDs of the integrators you accept, plus your own only for your own agents. A list that holds only your own TRID refuses everyone else's agents. Every Basis Theory test tenant's agents carry the sandbox TRID `40010092347`, so accepting it accepts anyone who made a test tenant.

What to accept by default:

- **In sandbox,** accept `40010092347`, knowing that means any Basis Theory test tenant's agents, and label those passes as sandbox test agents.
- **In production,** list the integrators whose agents you take, and always your own TRID too: your own house agent carries it, and if you register agents for your users through an enabler, every one of their agents carries it as well. A list without your own TRID refuses your own agents. Never the sandbox TRID.
- **Labelling a production pass,** name the integrator whose TRID the key carries, such as "registered with Visa by Acme". The pass says the key is listed and active under that TRID; what that integrator checked before registering it is theirs to state.
- **Visa CLI's agents** aren't accepted by TRID. Check them through Visa CLI's registry, as [Two lookup sources](/docs/marketplace-code.md#two-sources) shows.

 To accept only the TRIDs you choose, check the pass's `tokenRequestorId` and refuse the rest as `tap_key_unknown`. Do it around the verifier, not inside it, so your copy stays identical to this one and new versions drop straight in. `createTwoSourceVerifier` does the same with `enablerTrids`.

```js title="accepted-trids.mjs"
import { createVerifier } from './verify-agent.mjs'

export function createAcceptedVerifier({ acceptedTrids, ...options }) {
  const verify = createVerifier(options)
  return async (request) => {
    const result = await verify(request)
    if (!result.ok || acceptedTrids.includes(result.tokenRequestorId)) return result
    return { ok: false, code: 'tap_key_unknown', reason: 'trid_not_accepted', message: "The key is listed in Visa's directory under a TRID this service doesn't accept.", judged: true, status: 403, retryAfterSeconds: null }
  }
}
```

With this wrapper, an empty `acceptedTrids` refuses every key. Without the wrapper, `createVerifier` alone accepts any key listed in the Visa Agent Directory, under any TRID, so use it bare only where that's what you mean, such as a sandbox test. A refused TRID still uses up the request's nonce, which is what you want: the same request can't be sent again for a different answer.

## Test it yourself

The third is `fixture.mjs`. It starts a stand-in registry on localhost, signs requests with a key it generates, and sends them to the endpoint. It also signs with a P-256 key it generates and checks those requests against a stand-in answer from the Visa Agent Directory. The stand-ins aren't Visa CLI or Visa, and their answers say nothing about a real agent. If you reuse them in your app's own tests, make their passes recognisable: store the stand-in's origin with each pass and label the agent a test key, never a verified agent. A pass carries `simulated: true` when the stand-in registry marks its listing simulated and you created the verifier with `acceptSimulated: true`. [In your own tests](/docs/build-with-an-enabler.md#sandbox) has the rest.

```js title="fixture.mjs"
import { createHash, generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto'
import { createServer } from 'node:http'
import { connect } from 'node:net'
import { startMarketplace } from './server.mjs'
import { createVerifier, memoryNonceStore } from './verify-agent.mjs'

const PUBLIC_ORIGIN = 'https://market.example'
const { publicKey, privateKey } = generateKeyPairSync('ed25519')
const stranger = generateKeyPairSync('ed25519')
const jwk = publicKey.export({ format: 'jwk' })
const jkt = createHash('sha256')
  .update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: jwk.x }))
  .digest('base64url')
const keyId = randomUUID()
const agentId = randomUUID()

const listing = {
  id: agentId,
  name: 'fixture-agent',
  isActive: true,
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
  keys: [
    {
      id: keyId,
      agentId,
      keyName: jkt,
      status: 'active',
      algorithm: 'ed25519',
      publicKey: Buffer.from(publicKey.export({ type: 'spki', format: 'pem' })).toString('base64'),
      jkt,
      expirationDate: null,
    },
  ],
}

let registryMode = 'listed'
const registry = createServer((req, res) => {
  const id = decodeURIComponent(req.url.split('/').pop())
  if (registryMode === 'down') return res.writeHead(503).end('{"code":"unavailable"}')
  if (registryMode === 'redirect') return res.writeHead(302, { location: `https://elsewhere.example${req.url}` }).end()
  if (registryMode === 'paused' || (id !== keyId && id !== jkt)) {
    return res.writeHead(404).end('{"code":"not_found"}')
  }
  res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'public, max-age=60' })
  res.end(JSON.stringify(listing))
})
await new Promise((resolve) => registry.listen(0, '127.0.0.1', resolve))
const registryOrigin = `http://127.0.0.1:${registry.address().port}`

const market = await startMarketplace({ registryOrigin, publicOrigin: PUBLIC_ORIGIN })

function signedRequest(options = {}) {
  const {
    path = '/tasks/42/claim',
    origin = PUBLIC_ORIGIN,
    body = '{"task":42}',
    id = keyId,
    label = 'sig2',
    signer = privateKey,
    created = Math.floor(Date.now() / 1000),
    lifetime = 60,
    nonce = randomBytes(32).toString('base64'),
    tag = 'agent-browser-auth',
    signatureAgent = '"https://sbx.agenticdirectory.visa.com"',
    alg = 'ed25519',
  } = options
  const url = new URL(`${origin}${path}`)
  const digest = `sha-256=:${createHash('sha256').update(body).digest('base64')}:`
  const app = [
    ['accept', '*/*'],
    ['content-type', 'application/json'],
    ['signature-agent', signatureAgent],
  ]
  const values = [
    ['@method', 'POST'],
    ['@scheme', url.protocol.slice(0, -1)],
    ['@authority', url.host],
    ['@path', url.pathname],
    ['@query', url.search || '?'],
    ['content-digest', digest],
    ...app,
  ]
  const list = values.map(([name]) => `"${name}"`).join(' ')
  const params = `(${list});created=${created};expires=${created + lifetime};keyid="${id}";alg="${alg}";nonce="${nonce}";tag="${tag}"`
  const base = [
    ...values.map(([name, value]) => `"${name}": ${value}`),
    `"@signature-params": ${params}`,
  ].join('\n')
  const ecdsa = signer.asymmetricKeyType === 'ec'
  const signature = sign(ecdsa ? 'sha256' : null, Buffer.from(base), ecdsa ? { key: signer, dsaEncoding: 'ieee-p1363' } : signer).toString('base64')
  return {
    path,
    body,
    headers: {
      ...Object.fromEntries(app),
      'content-digest': digest,
      'signature-input': `${label}=${params}`,
      signature: `${label}=:${signature}:`,
    },
  }
}

async function send({ path, body, headers }, server) {
  const origin = `http://127.0.0.1:${server.address().port}`
  const response = await fetch(`${origin}${path}`, { method: 'POST', headers, body })
  const answer = await response.json()
  return `${response.status} ${answer.ok ? 'ok' : answer.code}`
}

const replay = signedRequest()
const cases = [
  ['correct request, UUID keyid', '200 ok', signedRequest()],
  ['correct request, thumbprint keyid', '200 ok', signedRequest({ id: jkt })],
  ['label sig1 is not this profile', '403 tap_malformed', signedRequest({ label: 'sig1' })],
  ['query string is covered', '200 ok', signedRequest({ path: '/tasks/42/claim?a=1' })],
  ['first send of a request', '200 ok', replay],
  ['same request sent again', '403 tap_replayed', replay],
  ['body changed in transit', '403 tap_signature_invalid', { ...signedRequest(), body: '{"task":43}' }],
  ['path changed in transit', '403 tap_signature_invalid', { ...signedRequest(), path: '/tasks/43/claim' }],
  ['signed for a different host', '403 tap_signature_invalid', signedRequest({ origin: 'https://other.example' })],
  ['signed by a different key', '403 tap_signature_invalid', signedRequest({ signer: stranger.privateKey })],
  ['signature already expired', '403 tap_expired', signedRequest({ created: Math.floor(Date.now() / 1000) - 120 })],
  ['lifetime over 60 seconds', '403 tap_expired', signedRequest({ lifetime: 300 })],
  ['paid tag on identity route', '403 tap_malformed', signedRequest({ tag: 'agent-payer-auth' })],
  ['Signature-Agent not allowlisted', '403 tap_signature_agent_not_accepted', signedRequest({ signatureAgent: '"https://other.example"' })],
  ['unknown key', '403 tap_key_unknown', signedRequest({ id: randomUUID() })],
  ['Authorization left on the request', '403 tap_malformed', (() => { const r = signedRequest(); return { ...r, headers: { ...r.headers, authorization: 'Bearer member-token' } } })()],
  ['unsigned header added in transit', '403 tap_malformed', (() => { const r = signedRequest(); return { ...r, headers: { ...r.headers, 'x-task': '43' } } })()],
  ['no signature at all', '403 tap_missing', { path: '/tasks/42/claim', body: '{}', headers: {} }],
]

let failed = 0
const report = (name, expected, actual) => {
  if (actual !== expected) failed += 1
  console.log(`${actual === expected ? 'PASS' : 'FAIL'}  ${name.padEnd(42)} ${actual}`)
}

for (const [name, expected, request] of cases) report(name, expected, await send(request, market))

function raw(server, target, { body = '', headers = {}, declared, closeEarly = false } = {}) {
  return new Promise((resolve) => {
    const socket = connect(server.address().port, '127.0.0.1')
    let data = ''
    socket.on('data', (chunk) => { data += chunk })
    socket.on('error', () => resolve('connection reset'))
    socket.on('close', () => {
      const status = /^HTTP\/1\.1 (\d+)/.exec(data)?.[1] ?? 'no answer'
      const code = /"code":"([^"]+)"/.exec(data)?.[1] ?? ''
      resolve(`${status} ${code}`.trim())
    })
    const lines = [`POST ${target} HTTP/1.1`, 'host: market.example', ...Object.entries(headers).map(([n, v]) => `${n}: ${v}`)]
    socket.write(`${lines.join('\r\n')}\r\ncontent-length: ${declared ?? Buffer.byteLength(body)}\r\nconnection: close\r\n\r\n${body}`)
    if (closeEarly) setTimeout(() => socket.destroy(), 50)
  })
}

const signed42 = () => signedRequest({ path: '/tasks/42/claim' })
for (const [name, target] of [
  ['dot segments in the path', '/tasks/43/../42/claim'],
  ['dot segments after a dotted segment', '/tasks/43/.x/../../42/claim'],
  ['encoded dots in the path', '/tasks/43/%2e%2e/42/claim'],
  ['backslashes in the path', '/tasks\\42\\claim'],
  ['a target that does not parse', '*%zz'],
  ['an absolute-form target', 'http://other.example/tasks/42/claim'],
]) {
  const request = signed42()
  report(name, '403 tap_malformed', await raw(market, target, { body: request.body, headers: request.headers }))
}
{
  const request = signedRequest({ origin: 'https://market.example.attacker.example' })
  report('a target that runs on into another host', '400', await raw(market, '.attacker.example/tasks/42/claim', { body: request.body, headers: request.headers }))
}
report('client disconnects mid-body', 'no answer', await raw(market, '/tasks/42/claim', { body: 'abc', declared: 100, closeEarly: true }))
report('body over 1 MiB', '413 body_too_large', await raw(market, '/tasks/42/claim', { body: 'x'.repeat(1024 * 1024 + 1) }))
{
  const request = signedRequest()
  report('a second, unsigned content-type', '403 tap_signature_invalid', await raw(market, '/tasks/42/claim', { body: request.body, headers: { ...request.headers, 'Content-Type': 'text/plain' } }))
}
report('still answering after all of that', '200 ok', await send(signedRequest(), market))

{
  const request = signedRequest()
  report('a host header such as fly-request-id', '200 ok', await send({ ...request, headers: { ...request.headers, 'fly-request-id': 'abc' } }, market))
  const verifyRequest = createVerifier({ registryOrigin, reserveNonce: memoryNonceStore() })
  const direct = (publicOrigin, extra = {}, verify = verifyRequest, { target, signedFor } = {}) => {
    const r = signedRequest(signedFor ? { origin: signedFor } : {})
    return verify({ method: 'POST', publicOrigin, target: target ?? r.path, headers: { ...r.headers, ...extra }, rawBody: Buffer.from(r.body) })
  }
  const unknown = await direct(PUBLIC_ORIGIN, { 'x-my-host': 'a' })
  report('a host header not on the list', '403 tap_malformed x-my-host', `${unknown.status} ${unknown.code} ${unknown.header}`)
  const allowing = createVerifier({ registryOrigin, reserveNonce: memoryNonceStore(), extraTransportHeaders: ['x-my-host'] })
  const allowed = await direct(PUBLIC_ORIGIN, { 'x-my-host': 'a' }, allowing)
  report('the same, with extraTransportHeaders', '200 ok', allowed.ok ? '200 ok' : `${allowed.status} ${allowed.code}`)
  const plain = await direct('http://market.example')
  report('verifier given an http origin', '403 origin_not_https', `${plain.status} ${plain.reason}`)
  const capitals = await direct('https://Market.example')
  report('verifier given https://Market.example', '403 origin_not_normal', `${capitals.status} ${capitals.reason}`)
  const trailingDot = await direct('https://market.example.')
  report('verifier given https://market.example.', '403 origin_not_normal', `${trailingDot.status} ${trailingDot.reason}`)
  for (const [name, signedFor, target] of [
    ['target .attacker.example/tasks/42/claim', 'https://market.example.attacker.example', '.attacker.example/tasks/42/claim'],
    ['target :8443/tasks/42/claim', 'https://market.example:8443', ':8443/tasks/42/claim'],
    ['target @attacker.example/tasks/42/claim', 'https://attacker.example', '@attacker.example/tasks/42/claim'],
  ]) {
    const moved = await direct(PUBLIC_ORIGIN, {}, verifyRequest, { target, signedFor })
    report(name, '403 request_target_invalid', `${moved.status} ${moved.reason}`)
  }
}
{
  const p256 = generateKeyPairSync('ec', { namedCurve: 'P-256' })
  const p256Id = randomUUID()
  const directoryVerifier = (algorithm) => createVerifier({
    directoryOrigin: 'https://sbx.agenticdirectory.visa.com',
    reserveNonce: memoryNonceStore(),
    fetchImpl: async () => new Response(JSON.stringify({
      agent: { name: 'fixture-agent', agentType: 'known', tokenRequestorId: 'YOUR_TOKEN_REQUESTOR_ID' },
      key: { id: p256Id, algorithm, status: 'active', expirationDate: null, publicKeyJwk: p256.publicKey.export({ format: 'jwk' }) },
    })),
  })
  const check = async (verify, { path, body, headers }) => {
    const result = await verify({ method: 'POST', publicOrigin: PUBLIC_ORIGIN, target: path, headers, rawBody: Buffer.from(body) })
    return result.ok ? '200 ok' : `${result.status} ${result.reason}`
  }
  const p256Request = (options = {}) => signedRequest({ id: p256Id, signer: p256.privateKey, alg: 'ecdsa-p256-sha256', ...options })
  report("P-256 key in Visa's directory, ecdsa-p256", '200 ok', await check(directoryVerifier('ecdsa-p256'), p256Request()))
  report("P-256 key in Visa's directory, ES256", '200 ok', await check(directoryVerifier('ES256'), p256Request()))
  report('P-256 key, signature says ed25519', '403 algorithm_mismatch', await check(directoryVerifier('ecdsa-p256'), p256Request({ alg: 'ed25519' })))
  const tampered = p256Request()
  const bytes = Buffer.from(tampered.headers.signature.slice('sig2=:'.length, -1), 'base64')
  bytes[10] ^= 1
  tampered.headers.signature = `sig2=:${bytes.toString('base64')}:`
  report('P-256 signature bytes changed', '403 signature_mismatch', await check(directoryVerifier('ecdsa-p256'), tampered))
  report("P-256 key, algorithm 'ecdsa-p384'", '503 listing_unusable', await check(directoryVerifier('ecdsa-p384'), p256Request()))
  const registryVerifier = createVerifier({ registryOrigin, reserveNonce: memoryNonceStore() })
  report('Ed25519 key, signature says ecdsa-p256', '403 algorithm_mismatch', await check(registryVerifier, signedRequest({ alg: 'ecdsa-p256-sha256' })))
}
const mixedCase = await startMarketplace({ registryOrigin, publicOrigin: 'https://Market.Example:443' })
report('pinned as https://Market.Example:443', '200 ok', await send(signedRequest(), mixedCase))
mixedCase.close()
let startup = 'started'
try {
  await startMarketplace({ registryOrigin, publicOrigin: 'http://market.example' })
} catch (error) {
  startup = error.message.split(' Got:')[0]
}
report('pinned as http://market.example', 'The public origin must be an https origin with a plain host name and no path, such as https://market.example.', startup)

let plainRegistry = 'started'
try {
  createVerifier({ registryOrigin: 'http://registry.example', reserveNonce: memoryNonceStore() })
} catch (error) {
  plainRegistry = error.message.split(' Got:')[0]
}
report('registry origin over plain http', 'The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1].', plainRegistry)

registryMode = 'redirect'
report('registry answers with a redirect', '503 tap_trust_unavailable', await send(signedRequest({ id: randomUUID() }), market))

registryMode = 'down'
report('registry outage', '503 tap_trust_unavailable', await send(signedRequest({ id: randomUUID() }), market))

registryMode = 'paused'
const coldCache = await startMarketplace({ registryOrigin, publicOrigin: PUBLIC_ORIGIN })
report('agent paused (registry answers 404)', '403 tap_key_unknown', await send(signedRequest(), coldCache))

for (const server of [market, coldCache, registry]) server.close()
console.log(failed ? `${failed} failed` : 'all passed (local fixture, not a real Visa CLI agent)')
process.exit(failed ? 1 : 0)
```

```sh
node fixture.mjs
```

This is the output from our run:

```text title="Output"
PASS  correct request, UUID keyid                200 ok
PASS  correct request, thumbprint keyid          200 ok
PASS  label sig1 is not this profile             403 tap_malformed
PASS  query string is covered                    200 ok
PASS  first send of a request                    200 ok
PASS  same request sent again                    403 tap_replayed
PASS  body changed in transit                    403 tap_signature_invalid
PASS  path changed in transit                    403 tap_signature_invalid
PASS  signed for a different host                403 tap_signature_invalid
PASS  signed by a different key                  403 tap_signature_invalid
PASS  signature already expired                  403 tap_expired
PASS  lifetime over 60 seconds                   403 tap_expired
PASS  paid tag on identity route                 403 tap_malformed
PASS  Signature-Agent not allowlisted            403 tap_signature_agent_not_accepted
PASS  unknown key                                403 tap_key_unknown
PASS  Authorization left on the request          403 tap_malformed
PASS  unsigned header added in transit           403 tap_malformed
PASS  no signature at all                        403 tap_missing
PASS  dot segments in the path                   403 tap_malformed
PASS  dot segments after a dotted segment        403 tap_malformed
PASS  encoded dots in the path                   403 tap_malformed
PASS  backslashes in the path                    403 tap_malformed
PASS  a target that does not parse               403 tap_malformed
PASS  an absolute-form target                    403 tap_malformed
PASS  a target that runs on into another host    400
PASS  client disconnects mid-body                no answer
PASS  body over 1 MiB                            413 body_too_large
PASS  a second, unsigned content-type            403 tap_signature_invalid
PASS  still answering after all of that          200 ok
PASS  a host header such as fly-request-id       200 ok
PASS  a host header not on the list              403 tap_malformed x-my-host
PASS  the same, with extraTransportHeaders       200 ok
PASS  verifier given an http origin              403 origin_not_https
PASS  verifier given https://Market.example      403 origin_not_normal
PASS  verifier given https://market.example.     403 origin_not_normal
PASS  target .attacker.example/tasks/42/claim    403 request_target_invalid
PASS  target :8443/tasks/42/claim                403 request_target_invalid
PASS  target @attacker.example/tasks/42/claim    403 request_target_invalid
PASS  P-256 key in Visa's directory, ecdsa-p256  200 ok
PASS  P-256 key in Visa's directory, ES256       200 ok
PASS  P-256 key, signature says ed25519          403 algorithm_mismatch
PASS  P-256 signature bytes changed              403 signature_mismatch
PASS  P-256 key, algorithm 'ecdsa-p384'          503 listing_unusable
PASS  Ed25519 key, signature says ecdsa-p256     403 algorithm_mismatch
PASS  pinned as https://Market.Example:443       200 ok
PASS  pinned as http://market.example            The public origin must be an https origin with a plain host name and no path, such as https://market.example.
PASS  registry origin over plain http            The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1].
PASS  registry answers with a redirect           503 tap_trust_unavailable
PASS  registry outage                            503 tap_trust_unavailable
PASS  agent paused (registry answers 404)        403 tap_key_unknown
all passed (local fixture, not a real Visa CLI agent)
```

To sign test requests yourself, use [sign.mjs](/examples/sign.mjs), printed on [Sign with a key you hold](/docs/sign-requests-as-an-agent.md#own-key). It's in [verify-example.zip](/examples/verify-example.zip) too, with [accepted-trids.mjs](/examples/accepted-trids.mjs). It signs with a key you hold, Ed25519 or P-256, in exactly the profile this verifier checks, so you don't need to write a signer. A stand-in registry that lists that key, as `fixture.mjs` runs one, gives you a pass end to end.

<a id="a-recorded-signature-to-test-against"></a>

## Test your rebuild against a recorded signature

`vector.mjs` checks your rebuild of the base offline, against a signature that came from Visa CLI's signing code. It uses a throwaway key that isn't listed anywhere, so it says nothing about a real agent, and it never touches the network. The request is `POST https://market.example/tasks/42/claim?ref=a`, and the body is `{"task":42}`.

`vector.py` does the same two cryptographic checks in Python 3 with only the standard library: it recomputes `content-digest`, rebuilds the signature base in the order `Signature-Input` gives, and verifies the Ed25519 signature with the RFC 8032 reference arithmetic. It doesn't do the freshness, nonce, registry or header checks, which `verify-agent.mjs` does. Use it as the starting point for a verifier in another language, with an Ed25519 library of your choice in place of the arithmetic.

```js title="vector.mjs"
import { createHash, createPublicKey } from 'node:crypto'
import { createVerifier, memoryNonceStore } from './verify-agent.mjs'

const publicKey = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUNvd0JRWURLMlZ3QXlFQUlWTDQwWnQ1SFNSRk1rTGhYeTZyYkxmUCtudHFYdE1BbDVZT0JwaUIyeEk9Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo='
const keyId = '11111111-2222-4333-8444-555555555555'
const pem = Buffer.from(publicKey, 'base64').toString('utf8')
const { x } = createPublicKey(pem).export({ format: 'jwk' })
const jkt = createHash('sha256').update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x })).digest('base64url')
const body = '{"task":42}'
const headers = {
  "accept": "*/*",
  "content-type": "application/json",
  "signature-agent": "\"https://sbx.agenticdirectory.visa.com\"",
  "x-idempotency-key": "abc",
  "content-digest": "sha-256=:lVH0Kpm71IxwuPvOjdCShjrzCouWTVbs3GY4TjGfhnk=:",
  "signature-input": "sig2=(\"@method\" \"@scheme\" \"@authority\" \"@path\" \"@query\" \"content-digest\" \"accept\" \"content-type\" \"signature-agent\" \"x-idempotency-key\");created=1794000000;expires=1794000060;keyid=\"11111111-2222-4333-8444-555555555555\";alg=\"ed25519\";nonce=\"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=\";tag=\"agent-browser-auth\"",
  "signature": "sig2=:EN91F8w5ZqTf9qkqzbm8c5MJp4Bj/OK99LlwyZN1Mx31F52vRlTxU9yhNazy6gsrK5FCI2LcCB6lU2bSP694AA==:"
}

const verifyRequest = createVerifier({
  registryOrigin: 'https://registry.invalid',
  reserveNonce: memoryNonceStore(() => 1794000030),
  now: () => 1794000030,
  fetchImpl: async () =>
    new Response(
      JSON.stringify({
        id: 'vector-agent',
        name: 'vector',
        isActive: true,
        keys: [{ id: keyId, agentId: 'vector-agent', jkt, status: 'active', algorithm: 'ed25519', publicKey }],
      }),
    ),
})

const result = await verifyRequest({
  method: 'POST',
  publicOrigin: 'https://market.example',
  target: '/tasks/42/claim?ref=a',
  headers,
  rawBody: Buffer.from(body),
})
console.log(result.ok ? 'vector verified' : `vector refused: ${result.code}`)
process.exit(result.ok ? 0 : 1)
```

```python title="vector.py"
import base64
import hashlib
import re
import sys

P = 2**255 - 19
L = 2**252 + 27742317777372353535851937790883648493
D = -121665 * pow(121666, P - 2, P) % P
SQRT_M1 = pow(2, (P - 1) // 4, P)


def recover_x(y, sign):
    if y >= P:
        return None
    x2 = (y * y - 1) * pow(D * y * y + 1, P - 2, P)
    if x2 % P == 0:
        return None if sign else 0
    x = pow(x2, (P + 3) // 8, P)
    if (x * x - x2) % P:
        x = x * SQRT_M1 % P
    if (x * x - x2) % P:
        return None
    return P - x if (x & 1) != sign else x


def decompress(data):
    if len(data) != 32:
        return None
    y = int.from_bytes(data, 'little')
    sign, y = y >> 255, y & ((1 << 255) - 1)
    x = recover_x(y, sign)
    return None if x is None else (x, y, 1, x * y % P)


def add(a, b):
    e = (a[1] - a[0]) * (b[1] - b[0]) % P
    f = (a[1] + a[0]) * (b[1] + b[0]) % P
    g = 2 * a[3] * b[3] * D % P
    h = 2 * a[2] * b[2] % P
    e, f, g, h = f - e, h - g, h + g, f + e
    return (e * f % P, g * h % P, f * g % P, e * h % P)


def multiply(scalar, point):
    result = (0, 1, 1, 0)
    while scalar:
        if scalar & 1:
            result = add(result, point)
        point = add(point, point)
        scalar >>= 1
    return result


def same(a, b):
    return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0


BASE_Y = 4 * pow(5, P - 2, P) % P
BASE = (recover_x(BASE_Y, 0), BASE_Y, 1, recover_x(BASE_Y, 0) * BASE_Y % P)


def ed25519_verify(public, message, signature):
    a, r = decompress(public), decompress(signature[:32])
    s = int.from_bytes(signature[32:], 'little')
    if a is None or r is None or len(signature) != 64 or s >= L:
        return False
    h = int.from_bytes(hashlib.sha512(signature[:32] + public + message).digest(), 'little') % L
    return same(multiply(s, BASE), add(r, multiply(h, a)))


public_key = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUNvd0JRWURLMlZ3QXlFQUlWTDQwWnQ1SFNSRk1rTGhYeTZyYkxmUCtudHFYdE1BbDVZT0JwaUIyeEk9Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo='
public_url = 'https://market.example/tasks/42/claim?ref=a'
body = b'{"task":42}'
headers = {
    'accept': '*/*',
    'content-type': 'application/json',
    'signature-agent': '"https://sbx.agenticdirectory.visa.com"',
    'x-idempotency-key': 'abc',
    'content-digest': 'sha-256=:lVH0Kpm71IxwuPvOjdCShjrzCouWTVbs3GY4TjGfhnk=:',
    'signature-input': 'sig2=("@method" "@scheme" "@authority" "@path" "@query" "content-digest" "accept" "content-type" "signature-agent" "x-idempotency-key");created=1794000000;expires=1794000060;keyid="11111111-2222-4333-8444-555555555555";alg="ed25519";nonce="BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";tag="agent-browser-auth"',
    'signature': 'sig2=:EN91F8w5ZqTf9qkqzbm8c5MJp4Bj/OK99LlwyZN1Mx31F52vRlTxU9yhNazy6gsrK5FCI2LcCB6lU2bSP694AA==:',
}

pem = base64.b64decode(public_key).decode()
der = base64.b64decode(''.join(line for line in pem.splitlines() if not line.startswith('-----')))
raw_key = der[-32:]

params = headers['signature-input'][len('sig2='):]
components = re.findall(r'"([^"]+)"', params[:params.index(')')])
match = re.fullmatch(r'https://([^/?#]+)(/[^?#]*)(\?[^#]*)?', public_url)
derived = {'@method': 'POST', '@scheme': 'https', '@authority': match[1], '@path': match[2], '@query': match[3] or '?'}

digest = 'sha-256=:' + base64.b64encode(hashlib.sha256(body).digest()).decode() + ':'
lines = [f'"{name}": {derived[name] if name.startswith("@") else headers[name]}' for name in components]
base = '\n'.join(lines + [f'"@signature-params": {params}']).encode()
signature = base64.b64decode(headers['signature'][len('sig2=:'):-1])

ok = digest == headers['content-digest'] and ed25519_verify(raw_key, base, signature)
print('vector verified' if ok else 'vector refused')
sys.exit(0 if ok else 1)
```

Run the Node version, or `python3 vector.py` for the Python one. Both print the same line.

```sh
node vector.mjs
```

```text title="Output"
vector verified
```

We have also run these checks ourselves, with these results:

| Check | Result |
| --- | --- |
| A real signature from a connected agent, against the registry that listed it | Accepted |
| A signature made by Visa CLI's signing code with a throwaway key, labelled `sig2` | Accepted |
| A paid signature from the same code | Refused with `tap_malformed` |
| That registry, using a real listed `keyid` and a signature from a different key | The real listing parsed, then `tap_signature_invalid`, as it should |
| The production registry, using that same `keyid` | `tap_key_unknown`, because production doesn't list that key |

To try a lookup yourself, see [Where to look up a key](/docs/keys-and-directories.md#a-real-lookup).

<a id="python"></a>

## The same verifier in Python

`verify_agent.py` is `verify-agent.mjs` ported to Python 3, with only the standard library. It makes the same checks in the same order, with the same `code`, `reason` and `judged`. Both accept a public origin only when its host is plain DNS labels or an IP address, so a trailing dot, an underscore, a label that starts or ends with a hyphen, or port `0` is refused in both, at startup by `pinnedOrigin()` and `pinned_origin()`, and as `origin_not_normal` if it reaches the check. Both refuse an HTTP method that isn't exactly `GET`, `HEAD` or `POST`, so `post` is refused rather than read as `POST`. Both read a listing's `expirationDate` with the same strict [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339#section-5.6) parser, a regular expression and the same date arithmetic, so they give the same verdict on every value: a full date, `T`, a time to the second, optional fractional seconds, then `Z` or an offset such as `+02:00`, in upper or lower case. Anything else is not a date, and the listing is couldn't check, `tap_trust_invalid` with `judged: false`: a date alone, a time with no zone, a space for `T`, hour `24`, second `60`, a day the month doesn't have, an offset past `23:59`, one-digit fields, a six-digit year, or text such as `foo 1`. That is stricter than `Date.parse`, which reads `foo 1` and `bar 2099` as dates. Visa CLI's registry sends the date the key's listing in the Visa Agent Directory ends, such as `2027-11-10T19:19:08.000Z`, and `null` only when it has no such date, which both read as no expiry. The one difference we know of is an internationalised host whose `xn--` label isn't valid Punycode: Node's URL parser refuses it, and Python, which checks only the characters, accepts it. The request target is checked the same way in both: each accepts exactly the characters a standard URL parser leaves as they are, which is what the Node verifier's check comes down to, and the test vectors include targets with `[ ] | ^ { }`, a backtick and a lone `%` to prove both agree. A `^` in the path is refused in both, because newer URL parsers, such as Node 26's, encode it, so the same target would otherwise pass on one Node version and fail on another. It passes every case in the [test vectors](/docs/conformance.md#run-the-vectors-against-your-verifier), and runs on every build of these docs. Its Ed25519 check is the RFC 8032 reference arithmetic, as in `vector.py`, and its P-256 check, for keys from the Visa Agent Directory, is textbook ECDSA arithmetic on the curve. Both are correct, but neither is a hardened library, so in production put a maintained library behind `ed25519_verify` and `p256_verify`, such as `cryptography`, whose ECDSA verify takes `r` and `s` once you encode them with `encode_dss_signature`.

```python title="verify_agent.py"
import base64
import hashlib
import ipaddress
import json
import re
import socket
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

REASONS = {
    'no_signature_headers': ('tap_missing', 'The request has no Signature-Input and Signature headers.'),
    'signature_input_format': ('tap_malformed', 'Signature-Input must be label sig2, then the covered components, created, expires, keyid, alg, nonce and tag="agent-browser-auth", in that order. The nonce is 32 bytes of base64.'),
    'signature_header_format': ('tap_malformed', 'Signature must be sig2=:<base64>:.'),
    'components_invalid': ('tap_malformed', 'The covered components are unreadable or repeated.'),
    'directory_components_missing': ('tap_malformed', 'A key named by directory ID must also cover @query, accept and content-type when sent.'),
    'required_components_missing': ('tap_malformed', 'The signature must cover @method, @scheme, @authority, @path, @query and content-digest first, in that order.'),
    'credential_header_present': ('tap_malformed', 'Authorization, Cookie, X-Payment and Payment-Signature are refused. Authenticate first and remove them before this check.'),
    'method_not_allowed': ('tap_malformed', 'Only GET, HEAD and POST can be signed.'),
    'signed_header_invalid': ('tap_malformed', 'A covered header is out of order, absent, starts or ends with a space, is not printable ASCII, is over 4096 characters, or is one this profile never signs, such as Origin, Host or X-Forwarded-For. At most 38 components and 16384 characters of signed headers.'),
    'uncovered_header': ('tap_malformed', 'The request carries a header the signature does not cover. Only transport headers may go unsigned.'),
    'nonce_format': ('tap_malformed', 'The nonce must be exactly 32 bytes of canonical base64.'),
    'body_too_large': ('tap_malformed', 'The body is over 1 MiB.'),
    'digest_format': ('tap_malformed', 'Content-Digest must be sha-256=:<base64>:.'),
    'not_yet_valid': ('tap_expired', 'The signature was created in the future. Check the clock.'),
    'expired': ('tap_expired', 'The signature has expired. Sign a new request.'),
    'lifetime_too_long': ('tap_expired', 'The signature lives longer than 60 seconds.'),
    'nonce_reused': ('tap_replayed', 'This key and nonce were already used. Sign a new request.'),
    'key_not_listed': ('tap_key_unknown', 'This key has no live listing. It may be unknown, paused or revoked; the registry does not say which.'),
    'agent_not_live': ('tap_key_inactive', 'The registry reports this agent as not live.'),
    'key_not_live': ('tap_key_inactive', "This key is not one of the agent's live keys: it was replaced, or its expirationDate has passed."),
    'body_digest_mismatch': ('tap_signature_invalid', 'The body does not match the signed Content-Digest. Digest the raw bytes, before anything parses them.'),
    'signature_mismatch': ('tap_signature_invalid', 'The signature does not verify for this exact request. Check that your pinned origin is what the agent signed for.'),
    'algorithm_mismatch': ('tap_signature_invalid', "The signature's alg is not the algorithm of the listed key."),
    'signature_agent_not_accepted': ('tap_signature_agent_not_accepted', 'Signature-Agent is not on your allowlist.'),
    'signature_agent_other_directory': ('tap_signature_agent_not_accepted', 'Signature-Agent names a different directory from the one this verifier reads.'),
    'key_not_in_directory': ('tap_key_unknown', "Visa's directory names keys by UUID, and this keyid is a thumbprint."),
    'simulated_listing': ('tap_simulated_not_accepted', 'This key belongs to a simulated test listing, which this verifier does not accept.'),
    'listing_unusable': ('tap_trust_invalid', 'The registry returned an unusable answer. The agent has not been judged.'),
    'registry_unavailable': ('tap_trust_unavailable', 'The registry could not be reached. The agent has not been judged; retry later.'),
    'nonce_store_unavailable': ('tap_trust_unavailable', 'The nonce store could not be reached. The agent has not been judged; retry later.'),
    'request_target_invalid': ('tap_malformed', 'The request target is not in normal form: it does not start with a single /, or it has dot segments, encoded dots, slashes or backslashes, a fragment, or does not parse. The signature covers the host and path exactly, so it is refused rather than normalized.'),
    'request_unreadable': ('tap_malformed', 'The request could not be read.'),
    'origin_not_https': ('tap_malformed', 'The pinned public origin is not https. Agents only sign https URLs, so pin an https origin.'),
    'origin_not_normal': ('tap_malformed', 'The pinned public origin is not in normal form: write the host in lowercase, as plain DNS labels or an IP address, with no default port, trailing dot or trailing slash, such as https://market.example. pinned_origin() does this for you.'),
}
COULD_NOT_CHECK = {'tap_trust_invalid', 'tap_trust_unavailable'}

INPUT = re.compile(r'sig2=\(([^)]+)\);created=(\d+);expires=(\d+);keyid="([A-Za-z0-9_-]{43}|[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})";alg="(ed25519|Ed25519|ecdsa-p256-sha256)";nonce="([A-Za-z0-9+/]{43}=)";tag="agent-browser-auth"')
SIGNATURE = re.compile(r'sig2=:((?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=):')
CORE = ['@method', '@scheme', '@authority', '@path', '@query', 'content-digest']
TRANSPORT_HEADERS = {
    'host', 'content-length', 'connection', 'transfer-encoding', 'keep-alive', 'accept', 'accept-language', 'accept-encoding', 'user-agent',
    'forwarded', 'via', 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-ssl', 'x-real-ip',
    'true-client-ip', 'cdn-loop', 'traceparent', 'tracestate', 'x-request-id', 'x-amzn-trace-id', 'x-cloud-trace-context',
    'b3', 'x-b3-traceid', 'x-b3-spanid', 'x-b3-parentspanid', 'x-b3-sampled',
    'cf-ray', 'cf-connecting-ip', 'cf-connecting-ipv6', 'cf-pseudo-ipv4', 'cf-connecting-o2o', 'cf-ew-via', 'cf-worker', 'cf-visitor',
    'cf-ipcountry', 'cf-ipcity', 'cf-ipcontinent', 'cf-iplatitude', 'cf-iplongitude', 'cf-region', 'cf-region-code', 'cf-metro-code',
    'cf-postal-code', 'cf-timezone',
    'x-vercel-id', 'x-vercel-forwarded-for', 'x-vercel-deployment-url', 'x-vercel-ip-continent', 'x-vercel-ip-country',
    'x-vercel-ip-country-region', 'x-vercel-ip-city', 'x-vercel-ip-latitude', 'x-vercel-ip-longitude', 'x-vercel-ip-timezone',
    'x-vercel-ip-postal-code',
    'fly-client-ip', 'fly-forwarded-port', 'fly-region', 'fly-request-id',
    'signature', 'signature-input', 'content-digest',
}
CREDENTIALS = ['authorization', 'cookie', 'x-payment', 'payment-signature']
NEVER_SIGNED = {
    'authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'host', 'connection', 'content-length', 'transfer-encoding', 'te',
    'trailer', 'upgrade', 'keep-alive', 'expect', 'via', 'forwarded', 'origin', 'referer', 'content-digest', 'signature', 'signature-input',
    'agent-payer-auth', 'payment', 'payment-signature', 'payment-required', 'payment-receipt', 'payment-response',
}
NEVER_SIGNED_PREFIX = re.compile(r'proxy-|sec-|x-forwarded-|x-visa(?:$|-)|x-stamp(?:$|-)|x-payment(?:$|-)')
HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9a-z-]{1,128}")
DIGEST = re.compile(r'sha-256=:[A-Za-z0-9+/]+={0,2}:')
EXPIRY = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:[Zz]|([+-])([0-9]{2}):([0-9]{2}))')
MAX_LIFETIME_SECONDS = 60
CLOCK_SKEW_SECONDS = 30
MAX_BODY_BYTES = 1024 * 1024
ED25519_SPKI = bytes.fromhex('302a300506032b6570032100')
HOST = re.compile(r'([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:]+\])(:[1-9][0-9]{0,4})?')
PATH = re.compile(r"/[!$%&'()*+,\-./0-9:;=@A-Z\[\]_a-z|~]*")
QUERY = re.compile(r"\?[!$%&()*+,\-./0-9:;=?@A-Z\[\\\]^_`a-z{|}~]+")

P = 2**255 - 19
L = 2**252 + 27742317777372353535851937790883648493
D = -121665 * pow(121666, P - 2, P) % P
SQRT_M1 = pow(2, (P - 1) // 4, P)


def _recover_x(y, sign):
    if y >= P:
        return None
    x2 = (y * y - 1) * pow(D * y * y + 1, P - 2, P)
    if x2 % P == 0:
        return None if sign else 0
    x = pow(x2, (P + 3) // 8, P)
    if (x * x - x2) % P:
        x = x * SQRT_M1 % P
    if (x * x - x2) % P:
        return None
    return P - x if (x & 1) != sign else x


def _decompress(data):
    if len(data) != 32:
        return None
    y = int.from_bytes(data, 'little')
    sign, y = y >> 255, y & ((1 << 255) - 1)
    x = _recover_x(y, sign)
    return None if x is None else (x, y, 1, x * y % P)


def _add(a, b):
    e = (a[1] - a[0]) * (b[1] - b[0]) % P
    f = (a[1] + a[0]) * (b[1] + b[0]) % P
    g = 2 * a[3] * b[3] * D % P
    h = 2 * a[2] * b[2] % P
    e, f, g, h = f - e, h - g, h + g, f + e
    return (e * f % P, g * h % P, f * g % P, e * h % P)


def _multiply(scalar, point):
    result = (0, 1, 1, 0)
    while scalar:
        if scalar & 1:
            result = _add(result, point)
        point = _add(point, point)
        scalar >>= 1
    return result


def _same(a, b):
    return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0


_BASE_Y = 4 * pow(5, P - 2, P) % P
_BASE = (_recover_x(_BASE_Y, 0), _BASE_Y, 1, _recover_x(_BASE_Y, 0) * _BASE_Y % P)


def ed25519_verify(public, message, signature):
    if len(signature) != 64:
        return False
    a, r = _decompress(public), _decompress(signature[:32])
    s = int.from_bytes(signature[32:], 'little')
    if a is None or r is None or s >= L:
        return False
    h = int.from_bytes(hashlib.sha512(signature[:32] + public + message).digest(), 'little') % L
    return _same(_multiply(s, _BASE), _add(r, _multiply(h, a)))


P256_P = 2**256 - 2**224 + 2**192 + 2**96 - 1
P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
P256_B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
P256_G = (0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)


def _p256_point(x, y):
    if not (0 <= x < P256_P and 0 <= y < P256_P) or (y * y - x * x * x + 3 * x - P256_B) % P256_P:
        return None
    return (x, y)


def _p256_add(a, b):
    if a is None:
        return b
    if b is None:
        return a
    if a[0] == b[0] and (a[1] + b[1]) % P256_P == 0:
        return None
    if a == b:
        m = (3 * a[0] * a[0] - 3) * pow(2 * a[1], -1, P256_P) % P256_P
    else:
        m = (b[1] - a[1]) * pow(b[0] - a[0], -1, P256_P) % P256_P
    x = (m * m - a[0] - b[0]) % P256_P
    return (x, (m * (a[0] - x) - a[1]) % P256_P)


def _p256_multiply(scalar, point):
    result = None
    while scalar:
        if scalar & 1:
            result = _p256_add(result, point)
        point = _p256_add(point, point)
        scalar >>= 1
    return result


def p256_verify(public, message, signature):
    if len(signature) != 64:
        return False
    r, s = int.from_bytes(signature[:32], 'big'), int.from_bytes(signature[32:], 'big')
    if not (0 < r < P256_N and 0 < s < P256_N):
        return False
    e = int.from_bytes(hashlib.sha256(message).digest(), 'big')
    w = pow(s, -1, P256_N)
    point = _p256_add(_p256_multiply(e * w % P256_N, P256_G), _p256_multiply(r * w % P256_N, public))
    return point is not None and point[0] % P256_N == r


def _signature_verifies(found, message, signature):
    if found['algorithm'] == 'ecdsa-p256-sha256':
        return p256_verify(found['raw'], message, signature)
    return ed25519_verify(found['raw'], message, signature)


def refusal(reason, retry_after_seconds=None, header=None):
    code, message = REASONS[reason]
    judged = code not in COULD_NOT_CHECK
    result = {'ok': False, 'code': code, 'reason': reason, 'message': f'{message} Header: {header}.' if header else message, 'judged': judged, 'status': 403 if judged else 503, 'retryAfterSeconds': retry_after_seconds}
    if header:
        result['header'] = header
    return result


def _canonical_host(host):
    if '%' in host:
        return None
    if ':' in host:
        try:
            number = int(ipaddress.IPv6Address(host))
        except ValueError:
            return None
        pieces = [(number >> (112 - 16 * i)) & 0xffff for i in range(8)]
        run, best = 0, (0, 8)
        for i, piece in enumerate(pieces):
            run = run + 1 if piece == 0 else 0
            if run > best[0]:
                best = (run, i - run + 1)
        text = lambda part: ':'.join(f'{piece:x}' for piece in part)
        if best[0] < 2:
            return f'[{text(pieces)}]'
        return f'[{text(pieces[:best[1]])}::{text(pieces[best[1] + best[0]:])}]'
    if re.fullmatch(r'[0-9]+|0x[0-9a-f]*', host.rsplit('.', 1)[-1]):
        try:
            return socket.inet_ntoa(socket.inet_aton(host))
        except OSError:
            return None
    return host


def _origin(value, schemes):
    if not isinstance(value, str) or re.search(r'[^\x21-\x7e]', value):
        return None
    try:
        parts = urllib.parse.urlsplit(value)
        port = parts.port
    except ValueError:
        return None
    if parts.scheme not in schemes or not parts.hostname or parts.username or parts.password or parts.path not in ('', '/') or parts.query or parts.fragment or value.endswith(('?', '#')):
        return None
    host = _canonical_host(parts.hostname)
    if not host:
        return None
    default = 443 if parts.scheme == 'https' else 80
    return parts.scheme, host, f'{parts.scheme}://{host}' + (f':{port}' if port is not None and port != default else '')


def pinned_origin(value):
    found = _origin(value, ('https',))
    if not found or not HOST.fullmatch(found[2][len('https://'):]):
        raise ValueError(f'The public origin must be an https origin with a plain host name and no path, such as https://market.example. Got: {value}')
    return found[2]


def registry_origin_from(value):
    found = _origin(value, ('https', 'http'))
    if not found or (found[0] == 'http' and found[1] not in ('localhost', '127.0.0.1', '[::1]')):
        raise ValueError(f'The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1]. Got: {value}')
    return found[2]


def _origin_is_normal(public_origin):
    found = _origin(public_origin, ('https',))
    return bool(found) and found[2] == public_origin and bool(HOST.fullmatch(public_origin[len('https://'):]))


def _split_target(target):
    if not isinstance(target, str) or not target.startswith('/') or target.startswith('//'):
        return None
    path, _, query = target.partition('?')
    query = f'?{query}' if '?' in target else ''
    if '#' in target or not PATH.fullmatch(path) or (query and not QUERY.fullmatch(query)):
        return None
    if re.search(r'%2e|%2f|%5c', path, re.IGNORECASE) or any(segment in ('.', '..') for segment in path.split('/')):
        return None
    return path, query


def _b64url(data):
    return base64.urlsafe_b64encode(data).rstrip(b'=').decode()


def _thumbprint(raw):
    if isinstance(raw, tuple):
        members = {'crv': 'P-256', 'kty': 'EC', 'x': _b64url(raw[0].to_bytes(32, 'big')), 'y': _b64url(raw[1].to_bytes(32, 'big'))}
    else:
        members = {'crv': 'Ed25519', 'kty': 'OKP', 'x': _b64url(raw)}
    return _b64url(hashlib.sha256(json.dumps(members, separators=(',', ':')).encode()).digest())


def _raw_key(public_key):
    pem = base64.b64decode(public_key, validate=True).decode()
    lines = pem.strip().splitlines()
    if lines[0] != '-----BEGIN PUBLIC KEY-----' or lines[-1] != '-----END PUBLIC KEY-----':
        return None
    der = base64.b64decode(''.join(lines[1:-1]), validate=True)
    if len(der) != 44 or not der.startswith(ED25519_SPKI):
        return None
    return der[len(ED25519_SPKI):]


def _expiry_seconds(value):
    found = EXPIRY.fullmatch(value) if isinstance(value, str) else None
    if not found:
        return None
    year, month, day, hour, minute, second = (int(part) for part in found.groups()[:6])
    offset_hours, offset_minutes = int(found.group(9) or 0), int(found.group(10) or 0)
    leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    month_days = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[month - 1] if 1 <= month <= 12 else 0
    if not month_days or not 1 <= day <= month_days or hour > 23 or minute > 59 or second > 59 or offset_hours > 23 or offset_minutes > 59:
        return None
    y = year - 1 if month <= 2 else year
    era = y // 400
    year_of_era = y - era * 400
    day_of_year = (153 * (month + (-3 if month > 2 else 9)) + 2) // 5 + day - 1
    days = era * 146097 + year_of_era * 365 + year_of_era // 4 - year_of_era // 100 + day_of_year - 719468
    offset = (-1 if found.group(8) == '-' else 1) * (offset_hours * 3600 + offset_minutes * 60)
    return days * 86400 + hour * 3600 + minute * 60 + second - offset + int((found.group(7) or '')[:3].ljust(3, '0')) / 1000


def _read_listing(key_id, doc):
    if not isinstance(doc, dict) or not isinstance(doc.get('id'), str) or not isinstance(doc.get('name'), str) or not isinstance(doc.get('isActive'), bool) or not isinstance(doc.get('keys'), list):
        return None
    for key in doc['keys']:
        if not isinstance(key, dict) or not isinstance(key.get('publicKey'), str) or not isinstance(key.get('jkt'), str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', key['jkt']) or key.get('agentId') != doc['id']:
            return None
        if key.get('status') != 'active' or key.get('algorithm') != 'ed25519':
            return None
        if key.get('expirationDate') is not None and _expiry_seconds(key['expirationDate']) is None:
            return None
    key = None if key_id is None else next((k for k in doc['keys'] if k.get('id') == key_id or k['jkt'] == key_id), None)
    if not key:
        return {'agent': doc}
    raw = _raw_key(key['publicKey'])
    if raw is None or _decompress(raw) is None:
        return None
    return {'agent': doc, 'key': key, 'raw': raw, 'algorithm': 'ed25519', 'thumbprint': _thumbprint(raw)}


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


_OPENER = urllib.request.build_opener(_NoRedirect)


def http_get(url):
    try:
        with _OPENER.open(urllib.request.Request(url, headers={'accept': 'application/json'}), timeout=5) as response:
            return response.status, dict(response.headers), response.read()
    except urllib.error.HTTPError as error:
        return error.code, dict(error.headers or {}), error.read()


P256_ALGORITHMS = ('ecdsa-p256', 'ecdsa-p256-sha256', 'es256', 'p-256')


def _directory_key(algorithm, jwk):
    def coordinate(name):
        value = jwk.get(name)
        return base64.urlsafe_b64decode(value + '=') if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{43}', value) else None

    if not isinstance(jwk, dict) or not isinstance(algorithm, str):
        return None
    if algorithm in ('ed25519', 'Ed25519') and jwk.get('kty') == 'OKP' and jwk.get('crv') == 'Ed25519' and coordinate('x'):
        raw = coordinate('x')
        return ('ed25519', raw) if _decompress(raw) is not None else None
    if algorithm.lower() in P256_ALGORITHMS and jwk.get('kty') == 'EC' and jwk.get('crv') == 'P-256' and coordinate('x') and coordinate('y'):
        point = _p256_point(int.from_bytes(coordinate('x'), 'big'), int.from_bytes(coordinate('y'), 'big'))
        return ('ecdsa-p256-sha256', point) if point else None
    return None


def _read_directory_entry(key_id, doc):
    key = doc.get('key') if isinstance(doc, dict) else None
    agent = doc.get('agent') if isinstance(doc, dict) else None
    if not isinstance(agent, dict) or not isinstance(agent.get('name'), str) or not isinstance(key, dict) or not isinstance(key.get('id'), str) or key.get('status') != 'active':
        return None
    usable = _directory_key(key.get('algorithm'), key.get('publicKeyJwk'))
    if not usable:
        return None
    if key['id'] != key_id or (key.get('expirationDate') is not None and _expiry_seconds(key['expirationDate']) is None):
        return None
    algorithm, raw = usable
    computed = _thumbprint(raw)
    found_agent = {'id': None, 'name': agent['name'], 'isActive': True, 'tokenRequestorId': agent['tokenRequestorId'] if isinstance(agent.get('tokenRequestorId'), str) else None}
    return {'agent': found_agent, 'key': {'id': key['id'], 'jkt': computed, 'expirationDate': key.get('expirationDate')}, 'raw': raw, 'algorithm': algorithm, 'thumbprint': computed}


def _read_registry(url, parse, fetch):
    try:
        status, headers, body = fetch(url)
    except Exception:
        return {'unavailable': True, 'retryAfterSeconds': None}
    if status == 404:
        return {'notListed': True}
    if status != 200:
        retry = {name.lower(): value for name, value in headers.items()}.get('retry-after', '')
        return {'unavailable': True, 'retryAfterSeconds': int(retry) if re.fullmatch(r'[0-9]+', str(retry)) and int(retry) > 0 else None}
    try:
        listing = parse(json.loads(body))
    except Exception:
        return {'invalid': True}
    return {'listed': True, **listing} if listing else {'invalid': True}


def read_key(registry_origin, key_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(registry_origin)}/v1/tap/registry/keys/{urllib.parse.quote(key_id, safe="")}', lambda doc: _read_listing(key_id, doc), fetch)


def read_agent(registry_origin, agent_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(registry_origin)}/v1/tap/registry/agents/{urllib.parse.quote(agent_id, safe="")}', lambda doc: _read_listing(None, doc), fetch)


def read_directory_key(directory_origin, key_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(directory_origin)}/.well-known/jwks/keys/{urllib.parse.quote(key_id, safe="")}', lambda doc: _read_directory_entry(key_id, doc), fetch)


def judge_key(key_id, answer, accept_simulated=False, now=None):
    if answer.get('unavailable'):
        return refusal('registry_unavailable', answer['retryAfterSeconds'])
    if answer.get('invalid'):
        return refusal('listing_unusable')
    if answer.get('notListed'):
        return refusal('key_not_listed')
    if answer['agent'].get('simulated') is True and not accept_simulated:
        return refusal('simulated_listing')
    if not answer['agent']['isActive']:
        return refusal('agent_not_live')
    if not answer.get('key'):
        return refusal('key_not_live')
    computed = answer['thumbprint']
    if computed != key_id and (len(key_id) != 36 or answer['key'].get('id') != key_id or answer['key']['jkt'] != computed):
        return refusal('key_not_live')
    if answer['key'].get('expirationDate') is not None and _expiry_seconds(answer['key']['expirationDate']) <= (int(time.time()) if now is None else now):
        return refusal('key_not_live')
    return None


def memory_nonce_store(now=lambda: int(time.time())):
    seen = {}
    lock = threading.Lock()

    def reserve(nonce_id, expires):
        with lock:
            for key, until in list(seen.items()):
                if until <= now():
                    del seen[key]
            if nonce_id in seen:
                return False
            seen[nonce_id] = expires
            return True

    return reserve


def read_own_key(key_id, lookup_key):
    try:
        found = lookup_key(key_id)
    except Exception:
        return {'unavailable': True, 'retryAfterSeconds': None}
    if found is None:
        return {'notListed': True}
    if not isinstance(found, dict):
        return {'invalid': True}
    if found.get('unavailable') is True:
        return {'unavailable': True, 'retryAfterSeconds': None}
    usable = _directory_key(found.get('algorithm'), found.get('publicKeyJwk')) if isinstance(found.get('name'), str) else None
    if not usable:
        return {'invalid': True}
    algorithm, raw = usable
    computed = _thumbprint(raw)
    return {'listed': True, 'agent': {'id': None, 'name': found['name'], 'isActive': True, 'tokenRequestorId': None}, 'key': {'id': key_id, 'jkt': computed, 'expirationDate': None}, 'raw': raw, 'algorithm': algorithm, 'thumbprint': computed}


def create_verifier(registry_origin=None, reserve_nonce=None, allowed_signature_agents=('"https://sbx.agenticdirectory.visa.com"', '"https://agenticdirectory.visa.com"'), accept_simulated=False, now=lambda: int(time.time()), fetch=http_get, cache_seconds=60, extra_transport_headers=(), directory_origin=None, lookup_key=None):
    directory = registry_origin_from(directory_origin) if directory_origin and not lookup_key else None
    registry = None if directory or lookup_key else registry_origin_from(registry_origin)
    cache = {}
    transport_headers = TRANSPORT_HEADERS | {name.lower() for name in extra_transport_headers}

    def lookup(key_id, fresh=False):
        hit = cache.get(key_id)
        if not fresh and hit and hit[1] > now():
            return hit[0]
        answer = read_own_key(key_id, lookup_key) if lookup_key else read_directory_key(directory, key_id, fetch) if directory else read_key(registry, key_id, fetch)
        if answer.get('unavailable') or answer.get('invalid'):
            return answer
        cache.pop(key_id, None)
        if answer.get('listed') and answer['agent']['isActive'] and answer.get('key'):
            cache[key_id] = (answer, now() + cache_seconds)
        return answer

    def check(method, public_origin, target, headers, raw_body):
        signature_input = headers.get('signature-input')
        signature_header = headers.get('signature')
        if not signature_input or not signature_header:
            return refusal('no_signature_headers')
        parsed = INPUT.fullmatch(signature_input)
        if not parsed:
            return refusal('signature_input_format')
        signed = SIGNATURE.fullmatch(signature_header)
        if not signed:
            return refusal('signature_header_format')

        parts = parsed[1].split()
        if not all(re.fullmatch(r'"[^"]+"', part) for part in parts):
            return refusal('components_invalid')
        components = [part[1:-1].lower() for part in parts]
        if len(set(components)) != len(components):
            return refusal('components_invalid')

        created, expires, key_id, nonce = int(parsed[2]), int(parsed[3]), parsed[4], parsed[6]
        alg = 'ecdsa-p256-sha256' if parsed[5] == 'ecdsa-p256-sha256' else 'ed25519'
        if not str(public_origin).startswith('https://'):
            return refusal('origin_not_https')
        if not _origin_is_normal(public_origin):
            return refusal('origin_not_normal')
        split = _split_target(target)
        if not split:
            return refusal('request_target_invalid')
        authority = public_origin[len('https://'):]
        path, query = split
        if len(key_id) == 36:
            needed = (['@query'] if query else []) + [name for name in ('accept', 'content-type') if name in headers]
            if any(name not in components for name in needed):
                return refusal('directory_components_missing')

        t = now()
        if created > t + CLOCK_SKEW_SECONDS:
            return refusal('not_yet_valid')
        if expires <= t or expires <= created:
            return refusal('expired')
        if expires - created > MAX_LIFETIME_SECONDS:
            return refusal('lifetime_too_long')

        if components[:len(CORE)] != CORE:
            return refusal('required_components_missing')
        if method not in ('GET', 'HEAD', 'POST'):
            return refusal('method_not_allowed')
        if any(name in headers for name in CREDENTIALS):
            return refusal('credential_header_present')

        if len(components) > 38:
            return refusal('signed_header_invalid')
        previous, size = '', 0
        for name in components[len(CORE):]:
            value = headers.get(name)
            if not HEADER_NAME.fullmatch(name) or name <= previous or not isinstance(value, str) or value.strip() != value or len(value) > 4096 or re.search(r'[^\x20-\x7e]', value):
                return refusal('signed_header_invalid')
            if name in NEVER_SIGNED or NEVER_SIGNED_PREFIX.match(name):
                return refusal('signed_header_invalid')
            previous = name
            size += len(name) + len(value)
        if size > 16384:
            return refusal('signed_header_invalid')
        for name in headers:
            if name not in components and name not in transport_headers and not name.startswith('sec-fetch-'):
                return refusal('uncovered_header', None, name)
        if base64.b64encode(base64.b64decode(nonce)).decode() != nonce:
            return refusal('nonce_format')

        if len(raw_body) > MAX_BODY_BYTES:
            return refusal('body_too_large')
        if not DIGEST.fullmatch(headers.get('content-digest') or ''):
            return refusal('digest_format')
        digest = 'sha-256=:' + base64.b64encode(hashlib.sha256(raw_body).digest()).decode() + ':'
        if headers.get('content-digest') != digest:
            return refusal('body_digest_mismatch')

        signature_agent = headers.get('signature-agent')
        if signature_agent is not None and signature_agent not in allowed_signature_agents:
            return refusal('signature_agent_not_accepted')
        if directory and len(key_id) != 36:
            return refusal('key_not_in_directory')
        if directory and signature_agent is not None and signature_agent != f'"{directory}"':
            return refusal('signature_agent_other_directory')

        found = lookup(key_id)
        refused = judge_key(key_id, found, accept_simulated, now())
        if refused:
            return refused

        derived = {'@method': method, '@scheme': 'https', '@authority': authority, '@path': path, '@query': query or '?'}
        lines = [f'"{name}": {derived[name] if name.startswith("@") else headers[name]}' for name in components]
        lines.append(f'"@signature-params": {signature_input[len("sig2="):]}')
        base = '\n'.join(lines).encode()
        signature = base64.b64decode(signed[1])

        if found['algorithm'] != alg or not _signature_verifies(found, base, signature):
            found = lookup(key_id, fresh=True)
            refused = judge_key(key_id, found, accept_simulated, now())
            if refused:
                return refused
            if found['algorithm'] != alg:
                return refusal('algorithm_mismatch')
            if not _signature_verifies(found, base, signature):
                return refusal('signature_mismatch')

        try:
            reserved = reserve_nonce(f'{key_id}:{nonce}', expires)
        except Exception:
            return refusal('nonce_store_unavailable')
        if not reserved:
            return refusal('nonce_reused')

        return {'ok': True, 'keyId': key_id, 'jkt': found['key']['jkt'], 'agentId': found['agent']['id'], 'agentName': found['agent']['name'], 'simulated': found['agent'].get('simulated') is True, 'covered': components, 'expires': expires, **({'tokenRequestorId': found['agent']['tokenRequestorId']} if directory else {}), **({'selfKey': True} if lookup_key else {})}

    def verify_request(method, public_origin, target, headers, raw_body):
        try:
            return check(method, public_origin, target, headers, raw_body)
        except Exception:
            return refusal('request_unreadable')

    return verify_request
```

`server.py` is the same small endpoint as `server.mjs`. It reads the raw body, whether it's sent with `Content-Length` or chunked, refuses one over 1 MiB with `413`, and answers every request, whatever its method, with the verifier's result. One difference is Python's own: its HTTP server answers a request with more than 100 headers with an HTML `431` page before any of this code runs.

```python title="server.py"
import json
import os
import re
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from verify_agent import MAX_BODY_BYTES, create_verifier, memory_nonce_store, pinned_origin


def make_server(registry_origin, public_origin, port=0, now=lambda: int(time.time()), **options):
    origin = pinned_origin(public_origin)
    verify_request = create_verifier(registry_origin, memory_nonce_store(now), now=now, **options)

    class Handler(BaseHTTPRequestHandler):
        def answer(self, status, body, headers=None):
            data = json.dumps(body).encode()
            self.send_response(status)
            for name, value in {'content-type': 'application/json', 'content-length': str(len(data)), **(headers or {})}.items():
                self.send_header(name, value)
            self.end_headers()
            if self.command != 'HEAD':
                self.wfile.write(data)

        def read_chunked(self):
            body = b''
            while True:
                size = self.rfile.readline(1026).split(b';')[0].strip()
                if not size or size.strip(b'0123456789abcdefABCDEF'):
                    return 400, 'bad_chunk', None
                size = int(size, 16)
                if size == 0:
                    while self.rfile.readline(1026).strip():
                        pass
                    return None, None, body
                if len(body) + size > MAX_BODY_BYTES:
                    return 413, 'body_too_large', None
                chunk = self.rfile.read(size)
                if len(chunk) < size or self.rfile.read(2) != b'\r\n':
                    return None, None, None
                body += chunk

        def read_body(self):
            encoding = self.headers.get('transfer-encoding')
            if encoding is not None:
                if encoding.strip().lower() != 'chunked' or 'content-length' in self.headers:
                    return 400, 'bad_transfer_encoding', None
                return self.read_chunked()
            lengths = self.headers.get_all('content-length') or ['0']
            if len(set(lengths)) != 1 or not re.fullmatch(r'[0-9]{1,16}', lengths[0]):
                return 400, 'bad_content_length', None
            length = int(lengths[0])
            if length > MAX_BODY_BYTES:
                return 413, 'body_too_large', None
            body = self.rfile.read(length)
            return (None, None, body) if len(body) == length else (None, None, None)

        def handle_request(self):
            status, code, body = self.read_body()
            if body is None:
                self.close_connection = True
                if status:
                    self.answer(status, {'ok': False, 'code': code}, {'connection': 'close'})
                return
            headers = {name.lower(): ', '.join(self.headers.get_all(name)) for name in set(self.headers.keys())}
            result = verify_request(self.command, origin, self.path, headers, body)
            retry = {'retry-after': str(result['retryAfterSeconds'] or 5)} if result.get('judged') is False else {}
            self.answer(200 if result['ok'] else result['status'], result, retry)

        def __getattr__(self, name):
            if name.startswith('do_'):
                return self.handle_request
            raise AttributeError(name)

        def log_message(self, *args):
            pass

    return ThreadingHTTPServer(('127.0.0.1', port), Handler)


if __name__ == '__main__':
    server = make_server(os.environ.get('REGISTRY_ORIGIN', 'https://auth.visacli.sh'), os.environ['PUBLIC_ORIGIN'], int(os.environ.get('PORT', '8080')), directory_origin=os.environ.get('DIRECTORY_ORIGIN'))
    print(f'listening on http://127.0.0.1:{server.server_address[1]}')
    server.serve_forever()
```

`test_server.py` starts `server.py` and a stand-in registry on localhost, and sends the recorded signature from `vector.py`, with the clock set to when it was signed. It also sends a request recorded with a throwaway P-256 key to a server reading a stand-in for the Visa Agent Directory, then the same request with its `alg` changed, and with its signature changed. It also sends, over a raw socket, the test vectors whose request target would move the host: it reads them from `tap-http-request-v1.json` in the same folder, which [verify-example.zip](/examples/verify-example.zip) includes, or which you can download from [Test your verifier](/docs/conformance.md). Each is refused here, and the first is also sent to a server pinned to the host it was signed for, where it passes, to show the signature itself is good. No real agent or network is involved.

```python title="test_server.py"
import http.client
import json
import socket
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from server import make_server

PUBLIC_KEY = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUNvd0JRWURLMlZ3QXlFQUlWTDQwWnQ1SFNSRk1rTGhYeTZyYkxmUCtudHFYdE1BbDVZT0JwaUIyeEk9Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo='
KEY_ID = '11111111-2222-4333-8444-555555555555'
JKT = 'nEArpjG3kYMcxbdzInyGlBEYQUw7RfAfe3Tw1fZvAA0'
SIGNED_AT = 1794000030
BODY = b'{"task":42}'
HEADERS = {
    'accept': '*/*',
    'content-type': 'application/json',
    'signature-agent': '"https://sbx.agenticdirectory.visa.com"',
    'x-idempotency-key': 'abc',
    'content-digest': 'sha-256=:lVH0Kpm71IxwuPvOjdCShjrzCouWTVbs3GY4TjGfhnk=:',
    'signature-input': 'sig2=("@method" "@scheme" "@authority" "@path" "@query" "content-digest" "accept" "content-type" "signature-agent" "x-idempotency-key");created=1794000000;expires=1794000060;keyid="11111111-2222-4333-8444-555555555555";alg="ed25519";nonce="BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";tag="agent-browser-auth"',
    'signature': 'sig2=:EN91F8w5ZqTf9qkqzbm8c5MJp4Bj/OK99LlwyZN1Mx31F52vRlTxU9yhNazy6gsrK5FCI2LcCB6lU2bSP694AA==:',
}
P256_HEADERS = {
    **HEADERS,
    'signature-input': 'sig2=("@method" "@scheme" "@authority" "@path" "@query" "content-digest" "accept" "content-type" "signature-agent" "x-idempotency-key");created=1794000000;expires=1794000060;keyid="11111111-2222-4333-8444-555555555555";alg="ecdsa-p256-sha256";nonce="BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=";tag="agent-browser-auth"',
    'signature': 'sig2=:8rMssObYj3QpeImOt1KJGtTkTCJhpXKtTHzAgl4qblMV8XbV7LfGDgT3WBVVSH5z8ReUy0oOpnYJqqiuVi1jYA==:',
}
P256_JWK = {'kty': 'EC', 'crv': 'P-256', 'x': 'uQmeO92RX9OAfCig8yN227ihnwm2O2TkZM9yWJ5Aw88', 'y': 'M9Lt3o3RrGnUDkw4sfxI9LODnshNIOZoofDVyCmqtew'}
LISTING = {'id': 'vector-agent', 'name': 'vector', 'isActive': True, 'keys': [{'id': KEY_ID, 'agentId': 'vector-agent', 'jkt': JKT, 'status': 'active', 'algorithm': 'ed25519', 'publicKey': PUBLIC_KEY}]}
with open('tap-http-request-v1.json') as handle:
    VECTORS = json.load(handle)
mode = {'value': 'listed'}


class Registry(BaseHTTPRequestHandler):
    def do_GET(self):
        if mode['value'] == 'redirect':
            self.send_response(302)
            self.send_header('location', f'https://elsewhere.example{self.path}')
            self.end_headers()
            return
        status, body = {'listed': (200, LISTING), 'vectors': (200, VECTORS['listing']), 'down': (503, {'code': 'unavailable'})}[mode['value']]
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header('content-type', 'application/json')
        self.send_header('content-length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


def start(server):
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


registry = start(ThreadingHTTPServer(('127.0.0.1', 0), Registry))
registry_origin = f'http://127.0.0.1:{registry.server_address[1]}'


def market(origin='https://market.example'):
    return start(make_server(registry_origin, origin, now=lambda: SIGNED_AT, cache_seconds=0))


def directory_market(algorithm):
    entry = {'agent': {'name': 'vector', 'agentType': 'known', 'tokenRequestorId': 'YOUR_TOKEN_REQUESTOR_ID'}, 'key': {'id': KEY_ID, 'algorithm': algorithm, 'status': 'active', 'expirationDate': None, 'publicKeyJwk': P256_JWK}}
    return start(make_server(registry_origin, 'https://market.example', now=lambda: SIGNED_AT, cache_seconds=0, directory_origin='https://sbx.agenticdirectory.visa.com', fetch=lambda url: (200, {}, json.dumps(entry).encode())))


def send(server, path='/tasks/42/claim?ref=a', body=BODY, extra=None, declared=None, method='POST', chunked=False):
    connection = http.client.HTTPConnection('127.0.0.1', server.server_address[1], timeout=10)
    if chunked:
        connection.request(method, path, body=iter([body[:5], body[5:]]), headers={**HEADERS, **(extra or {})}, encode_chunked=True)
    elif declared is None:
        connection.request(method, path, body=body, headers={**HEADERS, **(extra or {})})
    else:
        connection.putrequest('POST', path)
        connection.putheader('content-length', str(declared))
        connection.endheaders()
    response = connection.getresponse()
    answer = json.loads(response.read())
    connection.close()
    return f"{response.status} {'ok' if answer['ok'] else answer['code']}"


failed = 0


def report(name, expected, actual):
    global failed
    failed += actual != expected
    print(f"{'PASS' if actual == expected else 'FAIL'}  {name.ljust(42)} {actual}")


first = market()
report('the recorded signed request', '200 ok', send(first))
report('the same request again', '403 tap_replayed', send(first))
report('body changed in transit', '403 tap_signature_invalid', send(market(), body=b'{"task":43}'))
report('path changed in transit', '403 tap_signature_invalid', send(market(), path='/tasks/43/claim?ref=a'))
report('dot segments in the path', '403 tap_malformed', send(market(), path='/tasks/43/../42/claim?ref=a'))
report('dot segments after a dotted segment', '403 tap_malformed', send(market(), path='/tasks/43/.x/../../42/claim?ref=a'))
report('unsigned identity header added', '403 tap_malformed', send(market(), extra={'x-forwarded-user': 'alice'}))
report('body over 1 MiB', '413 body_too_large', send(market(), declared=1024 * 1024 + 1))
report('the recorded request, sent chunked', '200 ok', send(market(), chunked=True))
with socket.create_connection(('127.0.0.1', market().server_address[1]), timeout=10) as client:
    client.sendall(b'POST /tasks/42/claim HTTP/1.1\r\nhost: market.example\r\ntransfer-encoding: chunked\r\n\r\n100001\r\n')
    reply = client.makefile('rb').read().split(b'\r\n\r\n', 1)
report('chunked body over 1 MiB', '413 body_too_large', f"{reply[0].split()[1].decode()} {json.loads(reply[1])['code']}")
report('a PUT gets the verifier\'s answer', '403 tap_malformed', send(market(), method='PUT'))
report('a lowercase post is refused', '403 tap_malformed', send(market(), method='post'))
steady = market()
with socket.create_connection(('127.0.0.1', steady.server_address[1])) as client:
    client.sendall(b'POST /tasks/42/claim HTTP/1.1\r\nhost: market.example\r\ncontent-length: 100\r\n\r\nabc')
report('still answering after a client hung up', '200 ok', send(steady))
startup = 'started'
try:
    make_server('http://registry.example', 'https://market.example')
except ValueError as error:
    startup = str(error).split(' Got:')[0]
report('registry origin over plain http', 'The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1].', startup)


def send_raw(server, target, headers, method='GET', body=b''):
    lines = [f'{method} {target} HTTP/1.1', 'host: market.example', *[f'{name}: {value}' for name, value in headers], f'content-length: {len(body)}', 'connection: close']
    with socket.create_connection(('127.0.0.1', server.server_address[1]), timeout=10) as client:
        client.sendall(('\r\n'.join(lines) + '\r\n\r\n').encode() + body)
        head, _, body = client.makefile('rb').read().partition(b'\r\n\r\n')
    answer = json.loads(body)
    return f"{head.split()[1].decode()} {'ok' if answer['ok'] else answer['reason']}"


report('a second, unsigned content-type', '403 signature_mismatch', send_raw(market(), '/tasks/42/claim?ref=a', [*HEADERS.items(), ('content-type', 'text/plain')], 'POST', BODY))
report("a P-256 key in Visa's directory", '200 ok', send_raw(directory_market('ecdsa-p256'), '/tasks/42/claim?ref=a', P256_HEADERS.items(), 'POST', BODY))
report('the same, algorithm written ES256', '200 ok', send_raw(directory_market('ES256'), '/tasks/42/claim?ref=a', P256_HEADERS.items(), 'POST', BODY))
mislabelled = {**P256_HEADERS, 'signature-input': P256_HEADERS['signature-input'].replace('ecdsa-p256-sha256', 'Ed25519')}
report('P-256 key, signature says Ed25519', '403 algorithm_mismatch', send_raw(directory_market('ecdsa-p256'), '/tasks/42/claim?ref=a', mislabelled.items(), 'POST', BODY))
tampered = {**P256_HEADERS, 'signature': P256_HEADERS['signature'].replace('sig2=:8', 'sig2=:9')}
report('P-256 signature bytes changed', '403 signature_mismatch', send_raw(directory_market('ecdsa-p256'), '/tasks/42/claim?ref=a', tampered.items(), 'POST', BODY))
claims_p256 = {**HEADERS, 'signature-input': HEADERS['signature-input'].replace('ed25519', 'ecdsa-p256-sha256')}
report('Ed25519 key, signature says ecdsa-p256', '403 algorithm_mismatch', send_raw(market(), '/tasks/42/claim?ref=a', claims_p256.items(), 'POST', BODY))

mode['value'] = 'vectors'
moved = {case['request']['target']: case for case in VECTORS['cases'] if case['request'].get('target', '/').startswith(('.', ':', '@'))}
control = moved['.attacker.example/tasks/42/claim']
report('signed for another host, sent to that host', '200 ok', send_raw(market('https://market.example.attacker.example'), '/tasks/42/claim', control['request']['headers']))
for target, case in moved.items():
    report(f'sent as {target}', '403 request_target_invalid', send_raw(market(), target, case['request']['headers']))
mode['value'] = 'redirect'
report('registry answers with a redirect', '503 tap_trust_unavailable', send(market()))
mode['value'] = 'down'
report('registry outage', '503 tap_trust_unavailable', send(market()))
print(f'{failed} failed' if failed else 'all passed (recorded signature, local stand-in registry, not a real Visa CLI agent)')
sys.exit(1 if failed else 0)
```

```sh
python3 test_server.py
```

```text title="Output of test_server.py"
PASS  the recorded signed request                200 ok
PASS  the same request again                     403 tap_replayed
PASS  body changed in transit                    403 tap_signature_invalid
PASS  path changed in transit                    403 tap_signature_invalid
PASS  dot segments in the path                   403 tap_malformed
PASS  dot segments after a dotted segment        403 tap_malformed
PASS  unsigned identity header added             403 tap_malformed
PASS  body over 1 MiB                            413 body_too_large
PASS  the recorded request, sent chunked         200 ok
PASS  chunked body over 1 MiB                    413 body_too_large
PASS  a PUT gets the verifier's answer           403 tap_malformed
PASS  a lowercase post is refused                403 tap_malformed
PASS  still answering after a client hung up     200 ok
PASS  registry origin over plain http            The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1].
PASS  a second, unsigned content-type            403 signature_mismatch
PASS  a P-256 key in Visa's directory            200 ok
PASS  the same, algorithm written ES256          200 ok
PASS  P-256 key, signature says Ed25519          403 algorithm_mismatch
PASS  P-256 signature bytes changed              403 signature_mismatch
PASS  Ed25519 key, signature says ecdsa-p256     403 algorithm_mismatch
PASS  signed for another host, sent to that host 200 ok
PASS  sent as .attacker.example/tasks/42/claim   403 request_target_invalid
PASS  sent as :8443/tasks/42/claim               403 request_target_invalid
PASS  sent as @attacker.example/tasks/42/claim   403 request_target_invalid
PASS  registry answers with a redirect           503 tap_trust_unavailable
PASS  registry outage                            503 tap_trust_unavailable
all passed (recorded signature, local stand-in registry, not a real Visa CLI agent)
```

<a id="python-signer"></a>

### Sign, accept TRIDs and serve it in Python

These are the Python versions of `sign.mjs` and `accepted-trids.mjs`, so a Python service doesn't need Node to test end to end. Both use only the standard library and `verify_agent.py`, saved in the same folder.

`sign.py` signs a request with a key you hold, Ed25519 or P-256, as a private JWK. It signs the same components as `sign.mjs`: the core six, then `accept`, any headers you pass, and `signature-agent` when you name the Visa Agent Directory. Use it in tests, never in a production signer.

```python title="sign.py"
import base64
import hashlib
import json
import secrets
import time
import urllib.parse

from verify_agent import L, P, P256_G, P256_N, _BASE, _multiply, _p256_multiply


def _b64url_decode(value):
    return base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))


def _ed25519_encode(point):
    x, y, z, _ = point
    inverse = pow(z, P - 2, P)
    x, y = x * inverse % P, y * inverse % P
    return (y | ((x & 1) << 255)).to_bytes(32, 'little')


def _ed25519_scalar(seed):
    return int.from_bytes(hashlib.sha512(seed).digest()[:32], 'little') & ((1 << 254) - 8) | (1 << 254)


def _ed25519_sign(seed, message):
    prefix = hashlib.sha512(seed).digest()[32:]
    scalar = _ed25519_scalar(seed)
    public = _ed25519_encode(_multiply(scalar, _BASE))
    r = int.from_bytes(hashlib.sha512(prefix + message).digest(), 'little') % L
    point = _ed25519_encode(_multiply(r, _BASE))
    k = int.from_bytes(hashlib.sha512(point + public + message).digest(), 'little') % L
    return point + ((r + k * scalar) % L).to_bytes(32, 'little')


def _p256_sign(secret, message):
    e = int.from_bytes(hashlib.sha256(message).digest(), 'big')
    while True:
        k = secrets.randbelow(P256_N - 1) + 1
        r = _p256_multiply(k, P256_G)[0] % P256_N
        s = pow(k, -1, P256_N) * (e + r * secret) % P256_N
        if r and s:
            return r.to_bytes(32, 'big') + s.to_bytes(32, 'big')


def sign_request(url, key_id, private_jwk, method='GET', headers=None, body=b'', signature_agent=None, lifetime=60):
    target = urllib.parse.urlsplit(url)
    ecdsa = private_jwk.get('kty') == 'EC'
    digest = f'sha-256=:{base64.b64encode(hashlib.sha256(body).digest()).decode()}:'
    chosen = {'accept': '*/*', **{name.lower(): str(value) for name, value in (headers or {}).items()}}
    if signature_agent:
        chosen['signature-agent'] = json.dumps(signature_agent)
    app = sorted(chosen.items())
    values = [
        ('@method', method.upper()),
        ('@scheme', target.scheme),
        ('@authority', target.netloc.lower()),
        ('@path', target.path or '/'),
        ('@query', f'?{target.query}' if target.query else '?'),
        ('content-digest', digest),
        *app,
    ]
    created = int(time.time())
    nonce = base64.b64encode(secrets.token_bytes(32)).decode()
    names = ' '.join(f'"{name}"' for name, _ in values)
    alg = 'ecdsa-p256-sha256' if ecdsa else 'ed25519'
    params = f'({names});created={created};expires={created + lifetime};keyid="{key_id}";alg="{alg}";nonce="{nonce}";tag="agent-browser-auth"'
    base = '\n'.join([*(f'"{name}": {value}' for name, value in values), f'"@signature-params": {params}']).encode()
    secret = _b64url_decode(private_jwk['d'])
    signature = _p256_sign(int.from_bytes(secret, 'big'), base) if ecdsa else _ed25519_sign(secret, base)
    return {
        **dict(app),
        'content-digest': digest,
        'signature-input': f'sig2={params}',
        'signature': f'sig2=:{base64.b64encode(signature).decode()}:',
    }
```

`accepted_trids.py` wraps the verifier so a key from the Visa Agent Directory passes only under a TRID you list, as [Accept only some integrators](#accepted-trids) explains.

```python title="accepted_trids.py"
from verify_agent import create_verifier


def create_accepted_verifier(accepted_trids, **options):
    verify_request = create_verifier(**options)

    def check(method, public_origin, target, headers, raw_body):
        result = verify_request(method, public_origin, target, headers, raw_body)
        if not result['ok'] or result.get('tokenRequestorId') in accepted_trids:
            return result
        return {'ok': False, 'code': 'tap_key_unknown', 'reason': 'trid_not_accepted', 'message': "The key is listed in Visa's directory under a TRID this service doesn't accept.", 'judged': True, 'status': 403, 'retryAfterSeconds': None}

    return check
```

`test_sign.py` generates an Ed25519 key and a P-256 key, signs with `sign.py`, and checks the requests through `accepted_trids.py` against a stand-in for the Visa Agent Directory. It needs no network.

```python title="test_sign.py"
import base64
import json
import secrets

from accepted_trids import create_accepted_verifier
from sign import _ed25519_encode, _ed25519_scalar, sign_request
from verify_agent import P256_G, P256_N, _BASE, _multiply, _p256_multiply, memory_nonce_store, pinned_origin

KEY_ID = '11111111-2222-4333-8444-555555555555'
DIRECTORY = 'https://sbx.agenticdirectory.visa.com'
ORIGIN = pinned_origin('https://market.example')
URL = 'https://market.example/tasks/42/claim?ref=a'
BODY = b'{"pitch":"I can do this"}'
ACCEPTED = ['YOUR_TOKEN_REQUESTOR_ID']


def b64url(data):
    return base64.urlsafe_b64encode(data).rstrip(b'=').decode()


def ed25519_key():
    seed = secrets.token_bytes(32)
    public = _ed25519_encode(_multiply(_ed25519_scalar(seed), _BASE))
    return {'kty': 'OKP', 'crv': 'Ed25519', 'x': b64url(public), 'd': b64url(seed)}, 'ed25519'


def p256_key():
    secret = secrets.randbelow(P256_N - 1) + 1
    x, y = _p256_multiply(secret, P256_G)
    return {'kty': 'EC', 'crv': 'P-256', 'x': b64url(x.to_bytes(32, 'big')), 'y': b64url(y.to_bytes(32, 'big')), 'd': b64url(secret.to_bytes(32, 'big'))}, 'ecdsa-p256'


def verifier(jwk, algorithm, trid='YOUR_TOKEN_REQUESTOR_ID'):
    public = {name: value for name, value in jwk.items() if name != 'd'}
    entry = {'agent': {'name': 'test agent', 'agentType': 'known', 'tokenRequestorId': trid}, 'key': {'id': KEY_ID, 'algorithm': algorithm, 'status': 'active', 'expirationDate': None, 'publicKeyJwk': public}}
    return create_accepted_verifier(ACCEPTED, reserve_nonce=memory_nonce_store(), directory_origin=DIRECTORY, cache_seconds=0, fetch=lambda url: (200, {}, json.dumps(entry).encode()))


def signed(jwk):
    return sign_request(URL, KEY_ID, jwk, method='POST', headers={'content-type': 'application/json'}, body=BODY, signature_agent=DIRECTORY)


def answer(check, headers, body=BODY):
    result = check('POST', ORIGIN, '/tasks/42/claim?ref=a', headers, body)
    return '200 ok' if result['ok'] else f"{result['status']} {result['code']}"


def report(name, expected, actual):
    print(f"{'PASS' if actual == expected else 'FAIL'}  {name:<40} {actual}")
    if actual != expected:
        raise SystemExit(1)


ed_key, ed_alg = ed25519_key()
p_key, p_alg = p256_key()
check = verifier(ed_key, ed_alg)
headers = signed(ed_key)
report('Ed25519 key, TRID accepted', '200 ok', answer(check, headers))
report('the same request again', '403 tap_replayed', answer(check, headers))
report('P-256 key, TRID accepted', '200 ok', answer(verifier(p_key, p_alg), signed(p_key)))
for jwk, alg in [(ed_key, ed_alg), (p_key, p_alg)]:
    mixed = sign_request(URL, KEY_ID, jwk, method='POST', headers={'Accept': 'application/json', 'Signature-Agent': 'old', 'Content-Type': 'application/json'}, body=BODY, signature_agent=DIRECTORY)
    assert mixed['accept'] == 'application/json'
    assert mixed['signature-input'].count('"accept"') == 1
    assert mixed['signature-input'].count('"signature-agent"') == 1
    assert answer(verifier(jwk, alg), mixed) == '200 ok'
report('body changed after signing', '403 tap_signature_invalid', answer(verifier(ed_key, ed_alg), signed(ed_key), b'{"pitch":"changed"}'))
report('key listed under another TRID', '403 tap_key_unknown', answer(verifier(ed_key, ed_alg, trid='40010092347'), signed(ed_key)))
print('all passed (generated keys, local stand-in directory, not a real agent)')
```

```sh
python3 test_sign.py
```

```text title="Output of test_sign.py"
PASS  Ed25519 key, TRID accepted               200 ok
PASS  the same request again                   403 tap_replayed
PASS  P-256 key, TRID accepted                 200 ok
PASS  body changed after signing               403 tap_signature_invalid
PASS  key listed under another TRID            403 tap_key_unknown
all passed (generated keys, local stand-in directory, not a real agent)
```

To check requests in a FastAPI app, add the verifier as a dependency on the routes that need it. Two details matter. The verifier takes the raw target, so build it from the ASGI scope's `raw_path` and `query_string`, never from the parsed URL. It takes one value per header name, so join repeated headers with `, `. The verifier's lookups block, so it runs in a thread.

```python
import asyncio

from fastapi import Depends, FastAPI, HTTPException, Request

from verify_agent import create_verifier, memory_nonce_store, pinned_origin

ORIGIN = pinned_origin('https://market.example')
verify_request = create_verifier('https://auth.visacli.sh', memory_nonce_store())
app = FastAPI()


async def verified(request: Request):
    query = request.scope['query_string'].decode('latin-1')
    target = request.scope['raw_path'].decode('latin-1') + (f'?{query}' if query else '')
    headers = {}
    for name, value in request.scope['headers']:
        name, value = name.decode('latin-1').lower(), value.decode('latin-1')
        headers[name] = f'{headers[name]}, {value}' if name in headers else value
    result = await asyncio.to_thread(verify_request, request.method, ORIGIN, target, headers, await request.body())
    if not result['ok']:
        retry = {'retry-after': str(result['retryAfterSeconds'] or 5)} if result.get('judged') is False else None
        raise HTTPException(result['status'], result, retry)
    return result


@app.post('/tasks/{task_id}/claim')
async def claim(task_id: str, tap: dict = Depends(verified)):
    return {'task': task_id, 'keyId': tap['keyId']}
```

A refusal comes back as FastAPI's error body, with the verifier's answer under `detail`, and a couldn't-check answer carries `Retry-After`. For agents registered through an enabler, create the verifier with `directory_origin` instead of the registry, or use `create_accepted_verifier` from `accepted_trids.py`.

<a id="try-it"></a>

## The demo as a file

This is the code the Try it block runs. Save it as `try-it.mjs`. It uses WebCrypto, so it needs Node 22 and no dependencies. It's a demo, not a verifier: it checks the body, the signature, an unknown key and replays, and nothing else. It doesn't check freshness, the label, tag or algorithm, which components are covered, paused or revoked listings, or account binding, and it accepts its own listing although that listing is marked simulated, which `verify-agent.mjs` refuses unless you pass `acceptSimulated: true`. Its functions are named `demoCheck` and `demoNonceStore` so they can't be mistaken for the verifier above. It checks a test signature we recorded, made with a throwaway key that isn't listed anywhere and whose private half we discarded.

```js title="try-it.mjs"
const encoder = new TextEncoder()
const toBase64 = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes)))
const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0))
const toBase64Url = (bytes) => toBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
const sha256 = (data) => crypto.subtle.digest('SHA-256', typeof data === 'string' ? encoder.encode(data) : data)
const digestHeader = async (body) => `sha-256=:${toBase64(await sha256(body))}:`

export const SIGNATURE_AGENT = '"https://sbx.agenticdirectory.visa.com"'
export const PUBLIC_URL = 'https://market.example/tasks/42/claim?ref=a'
export const BODY = '{"task":42}'

export async function createAgent(name = 'TEST AGENT (simulated, not a real agent)') {
  const keys = await crypto.subtle.generateKey('Ed25519', true, ['sign', 'verify'])
  const jwk = await crypto.subtle.exportKey('jwk', keys.publicKey)
  const jkt = toBase64Url(await sha256(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: jwk.x })))
  const spki = await crypto.subtle.exportKey('spki', keys.publicKey)
  const pem = `-----BEGIN PUBLIC KEY-----\n${toBase64(spki)}\n-----END PUBLIC KEY-----\n`
  return { name, id: crypto.randomUUID(), keyId: crypto.randomUUID(), jkt, keys, pem, publicKey: btoa(pem) }
}

export function createRegistry() {
  const listings = new Map()
  let down = false
  return {
    publishListing(keyId, listing) {
      listings.set(keyId, listing)
    },
    publish(agent) {
      listings.set(agent.keyId, {
        id: agent.id,
        name: agent.name,
        simulated: true,
        isActive: true,
        keys: [{ id: agent.keyId, agentId: agent.id, status: 'active', algorithm: 'ed25519', jkt: agent.jkt, publicKey: agent.publicKey, expirationDate: null }],
      })
    },
    setDown(value) {
      down = value
    },
    lookup(keyId) {
      if (down) return { status: 503, body: { code: 'unavailable' } }
      const listing = listings.get(keyId)
      return listing ? { status: 200, body: listing } : { status: 404, body: { code: 'not_found' } }
    },
  }
}

export async function signRequest(agent, { url = PUBLIC_URL, method = 'POST', body = BODY, keyId = agent.keyId, now = Math.floor(Date.now() / 1000) } = {}) {
  const target = new URL(url)
  const digest = await digestHeader(body)
  const nonce = toBase64(crypto.getRandomValues(new Uint8Array(32)))
  const app = [['accept', '*/*'], ['content-type', 'application/json'], ['signature-agent', SIGNATURE_AGENT]]
  const values = [['@method', method], ['@scheme', target.protocol.slice(0, -1)], ['@authority', target.host], ['@path', target.pathname], ['@query', target.search || '?'], ['content-digest', digest], ...app]
  const list = values.map(([name]) => `"${name}"`).join(' ')
  const params = `(${list});created=${now};expires=${now + 60};keyid="${keyId}";alg="ed25519";nonce="${nonce}";tag="agent-browser-auth"`
  const base = [...values.map(([name, value]) => `"${name}": ${value}`), `"@signature-params": ${params}`].join('\n')
  const signature = toBase64(await crypto.subtle.sign('Ed25519', agent.keys.privateKey, encoder.encode(base)))
  return {
    method,
    url,
    body,
    headers: { ...Object.fromEntries(app), 'content-digest': digest, 'signature-input': `sig2=${params}`, signature: `sig2=:${signature}:` },
  }
}

function buildBase({ method, publicUrl, headers, components, rawParams }) {
  const url = new URL(publicUrl)
  const derived = { '@method': method, '@scheme': url.protocol.slice(0, -1), '@authority': url.host, '@path': url.pathname, '@query': url.search || '?' }
  const lines = components.map((name) => `"${name}": ${name.startsWith('@') ? derived[name] : headers[name]}`)
  return [...lines, `"@signature-params": ${rawParams}`].join('\n')
}

export function demoNonceStore() {
  const seen = new Set()
  return (id) => {
    if (seen.has(id)) return false
    seen.add(id)
    return true
  }
}

export async function demoCheck({ request, publicUrl, registry, reserveNonce }) {
  const steps = []
  const finish = (result) => ({ steps, result })
  const refuse = (code, message) => finish({ ok: false, code, message, status: 403, judged: true })
  const input = /^(\w+)=\(([^)]*)\)(.*)$/.exec(request.headers['signature-input'] ?? '')
  const signed = /^\w+=:([A-Za-z0-9+/]+={0,2}):$/.exec(request.headers.signature ?? '')
  if (!input || !signed) {
    steps.push({ id: 'arrives', outcome: 'stop', detail: 'No Signature or Signature-Input header.' })
    return refuse('tap_missing', 'The request has no Signature-Input and Signature headers.')
  }
  const components = input[2].split(' ').map((item) => item.replace(/"/g, ''))
  const keyId = /keyid="([^"]+)"/.exec(input[3])?.[1]
  const nonce = /nonce="([^"]+)"/.exec(input[3])?.[1]
  if (!keyId || !nonce) {
    steps.push({ id: 'arrives', outcome: 'stop', detail: 'Signature-Input has no keyid or no nonce.' })
    return refuse('tap_malformed', 'Signature-Input needs a keyid and a nonce.')
  }
  steps.push({ id: 'arrives', outcome: 'pass', detail: `${request.method} ${publicUrl}, signed with key ${keyId}.` })

  if ((await digestHeader(request.body)) !== request.headers['content-digest']) {
    steps.push({ id: 'base', outcome: 'stop', detail: "The body's digest doesn't match the signed one." })
    return refuse('tap_signature_invalid', 'The body does not match the signed Content-Digest. Digest the raw bytes, before anything parses them.')
  }
  const base = buildBase({ method: request.method, publicUrl, headers: request.headers, components, rawParams: `(${input[2]})${input[3]}` })
  steps.push({ id: 'base', outcome: 'pass', detail: base })

  const answer = await registry.lookup(keyId)
  if (answer.status === 503) {
    steps.push({ id: 'lookup', outcome: 'unknown', detail: "The registry answered 503, so nothing is known about this agent, good or bad." })
    return finish({ ok: false, code: 'tap_trust_unavailable', message: 'The registry could not be reached. The agent has not been judged; retry later.', status: 503, judged: false })
  }
  if (answer.status !== 200) {
    steps.push({ id: 'lookup', outcome: 'stop', detail: `The registry answered ${answer.status}.` })
    return refuse('tap_key_unknown', 'This key has no live listing. It may be unknown, paused or revoked; the registry does not say which.')
  }
  const key = answer.body.keys.find((k) => k.id === keyId)
  steps.push({ id: 'lookup', outcome: 'pass', detail: `The registry answered 200: ${answer.body.name}, key ${key.status}.` })

  const spki = fromBase64(atob(key.publicKey).replace(/-----[^-]+-----|\s/g, ''))
  const publicKey = await crypto.subtle.importKey('spki', spki, 'Ed25519', false, ['verify'])
  const valid = await crypto.subtle.verify('Ed25519', publicKey, fromBase64(signed[1]), encoder.encode(base))
  if (!valid) {
    steps.push({ id: 'signature', outcome: 'stop', detail: "The signature doesn't match the rebuilt base." })
    return refuse('tap_signature_invalid', 'The signature does not verify for this exact request. Check that your pinned origin is what the agent signed for.')
  }
  steps.push({ id: 'signature', outcome: 'pass', detail: 'The signature matches the rebuilt base.' })

  if (!(await reserveNonce(`${keyId}:${nonce}`))) {
    steps.push({ id: 'decision', outcome: 'stop', detail: 'This nonce has been used.' })
    return refuse('tap_replayed', 'This key and nonce were already used. Sign a new request.')
  }
  steps.push({ id: 'decision', outcome: 'pass', detail: `Accepted, as ${answer.body.name}.` })
  return finish({ ok: true, code: 'ok', status: 200, judged: true, agentId: answer.body.id })
}

export const RECORDED = {
  "created": 1794015659,
  "expires": 1794015719,
  "method": "POST",
  "url": "https://market.example/tasks/42/claim?ref=a",
  "body": "{\"task\":42}",
  "requestHeaders": [
    [
      "accept",
      "*/*"
    ],
    [
      "content-type",
      "application/json"
    ],
    [
      "signature-agent",
      "\"https://sbx.agenticdirectory.visa.com\""
    ]
  ],
  "signedHeaders": {
    "content-digest": "sha-256=:lVH0Kpm71IxwuPvOjdCShjrzCouWTVbs3GY4TjGfhnk=:",
    "signature-input": "sig2=(\"@method\" \"@scheme\" \"@authority\" \"@path\" \"@query\" \"content-digest\" \"accept\" \"content-type\" \"signature-agent\");created=1794015659;expires=1794015719;keyid=\"0724f773-1e12-4966-ab95-502df601b745\";alg=\"Ed25519\";nonce=\"wIQzesDQ80am35XZeFNxIkG9CEjM86EN87uqK4AAHz0=\";tag=\"agent-browser-auth\"",
    "signature": "sig2=:x5AU31TrhTFyRmGcPpQGYTgdQYUbeylnY4kXYa1+XUFsKLSH7y8P9zYXNNCOpMB5YmOEa8R8K4PkIS8PM1BaAw==:"
  },
  "listing": {
    "id": "test-agent",
    "name": "TEST AGENT (simulated, not a real agent)",
    "simulated": true,
    "domain": "https://test-agent.invalid/agent",
    "isActive": true,
    "createdAt": "2026-11-06T00:00:00.000Z",
    "updatedAt": "2026-11-06T00:00:00.000Z",
    "keys": [
      {
        "id": "0724f773-1e12-4966-ab95-502df601b745",
        "directory": {
          "agentDomain": "https://test-agent.invalid/agent",
          "directoryOrigin": "https://sbx.agenticdirectory.visa.com"
        },
        "agentId": "test-agent",
        "keyName": "gFiSNpv2_yiQursiwR10NPDojaaeo-hZqMQzyOkt880",
        "status": "active",
        "algorithm": "ed25519",
        "publicKey": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUNvd0JRWURLMlZ3QXlFQU9UOHYrMWFwL2hFeGV0L2wyZi90YyttblFPWCtOb3YydWxWS2RDNTRXNU09Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo=",
        "jkt": "gFiSNpv2_yiQursiwR10NPDojaaeo-hZqMQzyOkt880",
        "expirationDate": null
      }
    ]
  }
}

export const SCENARIOS = [
  { id: 'clean', label: 'Send it as signed' },
  { id: 'body', label: 'Change the body', code: 'tap_signature_invalid' },
  { id: 'url', label: 'Change the URL', code: 'tap_signature_invalid' },
  { id: 'replay', label: 'Send it twice', code: 'tap_replayed' },
  { id: 'unknown', label: 'Use an unknown key', code: 'tap_key_unknown' },
  { id: 'down', label: 'Take the registry down', code: 'tap_trust_unavailable' },
]

export function recordedRequest() {
  const headers = { ...Object.fromEntries(RECORDED.requestHeaders.map(([k, v]) => [k.toLowerCase(), v])), ...Object.fromEntries(Object.entries(RECORDED.signedHeaders).map(([k, v]) => [k.toLowerCase(), v])) }
  return { method: RECORDED.method, url: RECORDED.url, body: RECORDED.body, headers }
}

export function recordedKeyId() {
  return /keyid="([^"]+)"/.exec(RECORDED.signedHeaders['signature-input'])[1]
}

export function recordedRegistry() {
  const registry = createRegistry()
  registry.publishListing(recordedKeyId(), RECORDED.listing)
  return registry
}

export async function runScenario(id, agent, registry, reserveNonce = demoNonceStore()) {
  const signed = agent?.fetchSigned ? await agent.fetchSigned() : agent ? await signRequest(agent) : recordedRequest()
  let request = signed
  let publicUrl = signed.url
  if (id === 'body') request = { ...signed, body: '{"task":43}' }
  if (id === 'url') publicUrl = signed.url.replace('/tasks/42/', '/tasks/43/')
  if (id === 'unknown') {
    request = { ...signed, headers: { ...signed.headers, 'signature-input': signed.headers['signature-input'].replace(/keyid="[^"]+"/, `keyid="${crypto.randomUUID()}"`) } }
  }
  if (id === 'replay') await demoCheck({ request, publicUrl, registry, reserveNonce })
  registry.setDown(id === 'down')
  const outcome = await demoCheck({ request, publicUrl, registry, reserveNonce })
  registry.setDown(false)
  return { ...outcome, request, publicUrl }
}

export async function runAll() {
  const registry = recordedRegistry()
  const lines = []
  for (const scenario of SCENARIOS) {
    const { result } = await runScenario(scenario.id, null, registry)
    lines.push(`${scenario.label.padEnd(26)} ${String(result.status).padEnd(4)} ${result.code.padEnd(26)} judged: ${result.judged}`)
  }
  return lines.join('\n')
}

if (globalThis.process?.argv?.[1]?.endsWith('try-it.mjs')) console.log(['A recorded test signature from a throwaway key, with the freshness check off, against a stand-in registry. The listing is named TEST AGENT and marked simulated.', await runAll()].join('\n'))
```

```sh
node try-it.mjs
```

```text title="Output of try-it.mjs"
A recorded test signature from a throwaway key, with the freshness check off, against a stand-in registry. The listing is named TEST AGENT and marked simulated.
Send it as signed          200  ok                         judged: true
Change the body            403  tap_signature_invalid      judged: true
Change the URL             403  tap_signature_invalid      judged: true
Send it twice              403  tap_replayed               judged: true
Use an unknown key         403  tap_key_unknown            judged: true
Take the registry down     503  tap_trust_unavailable      judged: false
```
