{"slug": "building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents", "title": "Building an Agent Delegation Broker: scoped signing authority for TAP agents", "summary": "A developer built the Agent Delegation Broker, an open-source reference implementation that lets a main TAP agent mint signed, policy-bound Ed25519 tokens for sub-agents, with the broker verifying signatures, enforcing per-request policy such as endpoint and spend caps, revoking tokens on demand, and maintaining an audit trail. The MVP runs on Node.js 22 with Hono and tweetnacl, stores tokens and audits in in-memory Maps with no database, and ships with an interactive browser demo; the developer notes it lacks auth, replay protection and persistent keys, and also documented an ESM/CJS interop fix for tweetnacl-util on Node 22.", "body_md": "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.\n\nThe 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.\n\nStatus: MVP, not production. Keys are in-memory, no auth, no replay protection. See the roadmap at the end.\n\n| Layer | Technology | Reason | \n|---|---|---|\n| Runtime | Node.js 22 | LTS, native `crypto.randomUUID` | \n| Language | TypeScript 5.5 (strict, NodeNext ESM) | Type-safe service layer | \n| HTTP | Hono 4 + `@hono/node-server` | Tiny, fast, `serveStatic` for the demo | \n| Crypto | tweetnacl (Ed25519) + tweetnacl-util | Small, audited base64 + signing helpers | \n| Tooling | tsx, Vitest, ESLint, drizzle-kit | Hot reload, tests, lint, migrations | \n| Extras installed | Zod, pino, Drizzle + postgres.js | Ready to wire in later | \n| Demo | Vanilla HTML/CSS/JS | No build step, same-origin | \n| Packaging | Multi-stage Docker ( `node:22-alpine` ) | Slim runtime with `dist/` +`demo/` | \n\nDeliberate choice: **no database**. Three in-memory `Map` s (`tokens`, `audits`) remove all setup friction for a reference. `src/db.ts` is scaffolding for the day persistence is needed.\n\n```\n┌─────────────────────┐      fetch() JSON       ┌──────────────────────────────┐\n│  Browser (demo UI)  │ ───────────────────────► │  Hono app (src/server.ts)    │\n│  demo/index.html    │ ◄─────────────────────── │  REST routes + serveStatic   │\n└─────────────────────┘      JSON responses      └──────────────┬───────────────┘\n                                                                 │ imports\n                                                                 ▼\n                                                  ┌──────────────────────────────┐\n                                                  │ Service layer                │\n                                                  │ src/services/delegation.ts   │\n                                                  │ Ed25519 sign/verify, Maps,   │\n                                                  │ policy logic, audit log      │\n                                                  └──────────────┬───────────────┘\n                                                                 ▼\n                                                  ┌──────────────────────────────┐\n                                                  │ tweetnacl / tweetnacl-util   │\n                                                  │ Types (src/types.ts)         │\n                                                  └──────────────────────────────┘\n```\n\nLifecycle:\n\n```\nMain agent                Broker routes                Service layer (Maps)\n     │                         │                              │\n     │── POST /delegate ──────►│                              │\n     │                         │── mintToken() ──────────────►│  sign(JSON(token))\n     │◄── { token + signature }│◄─────────────────────────────│  tokens.set(id,…)\n     │  Sub-agent presents token                              │  audits.push(mint)\n     │── GET /verify/:id ─────►│── verifyToken() ────────────►│  verify(signature)\n     │◄── { chain, verified } ─│◄─────────────────────────────│  audits.push(verify)\n     │── POST /check ─────────►│── checkPolicy() ────────────►│  endpoint + spendCap\n     │◄── { allowed } ─────────│◄─────────────────────────────│  audits.push(violation?)\n     │── POST /revoke/:id ────►│── revokeToken() ────────────►│  revoked = true\n     │◄── { revoked } ─────────│◄─────────────────────────────│  audits.push(revoke)\n```\n\nThree decisions worth calling out:\n\n`server.ts` checks required fields and delegates. Business logic is testable over HTTP-free.`services/delegation.ts`, which owns the keypair and every sign/verify call.` serveStatic` serves `demo/index.html` from the same Hono process — no CORS, no second dev server.\n\n``` python\n// src/index.ts\nimport { serve } from '@hono/node-server'\nimport app from './server.js'\n\nconst PORT = Number(process.env.PORT) || 3000\nserve({ fetch: app.fetch, port: PORT }, (info) => {\n  console.log(`Agent Delegation Broker listening on :${info.port}`)\n})\njs\n// src/server.ts (excerpt)\nconst app = new Hono()\n\napp.use('/demo/*', serveStatic({ root: './' }))\napp.get('/demo', serveStatic({ path: './demo/index.html' }))\n\napp.post('/delegate', async (c: Context) => {\n  const body = await c.req.json()\n  const { mainAgentId, subAgentId, policy } = body\n  if (!mainAgentId || !subAgentId || !policy) {\n    return c.json({ code: 'invalid_request', detail: 'Missing …' }, 400)\n  }\n  const token = mintToken(mainAgentId, subAgentId, policy)\n  return c.json({ token }, 201)\n})\n```\n\nSmall details like `201 Created` and a `401` on invalid tokens make the API feel real to consumers and to the demo.\n\n``` python\n// src/services/delegation.ts (excerpt)\nimport nacl from 'tweetnacl'\nimport naclUtil from 'tweetnacl-util'\n\n// tweetnacl-util is CommonJS (`export = util`); Node's ESM loader cannot\n// provide named exports, so use the default (namespace) import instead.\nconst { encodeBase64, decodeBase64 } = naclUtil\n\nconst keyPair = nacl.sign.keyPair()\n\nfunction signToken(token: Omit<DelegationToken, 'signature'>): string {\n  const msgBytes = new TextEncoder().encode(JSON.stringify(token))\n  return encodeBase64(nacl.sign.detached(msgBytes, keyPair.secretKey))\n}\n\nfunction verifyTokenSignature(token: DelegationToken): boolean {\n  const { signature, ...rest } = token\n  const msgBytes = new TextEncoder().encode(JSON.stringify(rest))\n  return nacl.sign.detached.verify(msgBytes, decodeBase64(signature), keyPair.publicKey)\n}\n```\n\nBecause `JSON.stringify` preserves insertion order, signing the object without `signature` and verifying the same object with `signature` removed produces byte-identical messages.\n\nRunning `npm run dev` originally crashed:\n\n```\nSyntaxError: The requested module 'tweetnacl-util' does not provide\nan export named 'decodeBase64'\n```\n\nRoot cause: `tweetnacl-util@0.15.1` 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:\n\n``` python\nimport naclUtil from 'tweetnacl-util'\nconst { encodeBase64, decodeBase64 } = naclUtil\n```\n\nI 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.\n\n```\nexport function checkPolicy(tokenId: string, endpoint: string, amount: number) {\n  const chain = verifyToken(tokenId)\n  if (!chain) return { allowed: false, reason: 'Invalid or expired token' }\n  const { policy } = chain\n\n  if (policy.allowedEndpoints.length > 0 &&\n      !policy.allowedEndpoints.includes(endpoint)) {\n    return { allowed: false, reason: `Endpoint ${endpoint} not allowed` }\n  }\n  if (amount > policy.spendCap) {\n    return { allowed: false, reason: `Amount ${amount} exceeds spend cap ${policy.spendCap}` }\n  }\n  return { allowed: true }\n}\n```\n\nNote: `rateLimitPerMinute` is stored in the policy but not yet enforced — that's an open contribution.\n\n```\n// src/types.ts (excerpt)\nexport interface DelegationPolicy {\n  spendCap: number\n  allowedEndpoints: string[]\n  ttlSeconds: number\n  rateLimitPerMinute: number\n}\n\nexport interface DelegationToken {\n  id: string\n  mainAgentId: string\n  subAgentId: string\n  policy: DelegationPolicy\n  issuedAt: string\n  expiresAt: string\n  revoked: boolean\n  signature: string\n}\n```\n\nThe browser page is the part that makes this project explainable in a screenshot. It calls the real API:\n\n``` js\nasync function call(method, path, body) {\n  const res = await fetch(base() + path, {\n    method,\n    headers: body ? { 'Content-Type': 'application/json' } : {},\n    body: body ? JSON.stringify(body) : undefined,\n  })\n  const data = await res.json()\n  setResp(method + ' ' + path, res.status, data, !res.ok)\n  return { ok: res.ok, data }\n}\n```\n\nDesign: 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.\n\nThe demo also makes the in-memory caveat visible: it notes that restarting the server changes the public key and clears all tokens.\n\n```\nnpm install\nnpm run dev                      # http://localhost:3000\n# or PORT=3100 npm run dev        → demo at http://127.0.0.1:3100/demo\n\nnpm run build && npm start\ndocker build -t agent-delegation-broker .\ndocker run -p 3000:3000 agent-delegation-broker\n```\n\nTry the lifecycle:\n\n```\ncurl -X POST http://localhost:3000/delegate \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"mainAgentId\":\"main-1\",\"subAgentId\":\"shopping-agent\",\"policy\":{\"spendCap\":100,\"allowedEndpoints\":[\"/pay\"],\"ttlSeconds\":3600,\"rateLimitPerMinute\":30}}'\n\ncurl http://localhost:3000/verify/<tokenId>\ncurl -X POST http://localhost:3000/check \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"tokenId\":\"<tokenId>\",\"endpoint\":\"/pay\",\"amount\":50}'\ncurl -X POST http://localhost:3000/revoke/<tokenId>\ncurl http://localhost:3000/audit\n```\n\n`npm test` currently exits 1 with \"No test files found\" — the first good contribution is a Vitest suite for the service layer.\n\n`rateLimitPerMinute` (stored but unused).`src/db.ts`: persist tokens/audits and the signing key with Drizzle.` kid` in tokens; auth on `/delegate` and `/revoke`.`/check`.\nMIT licensed and fork-friendly — if any of that sounds like a good first PR, go for it.\n\nCode & more: [https://www.dailybuild.xyz/project/333-agent-delegation-broker](https://www.dailybuild.xyz/project/333-agent-delegation-broker)", "url": "https://wpnews.pro/news/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents", "canonical_source": "https://dev.to/harishkotra/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents-11bm", "published_at": "2026-12-03 18:06:02+00:00", "updated_at": "2026-12-03 18:17:06.878567+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "developer-tools"], "entities": ["Agent Delegation Broker", "TAP", "Node.js 22", "Hono", "tweetnacl", "tweetnacl-util", "TypeScript", "Drizzle"], "also_reported_by": [], "takeaway": "Mint a signed, policy-bound Ed25519 token per sub-agent and enforce endpoint and spend-cap policy at a broker on every request, rather than issuing each sub-agent its own key and card step.", "recommendation": {"advice": "Give sub-agents broker-minted scoped tokens instead of their own keys, and verify signature plus policy on every request; add replay protection and persistent keys before production.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents", "markdown": "https://wpnews.pro/news/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents.md", "text": "https://wpnews.pro/news/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents.txt", "jsonld": "https://wpnews.pro/news/building-an-agent-delegation-broker-scoped-signing-authority-for-tap-agents.jsonld"}}