---
title: "Marketplace code"
description: "The whole worked marketplace example, with its test: a gate, a stand-in registry and the output to compare."
url: https://app.visacli.sh/docs/marketplace-code
updated: 2026-11-18
---

# Marketplace code

> The whole worked marketplace example, with its test: a gate, a stand-in registry and the output to compare.

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

All the code behind [Add verified agents to a marketplace](/docs/add-verified-agents-to-a-marketplace.md), in Node 22.

You'll need `verify-agent.mjs` from [Verify a signed request](/docs/verifier-code.md#the-example) in the same folder as these two files. No real agent or network is involved. [marketplace-example.zip](/examples/marketplace-example.zip) has all three files in one folder, with a `package.json`, so `npm test` runs it. `marketplace.mjs` is the gate. Its `createStore` stands in for your database: it keeps members and their agent bindings together, so a restart keeps the bindings, and `bind` is the one atomic write.

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

export const MEMBER_HEADER = 'x-market-member'

export const houseAgentMayClaim = (task) => !task.verifiedOnly

export function createStore(members) {
  const byAgent = new Map()
  const byMember = new Map()
  return {
    members: new Map(members),
    ownerOf: (agentId) => byAgent.get(agentId),
    bindingOf: (memberId) => byMember.get(memberId),
    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
    },
  }
}

export const payoutCheck = (registryOrigin, agentId) => agentStatus(registryOrigin, agentId)

export async function directoryPayoutCheck(directoryOrigin, keyId, enablerTrids) {
  const answer = await readDirectoryKey(directoryOrigin, keyId)
  const refused = judgeKey(keyId, answer)
  if (refused) return refused.judged ? 'not_listed' : 'unavailable'
  return enablerTrids.includes(answer.agent.tokenRequestorId) ? 'listed' : 'not_listed'
}

export function createTwoSourceVerifier({ registryOrigin, directoryOrigin, enablerTrids, allowedSignatureAgents, cacheSeconds }) {
  const options = { cacheSeconds, ...(allowedSignatureAgents ? { allowedSignatureAgents } : {}) }
  const registry = createVerifier({ registryOrigin, reserveNonce: memoryNonceStore(), ...options })
  const directory = createVerifier({ directoryOrigin, reserveNonce: memoryNonceStore(), ...options })
  return async (request) => {
    const fromDirectory = await directory(request)
    if (fromDirectory.ok && enablerTrids.includes(fromDirectory.tokenRequestorId)) return fromDirectory
    const notAnEnablerAgent = fromDirectory.ok || fromDirectory.code === 'tap_key_unknown' || fromDirectory.reason === 'signature_agent_other_directory'
    return notAnEnablerAgent ? registry(request) : fromDirectory
  }
}

export async function agentStatus(registryOrigin, agentId) {
  const answer = await readAgent(registryOrigin, agentId)
  if (answer.unavailable || answer.invalid) return 'unavailable'
  if (answer.notListed) return 'not_listed'
  if (answer.agent.id !== agentId) return 'unavailable'
  if (answer.agent.simulated === true || !answer.agent.isActive) return 'not_listed'
  const now = Date.now()
  const live = answer.agent.keys.some((key) => key.expirationDate == null || Date.parse(key.expirationDate) > now)
  return live ? 'listed' : 'not_listed'
}

