Dev.to AI πŸ€– Ai πŸ‘ 2 πŸ“– 6 min read

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

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 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

  1. Main agent mints a delegation token for a sub-agent.
  2. The policy embeds a spend cap, allowed endpoints, TTL, and a rate limit.
  3. The token is signed with the broker's Ed25519 key.
  4. Sub-agent presents the token; the broker verifies the signature.
  5. On each action, policy gates the endpoint and amount.
  6. Main agent can revoke at any time.
  7. 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:

  1. Routes are thin. server.ts checks required fields and delegates. Business logic is testable over HTTP-free.
  2. Crypto is isolated in services/delegation.ts, which owns the keypair and every sign/verify call.
  3. The demo is same-origin. serveStatic serves demo/index.html from 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.

Demo UI

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 kid in tokens; auth on /delegate and /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

Code & more: https://www.dailybuild.xyz/project/333-agent-delegation-broker

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.