This page takes you from a request with a Signature header to a decision, in Node 22 with no dependencies. You don't need an account, an API key or a card to check someone else's agent. When a request passes, you know the agent was admitted to Visa CLI's registry, which tells you what a check means. If you run a marketplace, Add verified agents to a marketplace builds on this page.
You look up the key that signed a request at the registry:
https:/ / auth.visacli.sh/ v1/ tap/ registry/ keys/ {jkt}A key that production's registry doesn't list returns the documented not-listed 404, as a real lookup shows. To see a pass without a listed agent signing for you, use Try it in your browser, npm test in the shortest working verifier, or the test vectors. Test values has everything else you can run without a listed agent.
Decisions
| Decision | What to do |
|---|---|
| Pin | Your public https:// origin, passed once through pinnedOrigin() at startup, and the origin you read keys from: Visa CLI's registry, https://auth.visacli.sh, or for agents registered through an enabler, the Visa Agent Directory, https://agenticdirectory.visa.com (https://sbx.agenticdirectory.visa.com in sandbox). Never take either from Host, forwarding headers or Signature-Agent |
| Accept | A request in the exact profile, signed by a key that's listed and active, with no Signature-Agent or one on your allowlist, "https://sbx.agenticdirectory.visa.com" or "https://agenticdirectory.visa.com". From the Visa Agent Directory, accept only the TRIDs you list: in sandbox that's Basis Theory's shared 40010092347, which is for tests only, and in production the integrators you've chosen |
| What a pass tells you | It depends on where the key is listed. From Visa CLI's registry, the agent's owner passed Visa CLI's card step with a Visa card. From the Visa Agent Directory, it's what the integrator under that TRID checks before it registers an agent, so ask each integrator you accept. From the sandbox TRID, nothing: anyone with a Basis Theory test tenant can register an agent |
Refuse, 403 | Every code except the two below, as the table lists. tap_key_unknown covers an unknown, paused or revoked key alike, and tap_key_inactive a key whose expirationDate has passed |
Couldn't check, 503 | tap_trust_unavailable and tap_trust_invalid. Answer 503 with Retry-After, don't let the request through, and don't record it against the agent |
| Look up fresh | Once without the cache after a signature fails, before you release money, by the agent ID you bound, and wherever acting on a key revoked in the last 60 seconds would matter. Otherwise an answer may be cached for up to 60 seconds |
Try it
Break a request on purpose and watch which check refuses it. It runs in your browser with no account, and a first check takes under a minute. It runs on a recorded signature with the freshness check off, against a stand-in registry, and the block labels it that way. The signature was made with a throwaway test key, not a real agent's, and the listing is marked simulated. The demo accepts that simulated listing so you can see a pass. The real verifier refuses a simulated listing as tap_simulated_not_accepted, unless you create it with acceptSimulated: true for a test. The shortest working verifier checks a signature made by Visa CLI's own signing code.
This step was not reached.
const input = /^(\w+)=\(([^)]*)\)(.*)$/.exec(
request.headers['signature-input'] ?? '',
)
const signed = /^\w+=:([A-Za-z0-9+/]+={0,2}):$/.exec(
request.headers.signature ?? '',
)
if (!input || !signed) return refuse('tap_missing')
Getting ready…
Run it on your machine
This needs Node 22 and no dependencies, and the script itself makes no network calls:
The docs serve these files themselves, so you can also download try-it.mjs and verify-example.zip from this page. DOCS defaults to https://app.visacli.sh; if you're reading these docs at another address, run export DOCS=<that address> first. While the docs are private, add -H "Authorization: Bearer <your docs key>" to each curl.
There's no published checksum or signature, so read the file before you run it: the less line opens what you saved. It's the same file as the try-it.mjs printed in full on Verifier code, because the download is served from that printed code, byte for byte.
That's the same code the block above runs, and it prints the same six results. Verifier code has it, along with the verifier to copy and its tests.
DOCS="${DOCS:-https://app.visacli.sh}"
curl -fsSO "$DOCS/examples/try-it.mjs"
less try-it.mjs
node try-it.mjsHow far this has been run
A real Visa CLI signature has passed this page's verifier against the real sandbox registry. On 18 November 2026 a newly connected production agent's key resolved in the Visa Agent Directory as active, ed25519, with agentType: "known", and Visa CLI's registry answered 200 with directoryOrigin set to https://agenticdirectory.visa.com. On 17 November 2026 we also revoked a real sandbox key through Basis Theory: the Visa Agent Directory sandbox answered 404 for it straight away, and the verifier, reading the Visa Agent Directory, refused the next request as tap_key_unknown.
What we tested with a real agent
The agent was a real one, connected through Visa CLI by an owner who had passed the card step. It signed an identity request with attest_http_request, and we sent that request to the verifier on this page, which read the sandbox registry.
- The key's status. In the Visa Agent Directory sandbox, the key was
activeand the agent readagentType: "known". The registry answered200for the same key. - The sandbox registry. Its key list,
/.well-known/http-message-signatures-directoryAPI, held 25 keys at the time, and a key lookup answered200withcache-control: public, max-age=60. - Money. No money moved. It was an identity request, so nothing was paid or charged.
- The key ID. The
keyidwas a UUID from the Visa Agent Directory, 36 characters, not a 43-character thumbprint. The agent also signedsignature-agentand sentSignature-Agent: "https://sbx.agenticdirectory.visa.com", quotes included, which is the value an agent in the Visa Agent Directory sandbox sends. Visa CLI agents send it. The example verifier accepts a request without it and checks it when it's sent.
What we sent, and what came back
| What we sent | Result |
|---|---|
| The real signed request | Accepted |
| The same request again | tap_replayed |
| The body changed | tap_signature_invalid |
| The URL changed | tap_signature_invalid |
| No signature | tap_missing |
The verifier's code names have changed since that run, and these are today's names. Since that run we've added several refusals to the verifier. We ran the new version offline against a recording of that real signature, and it was accepted. There's no public test agent, so to test against a real one, see Before you start.
The shortest working verifier
This is a whole server that verifies signed requests and answers each one with the result, in Node or in Python. Every check described below is already wired up in it. verify-example.zip has both servers, with the verifier beside each and their tests, and npm test runs all of them without the network. It needs Node 22 and Python 3, and no packages.
The zip has no published checksum or signature, so read it before you run it: the less line opens every code file you unpacked. Each one is the same file as the one printed in full on Verifier code and Test your verifier, because the zip is built from that printed code, byte for byte.
DOCS="${DOCS:-https://app.visacli.sh}"
curl -fsSO "$DOCS/examples/verify-example.zip"
unzip verify-example.zip && cd verify-example
less *.mjs *.py
npm test
PUBLIC_ORIGIN=https://market.example node server.mjs- Run
npm test. Each test ends withall passed, and both vector runners end with94 of 94 passed. - Set
PUBLIC_ORIGINto thehttps://origin agents sign for, then startnode server.mjsorpython3 server.py. It listens on port 8080, or onPORT. - Send it a signed request. A pass answers
200with the key ID and agent ID. A refusal answers403, except a body over 1 MiB, which the server refuses with413before the check runs. A check that couldn't run answers503withRetry-After.
REGISTRY_ORIGIN sets where keys are looked up, and defaults to https://auth.visacli.sh. The verifier never follows a redirect from the registry, which counts as couldn't check, tap_trust_unavailable with 503, and it accepts a plain http:// registry origin only for the exact loopback origins localhost, 127.0.0.1 and [::1], refusing any other at startup. A redirect is refused because trust in a key must not move to another origin: Node reads with redirect: 'error', Python with redirects turned off, and a test vector pins it. The loopback origins are for development, which is how the tests reach their stand-in registry. Visa CLI's own verifier has the same http:// rule.
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}`)
}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
}
}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()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_requestThe full verifier files are on Verifier code: verify-agent.mjs, and verify_agent.py with its test.
One signed request, step by step
A Visa CLI agent signs one request with Visa CLI's profile of TAP, named tap-http-request-v1. The name doesn't appear in the headers, so you recognize it by the tag and the signed components. These headers are in the exact form Visa CLI's signer produces, signed with a throwaway test key:
In words: the signature covers the method, scheme, host, path, query and body digest, and the headers the agent chose to sign, so changing any of them makes the check fail. keyid says which key to look up, and the nonce lets you refuse a replay.
What each piece is, and what it proves
| Piece | Value here | What it proves |
|---|---|---|
signature | sig2=:EN91…: | The holder of the private key signed everything below |
keyid | 11111111-… | Which key to look up. Its listing tells you which agent it belongs to |
tag | agent-browser-auth | This is an identity request and not a payment |
alg | ed25519 | Which algorithm to verify with. Earlier Visa CLI releases sent Ed25519, so accept both |
created, expires | 60 seconds apart | The signature is fresh |
nonce | 32 random bytes | With your store, that you haven't accepted it before |
@method, @scheme, @authority, @path, @query | POST, https, market.example, /tasks/42/claim, ?ref=a | It was signed for this action at this address, and can't be pointed elsewhere. @authority is the host the client dialled, your public origin, even behind a CDN |
content-digest | sha-256=:lVH0…: | The body is the one the agent signed |
accept, content-type | */*, application/json | These headers weren't changed |
signature-agent | The Visa Agent Directory sandbox | Whether the agent says it's in the Visa Agent Directory or its sandbox. It's only a claim, so compare it to an allowlist and never fetch from it |
x-idempotency-key | abc | The agent's own header, also signed. Any header it signs gets this protection |
Host is deliberately missing from that table, because you rebuild @authority from your own origin rather than trusting it. That's why the verifier takes your pinned origin and the request target as two separate inputs, publicOrigin and target in Node, and builds the URL itself: it refuses a target that doesn't start with a single / first, so nothing in the request line can change the host or port it checks against. Pass the target exactly as it arrived, such as req.url in Node's http module or self.path in Python's http.server.
For a JSON POST that a Visa CLI agent signs with a UUID keyid, the signed headers after content-digest are accept, content-type and signature-agent, sorted by name together with any other header the agent asked to sign, such as x-idempotency-key here.
The signature base is what actually got signed: one "name": value line per signed component, in the signed order, then the @signature-params line. That last line is "@signature-params": followed by the Signature-Input member value exactly as it arrived, everything after sig2=, copied as received rather than parsed and serialised again.
POST /tasks/42/claim?ref=a HTTP/1.1
Host: market.example
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==:
{"task":42}"@method": POST
"@scheme": https
"@authority": market.example
"@path": /tasks/42/claim
"@query": ?ref=a
"content-digest": sha-256=:lVH0Kpm71IxwuPvOjdCShjrzCouWTVbs3GY4TjGfhnk=:
"accept": */*
"content-type": application/json
"signature-agent": "https://sbx.agenticdirectory.visa.com"
"x-idempotency-key": abc
"@signature-params": ("@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"The exact profile
In words: the label is sig2, the tag is agent-browser-auth, alg is Ed25519 or ed25519, a signature lives at most 60 seconds, the nonce is 32 random bytes, and the covered components always start with @method, @scheme, @authority, @path, @query and content-digest, in that order.
The full profile, field by field
| Field | Rule |
|---|---|
| Label | sig2. attest_http_request signs with sig2, and that's the only label this check accepts. Visa CLI's built-in task tools sign the same tag and components with the label sig1, and this check refuses those as tap_malformed. They only reach a marketplace that's in those tools, as Sign requests as an agent explains |
| Tag | agent-browser-auth for identity requests. attest_http_request answers with "profile": "tap-http-request-v1", which names the profile. The signature itself carries tag="agent-browser-auth", so check the tag, not the profile name. With its default settings, the example verifier refuses any other tag, including the paid tag agent-payer-auth, as tap_malformed with the reason signature_input_format. It has no separate code for a tag, such as tag_not_accepted |
| Algorithm | Ed25519. The alg value is exactly Ed25519 or ed25519. Other spellings, such as ED25519, are refused. The listed key has to be an Ed25519 key too, or the check can't use it. Reading the Visa Agent Directory, the example verifier also accepts a P-256 key with alg="ecdsa-p256-sha256", as Read the Visa Agent Directory instead explains. A signature whose alg doesn't match the key is refused as tap_signature_invalid, with the reason algorithm_mismatch |
keyid | A lowercase UUID when the key has metadata from the Visa Agent Directory, otherwise a thumbprint. The registry resolves both |
| Lifetime | At most 60 seconds, with up to 30 seconds of clock skew on created |
| Nonce | 32 random bytes in canonical base64 |
| Covered, in order | @method, @scheme, @authority, @path, @query, content-digest, then every application header the agent asked to sign, sorted by name. Headers the agent didn't sign are refused, except the transport headers, which include accept and user-agent because HTTP clients add them on their own. Don't rely on an unsigned accept Two of those headers can come from the signer rather than your app: signature-agent, which the signer adds when it names the Visa Agent Directory, and accept, which sign.mjs and sign.py sign as */* unless you pass one. Every other header after content-digest is one your app chose to sign. When you list your app's own signed headers for a signer, leave those two and the derived components out, or they're signed twice |
| Never signed | Origin, Host, Via, Forwarded, Referer, Connection, Content-Length, Transfer-Encoding, Cookie, Authorization, the payment headers, and any name starting x-forwarded-, sec- or proxy-. A signature that covers one is refused, as Visa CLI's own verifier does |
| Limits | At most 38 covered components. Each signed header value is printable ASCII, at most 4096 characters, with no space at either end, and the signed headers come to at most 16384 characters |
@query | The raw query with its ?, or a lone ? when there's none |
content-digest | SHA-256 of the raw body, as sha-256=:<base64>:. Always present, including for an empty body |
| Methods | GET, HEAD and POST over HTTPS. The check refuses a pinned origin that isn't https://, as origin_not_https |
A Visa CLI agent with a UUID keyid also signs signature-agent. The example verifier accepts a request without that header, and checks it when it's sent. A generic TAP library may not accept this profile, as the next section explains.
How this differs from Visa's published TAP
These pages describe the profile Visa CLI's agents sign with. A tool built only for Visa's published TAP won't necessarily accept it. For example, Visa CLI signs @scheme, which Visa's published minimum doesn't include, so a verifier that only allows the published components will refuse it.
It works the other way too. The example verifier checks Visa CLI's profile only, so it refuses a signature made to Visa's published minimum, such as one from mppx's TAP signer: label tap, only @authority and @path, and up to 480 seconds. To accept those agents, use a verifier for the published minimum, such as mppx's TAP verifier, with a key resolver that reads the Visa Agent Directory and applies the example's listing checks: key status, expiry and the keyid match. Know what mppx's verifier refuses before you choose it:
- It reads
algonly ased25519orrsa-pss-sha512, so it refusesEd25519and P-256 keys, which Basis Theory recommends. If you accept agents registered through Basis Theory, use the example verifier with the Visa Agent Directory instead. - It can't rebuild
@method,@queryor@scheme, so it refuses Visa CLI's agents and any agent that signs more than the minimum. - It reports an outage of the Visa Agent Directory, or a failed nonce store, as a 403 refusal. Treat that as couldn't check, not as a bad agent.
- It doesn't check the tag per route. A payment signature passes an identity route, and the reverse, so your handler has to check the returned
intenton every route.
An mppx agent-payer-auth signature covers only @authority and @path, not Authorization, so it says nothing about who paid. Visa CLI's paid signatures do cover it.
| Visa's published TAP | Visa CLI | |
|---|---|---|
| Tags | agent-browser-auth, agent-payer-auth | agent-browser-auth on identity requests, such as a claim or a pitch. agent-payer-auth only on paid requests, which an identity check refuses |
| Minimum signed components | @authority, @path | @method @scheme @authority @path @query content-digest, then every application header, for identity requests |
| Signature lifetime | Up to 480 seconds | 60 seconds for identity requests. Paid requests are in the table below |
| Algorithm | Matches the key | Ed25519 |
| Where you look up keys | The Visa Agent Directory | The Visa Agent Directory, or Visa CLI's registry. See Where to look up a key |
Visa CLI signs three kinds of request, and a paid request has two forms. The maximum is the longest a verifier should accept.
- Identity request (sig2)
Maximum lifetime: 60 seconds
Covered components: As in the table above
Tag:
agent-browser-auth- Built-in verified task (sig1)
Maximum lifetime: 60 seconds
Covered components: The same as an identity request
Tag:
agent-browser-auth
On a paid request authorization is the Authorization: Payment credential, and only that scheme counts. A Bearer or Basic value never binds to an identity. Checking the signature doesn't check the payment: verify the credential and its settlement through your payment integration before you deliver anything, as Pay with MPP describes.
Run the checks in this order
The order decides which code comes back when a request has more than one fault, and the test vectors pin it.
- Parse
Signature-InputandSignature, and keep the raw parameters. - Refuse a pinned origin that isn't
https://or isn't in normal form. Then refuse a request target that doesn't start with a single/, before building any URL from it, and one that isn't in normal form: dot segments, encoded dots or slashes, backslashes or a fragment. What counts as normal form is explained below the list. - Enforce the components a key ID from the Visa Agent Directory needs, the lifetime, the required components, the method, and refuse
Authorization,Cookie,X-PaymentorPayment-Signature, even unsigned. If your API uses a login, take it off first. - Refuse a covered header that's out of order, missing, over the limits or never signed in this profile. Then refuse any header the signature doesn't cover, unless it's a transport header.
- Refuse a body over 1 MiB and a
content-digestthat isn'tsha-256=:<base64>:, astap_malformed. Then recomputecontent-digestfrom the raw body bytes, before anything parses them. - Compare any
Signature-Agentto your allowlist. - Fetch the key. A listing whose key isn't one the source allows (Ed25519 from Visa CLI's registry; Ed25519 or P-256 from the Visa Agent Directory), or whose
expirationDateisn't an RFC 3339 date-time with a zone, such as2027-01-01T00:00:00Z, is couldn't check,tap_trust_invalidwith503, not a refusal. Use the listed key only if the thumbprint you compute from itspublicKeyequals thekeyid, or, when thekeyidis a 36-character UUID, the key'sidequals thekeyidand itsjktequals the thumbprint you computed. Never take a thumbprintkeyidon the listing's word: a listing that pairs it with a different key is refused astap_key_inactive, as Visa CLI's own verifier does. A key whoseexpirationDatehas passed is refused, astap_key_inactive. Visa CLI's registry sends the date the key's listing in the Visa Agent Directory ends. Then rebuild the signature base from your own public origin, not fromHostor forwarding headers, and verify the signature. If it fails, fetch the key once more without the cache and verify again before refusing, even if the cached key is only seconds old, in case the key has just changed. The example does exactly this. If that fresh fetch can't be made, the answer is couldn't check, not a refusal, and the cached key stays in the cache. - Reserve
keyidplus nonce untilexpires. Do this last, so a forged request can't use up a nonce. Once a signature verifies, its nonce is used up, even if your own later step, such as taking payment, then refuses or fails, so a retry needs a freshly signed request with a new nonce.
What counts as normal form, and why
Pasted after your origin, a target such as .attacker.example/tasks/42/claim, :8443/tasks/42/claim or @attacker.example/tasks/42/claim would move @authority to a host or port the agent signed for elsewhere, so a signature meant for another site would pass. The signature covers the path exactly, and many servers would route /tasks/43/../42/claim to task 42, so it's refused rather than normalized. Check each path segment yourself and refuse any that is . or ..: some URL parsers, Node 22's among them, leave /tasks/43/.x/../../42/claim as it is, though other parsers route it to task 42. A target is in normal form when a standard URL parser would leave it exactly as sent. So [, ] and | in the path, the same plus ^, {, } and a backtick in the query, and a % that isn't followed by two hex digits all pass as they are. A space, a non-ASCII character, ", < or > anywhere, ^, {, } or a backtick in the path, or ' in the query is refused, because a parser would encode it.
The check never throws. A request it can't read is refused as tap_malformed, and a nonce store that fails is "couldn't check".
Which key in a listing to verify with
A listing, from /v1/tap/registry/keys/{jkt}API or /v1/tap/registry/agents/{tapAgentId}API, is an agent document with a keys array. Verify with one entry only, and trust it only when all of this holds:
- Pick the entry by the
keyid. For a 43-character thumbprintkeyid, take the entry whosejktequals it. For a 36-character UUIDkeyid, take the entry whoseidequals it. - The thumbprint rule. Compute the RFC 7638 thumbprint of the entry's
publicKeyyourself. Use the entry only if that thumbprint equals thekeyid, or, for a UUIDkeyid, if the entry'sidequals thekeyidand itsjktequals the thumbprint you computed. Never take a thumbprintkeyidon the listing's word. statusisactiveandalgorithmised25519on every entry, and each entry'sagentIdis the document'sid. Anything else means the answer is unusable: couldn't check,tap_trust_invalid.- The agent is live:
isActiveistrue, or the refusal istap_key_inactive. - Not expired:
expirationDateisnullor an RFC 3339 date-time still ahead. Passed istap_key_inactive; unreadable is couldn't check.
If no entry matches, the key isn't one of the agent's live keys, tap_key_inactive. The example's readListing and judgeKey do exactly this.
Transport headers
These may arrive unsigned, and every other header has to be signed or the request is refused. Is a request refused for a header that isn't in Signature-Input? No, if it's one of these transport headers, such as x-request-id or cf-ray: the check ignores it. Yes for any other header: the example refuses it as tap_malformed with the reason uncovered_header, as Visa CLI's own verifier does, which is stricter than plain RFC 9421, where an uncovered header is simply not checked. In words: standard client, proxy and tracing headers, such as host, user-agent, x-forwarded-for and traceparent, may arrive unsigned, and so may every request header that Cloudflare, Vercel, Fly.io and Google Cloud document. Any other header, including an identity header that a proxy adds, has to be signed.
Every transport header, by host
| Added by | Headers |
|---|---|
| HTTP clients and servers | host, content-length, connection, transfer-encoding, keep-alive, accept, accept-language, accept-encoding, user-agent, and anything starting sec-fetch- |
| Proxies, as standard forwarding | 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 |
| Tracing: W3C, Zipkin, AWS and request IDs | 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 |
| Cloudflare, from its request headers and visitor location headers | 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 |
| Vercel, from its request headers | 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.io, from its request headers | fly-client-ip, fly-forwarded-port, fly-region, fly-request-id |
| Google Cloud's load balancer, from its target proxies | via, x-forwarded-for, x-forwarded-proto, x-cloud-trace-context, all in the rows above |
Each host's row holds every request header its page lists, checked on 7 November 2026, and the test vectors have one accepted case per host that sends all of them unsigned. A few host headers are left out on purpose, because an app might act on them: Cloudflare's optional bot score, client certificate and leaked-credential headers, and Vercel's x-vercel-signature, which Vercel sends only with its own webhooks.
When your host adds a header that isn't listed
Hosts add headers over time, and other hosts add their own. If yours adds one that isn't listed, the refusal is tap_malformed with the reason uncovered_header, and header names the one that caused it. You can then take it off before the check, the way the marketplace example takes off Authorization and Cookie, or name it once when you create the verifier:
const verifyRequest = createVerifier({
registryOrigin: 'https://auth.visacli.sh',
reserveNonce: memoryNonceStore(),
extraTransportHeaders: ['x-my-host-request-id'],
})Only name a header there that your own edge sets on every request and that you never act on.
Don't trust an unsigned identity header. Headers such as x-forwarded-user or x-forwarded-email aren't on the list, so the check refuses a request that carries them unsigned. If your proxy adds them, take them off before the check, and never act on one that the agent didn't sign.
Refuse a request
Every outcome of the check is one of three kinds: verified, refused or couldn't check. judged keeps the last two apart, and that's what stops a registry outage from reading as a bad agent. These are the codes the check returns, so they're safe to branch on.
In words: tap_trust_unavailable and tap_trust_invalid are the only codes that mean couldn't check, and they answer 503 with judged: false. Every other code is a refusal that answers 403 with judged: true, and tap_key_unknown covers an unknown, paused or revoked key alike.
The answers people look for most:
tap_key_unknownis403,judged: true. The registry answered404.tap_key_inactiveis403,judged: true. The registry answered200, but the agent isn't live or thiskeyidisn't one of its live keys, such as a key whoseexpirationDatehas passed.- A paused Visa CLI agent gets
tap_key_unknown,403, because Visa CLI's registry answers404for a paused agent. You'd seetap_key_inactiveonly from a source that answers200withisActive: false. - A registry
200whose body the verifier can't parse or use getstap_trust_invalid,503,judged: false, withreason: "listing_unusable". It's couldn't check, never a refusal. - A registry, or the Visa Agent Directory, that can't be reached, times out, redirects, or answers anything other than
200or404, such as401,429or5xx, getstap_trust_unavailable,503,judged: false.
Every refusal code and its HTTP status
tap_missingStatus:
403judged:
trueWhat it means: No signature headers
What to do: The sender needs to sign the request
tap_malformedStatus:
403judged:
trueWhat it means: Not this profile: wrong label or tag, a nonce that isn't 32 bytes, a required component left out,
Authorization,Cookie,X-PaymentorPayment-Signaturestill on the request, a header the signature doesn't cover, a covered header that's out of order or never signed in this profile, acontent-digestthat isn'tsha-256=:<base64>:, a request target that doesn't start with a single/or isn't in normal form, or a pinned origin that isn'thttps://or isn't in normal form.reasonsays which, andheadernames an uncovered headerWhat to do: Remove your own login headers before the check. Otherwise refuse, because something added a header or the sender isn't using this profile
tap_expiredStatus:
403judged:
trueWhat it means: Past
expires,createdmore than 30 seconds in the future, or a lifetime over 60 secondsWhat to do: A new signature fixes it. If every request fails, check your clock
tap_signature_invalidStatus:
403judged:
trueWhat it means: The body or the rebuilt signature doesn't match, or the signature's
algisn't the listed key's algorithm.reasonisbody_digest_mismatch,signature_mismatchoralgorithm_mismatchWhat to do: Check you're digesting raw bytes and that your pinned origin is what the agent signed for. Otherwise refuse
tap_replayedStatus:
403judged:
trueWhat it means: You've already accepted this
keyidand nonce, even if your own step after the check then failedWhat to do: The agent asks Visa CLI to sign the request again, which gives it a new nonce, and sends that. Never accept the same nonce twice
tap_key_unknownStatus:
403judged:
trueWhat it means: Registry
404: unknown, paused, revoked or still publishingWhat to do: Refuse. These look the same on purpose
tap_key_inactiveStatus:
403judged:
trueWhat it means: A listing that says the agent isn't live, or has no live key for this
keyid, such as a key whoseexpirationDatehas passed. Visa CLI's registry answers404for a paused agent instead, so from it you'll seetap_key_unknown. The check handlesisActive: falsefor other sourcesWhat to do: Refuse
tap_signature_agent_not_acceptedStatus:
403judged:
trueWhat it means: The value isn't on your allowlist
What to do: Allow only the values you accept
tap_simulated_not_acceptedStatus:
403judged:
trueWhat it means: The listing is marked
simulated, so it's a testWhat to do: Refuse outside a test
tap_trust_invalidStatus:
503judged:
falseWhat it means: Couldn't check. The registry answered something that can't be right: a
200body that isn't JSON or isn't a listing, a key whosestatusis missing or isn'tactive, since the registry only lists active keys and always says so, a key whosealgorithmis missing or that isn't Ed25519, or anexpirationDatethat isn't an RFC 3339 date-time with a zoneWhat to do: The same as above
When the registry answers 200 with a body that isn't a usable listing, the example answers tap_trust_invalid with 503 and Retry-After, while Visa CLI's own verifier answers 500 and treats it as not worth retrying. The example uses 503 because the fault is upstream rather than in the request, so the agent can try again later and nobody reads it as a bad agent.
Every result of the check that isn't a pass carries reason, which is finer than the code and meant for your logs, and message, which says what to fix. Branch on code.
Errors the example servers answer before the check
The example servers also answer a few HTTP errors before the check runs. These aren't results of the check, so they carry only ok: false and code, with no judged, reason or message: 413 with body_too_large for a body over 1 MiB, from both servers, 500 with internal_error when the server fails unexpectedly, where server.py closes the connection instead, and, from server.py only, 400 with bad_content_length (a missing number, a sign, or two different values), bad_transfer_encoding or bad_chunk for a body it can't read. Node's own HTTP parser answers those cases with a plain 400 before server.mjs sees them. A client can treat any of them as "the request didn't reach the check".
When a request passes you get ok: true, with keyId, jkt, agentId, agentName, simulated, covered and expires. Keep the key ID, agent ID and the time you checked.
A 404 from the registry looks the same for unknown, revoked, paused and expired keys, and Visa sends no notice when a key is revoked. The body also carries guidance fields worded for Visa CLI's own agent, such as message and fix, which a verifier doesn't read, so branch on the status and code. Real responses are on Where to look up a key.
What differs from Visa CLI's own verifier
There's no installable package, so you copy the example file.
- The example fetches a key again after a failed signature, so a replaced key doesn't fail for up to 60 seconds. Visa CLI's own verifier doesn't. Step 7 of the checks is our advice for your verifier.
- Visa CLI's own verifier takes a Fetch API
Request, which has already parsed the target and uppercased the method. So it checks the signature against the parsed path where the example refuses a target that isn't in normal form, it accepts a^in the path where the URL parser leaves it, as Node 22's does. Node 22's parser also leaves..in place after a segment that starts with a dot, as in/tasks/43/.x/../../42/claim, so on Node 22 Visa CLI's own verifier accepts that path when it was signed as sent, where the example refuses it. And it readspostasPOSTwhere the example refuses it. - The example requires
isActiveon the listing. Visa CLI's own verifier also accepts the agent'sstatusin its place. Visa CLI's registry always sendsisActive. - When the registry answers
200with an unusable body, Visa CLI's own verifier answers500. The example answers503withRetry-After, as couldn't check, for the reason under Refuse a request. - Visa CLI's own verifier returns only a
code: noreason, and no wait taken from the registry'sRetry-After. - Visa CLI's own verifier reads only Visa CLI's registry, never the Visa Agent Directory, and has no settings for which
Signature-Agentvalues, simulated listings or extra transport headers it accepts. It always uses the example's defaults.
If you find documentation for a verifier that expects a payment credential, that's the paid path. It refuses every unpaid identity request as though the signature were missing. The relying-party handler in Visa CLI's verifier SDK, and the sample server built on it, are the legacy x402 path, from before Visa CLI retired x402, so don't use them for a new paid endpoint.
Why the example accepts both Signature-Agent values
The example accepts the sandbox value and the production value of Signature-Agent, so one verifier keeps working when listings move. The header is only the agent's claim about whether it's in the Visa Agent Directory or its sandbox. You compare it to your allowlist and never fetch from it. What decides a pass is the registry you read and pin in config, so accepting both values doesn't widen who passes. If you want only one, pass allowedSignatureAgents.
Mistakes that cost the most time
A wrong public origin
Behind a proxy, a rebuilt @authority that differs from what the agent signed fails every request with the same tap_signature_invalid. Behind a load balancer, proxy or CDN, @authority is the host the client dialled, which is your public origin, not the internal hostname your app sees in Host. So verify against the public origin you pinned. The example never reads X-Forwarded-Host or Forwarded for this, even though they often carry the public host. Anyone who reaches your app can set those headers, so a request signed for another site could be sent to yours with that site's name in X-Forwarded-Host, and a check that trusted it would pass. A pinned origin makes the check ask whether the agent signed for your address. Pin the origin in config, and pass it through pinnedOrigin() once at startup: it lowercases the host, drops :443 and a trailing slash, and stops the server with a clear message if the origin isn't https://, or if its host isn't plain DNS labels or an IP address, such as one with a trailing dot or an underscore. A pinned origin with capitals or :443 that reaches the check directly is refused as origin_not_normal, so it doesn't send you looking at paths that are fine. Agents can only sign https:// URLs, so in local development pin the HTTPS origin you asked the agent to sign for, even if your server listens on plain HTTP.
A proxy that drops headers
Your proxy or gateway has to forward every signed header, along with signature, signature-input and content-digest, and pass Retry-After back. A gateway that forwards only content-type and authorization removes the signature entirely.
A proxy in front of the check
A gateway that passes requests through to the app doing the check is fine, as long as it forwards everything above and the app pins the public origin. What fails is checking a signature and then sending it on to another service to check again: a signature is for one request to one address, and the nonce is used up after the first check.
Parsed bodies
Digest the raw bytes. Re-serialised JSON won't match. Reading the raw body shows it for Next.js and Express.
Your API already uses Authorization
Agents can't sign it. Authenticate first, remove it before the check, and have the agent sign a header naming the account, then compare the two. Here's the whole pattern.
A per-process nonce store
The example's in-memory store only works for one process, and a restart empties it, so a request captured in the last 60 seconds is accepted again after a restart. Production needs an atomic shared store, such as a Redis SET NX with an expiry or a unique SQL row.
Assuming an outage always shows up
A key cached in the last 60 seconds keeps verifying while the registry is down, so a request can still pass in an outage. A key you don't have cached gets 503, as does a signature that fails against a cached key, because it forces a fetch. To refuse during an outage instead, pass cacheSeconds: 0: every check then reads the registry, so an outage gives 503 for every key, and each check uses up a lookup. In a test, an outage right after a good request still passes on the cached key, which looks like a bug and isn't. Use cacheSeconds: 0 to see the 503. A failed refresh keeps a still-valid cached key, so a forged signature during an outage can't knock out real requests.
Trusting a test key or a stand-in
The test values' key is public, so anyone can sign with it. A stand-in key lookup you run for tests isn't Visa's. Keep both behind a test-only switch that production refuses, never let a stand-in answer for the Visa Agent Directory hosts, and never accept a header that names a key without a signature. Testing in your own code shows the pattern.
Trusting the cache for something consequential
Revocation can take up to 60 seconds to reach you through a cached answer. Make a fresh lookup before a payout. Which ID to use.
Letting bad signatures reach the registry
Each failed signature forces a fresh lookup, so a stream of bad signatures turns into load on the registry. Rate-limit callers before the check.
A paid request
A paid request carries a different tag and component set, described in Sign requests as an agent. The example refuses it as tap_malformed. When a paid request carries more than one payment credential, such as X-Payment and Authorization: Payment, its signature must cover every one of them, so a signature over one can't carry another along unsigned. Visa CLI's own verifier refuses a paid request that leaves one out, as tap_malformed. Verify the payment yourself, since the signature doesn't prove settlement.
If you're a wallet or protocol
The check is the same for any service that receives HTTPS requests from an agent, not only a marketplace. To verify an agent on demand, give it a nonce of your own and have it sign a POST to your endpoint with that nonce in the body. That shows it controls a listed key for that one exchange.
Two things aren't possible today. You can't start from a wallet address and ask whether it's a verified agent, since lookups are by key or agent only. Signing also covers HTTPS GET, HEAD and POST, so there's no on-chain or other non-HTTP proof.
Copy the verifier
The whole verifier and its tests are on Verifier code: three files for Node 22 with no dependencies, the output to compare with yours, and a recorded signature for testing a rebuild in another language.