export function startTaskMarket({ registryOrigin, directoryOrigin, enablerTrids = [], allowedSignatureAgents, publicOrigin: configured, store, tasks, cacheSeconds }) {
  const publicOrigin = pinnedOrigin(configured)
  const verifyRequest = directoryOrigin
    ? createTwoSourceVerifier({ registryOrigin, directoryOrigin, enablerTrids, allowedSignatureAgents, cacheSeconds })
    : createVerifier({ registryOrigin, reserveNonce: memoryNonceStore(), cacheSeconds })
  const identity = (result) => result.agentId ?? `key:${result.keyId}`

  async function bindAgent(member, result, notMet) {
    const elsewhere = (fix) => notMet('verification_failed', 'key_bound_elsewhere', fix)
    const agentId = identity(result)
    const owner = store.ownerOf(agentId)
    if (owner && owner !== member.id) return elsewhere('This agent is bound to another member.')

    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.')
    }

    if (!store.bind(member.id, bound, { agentId, keyId: result.keyId })) {
      return elsewhere('The binding changed while this claim was checked.')
    }
    return null
  }

  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(),
      },
    }
  }

  const reply = (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 reply(res, 413, { code: 'body_too_large' }, { connection: 'close' })
    const match = /^\/api\/tasks\/([^/?]+)\/claim(?:\?|$)/.exec(req.url)
    const task = match && tasks.get(match[1])
    const member = store.members.get((req.headers.authorization ?? '').replace(/^Bearer /, ''))
    if (task && req.method !== 'POST') return reply(res, 405, { code: 'method_not_allowed' }, { allow: 'POST' })
    const answer = !task
      ? { status: 404, body: { code: 'not_found' } }
      : !member
        ? { status: 401, body: { code: 'member_unknown' } }
        : await claim(req, task, member, read.body)
    reply(res, answer.status, answer.body, answer.retryAfter ? { 'retry-after': answer.retryAfter } : {})
  }

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

  return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)))
}
```

`marketplace-test.mjs` runs a stand-in registry and a stand-in signer, then sends each case through real HTTP. The stand-in returns the attestation fields of `attest_http_request`: `profile`, `request_id`, `request`, `key_id`, `created`, `expires`, `nonce` and `headers`. The real tool's answer also carries `ok`, `turn` and `next`, which say whose move it is and don't affect the signature.

```js title="marketplace-test.mjs"
import { createHash, generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto'
import { createServer } from 'node:http'
import { connect } from 'node:net'
import { createStore, houseAgentMayClaim, MEMBER_HEADER, payoutCheck, startTaskMarket } from './marketplace.mjs'

const PUBLIC_ORIGIN = 'https://market.example'
const { publicKey, privateKey } = generateKeyPairSync('ed25519')
const jwk = publicKey.export({ format: 'jwk' })
const jkt = createHash('sha256').update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: jwk.x })).digest('base64url')
const keyId = randomUUID()
const agentId = randomUUID()
const listing = {
  id: agentId,
  name: 'example-agent',
  isActive: true,
  keys: [{
    id: keyId,
    agentId,
    keyName: jkt,
    status: 'active',
    algorithm: 'ed25519',
    publicKey: Buffer.from(publicKey.export({ type: 'spki', format: 'pem' })).toString('base64'),
    jkt,
    expirationDate: null,
  }],
}

const second = generateKeyPairSync('ed25519')
const secondKeyId = randomUUID()
const secondAgentId = randomUUID()
const secondJwk = second.publicKey.export({ format: 'jwk' })
const secondJkt = createHash('sha256').update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x: secondJwk.x })).digest('base64url')
const secondAgent = {
  id: secondAgentId,
  name: 'example-agent-2',
  isActive: true,
  keys: [{
    id: secondKeyId,
    agentId: secondAgentId,
    keyName: secondJkt,
    status: 'active',
    algorithm: 'ed25519',
    publicKey: Buffer.from(second.publicKey.export({ type: 'spki', format: 'pem' })).toString('base64'),
    jkt: secondJkt,
    expirationDate: null,
  }],
}

let registryMode = 'listed'
let keyReplaced = false
let agentLookups = 'normal'
const registry = createServer(async (req, res) => {
  const id = decodeURIComponent(req.url.split('/').pop())
  if (registryMode === 'down') return res.writeHead(503).end('{"code":"unavailable"}')
  if (req.url.includes('/agents/') && agentLookups === 'garbage') return res.writeHead(200, { 'content-type': 'application/json' }).end('{"nope":true}')
  if (req.url.includes('/agents/') && agentLookups === 'slow') await new Promise((resolve) => setTimeout(resolve, 200))
  if (registryMode === 'simulated' && (id === keyId || id === jkt || id === agentId)) {
    res.writeHead(200, { 'content-type': 'application/json' })
    return res.end(JSON.stringify({ ...listing, simulated: true }))
  }
  if (req.url.includes('/agents/')) {
    const agent = id === agentId && registryMode !== 'paused' ? listing : id === secondAgent.id ? secondAgent : null
    if (!agent) return res.writeHead(404).end('{"code":"not_found"}')
    res.writeHead(200, { 'content-type': 'application/json' })
    return res.end(JSON.stringify(agent))
  }
  if (keyReplaced && (id === keyId || id === jkt)) return res.writeHead(404).end('{"code":"not_found"}')
  if (id === secondKeyId) {
    res.writeHead(200, { 'content-type': 'application/json' })
    return res.end(JSON.stringify(secondAgent))
  }
  if (registryMode === 'paused' || (id !== keyId && id !== jkt)) return res.writeHead(404).end('{"code":"not_found"}')
  res.writeHead(200, { 'content-type': 'application/json' })
  res.end(JSON.stringify(listing))
})
await new Promise((resolve) => registry.listen(0, '127.0.0.1', resolve))
const registryOrigin = `http://127.0.0.1:${registry.address().port}`

