Building an Agent Delegation Broker: scoped signing authority for TAP agents
The gap Every app in the TAP ecosystem gets its own agent. But there's no delegation primitive: a main agent can't spawn sub-agents with scoped permissions. Without delegation, every sub-agent would need its own key an
The gap
Every app in the TAP ecosystem gets its own agent. But there's no delegation primitive: a main agent can't spawn sub-agents with scoped permissions. Without delegation, every sub-agent would need its own key and its own card step β which doesn't scale to multi-agent workflows.
The Agent Delegation Broker is a small runnable reference that closes that gap. A main agent mints a signed, policy-bound token for a sub-agent; the broker verifies the signature, enforces the policy on each request, revokes on demand, and keeps an audit trail. I also built an interactive browser demo so the flow is visible rather than abstract, and fixed an ESM/CJS interop bug along the way that's worth documenting for anyone shipping tweetnacl-util on Node 22.
Status: MVP, not production. Keys are in-memory, no auth, no replay protection. See the roadmap at the end.
What it does
- Main agent mints a delegation token for a sub-agent.
- The policy embeds a spend cap, allowed endpoints, TTL, and a rate limit.
- The token is signed with the broker's Ed25519 key.
- Sub-agent presents the token; the broker verifies the signature.
- On each action, policy gates the endpoint and amount.
- Main agent can revoke at any time.
- Every event (mint, verify, revoke, expire, policy violation) is audit-logged.
Tech stack
| Layer | Technology | Reason |
|---|---|---|
| Runtime | Node.js 22 | LTS, native crypto.randomUUID
|
| Language | TypeScript 5.5 (strict, NodeNext ESM) | Type-safe service layer |
| HTTP | Hono 4 + @hono/node-server
|
Tiny, fast, serveStatic for the demo |
| Crypto | tweetnacl (Ed25519) + tweetnacl-util | Small, audited base64 + signing helpers |
| Tooling | tsx, Vitest, ESLint, drizzle-kit | Hot reload, tests, lint, migrations |
| Extras installed | Zod, pino, Drizzle + postgres.js | Ready to wire in later |
| Demo | Vanilla HTML/CSS/JS | No build step, same-origin |
| Packaging | Multi-stage Docker (node:22-alpine) |
Slim runtime with dist/ + demo/
|
Deliberate choice: no database. Three in-memory Maps (tokens, audits) remove all setup friction for a reference. src/db.ts is scaffolding for the day persistence is needed.
Architecture
βββββββββββββββββββββββ fetch() JSON ββββββββββββββββββββββββββββββββ
β Browser (demo UI) β ββββββββββββββββββββββββΊ β Hono app (src/server.ts) β
β demo/index.html β ββββββββββββββββββββββββ β REST routes + serveStatic β
βββββββββββββββββββββββ JSON responses ββββββββββββββββ¬ββββββββββββββββ
β imports
βΌ
ββββββββββββββββββββββββββββββββ
β Service layer β
β src/services/delegation.ts β
β Ed25519 sign/verify, Maps, β
β policy logic, audit log β
ββββββββββββββββ¬ββββββββββββββββ
βΌ
ββββββββββββββββββββββββββββββββ
β tweetnacl / tweetnacl-util β
β Types (src/types.ts) β
ββββββββββββββββββββββββββββββββ
Lifecycle:
Main agent Broker routes Service layer (Maps)
β β β
βββ POST /delegate βββββββΊβ β
β βββ mintToken() βββββββββββββββΊβ sign(JSON(token))
ββββ { token + signature }ββββββββββββββββββββββββββββββββ tokens.set(id,β¦)
β Sub-agent presents token β audits.push(mint)
βββ GET /verify/:id ββββββΊβββ verifyToken() βββββββββββββΊβ verify(signature)
ββββ { chain, verified } βββββββββββββββββββββββββββββββββ audits.push(verify)
βββ POST /check ββββββββββΊβββ checkPolicy() βββββββββββββΊβ endpoint + spendCap
ββββ { allowed } βββββββββββββββββββββββββββββββββββββββββ audits.push(violation?)
βββ POST /revoke/:id βββββΊβββ revokeToken() βββββββββββββΊβ revoked = true
ββββ { revoked } βββββββββββββββββββββββββββββββββββββββββ audits.push(revoke)
Three decisions worth calling out:
-
Routes are thin.
server.tschecks required fields and delegates. Business logic is testable over HTTP-free. -
Crypto is isolated in
services/delegation.ts, which owns the keypair and every sign/verify call. -
The demo is same-origin.
serveStaticservesdemo/index.htmlfrom the same Hono process β no CORS, no second dev server.
Walking the code
Entry point
// src/index.ts
import { serve } from '@hono/node-server'
import app from './server.js'
const PORT = Number(process.env.PORT) || 3000
serve({ fetch: app.fetch, port: PORT }, (info) => {
console.log(`Agent Delegation Broker listening on :${info.port}`)
})
Routes + demo static serving
// src/server.ts (excerpt)
const app = new Hono()
app.use('/demo/*', serveStatic({ root: './' }))
app.get('/demo', serveStatic({ path: './demo/index.html' }))
app.post('/delegate', async (c: Context) => {
const body = await c.req.json()
const { mainAgentId, subAgentId, policy } = body
if (!mainAgentId || !subAgentId || !policy) {
return c.json({ code: 'invalid_request', detail: 'Missing β¦' }, 400)
}
const token = mintToken(mainAgentId, subAgentId, policy)
return c.json({ token }, 201)
})
Small details like 201 Created and a 401 on invalid tokens make the API feel real to consumers and to the demo.
Signing and verification
// src/services/delegation.ts (excerpt)
import nacl from 'tweetnacl'
import naclUtil from 'tweetnacl-util'
// tweetnacl-util is CommonJS (`export = util`); Node's ESM loader cannot
// provide named exports, so use the default (namespace) import instead.
const { encodeBase64, decodeBase64 } = naclUtil
const keyPair = nacl.sign.keyPair()
function signToken(token: Omit<DelegationToken, 'signature'>): string {
const msgBytes = new TextEncoder().encode(JSON.stringify(token))
return encodeBase64(nacl.sign.detached(msgBytes, keyPair.secretKey))
}
function verifyTokenSignature(token: DelegationToken): boolean {
const { signature, ...rest } = token
const msgBytes = new TextEncoder().encode(JSON.stringify(rest))
return nacl.sign.detached.verify(msgBytes, decodeBase64(signature), keyPair.publicKey)
}
Because JSON.stringify preserves insertion order, signing the object without signature and verifying the same object with signature removed produces byte-identical messages.
The ESM bug and the fix
Running npm run dev originally crashed:
SyntaxError: The requested module 'tweetnacl-util' does not provide
an export named 'decodeBase64'
Root cause: [email protected] is a CommonJS package whose .d.ts declares export = util β it exports a single object via module.exports. Node 22's ESM loader cannot statically detect named exports from that shape, so import { encodeBase64, decodeBase64 } fails at instantiation. The fix is a default import (Node supports that for CJS), then destructure:
import naclUtil from 'tweetnacl-util'
const { encodeBase64, decodeBase64 } = naclUtil
I applied the same default import to tweetnacl for consistency. TypeScript's esModuleInterop: true keeps both correctly typed. npm run build, npm run dev, and the compiled node dist/index.js all work after this change.
Policy check
export function checkPolicy(tokenId: string, endpoint: string, amount: number) {
const chain = verifyToken(tokenId)
if (!chain) return { allowed: false, reason: 'Invalid or expired token' }
const { policy } = chain
if (policy.allowedEndpoints.length > 0 &&
!policy.allowedEndpoints.includes(endpoint)) {
return { allowed: false, reason: `Endpoint ${endpoint} not allowed` }
}
if (amount > policy.spendCap) {
return { allowed: false, reason: `Amount ${amount} exceeds spend cap ${policy.spendCap}` }
}
return { allowed: true }
}
Note: rateLimitPerMinute is stored in the policy but not yet enforced β that's an open contribution.
Shared types
// src/types.ts (excerpt)
export interface DelegationPolicy {
spendCap: number
allowedEndpoints: string[]
ttlSeconds: number
rateLimitPerMinute: number
}
export interface DelegationToken {
id: string
mainAgentId: string
subAgentId: string
policy: DelegationPolicy
issuedAt: string
expiresAt: string
revoked: boolean
signature: string
}
The demo UI
The browser page is the part that makes this project explainable in a screenshot. It calls the real API:
async function call(method, path, body) {
const res = await fetch(base() + path, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
})
const data = await res.json()
setResp(method + ' ' + path, res.status, data, !res.ok)
return { ok: res.ok, data }
}
Design: solid layered dark surfaces (no gradients), a translucent sticky header (backdrop-filter: saturate(180%) blur(20px)), iOS system colors (#0a84ff, #30d158, #ff453a, #bf5af2), size-specific type tracking, instant press feedback on :active, and proper reduced-motion / reduced-transparency / increased-contrast handling. The page shows a mint form, token card, step tracker, live JSON responses, audit trail, and the service public key β so someone can understand delegation in a minute without reading a single curl command.
The demo also makes the in-memory caveat visible: it notes that restarting the server changes the public key and clears all tokens.
Running it
npm install
npm run dev # http://localhost:3000
# or PORT=3100 npm run dev β demo at http://127.0.0.1:3100/demo
npm run build && npm start
docker build -t agent-delegation-broker .
docker run -p 3000:3000 agent-delegation-broker
Try the lifecycle:
curl -X POST http://localhost:3000/delegate \
-H 'Content-Type: application/json' \
-d '{"mainAgentId":"main-1","subAgentId":"shopping-agent","policy":{"spendCap":100,"allowedEndpoints":["/pay"],"ttlSeconds":3600,"rateLimitPerMinute":30}}'
curl http://localhost:3000/verify/<tokenId>
curl -X POST http://localhost:3000/check \
-H 'Content-Type: application/json' \
-d '{"tokenId":"<tokenId>","endpoint":"/pay","amount":50}'
curl -X POST http://localhost:3000/revoke/<tokenId>
curl http://localhost:3000/audit
npm test currently exits 1 with "No test files found" β the first good contribution is a Vitest suite for the service layer.
Where I'd take it next
- Vitest coverage for signing, verification, expiry, revocation, and policy.
- Enforce
rateLimitPerMinute(stored but unused). - Wire up
src/db.ts: persist tokens/audits and the signing key with Drizzle. - Key rotation with a
kidin tokens; auth on/delegateand/revoke. - Replay protection (nonce/jti) on
/check. - Zod validation and pino logging.
- CI running build + lint + tests on PRs.
MIT licensed and fork-friendly β if any of that sounds like a good first PR, go for it.
Links
- Visa CLI Docs: https://app.visacli.sh/docs
- Agent identity: https://app.visacli.sh/docs/agent-identity.md
- Message signing: https://app.visacli.sh/docs/message-signing.md
Code & more: https://www.dailybuild.xyz/project/333-agent-delegation-broker
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.