A poster marks a task verified only, and only an agent whose signed request checks out can claim it. You read one public lookup. Your marketplace doesn't touch a card, and it needs no account or API key.
Run the whole thing
Building the gate takes this page and Verifier code. The rest of the site is background and reference. This needs Node 22 and no dependencies, and the test itself makes no network calls:
The docs serve these files themselves, so you can also download verify-agent.mjs, marketplace.mjs and marketplace-test.mjs 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 files before you run them: the less line opens what you saved. Each is the same file as the one printed in full, verify-agent.mjs on Verifier code, and marketplace.mjs and marketplace-test.mjs on Marketplace code, because the downloads are served from that printed code, byte for byte.
Or download the same three files, with directory-fixture.mjs, a package.json and a README, as one folder of six files: marketplace-example.zip. Unzip it and run npm test.
That started a stand-in registry and a working marketplace, signed requests the way an agent does, and ran 42 cases, including every attack below. Agents' keys are registered in sandbox today, in the Visa Agent Directory sandbox, so label your checks accordingly. What is TAP? says what a check means.
DOCS="${DOCS:-https://app.visacli.sh}"
curl -fsSO "$DOCS/examples/verify-agent.mjs"
curl -fsSO "$DOCS/examples/marketplace.mjs"
curl -fsSO "$DOCS/examples/marketplace-test.mjs"
less verify-agent.mjs marketplace.mjs marketplace-test.mjs
node marketplace-test.mjsall passed (local stand-in registry, not a real Visa CLI agent)The whole gate, in one function
The gate runs four checks, in this order:
- An open task needs nothing. Only a verified-only task goes further.
- The signed member header has to name the logged-in member. This runs before the check, so another member's attempt can't use up the real agent's nonce. See account binding.
- The signature has to check out. A refusal answers
403, and a check that couldn't run answers503withRetry-After, never "unverified". - The agent has to belong to that member.
bindAgentenforces the binding both ways. See Bind a key to a member.
Your app's own refusals, such as a closed task or a duplicate claim, can run before or after the check. Before is cheaper and doesn't use up the nonce; after makes a replayed request read as tap_replayed, which is easier to test. Either is safe.
Marketplace code has the rest of the file. The sections below explain each part.
async function claim(req, task, member, rawBody) {
if (!task.verifiedOnly) return { status: 200, body: { claimed: task.id, checked: false } }
const notMet = (reason, detail, fix, status = 403) => ({
status,
body: { code: 'task_requirement_not_met', reason, detail, fix },
})
const { authorization, cookie, ...headers } = requestHeaders(req)
if (headers['signature-input'] && headers[MEMBER_HEADER] !== member.id) {
return notMet('verification_failed', 'member_mismatch', 'Sign x-market-member as the member who is logged in.')
}
const result = await verifyRequest({
method: req.method,
publicOrigin,
target: req.url,
headers,
rawBody,
})
if (!result.ok) {
return result.judged
? notMet('verification_failed', result.code, result.message)
: { ...notMet('verifier_unavailable', result.code, result.message, 503), retryAfter: String(result.retryAfterSeconds ?? 5) }
}
const refused = await bindAgent(member, result, notMet)
if (refused) return refused
return {
status: 200,
body: {
claimed: task.id,
checked: true,
member: member.id,
keyId: result.keyId,
agentId: result.agentId,
checkedAt: new Date().toISOString(),
},
}
}Stop a signature being used for someone else's account
This is the mistake that matters most. A pass tells you a listed agent signed this request. It doesn't tell you which of your accounts that agent belongs to. If you check the signature and then act for whoever is logged in, or for an account named in the request, then a real signature can be spent on someone else's account.
The safe pattern has three parts, and you need all of them:
- The agent signs a header naming the account, such as
x-market-member: alice. The header carries your own member ID, in whatever form your app uses, such asm_aliceor a UUID. - You compare that header to the logged-in member, and refuse any difference, before you run the check, so an attempt can't use up the real agent's nonce.
- You bind the agent to the member the first time it passes, once the member has just confirmed it with a one-time code sent to the email or phone on file, or an operator's confirmation, never a recent sign-in, and enforce it in both directions after that.
| The attack | What stops it | Test case |
|---|---|---|
| Bob logs in as himself and sends a signed request Alice's agent made | The signed header says alice, and the login says bob | bob sends alice's signature |
Bob's own verified agent signs a request naming alice, sent with Bob's login | The same comparison | bob's own agent signs for alice |
| A signed request that names no member at all | No signed header means no match | signed, but names no member at all |
Something adds x-market-member after signing | The verifier refuses a header the signature doesn't cover | member header added but not signed |
| Bob signs for himself with an agent already bound to Alice | The binding | bob signs for himself with alice's key |
| Someone with Alice's stolen login binds their own agent before Alice has one | A first binding needs a fresh confirmation | first binding on a stolen login alone |
| Mallory types Alice's key ID into her own join form before Alice joins | Bindings come only from a passing signature, never from a typed key ID | See If your app already takes a key ID at sign-up |
| Alice, already bound, types a new key ID into her join form, then signs with that key | A typed key ID can't move a binding | See If your app already takes a key ID at sign-up |
Never take the account from the request body, or from a header that isn't signed, without this comparison. If your service has no login, a signed header on its own proves nothing about the account, because any verified agent can sign any name. Bind each account to its agent ahead of time, through a step only the account's owner can take, and look the account up from the agent ID the check returns.
Decide what you're gating
Gate the requests that commit someone to work or money. Reading a task list doesn't need a signature, and neither does an agent's first look at a task. Claiming a task and submitting work are the usual two. Accept those routes only with the method they're signed for, which is POST. Claiming and binding change state, so a signed GET or HEAD mustn't do either: the example answers any other method on a claim path with 405 and Allow: POST, before it acts on the login or runs the check.
What the agent sends
The agent asks Visa CLI to sign one request, then sends it itself. attest_http_request takes a description of the request and returns this, shown in full on Sign requests as an agent:
| Returned field | What it is |
|---|---|
request.url, request.method | Where and how to send it |
request.headers | Application headers to send, including accept and signature-agent that Visa CLI added |
key_id, created, expires, nonce | The signature's parameters, for logging |
headers | content-digest, signature-input, signature to send |
Tell your integrators this in your own docs: send request.headers AND headers, with the exact body bytes that were hashed, within 60 seconds. Sending only headers fails, because the signature covers headers that wouldn't be there.
Signatures and your existing logins
Most marketplaces already log members in with Authorization: Bearer. A signature can't cover that header: Authorization is refused in this profile, along with Cookie, so that a login token never gets tied up in an identity signature. A paid request is different: it uses another profile, which covers Authorization: Payment and can last longer than 60 seconds, and it's described in Sign requests as an agent. So you keep two separate things, and bind them.
- The login says which member is calling. It travels unsigned, as it does today.
- The signature is a separate proof that a listed agent's key signed this exact request.
- A signed
x-market-memberheader names the member inside the signed request, so the two can be compared. The account ID in the signed body works just as well.
Without that third piece, anyone could take a real agent's signed request and send it with their own login. Agents sign the header like any other:
Then the agent sends the returned headers, adds Authorization: Bearer <token> of its own, and you do this, in this order:
- Authenticate the login, as you do today.
- Take
AuthorizationandCookieoff the headers you pass to the verifier, andX-PaymentorPayment-Signatureif your API uses them. The verifier refuses all four, even unsigned, and refuses any other application header that isn't signed. - If there's a signature, compare the signed member header to the logged-in member. Do this first, so another member's attempt can't use up the real agent's nonce.
- Run the check.
- Check the key's binding.
The member header has to be signed for this to mean anything. The verifier enforces that, because an unsigned x-market-member gets tap_malformed, with the reason uncovered_header.
{
"url": "https://market.example/api/tasks/gated-1/claim",
"method": "POST",
"headers": [
["content-type", "application/json"],
["x-market-member", "alice"]
],
"body_sha256": "BASE64URL_SHA256_OF_THE_BODY"
}Tell agents what to sign
An agent can't guess your member string or the exact URL, and your public origin may not be what it dials. Say so where it finds the task. There's no standard shape, so we suggest this one, which the example uses: sign one header, x-market-member, carrying your member ID, on a POST to the exact claim URL, and publish both with the task:
{
"id": "gated-1",
"verifiedOnly": true,
"signing": {
"url": "https://market.example/api/tasks/gated-1/claim",
"memberHeader": "x-market-member",
"member": "alice"
}
}Read the raw body
The digest covers the bytes the agent sent, so read them before anything parses them. In a Next.js route handler, read the body stream yourself, stop at 1 MiB, and don't call json() on the same request. Keep verify-agent.mjs and its types, verify-agent.d.mts, in lib/. The handler pins the origin once with pinnedOrigin(), and it type-checks with strict on every docs build:
Next.js normalizes the path before your handler runs. It resolves dot segments and encoded dots in request.url, and it picks the route from that same normalized path. So this handler checks the signature against the path Next actually acted on, and the two can't disagree. That's why it takes the target from request.url and is still safe, even though the path-shape request_target_invalid test cases, such as dot segments, never reach it in that form. We sent raw requests over a socket to this handler on a real Next.js 16 build, with a signature made for task 42:
| Request line target | What Next did | Result |
|---|---|---|
/api/tasks/42/claim | Routed to task 42 | 200, accepted |
/api/tasks/43/../42/claim | Routed to task 42, request.url path /api/tasks/42/claim | 200, accepted |
/api/tasks/43/%2e%2e/42/claim | The same | 200, accepted |
/api/tasks\42\claim | Answered 308 before the handler ran | Never checked |
/api/tasks/42/claim#frag | Dropped the fragment, routed to task 42 | 200, accepted |
/api/tasks/43/claim | Routed to task 43 | 403, tap_signature_invalid |
The accepted ones all act on task 42, the task that was signed for. A framework that routes on the raw request target, as Node's http module and Express do, has to pass that raw target to the verifier instead, and must refuse every request_target_invalid case in the test cases. The Express route below does that with req.originalUrl. If you're unsure what your framework does, send it /api/tasks/43/../42/claim signed for 42 and see which task acts.
In Express, give the route the raw parser, ahead of any global express.json():
Both handlers answer a check that couldn't run with 503 and Retry-After, as server.mjs does, so a caller can back off at the HTTP level.
requestHeaders(req) comes from verify-agent.mjs. It keeps every value of a repeated header, because req.headers keeps only the first Content-Type and drops the rest, so the verifier would never see a second, unsigned one. Express doesn't hand you a buffer when a request has no body: req.body is {} on Express 4 and undefined on Express 5, and the sender decides whether there's a body. So the route treats anything that isn't a buffer as empty bytes, and the check refuses it like any other bad request. The error handler answers 413 for a body over the limit and 400 for one that couldn't be read, instead of a stack trace. req.originalUrl is the path exactly as it arrived, and the check refuses any path that isn't in normal form, so the route acts on the same path the signature covers. This runs on Express 4 and 5. Hosts can add headers of their own. The verifier allows the common ones by name, listed under Transport headers, and refuses any other unsigned header as tap_malformed, naming it in header. Take others off at the edge, or name them in extraTransportHeaders.
import { createVerifier, memoryNonceStore, pinnedOrigin } from '@/lib/verify-agent.mjs'
const LIMIT = 1024 * 1024
const publicOrigin = pinnedOrigin(process.env.PUBLIC_ORIGIN ?? '')
const verifyRequest = createVerifier({ registryOrigin: 'https://auth.visacli.sh', reserveNonce: memoryNonceStore() })
const tooLarge = () => Response.json({ ok: false, code: 'body_too_large' }, { status: 413 })
export async function POST(request: Request) {
if (Number(request.headers.get('content-length') ?? 0) > LIMIT) return tooLarge()
const chunks: Uint8Array[] = []
let size = 0
const reader = request.body?.getReader()
while (reader) {
const { done, value } = await reader.read()
if (done) break
size += value.byteLength
if (size > LIMIT) {
await reader.cancel()
return tooLarge()
}
chunks.push(value)
}
const rawBody = Buffer.concat(chunks)
const { authorization, cookie, 'x-payment': payment, 'payment-signature': paymentSignature, ...headers } = Object.fromEntries(request.headers)
const url = new URL(request.url)
const result = await verifyRequest({
method: request.method,
publicOrigin,
target: `${url.pathname}${url.search}`,
headers,
rawBody,
})
const retry = result.ok || result.judged ? undefined : { 'retry-after': String(result.retryAfterSeconds ?? 5) }
return Response.json(result, { status: result.ok ? 200 : result.status, headers: retry })
}const publicOrigin = pinnedOrigin(process.env.PUBLIC_ORIGIN)
app.post('/api/tasks/:id/claim', express.raw({ type: '*/*', limit: '1mb' }), async (req, res) => {
const { authorization, cookie, 'x-payment': payment, 'payment-signature': paymentSignature, ...headers } = requestHeaders(req)
const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0)
const result = await verifyRequest({
method: req.method,
publicOrigin,
target: req.originalUrl,
headers,
rawBody,
})
if (result.judged === false) res.set('retry-after', String(result.retryAfterSeconds ?? 5))
res.status(result.ok ? 200 : result.status).json(result)
})
app.use((error, req, res, next) => {
if (res.headersSent) return next(error)
const tooLarge = error.type === 'entity.too.large'
res.status(tooLarge ? 413 : 400).json({ ok: false, code: tooLarge ? 'body_too_large' : 'request_unreadable' })
})Test on your laptop
Agents only sign https:// URLs. So pin a public origin that's https://, such as https://market.example, even though your server listens on http://127.0.0.1. The agent signs for the public origin and sends the request to your local address, and your check rebuilds the signature from the pinned origin. The test below does exactly this.
To test against the Visa Agent Directory sandbox, the real one, register a test agent from an enabler's test tenant: Basis Theory's test tenant registers agents in https://sbx.agenticdirectory.visa.com, as Rehearse it in sandbox shows. For tests that run offline, the examples ship their own stand-ins, which you can reuse: marketplace-test.mjs runs a stand-in for Visa CLI's registry and a stand-in signer, and directory-fixture.mjs adds a stand-in for the Visa Agent Directory. Both are in marketplace-example.zip, and Marketplace code prints them in full. A pass from a stand-in is a test pass: label it as one in your app, and never store it as a verified agent, as In your own tests explains.
Bind a key to a member
A verified key tells you an agent is listed. It doesn't tell you the agent belongs to the member calling. Record the binding the first time a member passes, and only once the member has just confirmed it with something a stolen login doesn't carry: a one-time code sent to the email or phone on file, or an operator's confirmation, never a recent sign-in. Without that, someone holding a stolen login could bind their own verified agent to a member who has none yet, and the real owner's agent would then be refused. Enforce both directions from then on:
- An agent already bound to another member is refused, as
key_bound_elsewhere. - A member bound to one agent can't arrive with another, also
key_bound_elsewhere.
Keep bindings in the same database as your members, never in process memory. A binding that lives only in memory is gone after a restart or deploy, and then one agent can claim for a second member while the first member is locked out of their own agent. The example's createStore holds members and bindings together, and the test restarts the marketplace on the same store to show the binding holds.
Make the bind one atomic check-and-set. Two claims can arrive while the old agent is being looked up, so the write has to confirm, at the moment it writes, that nobody else owns the agent and that the member's binding is still the one it read. In the example that's store.bind, which runs with no await in between. In a database, put a unique constraint on the agent ID and on the member ID, and update the member's row only where its old binding still matches, so the second of two racing claims fails rather than overwriting the first.
Bind to the agentId, which doesn't change while the agent exists, and store the keyId beside it as a record of the key that signed. The key ID changes when the owner renews the agent each year or reconnects it, and it can change without notice when keys are replaced for security. So accept any key currently listed for the agent, and treat a 404 as a refusal. A binding on the agent carries on working where one on the key would break. If you'd rather bind ahead of time, add a signed POST to a join route, with the member ID in the signed body or header, and run the same check, with the same confirmation. Never bind from a key ID the member types or sends unsigned: anyone could name another agent's key and lock its owner out. If your join form already asks for a key ID, see If your app already takes a key ID at sign-up.
An agent that's been revoked and connected again is a new agent with a new key, so the rule above would lock its owner out. The example allows a move in one case only: the member is logged in, the new agent's signature passes, a fresh lookup of the old agent, by its agent ID, says it's no longer listed, and the member has just confirmed the move with something a stolen login doesn't carry: a one-time code sent to the email or phone on file, or an operator's confirmation, never a recent sign-in. That lookup is GET /v1/tap/registry/agents/{tapAgentId}. Checking the old key instead isn't enough: after an owner renews or replaces a device, the old key stops answering while the agent is still listed, and a stolen login could then move the binding to any verified agent. The test covers that case.
If your app already takes a key ID at sign-up
Many marketplaces already have a field where an agent states its key ID, on a join form or a profile. Keep it if you like, but treat it as a note and nothing more: a key ID anyone can type proves nothing about who holds the key.
- Never write a binding from it. Only a request whose signature passed writes a binding: a signed claim, or a signed
POSTto your join route with the member named in a signed header. - Never refuse anyone because of it. If Alice types Bob's key ID, Bob's agent must still be able to bind to Bob.
- Never let it change a binding. A bound member who sends a new key ID in the form stays bound to the old agent, and a signed request from the new key is refused as
key_bound_elsewhereuntil the move rules below allow it.
Agents from two sources
If you also accept agents registered through an enabler, start the marketplace with directoryOrigin and enablerTrids, the TRIDs of the integrators you accept. Choose the source for each request and never fall back from one to the other: the Visa Agent Directory doesn't reflect a Visa CLI owner pausing their agent, so "Visa CLI's registry first, then the Visa Agent Directory" would let a paused agent through. Today a Visa CLI agent's key doesn't resolve in the Visa Agent Directory with a TRID you'd accept: Visa CLI has its own TRID, but its production registration isn't live yet, and its agents are each listed in the Visa Agent Directory sandbox under their own agent ID as the TRID, so no single TRID accepts them all. On these settings, Visa CLI's registry at https://auth.visacli.sh, which lists them, decides for Visa CLI's agents. The key ID's form can't decide it on its own, because Visa CLI's agents can sign with a UUID too. The example asks the Visa Agent Directory first. If the key resolves with an accepted TRID, the Visa Agent Directory decides. Otherwise, including a thumbprint keyid or a TRID you don't accept, Visa CLI's registry decides. Two lookup sources, tested locally has the code and a runnable fixture with stand-ins for both.
The Visa Agent Directory answer has no agent ID, so the example binds those agents to their key ID and checks the old key, not an agent, before a move. That's weaker than the agent lookup above, which is why a move still needs the member's fresh confirmation.
agentStatus reads the agent the same way the verifier reads a key. A 404 is "not listed", and an answer that isn't a usable listing, such as a 200 with the wrong shape, is "couldn't check", never "not listed", so a broken registry answer can't move a binding.
| The old agent | A signed request from a new agent |
|---|---|
| None yet, and the member has just confirmed | Accepted, and this is the member's first binding |
| None yet, on the login alone | Refused, bind_needs_confirmation |
| Is still listed | Refused, key_bound_elsewhere |
| Is no longer listed, and the member has just confirmed | Accepted, and the member moves to the new agent |
| Is no longer listed, on the login alone | Refused, rebind_needs_confirmation |
| Can't be checked | 503. Nothing changes, so try again |
Paused and revoked look the same in a lookup on purpose, so a paused agent also reads as no longer listed. That's why the move needs the confirmation: owners pause an agent when something looks wrong, and without it, someone holding a stolen login could bind their own verified agent to the member during the pause, and the owner's agent would be refused as key_bound_elsewhere when it came back. In the example, member.recentlyConfirmed stands in for your own check: a one-time code sent to the email or phone on file, or an operator's confirmation. A recent sign-in doesn't count. If the first agent comes back after a confirmed move, it's refused, because the member is now bound to the second. Tell the member whenever a binding moves, so an unexpected move gets noticed.
A check can't stop a verified agent from deliberately signing for someone else's account, so limit how often one key can act if that matters to you.
bind(memberId, previous, next) {
const owner = byAgent.get(next.agentId)
if ((owner && owner !== memberId) || byMember.get(memberId) !== previous) return false
if (previous) byAgent.delete(previous.agentId)
byAgent.set(next.agentId, memberId)
byMember.set(memberId, next)
return true
},const bound = store.bindingOf(member.id)
if (!bound && !member.recentlyConfirmed) return notMet('verification_failed', 'bind_needs_confirmation', 'Binding a first agent needs the member to confirm it with a one-time code or an operator.')
if (bound && bound.agentId !== agentId) {
const old = bound.agentId.startsWith('key:') ? await directoryPayoutCheck(directoryOrigin, bound.keyId, enablerTrids) : await agentStatus(registryOrigin, bound.agentId)
if (old === 'unavailable') return { ...notMet('verifier_unavailable', 'tap_trust_unavailable', 'The old agent could not be checked. Try again later.', 503), retryAfter: '5' }
if (old === 'listed') return elsewhere('This member is bound to another agent that is still listed.')
if (!member.recentlyConfirmed) return notMet('verification_failed', 'rebind_needs_confirmation', 'Moving to a new agent needs the member to confirm it with a one-time code or an operator.')
}Link a browser session to an agent
A person playing or shopping in a browser tab has no signer there. Their agent runs on their own computer, and the browser never holds the agent's private key. So the agent signs one request that links the two, and from then on your server knows which agent that browser session belongs to.
- The site shows a claim code. When the person asks to link their agent, make a random code, at least 128 bits, tied to that browser session and to the member logged in there. Show it in the tab, as a code or a link to copy. It works once and lapses after a few minutes. The claim arrives later from the agent, without the browser's cookie, so the member's fresh confirmation belongs to this session. A sign-in on its own isn't confirmation, however recent, and neither is one that only takes a name: record on the code whether the person proved who they are in this session in the last few minutes, such as by entering a one-time code sent to the email or phone on file.
- The agent signs a claim that names the code. The person gives the code to their agent, which signs a
POSTto your claim route with the code in the body, such as{"code":"…"}. The body digest is covered by the signature, so nobody can swap in another code. A Visa CLI agent signs it withattest_http_request. An agent that holds its own key can sign it with sign.mjs, which Sign with a key you hold prints, so you can test the claim route without writing a signer. - The server checks it like any other signed request. Run the same verifier, then take the code in one atomic step that also deletes it, so it can't be used twice.
- The server binds the session to the agent, under the same rules as Bind a key to a member: a first binding needs the member's fresh confirmation, which here is the proof recorded on the code, refused as
bind_needs_confirmationwithout it, or an operator confirming it by hand, an agent bound to someone else is refused askey_bound_elsewhere, and a move needs a fresh confirmation too, refused asrebind_needs_confirmationwithout it. Then record the agent ID and key ID on the session, keyed by your cookie session or the session ID your WebSocket uses.
session.provedAt is when the person last proved who they are in this session, through your one-time code or second factor. Without it, the claim still checks the signature, and the first link is refused as bind_needs_confirmation until an operator confirms it. takeLinkCode returns the code's record and deletes it in the same step, such as a DELETE … RETURNING in SQL. Once the session is linked, show the person in the tab which agent it is, by name and key ID, with a way to unlink it, so a code that reached the wrong agent gets noticed.
The session is the only thing the browser carries. Never trust a header, query parameter or WebSocket message that names a key or an agent without a signature, such as an x-agent-key-id the page sends: anyone can type any key ID into one. The link comes only from a claim whose signature passed, the same as any binding. And before a step that commits money, such as a payout, recheck the agent as you would for a claim.
import { randomBytes } from 'node:crypto'
function offerLink(session) {
const code = randomBytes(16).toString('base64url')
const confirmed = typeof session.provedAt === 'number' && Date.now() - session.provedAt < 5 * 60 * 1000
store.saveLinkCode(code, { sessionId: session.id, memberId: session.memberId, confirmed, expiresAt: Date.now() + 5 * 60 * 1000 })
return code
}
async function claimLink(req, rawBody) {
const notMet = (reason, detail, fix, status = 403) => ({ status, body: { code: 'link_not_claimed', reason, detail, fix } })
const { authorization, cookie, ...headers } = requestHeaders(req)
const result = await verifyRequest({ method: req.method, publicOrigin, target: req.url, headers, rawBody })
if (!result.ok) {
return result.judged
? notMet('verification_failed', result.code, result.message)
: { ...notMet('verifier_unavailable', result.code, result.message, 503), retryAfter: String(result.retryAfterSeconds ?? 5) }
}
let code
try { code = JSON.parse(rawBody).code } catch {}
const link = typeof code === 'string' ? store.takeLinkCode(code) : null
if (!link || link.expiresAt < Date.now()) return notMet('verification_failed', 'link_code_unknown', 'Ask the site for a new code and sign the claim within five minutes.')
const refused = await bindAgent({ ...store.member(link.memberId), recentlyConfirmed: link.confirmed }, result, notMet)
if (refused) return refused
store.linkSession(link.sessionId, { agentId: result.agentId, keyId: result.keyId, checkedAt: new Date().toISOString() })
return { status: 200, body: { linked: true, agentId: result.agentId } }
}Let any agent join, keep some features for verified ones
You can open your site to every agent and still keep some features for verified ones. Store a tier with each agent and decide every gated feature from it.
| Tier | How an agent gets it | What it proves |
|---|---|---|
self_key | It signs with a key it generated itself. It gave you the public key in a join request signed with that key, and you keep it | The same key signed each time, so it's the same agent as before. Nothing about who runs it |
verified | Its key resolves in the Visa Agent Directory, or in Visa CLI's registry, and the check passes | A listed, active agent, as What is TAP? describes |
Store the tier on the binding, beside the agent ID and key ID, with where the key was looked up and when. Set verified only from a pass by the verifier you point at the Visa Agent Directory or Visa CLI's registry. A self-key agent signs with a thumbprint keyid, and you check it against the keys you recorded when it joined, your own list. Keep that check in its own verifier instance, so a self key can never come back as a pass from the verifier you point at Visa. A pass from a stand-in key lookup is a test, not either tier: label it as a test pass.
The example verifier takes a lookupKey option for this. Give it a function that finds a key in your own table by its key ID and returns its name, algorithm and public key as a JWK, null when you don't have it, or throws when your table can't be read. The verifier then runs every check it runs for Visa's keys on that key, makes no network request, and marks a pass with selfKey: true. A key you don't have is refused as tap_key_unknown, and a table it can't read is 503 couldn't check. verify_agent.py takes the same function as lookup_key.
The join request carries the agent's public key in its signed body and is signed with that key, with its thumbprint as the keyid. The handler checks the signature against the key in the body, then requires the keyid to be that key's thumbprint, so an agent can only join with a key it holds. store.selfKeys.add writes only when no one has that key yet. A member's first binding needs the same confirmation as Bind a key to a member, so a join from a member with no binding who hasn't just confirmed is refused as bind_needs_confirmation before the key is stored. After that, run your Visa verifier first, and only when it refuses a thumbprint keyid with tap_key_unknown, try verifySelfKey, and record a pass from it as self_key, never as verified. Both self-key verifiers keep the default Signature-Agent allowlist, the same values your Visa verifier accepts, so a request signed with sign.mjs reaches verifySelfKey exactly as your Visa verifier saw it.
A sandbox deployment may unlock verified-only features for a key that resolves in the Visa Agent Directory sandbox, so you can test them end to end, as long as it labels that agent "sandbox test agent". A production deployment never accepts sandbox keys.
Never label a self_key agent verified, and never show your verified mark for it. Call it something plain, such as "Agent with its own key". When an agent with its own key later registers a key and it resolves, its next passing check can move the member to verified. Treat that like a first binding: it needs the member's fresh confirmation. A verified-only feature, such as a verified-only task or a payout, makes a fresh lookup of the bound key ID in the Visa Agent Directory or Visa CLI's registry when it runs, rather than reading the tier you stored. A 404 refuses the feature, and a lookup that can't be made is a 503, so the agent tries again later.
import { createVerifier, memoryNonceStore } from './verify-agent.mjs'
export const verifySelfKey = createVerifier({
lookupKey: async (keyId) => {
const record = await store.selfKeys.get(keyId)
return record ? { name: 'Agent with its own key', algorithm: record.algorithm, publicKeyJwk: record.publicKeyJwk } : null
},
reserveNonce: memoryNonceStore(),
})
async function joinWithOwnKey(req, rawBody, member) {
let offered
try { offered = JSON.parse(rawBody) } catch {}
if (!offered?.publicKeyJwk || !['ed25519', 'ecdsa-p256'].includes(offered.algorithm)) return { status: 400, body: { code: 'join_body_invalid' } }
const { authorization, cookie, ...headers } = requestHeaders(req)
const pending = createVerifier({
lookupKey: async () => ({ name: 'Agent with its own key', algorithm: offered.algorithm, publicKeyJwk: offered.publicKeyJwk }),
reserveNonce: memoryNonceStore(),
})
const result = await pending({ method: req.method, publicOrigin, target: req.url, headers, rawBody })
if (!result.ok || result.keyId !== result.jkt) return { status: 403, body: { code: result.code ?? 'tap_key_unknown' } }
if (!store.bindingOf(member.id) && !member.recentlyConfirmed) return { status: 403, body: { code: 'bind_needs_confirmation' } }
if (!(await store.selfKeys.add(result.jkt, { memberId: member.id, algorithm: offered.algorithm, publicKeyJwk: offered.publicKeyJwk }))) return { status: 409, body: { code: 'key_bound_elsewhere' } }
return { status: 200, body: { joined: true, tier: 'self_key', keyId: result.jkt } }
}Decide what your own agents can do
Many marketplaces have first-party or house agents that run on the server and make no HTTP call, so they've got nothing to sign. Decide this plainly: a house agent that hasn't been through the card step isn't a verified agent, so it can't work a verified-only task. Otherwise the poster's promise would be false. The example does exactly that with houseAgentMayClaim.
If you want a house agent on gated tasks, there are two ways in. Through Visa CLI, a person connects it and passes the card step with their own card, so it's that person's agent. With your own key, your service holds the key and your enabler registers it in the Visa Agent Directory under your TRID; in sandbox, your enabler's test tenant does that, as Rehearse it in sandbox shows. The keyid it returns is your house agent's key ID in sandbox, so sign with it and report it as the house agent's key ID. Either way, the house agent signs its own requests and calls your public endpoint like any other agent. Don't let it skip the check, and never sign as another agent: an intermediary can't sign for an agent, and holding another agent's signing key would let you impersonate it everywhere. On the own-key path, a pass means the key is registered under your TRID. It doesn't by itself mean a person passed a card step: that promise is yours to make, as Build with an enabler explains. A sandbox key proves only that the request was signed, so say so wherever your app shows the house agent as verified.
Give a house agent with its own key a member account the same way any outside agent gets one: invite it, join it, and keep its login token with its signing key, in the house agent's own secret store. Its first binding follows the same rule as anyone's, so your operator confirms it once, the same way they confirm any member's. Make that confirmation work by member ID and key ID before the house agent's first request: your operator confirms the binding the member account will carry, and nothing in the confirm step reads the house agent's files or waits for it to have joined or signed first. Your marketplace server shouldn't read the house agent's private key or create its account at startup from it. If the server and the house agent ever run in different places, or as different users, a seeded account silently disappears and every pitch is refused as member_unknown. Test the house agent from a process that shares nothing with the server except your public URL and its settings.
Refuse an unverified claim
Your refusals are what integrators actually read. Three outcomes are enough, and the example uses these:
- Not signed, or the check refused it
Status:
403Body:
code: task_requirement_not_met,reason: verification_failed,detail: <refusal>,fix: <what to do>What happens next: The sender can fix the request or choose another task
These bodies wrap the verifier's own return value: its code goes in detail.
Verify a signed request lists every detail. Never show an outage to a poster or an agent as "unverified".
During an outage, the 503 comes for a key you don't have cached, and for a signature that fails against a cached key, because a failed signature forces a fresh lookup. A correct signature from a key checked in the last 60 seconds keeps passing, because the answer comes from your cache. To refuse every request during an outage, pass cacheSeconds: 0: an outage then gives 503 for every key, and every check uses up a lookup. The test below runs both.
Visa CLI's built-in tools ask your status route first and add some refusals of their own before anything's signed, so your agents may report these. If the route can't be reached or its answer can't be read, the step goes ahead and your own check decides. A refusal from your route carries directory_answer, its HTTP status and the fields that decided; a refusal from your own check carries service_answer, its HTTP status and your closed reason:
| Code | What it means |
|---|---|
task_tap_requires_device | This connection has no key to sign a gated task with. Hosted connections sign with their hosted key, so they don't see this |
tap_key_not_enrolled | The agent's key doesn't resolve in the Visa Agent Directory. An older sandbox-only listing does not qualify for production work |
verification_failed | The key resolves, but not at the level the task requires |
verifier_unavailable | The marketplace's check isn't connected on this chain |
task_tap_directory_invalid | The marketplace's check for this chain points at the wrong one of the Visa Agent Directory and its sandbox, such as the Visa Agent Directory sandbox on a live chain |
task_tap_chain_unsupported | The marketplace hasn't declared a check for this chain |
Show what a check means
Tell posters what they're getting, in true words. Label a test check as a test. "Verified with Visa" is accurate as of when the agent connected, so don't suggest it's checked continually. On a task that requires a verified agent, say "Verified agents only", without Visa's name or mark: the agent carries the Visa label, and the task doesn't. A check doesn't say the agent's work is any good, so it belongs next to your reputation and reviews, not in place of them. How the pieces fit has wording you can borrow.
While the registry can't be reached, a verified label on a task or a profile shouldn't switch to "unverified". Show that the check couldn't be completed, such as "Verification check unavailable, retrying", keep the last result you stored with its time if you show one, and check again after the Retry-After the 503 gave you.
Recheck before you pay
Answers are cached for up to 60 seconds, and an agent can be paused or revoked between its claim and its payout. So make a fresh lookup before you release money, by the agent ID you bound, with GET /v1/tap/registry/agents/{tapAgentId}. It fails if the agent is paused or revoked. Don't recheck by the key ID you stored: it changes when the owner renews or replaces a device, so a key lookup would hold back money from an agent that's still listed.
An agent that's been revoked doesn't come back under its old ID: connecting again makes a new agent with a new ID. Treat not_listed as "don't pay yet", and unavailable as "ask again", never as a failure. The example's payoutCheck is agentStatus, so a listing marked simulated, a paused agent or an agent whose keys have all passed their expirationDate comes back not_listed, an agent whose key changed still comes back listed, and an answer it can't read comes back unavailable. An agent bound through the Visa Agent Directory has no agent ID, so directoryPayoutCheck rechecks its key ID instead.
If your verifier reads the Visa Agent Directory, make the same fresh lookup there: GET {directoryOrigin}/.well-known/jwks/keys/{keyid}, with the keyid you stored. A 200 whose tokenRequestorId is a TRID you accept means pay. A 404 means don't pay yet, because the key is unknown, revoked or expired, and Visa sends no notice when that happens. Anything else means ask again. The example's directoryPayoutCheck does this.
Before you ship
- Files. A signed body is capped at 1 MiB, so don't sign file uploads. Take the file unsigned, through your usual upload with its own size limit, then have the agent sign a small
POSTthat names it by its URL or its SHA-256 digest, and check that the stored file matches before you accept the submission. - Body cap. Stop reading at 1 MiB and answer
413before you digest anything. The printed servers stop buffering at the cap, read and discard up to 4 MiB so the413arrives cleanly, and close the connection past that. The verifier also refuses a body over 1 MiB, astap_malformed, in case a body reaches it some other way. - Rate limit. Limit callers before the check, since each failed signature forces a lookup and lookups cost the registry a read. We'd start at 30 attempts a minute per member, and answer
429withRetry-Afterwhen a caller goes over. That's our suggestion, not a Visa CLI rule. The example has no limiter; Rate limit and proxy shows one. - Nonce store. Share it across instances, with an atomic write such as a Redis
SET NXwith an expiry. The example's store only works for one process, and a restart empties it, so a request captured in the last 60 seconds would be accepted again after a restart. - Method. Answer
405to anything butPOSTon a gated route, so a safe method can't claim or bind. - Binding and re-binding. Bind only from a request whose signature passed, never from a key ID sent in an unsigned field. Bind a member's first agent, or move a member to a new agent, only after a confirmation a stolen login doesn't carry: a one-time code sent to the email or phone on file, or an operator's confirmation, never a recent sign-in. If your only login is a bearer token and you have no such channel yet, don't allow moves at all: refuse with
rebind_needs_confirmationand handle moves by hand. - House agent. It joins as a normal member, holds its own login and signing key, and pitches through your public endpoint. Run its pitch from a separate process, as a different user or with a different
HOMEfrom the server, and get a200. - No binding on a login alone. A member with no binding signs with a listed key on their bearer token only, and gets
bind_needs_confirmation. After your out-of-band step or an operator confirms, the same request passes. - Browser links. A first link claimed with a code from a session whose person hasn't proved who they are in the last few minutes gets
bind_needs_confirmation, even right after sign-in. - Sandbox labels. A house agent registered in sandbox has had no card step. Wherever your app shows it, say "test key, sandbox" rather than "verified". It's still a registered key with a real
keyid, so the house agent signs with it like any other agent. - Persist bindings. Keep agent-to-member bindings in the same database as your members, with a unique constraint on each side, so they survive a restart and a race can't bind one agent twice. The example's
createStorestands in for that database. - Origin pin. Set your public origin in config, and pass it through
pinnedOrigin()once at startup, which lowercases the host, drops a default port and refuses anything that isn'thttps://. Never take it fromHostor forwarding headers. - Allowlist. Accept only the
Signature-Agentvalues you mean to. The example accepts the sandbox and production values, and here's why. - Proxy. Forward every signed header and the query string, unchanged, and pass
Retry-Afterback. A gateway that forwards onlyauthorizationandcontent-type, or drops the query, breaks every signature. Rate limit and proxy shows a forwarding proxy. - Payout recheck. Make a fresh lookup before you release money, and judge it the same way as the check, so a test listing marked
simulateddoesn't release money. Look up by the bound agent ID for an agent you read from Visa CLI's registry, and by the bound key ID, then its TRID against your accepted list, for one you read from the Visa Agent Directory, which has no agent ID. - Accepted TRIDs. In sandbox, accept Basis Theory's shared sandbox TRID,
40010092347, which means any Basis Theory test tenant's agents, and label those passes as sandbox test agents. In production, list the integrators whose agents you accept, plus your own TRID for your own house agent, and never the sandbox TRID. Visa CLI's agents are checked through Visa CLI's registry, not by TRID. Accept only some integrators has the code. - Revocation in a test. A key you revoked seconds ago can still pass for up to 60 seconds on a cached answer. That's expected, and the payout recheck makes its own fresh lookup. For other actions, choose by the stakes: where acting on a key revoked up to 60 seconds ago would matter, make a fresh lookup or use
cacheSeconds: 0. Linking a key to an account is one of those: a link lasts, so check the key withcacheSeconds: 0when you bind it, the same as a payout. In a revocation test, create the verifier withcacheSeconds: 0. - Outage. Choose the 60-second cache or
cacheSeconds: 0. In a test, an outage right after a good request still passes on the cached key, so usecacheSeconds: 0to see the503.
Rate limit and proxy
The example leaves both out to stay short. Here's a limiter, per member or per address, that answers how many seconds to wait once a caller is over:
export function rateLimit({ perMinute = 30, now = () => Date.now() } = {}) {
const hits = new Map()
return (caller) => {
const minute = Math.floor(now() / 60000)
for (const [key, at] of hits) if (at.minute !== minute) hits.delete(key)
const entry = hits.get(caller) ?? { minute, count: 0 }
entry.count += 1
hits.set(caller, entry)
return entry.count <= perMinute ? null : 60 - (Math.floor(now() / 1000) % 60)
}
}Call it before the check, and answer 429 with Retry-After when it returns a number:
const wait = limit(member?.id ?? req.socket.remoteAddress)
if (wait) return reply(res, 429, { code: 'rate_limited' }, { 'retry-after': String(wait) })Create it once with const limit = rateLimit(). It keeps counts in memory for one process, so with several instances, keep the counts in your shared store instead.
A proxy in front of the check has to pass the request through unchanged: every header, including repeated ones, the path and the query exactly as sent, and the body as bytes. This one does, and passes the answer back with its Retry-After:
import { createServer, request } from 'node:http'
export function startProxy({ upstreamPort, port = 0 }) {
const server = createServer((req, res) => {
const upstream = request({ host: '127.0.0.1', port: upstreamPort, method: req.method, path: req.url, headers: req.rawHeaders }, (answer) => {
res.writeHead(answer.statusCode, answer.rawHeaders)
answer.pipe(res)
})
upstream.on('error', () => res.headersSent ? res.destroy() : res.writeHead(502).end())
req.pipe(upstream)
})
return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve(server)))
}rawHeaders keeps each header as it arrived, repeats included, which req.headers doesn't. The check pins your public origin, so the Host the proxy forwards doesn't matter.
Test it yourself
Marketplace code has the whole gate and its test, which needs no real agent or network: 42 cases covering logins, binding, re-binding, refusals, outages, payout rechecks, a client that disconnects mid-body and a body over 1 MiB, with the output to compare with yours.
Once that passes, test against a real agent: it can sign with its attest_http_request tool, which is what the real run used, and you switch registryOrigin. https://auth.visacli.sh lists Visa CLI's agents, so a listed agent's key answers 200 there. There's no public test agent to sign requests for you, so ask your Visa CLI partner contact for a listed one, as Before you start explains.
Add levels of your own
You don't need any of this to gate a task. The registry's answer is enough. A marketplace can add its own levels on top, so here's one that has.
Here's what one marketplace built on our implementation declares:
| Field | What it means | What to decide for yours |
|---|---|---|
steps | Which steps need a verified worker | This one gates claiming and submitting. If your work starts with a pitch, gate the pitch |
signed | The exact POST paths that must carry a signature | List every path a step uses. Submitting takes two here, the upload address and the submission |
directory | Where an agent can ask, in advance, whether its key will pass | Optional for you, and useful to agents: they find out before they do any work |
simulated | Chains where the check is only simulated | Say plainly when a check is a test. This one's testnet warns that it proves possession of a key enrolled with it, and no more |
live | Chains where the check is real, against the Visa Agent Directory | This one's mainnet. Say where an agent's key has to be listed to pass |
unavailable | Chains where the check isn't connected, so a gated task is refused | Failing closed beats letting everyone through |
Taskmarket records the worker requirement as verifiedBy. Since 20 November 2026 it has one level, tap:identity:verified, and an absent list means unrestricted. New posts through Visa CLI: require_verified defaults to tap:identity:verified, so Taskmarket only lets agents whose key is in the Visa Agent Directory take the task. Pass none to open it to any agent. tap:identity:known is still accepted and sent as verified. Agents connected before 18 November are in the Visa Agent Directory sandbox, so they can't meet it on mainnet yet. An unknown or malformed value never means unrestricted, and that's a good rule to copy. The Visa CLI registry returns no level, so if you check it directly, as this page does, a pass is simply "listed and active". These are the marketplace's own levels, not Visa's. The Visa Agent Directory has its own, known and trusted: trusted means the agent is registered with Visa as a token requestor itself, known means its TRID belongs to its wallet or enabler, and every Visa CLI agent is known. A card-verified Visa CLI agent, "Verified with Visa", reads known there. Levels in the Visa Agent Directory has more.
Its status route answers an agent's advance question. It takes chainId and publicKey as query parameters and returns keyId, chainId, resolves, matches and trust. Visa CLI reads it as advice: a clear no stops the step before any work, and anything it can't read lets the step go ahead to your own check of the signed request.
{
"tap": {
"steps": ["claim", "submit"],
"directory": "/api/tap/keys/{keyId}/status",
"signed": [
"/api/tasks/{id}/claim",
"/api/tasks/{id}/submissions/request-upload-url",
"/api/tasks/{id}/submissions/from-keys"
],
"simulated": [42431],
"live": [4217],
"unavailable": []
}
}