const memberList = [
  ['token-alice', { id: 'alice' }],
  ['token-alice-confirmed', { id: 'alice', recentlyConfirmed: true }],
  ['token-bob', { id: 'bob' }],
  ['token-bob-confirmed', { id: 'bob', recentlyConfirmed: true }],
]
const store = createStore(memberList)
const tasks = new Map([
  ['open-1', { id: 'open-1', verifiedOnly: false }],
  ['gated-1', { id: 'gated-1', verifiedOnly: true }],
])
const market = await startTaskMarket({ registryOrigin, publicOrigin: PUBLIC_ORIGIN, store, tasks })
const origin = `http://127.0.0.1:${market.address().port}`

function attest({ url, method, headers, body_sha256 }, { id = keyId, key = privateKey } = {}) {
  const added = [...headers, ['accept', '*/*'], ['signature-agent', '"https://sbx.agenticdirectory.visa.com"']]
  const sorted = added.sort(([a], [b]) => (a < b ? -1 : 1))
  const u = new URL(url)
  const digest = `sha-256=:${Buffer.from(body_sha256, 'base64url').toString('base64')}:`
  const values = [
    ['@method', method], ['@scheme', 'https'], ['@authority', u.host], ['@path', u.pathname],
    ['@query', u.search || '?'], ['content-digest', digest], ...sorted,
  ]
  const created = Math.floor(Date.now() / 1000)
  const expires = created + 60
  const nonce = randomBytes(32).toString('base64')
  const params = `(${values.map(([n]) => `"${n}"`).join(' ')});created=${created};expires=${expires};keyid="${id}";alg="ed25519";nonce="${nonce}";tag="agent-browser-auth"`
  const base = [...values.map(([n, v]) => `"${n}": ${v}`), `"@signature-params": ${params}`].join('\n')
  return {
    ok: true,
    profile: 'tap-http-request-v1',
    request_id: randomUUID(),
    request: { url, method, headers: sorted, body_sha256 },
    key_id: id,
    created,
    expires,
    nonce,
    headers: {
      'content-digest': digest,
      'signature-input': `sig2=${params}`,
      signature: `sig2=:${sign(null, Buffer.from(base), key).toString('base64')}:`,
    },
  }
}

const sha = (body) => createHash('sha256').update(body).digest('base64url')
const claimUrl = (task) => `${PUBLIC_ORIGIN}/api/tasks/${task}/claim`

function signedClaim(task, member, { body = `{"task":"${task}"}`, sendBody = body, signMember = true, id, key, method = 'POST' } = {}) {
  const headers = [['content-type', 'application/json']]
  if (signMember) headers.push([MEMBER_HEADER, member])
  const attestation = attest({ url: claimUrl(task), method, headers, body_sha256: sha(body) }, { id, key })
  return { task, body: sendBody, headers: Object.fromEntries([...attestation.request.headers, ...Object.entries(attestation.headers)]) }
}

async function send({ task, body = '{}', headers = {} }, token, to = origin) {
  const response = await fetch(`${to}/api/tasks/${task}/claim`, {
    method: 'POST',
    headers: { ...headers, authorization: `Bearer ${token}` },
    body,
  })
  const answer = await response.json()
  return `${response.status} ${answer.detail ?? (answer.checked ? 'claimed, checked' : 'claimed, no check needed')}`
}

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

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

const first = signedClaim('gated-1', 'alice')
report('open task, no signature', '200 claimed, no check needed', await send({ task: 'open-1' }, 'token-alice'))
const signedGet = signedClaim('gated-1', 'alice', { method: 'GET', body: '' })
report('signed claim sent as GET', '405 method_not_allowed', await raw(['GET /api/tasks/gated-1/claim HTTP/1.1', 'host: market.example', 'authorization: Bearer token-alice', ...Object.entries(signedGet.headers).map(([n, v]) => `${n}: ${v}`)]))
report('open task claimed with PUT', '405 method_not_allowed', await raw(['PUT /api/tasks/open-1/claim HTTP/1.1', 'host: market.example', 'authorization: Bearer token-alice']))
report('first binding on a stolen login alone', '403 bind_needs_confirmation', await send(signedClaim('gated-1', 'alice', { id: secondKeyId, key: second.privateKey }), 'token-alice'))
report('gated task, signed, Bearer alongside', '200 claimed, checked', await send(first, 'token-alice-confirmed'))
report('same request sent again', '403 tap_replayed', await send(first, 'token-alice'))
report('bound member, plain login', '200 claimed, checked', await send(signedClaim('gated-1', 'alice'), 'token-alice'))
report('gated task, no signature', '403 tap_missing', await send({ task: 'gated-1' }, 'token-alice'))
report('body changed after signing', '403 tap_signature_invalid', await send(signedClaim('gated-1', 'alice', { sendBody: '{"task":"other"}' }), 'token-alice'))
report("bob sends alice's signature", '403 member_mismatch', await send(signedClaim('gated-1', 'alice'), 'token-bob'))
report("bob's own agent signs for alice", '403 member_mismatch', await send(signedClaim('gated-1', 'alice', { id: secondKeyId, key: second.privateKey }), 'token-bob'))
report('signed, but names no member at all', '403 member_mismatch', await send(signedClaim('gated-1', 'bob', { signMember: false }), 'token-bob'))
const unsigned = signedClaim('gated-1', 'bob', { signMember: false })
report('member header added but not signed', '403 tap_malformed', await send({ ...unsigned, headers: { ...unsigned.headers, [MEMBER_HEADER]: 'bob' } }, 'token-bob'))
report("bob signs for himself with alice's key", '403 key_bound_elsewhere', await send(signedClaim('gated-1', 'bob'), 'token-bob'))
report('made-up key', '403 tap_key_unknown', await send(signedClaim('gated-1', 'alice', { id: randomUUID() }), 'token-alice'))
report('house agent on an open task', 'true', String(houseAgentMayClaim(tasks.get('open-1'))))
report('house agent on a gated task', 'false', String(houseAgentMayClaim(tasks.get('gated-1'))))

const secondAgentClaim = () => signedClaim('gated-1', 'alice', { id: secondKeyId, key: second.privateKey })
report('alice arrives with a second agent', '403 key_bound_elsewhere', await send(secondAgentClaim(), 'token-alice'))

const uncached = await startTaskMarket({ registryOrigin, publicOrigin: PUBLIC_ORIGIN, store, tasks, cacheSeconds: 0 })
const uncachedOrigin = `http://127.0.0.1:${uncached.address().port}`
report('cacheSeconds 0, registry up', '200 claimed, checked', await send(signedClaim('gated-1', 'alice'), 'token-alice', uncachedOrigin))

report('client disconnects mid-body', 'no answer', await raw(['POST /api/tasks/gated-1/claim HTTP/1.1', 'host: market.example', 'authorization: Bearer token-alice'], { body: 'abc', declared: 100, closeEarly: true }))
report('market still answers after that', '200 claimed, no check needed', await send({ task: 'open-1' }, 'token-alice'))
report('body over 1 MiB', '413 body_too_large', await raw(['POST /api/tasks/gated-1/claim HTTP/1.1', 'host: market.example', 'authorization: Bearer token-alice'], { body: 'x'.repeat(1024 * 1024 + 1) }))
const dotted = signedClaim('gated-1', 'alice')
report('signed for task 42, sent to a dotted path', '404 not_found', await raw(['POST /api/tasks/open-1/../gated-1/claim HTTP/1.1', 'host: market.example', 'authorization: Bearer token-alice', ...Object.entries(dotted.headers).map(([n, v]) => `${n}: ${v}`)], { body: dotted.body }))

keyReplaced = true
report("key replaced, then another agent tries", '403 key_bound_elsewhere', await send(secondAgentClaim(), 'token-alice'))
report('payout check after the key changed', 'listed', await payoutCheck(registryOrigin, agentId))
keyReplaced = false

registryMode = 'down'
const forged = signedClaim('gated-1', 'alice', { key: second.privateKey })
report('forged signature during an outage', '503 tap_trust_unavailable', await send(forged, 'token-alice'))
report('real request still passes on the cached key', '200 claimed, checked', await send(signedClaim('gated-1', 'alice'), 'token-alice'))
report('cacheSeconds 0, outage, same key', '503 tap_trust_unavailable', await send(signedClaim('gated-1', 'alice'), 'token-alice', uncachedOrigin))
report('outage, key cached under 60 seconds', '200 claimed, checked', await send(signedClaim('gated-1', 'alice'), 'token-alice'))
report('outage, key not cached', '503 tap_trust_unavailable', await send(signedClaim('gated-1', 'alice', { id: randomUUID() }), 'token-alice'))
report('payout check during an outage', 'unavailable', await payoutCheck(registryOrigin, agentId))

registryMode = 'listed'
report('payout check, agent active', 'listed', await payoutCheck(registryOrigin, agentId))
registryMode = 'paused'
report('payout check, agent paused', 'not_listed', await payoutCheck(registryOrigin, agentId))

report('paused agent, re-bind on the login alone', '403 rebind_needs_confirmation', await send(secondAgentClaim(), 'token-alice'))
report('re-bind once the member confirms', '200 claimed, checked', await send(secondAgentClaim(), 'token-alice-confirmed'))
registryMode = 'listed'
report('first agent returns after the re-bind', '403 key_bound_elsewhere', await send(signedClaim('gated-1', 'alice'), 'token-alice'))

registryMode = 'simulated'
report('payout check, simulated listing', 'not_listed', await payoutCheck(registryOrigin, agentId))
registryMode = 'listed'

const restarted = await startTaskMarket({ registryOrigin, publicOrigin: PUBLIC_ORIGIN, store, tasks })
const restartedOrigin = `http://127.0.0.1:${restarted.address().port}`
report("after a restart, bob uses alice's agent", '403 key_bound_elsewhere', await send(signedClaim('gated-1', 'bob', { id: secondKeyId, key: second.privateKey }), 'token-bob', restartedOrigin))
restarted.close()

const fresh = createStore(memberList)
const race = await startTaskMarket({ registryOrigin, publicOrigin: PUBLIC_ORIGIN, store: fresh, tasks })
const raceOrigin = `http://127.0.0.1:${race.address().port}`
report('fresh store: alice binds her first agent', '200 claimed, checked', await send(signedClaim('gated-1', 'alice'), 'token-alice-confirmed', raceOrigin))
registryMode = 'paused'
agentLookups = 'garbage'
report('re-bind, agent lookup answers garbage', '503 tap_trust_unavailable', await send(secondAgentClaim(), 'token-alice', raceOrigin))
agentLookups = 'slow'
const [aliceRace, bobRace] = await Promise.all([
  send(secondAgentClaim(), 'token-alice-confirmed', raceOrigin),
  new Promise((resolve) => setTimeout(resolve, 50)).then(() => send(signedClaim('gated-1', 'bob', { id: secondKeyId, key: second.privateKey }), 'token-bob-confirmed', raceOrigin)),
])
report('re-bind race: bob, unbound, claims first', '200 claimed, checked', bobRace)
report('re-bind race: alice, mid re-bind, is refused', '403 key_bound_elsewhere', aliceRace)
agentLookups = 'normal'
registryMode = 'listed'
race.close()

uncached.close()
market.close()
registry.close()
console.log(failed ? `${failed} failed` : 'all passed (local stand-in registry, not a real Visa CLI agent)')
process.exit(failed ? 1 : 0)
```

```sh
node marketplace-test.mjs
```

This is the output from our run:

```text title="Output"
PASS  open task, no signature                      200 claimed, no check needed
PASS  signed claim sent as GET                     405 method_not_allowed
PASS  open task claimed with PUT                   405 method_not_allowed
PASS  first binding on a stolen login alone        403 bind_needs_confirmation
PASS  gated task, signed, Bearer alongside         200 claimed, checked
PASS  same request sent again                      403 tap_replayed
PASS  bound member, plain login                    200 claimed, checked
PASS  gated task, no signature                     403 tap_missing
PASS  body changed after signing                   403 tap_signature_invalid
PASS  bob sends alice's signature                  403 member_mismatch
PASS  bob's own agent signs for alice              403 member_mismatch
PASS  signed, but names no member at all           403 member_mismatch
PASS  member header added but not signed           403 tap_malformed
PASS  bob signs for himself with alice's key       403 key_bound_elsewhere
PASS  made-up key                                  403 tap_key_unknown
PASS  house agent on an open task                  true
PASS  house agent on a gated task                  false
PASS  alice arrives with a second agent            403 key_bound_elsewhere
PASS  cacheSeconds 0, registry up                  200 claimed, checked
PASS  client disconnects mid-body                  no answer
PASS  market still answers after that              200 claimed, no check needed
PASS  body over 1 MiB                              413 body_too_large
PASS  signed for task 42, sent to a dotted path    404 not_found
PASS  key replaced, then another agent tries       403 key_bound_elsewhere
PASS  payout check after the key changed           listed
PASS  forged signature during an outage            503 tap_trust_unavailable
PASS  real request still passes on the cached key  200 claimed, checked
PASS  cacheSeconds 0, outage, same key             503 tap_trust_unavailable
PASS  outage, key cached under 60 seconds          200 claimed, checked
PASS  outage, key not cached                       503 tap_trust_unavailable
PASS  payout check during an outage                unavailable
PASS  payout check, agent active                   listed
PASS  payout check, agent paused                   not_listed
PASS  paused agent, re-bind on the login alone     403 rebind_needs_confirmation
PASS  re-bind once the member confirms             200 claimed, checked
PASS  first agent returns after the re-bind        403 key_bound_elsewhere
PASS  payout check, simulated listing              not_listed
PASS  after a restart, bob uses alice's agent      403 key_bound_elsewhere
PASS  fresh store: alice binds her first agent     200 claimed, checked
PASS  re-bind, agent lookup answers garbage        503 tap_trust_unavailable
PASS  re-bind race: bob, unbound, claims first     200 claimed, checked
PASS  re-bind race: alice, mid re-bind, is refused 403 key_bound_elsewhere
all passed (local stand-in registry, not a real Visa CLI agent)
```


<a id="two-sources"></a>

## Two lookup sources, tested locally

A marketplace usually has both kinds of agent: Visa CLI's agents, listed in Visa CLI's registry, and agents an integrator registered through an enabler, listed in the Visa Agent Directory. Choose the source for each request; never fall back from one to the other. The Visa Agent Directory doesn't reflect a Visa CLI owner pausing their agent, so "registry first, then the Visa Agent Directory" would let a paused Visa CLI agent through.

The key ID's form alone can't decide it. A thumbprint `keyid` can only be a Visa CLI agent, but a Visa CLI agent whose key has metadata from the Visa Agent Directory signs with a UUID too. So `createTwoSourceVerifier` asks the Visa Agent Directory first and decides by the TRID it returns:

- The Visa Agent Directory resolves the key and its `tokenRequestorId` is one of `enablerTrids`, the integrators you accept: the Visa Agent Directory decides, and the agent is bound by its key ID;
- The Visa Agent Directory resolves the key with any other TRID, or doesn't list it, or the `keyid` is a thumbprint: Visa CLI's registry decides, and a pause there is a refusal;
- The Visa Agent Directory can't be read: couldn't check, `503`, for every agent with a UUID `keyid`. A thumbprint `keyid` never needs the Visa Agent Directory, so Visa CLI's registry still decides it while the Visa Agent Directory is down.

Each source has its own nonce store, so a request checked by both is still accepted only once by each. `directoryPayoutCheck` re-checks an agent bound through the Visa Agent Directory before a payout, with the same TRID rule. Start the market with `startTaskMarket({ registryOrigin, directoryOrigin, enablerTrids, ... })`.

`directory-fixture.mjs` runs both sources as local stand-ins. To test against a stand-in for the Visa Agent Directory, the verifier must accept its address in `Signature-Agent`, so the fixture passes a test-only allowlist, `allowedSignatureAgents: ['"http://127.0.0.1:<port>"']`. Never ship that entry: in production, leave `allowedSignatureAgents` at its default. The stand-ins' passes are test passes. In `outcome` below, `agentId === null` tells you which source decided, and your app knows which origin it pointed each source at, so store that origin with the pass and label the agent a test key, never a verified agent. Save it beside `verify-agent.mjs` and `marketplace.mjs`, and run `node directory-fixture.mjs`.

```js title="directory-fixture.mjs"
import { createHash, generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto'
import { createServer } from 'node:http'
import { createTwoSourceVerifier, directoryPayoutCheck } from './marketplace.mjs'

const ENABLER_TRID = 'TEST-ENABLER-TRID'
const PUBLIC_ORIGIN = 'https://market.example'

function makeAgent(name, tokenRequestorId) {
  const { publicKey, privateKey } = generateKeyPairSync('ed25519')
  const { x } = publicKey.export({ format: 'jwk' })
  const jkt = createHash('sha256').update(JSON.stringify({ crv: 'Ed25519', kty: 'OKP', x })).digest('base64url')
  const pem = Buffer.from(publicKey.export({ format: 'pem', type: 'spki' })).toString('base64')
  return { name, tokenRequestorId, privateKey, x, jkt, pem, id: randomUUID(), keyId: randomUUID() }
}

const enablerAgent = makeAgent('enabler agent', ENABLER_TRID)
const visaCliAgent = makeAgent('visa cli agent', randomUUID())
const otherAgent = makeAgent('another integrator agent', 'TEST-OTHER-TRID')
const state = { directoryDown: false, inDirectory: new Set([enablerAgent, visaCliAgent, otherAgent]), inRegistry: new Set([visaCliAgent]) }

const listen = (handler) => new Promise((resolve) => {
  const server = createServer(handler)
  server.listen(0, '127.0.0.1', () => resolve(server))
})
const json = (res, status, body) => res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body))
const byKeyId = (set, keyId) => [...set].find((agent) => agent.keyId === keyId || agent.jkt === keyId)

const directory = await listen((req, res) => {
  if (state.directoryDown) return json(res, 503, { message: 'Service unavailable' })
  const agent = byKeyId(state.inDirectory, decodeURIComponent(req.url.split('/').pop()))
  if (!agent) return json(res, 404, { message: 'The requested key was not found' })
  json(res, 200, {
    agent: { name: agent.name, agentType: 'known', tokenRequestorId: agent.tokenRequestorId },
    key: { id: agent.keyId, algorithm: 'ed25519', status: 'active', expirationDate: null, publicKeyJwk: { kty: 'OKP', crv: 'Ed25519', x: agent.x } },
    message: 'Key found',
  })
})
const registry = await listen((req, res) => {
  const agent = byKeyId(state.inRegistry, decodeURIComponent(req.url.split('/').pop()))
  if (!agent) return json(res, 404, { code: 'not_found' })
  json(res, 200, {
    id: agent.id, name: agent.name, isActive: true,
    keys: [{ id: agent.keyId, agentId: agent.id, keyName: agent.jkt, status: 'active', algorithm: 'ed25519', publicKey: agent.pem, jkt: agent.jkt, expirationDate: null }],
  })
})
const directoryOrigin = `http://127.0.0.1:${directory.address().port}`
const registryOrigin = `http://127.0.0.1:${registry.address().port}`

const verifyRequest = createTwoSourceVerifier({
  registryOrigin,
  directoryOrigin,
  enablerTrids: [ENABLER_TRID],
  allowedSignatureAgents: [`"${directoryOrigin}"`],
  cacheSeconds: 0,
})

function signedRequest(agent) {
  const body = '{"task":42}'
  const digest = `sha-256=:${createHash('sha256').update(body).digest('base64')}:`
  const headers = { accept: '*/*', 'content-type': 'application/json', 'signature-agent': `"${directoryOrigin}"`, 'x-market-member': 'm_1' }
  const names = Object.keys(headers).sort()
  const created = Math.floor(Date.now() / 1000)
  const params = `("@method" "@scheme" "@authority" "@path" "@query" "content-digest" ${names.map((n) => `"${n}"`).join(' ')});created=${created};expires=${created + 60};keyid="${agent.keyId}";alg="ed25519";nonce="${randomBytes(32).toString('base64')}";tag="agent-browser-auth"`
  const base = ['"@method": POST', '"@scheme": https', '"@authority": market.example', '"@path": /tasks/42/claim', '"@query": ?', `"content-digest": ${digest}`, ...names.map((n) => `"${n}": ${headers[n]}`), `"@signature-params": ${params}`].join('\n')
  const signature = sign(null, Buffer.from(base), agent.privateKey).toString('base64')
  return { method: 'POST', publicOrigin: PUBLIC_ORIGIN, target: '/tasks/42/claim', rawBody: Buffer.from(body), headers: { ...headers, 'content-digest': digest, 'signature-input': `sig2=${params}`, signature: `sig2=:${signature}:` } }
}

let failed = 0
const report = (name, expected, got) => {
  const pass = got === expected
  if (!pass) failed += 1
  console.log(`${pass ? 'PASS' : 'FAIL'}  ${name.padEnd(52)} ${got}`)
}
const outcome = (result) => (result.ok ? `200 ok, ${result.agentId === null ? "Visa's directory" : "Visa CLI's registry"}` : `${result.status} ${result.code}`)

report('enabler agent, its TRID accepted', "200 ok, Visa's directory", outcome(await verifyRequest(signedRequest(enablerAgent))))
report('Visa CLI agent, also in the directory', "200 ok, Visa CLI's registry", outcome(await verifyRequest(signedRequest(visaCliAgent))))
report("another integrator's agent, TRID not accepted", '403 tap_key_unknown', outcome(await verifyRequest(signedRequest(otherAgent))))
state.inRegistry.delete(visaCliAgent)
report('Visa CLI agent paused, still in the directory', '403 tap_key_unknown', outcome(await verifyRequest(signedRequest(visaCliAgent))))
state.inDirectory.delete(enablerAgent)
report('enabler agent revoked', '403 tap_key_unknown', outcome(await verifyRequest(signedRequest(enablerAgent))))
state.inDirectory.add(enablerAgent)
state.directoryDown = true
report('directory down', '503 tap_trust_unavailable', outcome(await verifyRequest(signedRequest(enablerAgent))))
state.directoryDown = false
report('payout check, enabler agent', 'listed', await directoryPayoutCheck(directoryOrigin, enablerAgent.keyId, [ENABLER_TRID]))
report('payout check, Visa CLI agent read from the directory', 'not_listed', await directoryPayoutCheck(directoryOrigin, visaCliAgent.keyId, [ENABLER_TRID]))

directory.close()
registry.close()
console.log(failed ? `${failed} failed` : 'all passed (local stand-ins, not real agents)')
process.exit(failed ? 1 : 0)
```

```text title="Output of directory-fixture.mjs"
PASS  enabler agent, its TRID accepted                     200 ok, Visa's directory
PASS  Visa CLI agent, also in the directory                200 ok, Visa CLI's registry
PASS  another integrator's agent, TRID not accepted        403 tap_key_unknown
PASS  Visa CLI agent paused, still in the directory        403 tap_key_unknown
PASS  enabler agent revoked                                403 tap_key_unknown
PASS  directory down                                       503 tap_trust_unavailable
PASS  payout check, enabler agent                          listed
PASS  payout check, Visa CLI agent read from the directory not_listed
all passed (local stand-ins, not real agents)
```

Once that passes, test against a real agent: it can sign with its `attest_http_request` tool, which is what [the real run](/docs/verify-a-signed-request.md#how-far-this-has-been-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](/docs/quickstart.md#before-you-start) explains.
