# AllowedBy for JavaScript # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- # AllowedBy SDK for TypeScript and JavaScript `@allowedby/sdk` lets AI agents use your API for a person, with that person's approval (a passkey tap on their AllowedBy node). Your service publishes what each operation needs; the SDK verifies every agent request offline (ABY-2 §5), answers with a challenge when an approval is missing, and creates the approval itself for serious actions. The concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in TypeScript and JavaScript. Terms used here: an **agent passport** is the agent's signed identity from its node; a **grant** is the person's signed approval; a **proof** is a JWT the agent signs for each request; **JWS** is a signed JSON document (RFC 7515); **JCS** is canonical JSON (RFC 8785). ## Install Install the package with npm (or pnpm, yarn, bun); it has no runtime dependency. ```sh npm install @allowedby/sdk ``` - **Runtimes**: Node.js 20, 22 and 24; Bun 1.3.3+; Deno 2; Cloudflare Workers (through the Hono adapter). The core uses only WebCrypto (`globalThis.crypto.subtle`: Ed25519, P-256 ECDSA, HMAC), `fetch`, `TextEncoder` and `DecompressionStream`, so the same code runs everywhere. - **Modules**: ES modules and CommonJS (`import` or `require`), with TypeScript types. - **Dependencies**: none at run time. Frameworks are optional peer dependencies: the adapter for a framework is under its own import path (`@allowedby/sdk/express`, `/fastify`, `/hono`, `/next`, `/nest`, `/node`) and loads nothing else. The shared Redis store (`@allowedby/sdk/redis`) takes an `ioredis` client you create. - **Not published yet**: until the package is on npm, build it from this repository: ```sh cd sdks/js npm ci npm run build npm pack # -> allowedby-sdk-0.1.0.tgz, then: npm install /path/to/allowedby-sdk-0.1.0.tgz ``` ## Quick start A service that accepts agents is one `AllowedBy` object and one wrapper around your server (file: `sdks/js/examples/quickstart.mjs`). ```js import http from "node:http"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedByNode } from "@allowedby/sdk/node"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "http://localhost:3000", node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, }); http.createServer(allowedByNode(aby, (req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ notes: [], person: req.allowedby?.humanId ?? null })); })).listen(Number(process.env.PORT ?? 3000), process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` See it work against a local node. The node and its demo sites run from the repository (Python 3.10+ with the packages of `requirements.txt`): Linux and macOS: ```sh python demo/run.py --port 8700 & # the node on http://localhost:8700 node sdks/js/examples/quickstart.mjs & sleep 5 # both have started curl -s http://localhost:3000/.well-known/allowedby # what agents read curl -si http://localhost:3000/notes # 401 passport_required: an agent must present a passport ``` Windows (PowerShell): ```powershell Start-Process python -ArgumentList "demo/run.py", "--port", "8700" Start-Process node sdks/js/examples/quickstart.mjs Start-Sleep 5 Invoke-RestMethod http://localhost:3000/.well-known/allowedby curl.exe -si http://localhost:3000/notes ``` The whole flow (an agent asks, a person approves with a passkey, the agent retries) is what the interop test runs: see [Testing](#testing). In a container, see `sdks/js/examples/Dockerfile`: ```sh docker build -f sdks/js/examples/Dockerfile -t allowedby-notes sdks/js docker run -p 3000:3000 -e ALLOWEDBY_ORIGIN=http://localhost:3000 -e ALLOWEDBY_NODE=https://node.example.org allowedby-notes ``` ## Routes and templates Each operation agents may call is one `route(method, path, capability, options)` line, and each capability has a template: the sentence the person reads and signs (file: `sdks/js/examples/routes.mjs`). ```js import { route } from "@allowedby/sdk"; export const routes = [ route("GET", "/me", undefined, { level: 0 }), // the agent's passport is enough route("GET", "/notes", "notes:read", { resource: "note:*" }), // read, level 1 (a passkey tap) route("POST", "/notes", "notes:write", { class: "write", resource: "note:new", body: { text: "the note" } }), route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}" }), route("POST", "/invoices/{id}/pay", "invoices:pay", { class: [{ upTo: "1000.00", class: "write-hard" }, { class: "irreversible" }], // the class by amount amountField: "/total", currencyField: "/currency", level: 2, authn: "hardware", resource: "invoice:{id}", }), ]; export const templates = { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}", "invoices:pay": { summary: { en: "Pay {scope}, up to {amount.max} {amount.currency}" }, lines: { en: "Pay {scope}" } }, }; ``` | Option | Meaning | Default | |---|---|---| | `class` | `read`, `write`, `write-hard` (hard to undo), `irreversible`; or amount thresholds `[{upTo, class}, ..., {class}]` | `read` | | `level` | 0 agent only (a route without a capability: `route()` refuses a capability at level 0), 1 passkey tap, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey | 1 | | `resource` | What the grant's `scope` must cover; `{param}` from the path | `:*` | | `amountField`, `currencyField` | JSON Pointers to the amount and its currency in the body; the grant must cap the amount | none, `/currency` | | `authn` | The weakest passkey accepted: `synced` or `hardware` | any | | `tier` | Custody tier of the agent's key (OAID-6), 0 to 3 | 0 | | `maxLifetime` | Longest grant lifetime accepted, 60 s to 30 days | the class maximum (30 d, 7 d, 1 d, 1 h) | | `levelProfile` | `eu` or `na`, on a level-3 route ([Level profiles](#level-profiles)) | none | | `nonce` | The proof must carry a current service nonce ([AllowedBy-Nonce](#allowedby-nonce)); needs the service option `nonce` | false | | `summary`, `body` | Describe the operation to agents (OpenAPI) | none | | `requireLink` | The person must have linked their identity to one of your accounts ([Account linking](#account-linking)); else 403 `human_not_linked`. A route of level 1 or more | false | | `accountParam` | The path parameter that names one of your accounts: with `requireLink`, the person must be linked to that account | `account` | `write-hard` and `irreversible` routes are approved every time, for the exact request: the SDK creates that approval itself (a signed `POST {approvals}` to the node, ABY-2 §7) and the grant works once. `read` and `write` approvals are standing: the agent reuses them until they expire or the person withdraws them. The Python options `mandate`, `disclose`, `discloseOptional`, `authority` and `qes` are not enforced by this SDK yet: `route()` refuses them, so a route never accepts what it cannot check. ## Framework recipes Each recipe is the same notes service on one framework. CI runs each on every version below against a real node, agent and person, all the interop scenarios (`examples/frameworks.json`): | Framework | Versions run in CI | |---|---| | Node.js http | Node.js 20.20.2, 22.23.5, 24.22.3 | | Express | 4.18.0, 4.22.3, 5.0.0, 5.3.0 | | Fastify | 4.20.0, 4.29.1, 5.0.0, 5.12.8 | | Hono 4.0.6 (Node.js) and 4.13.22 | on Node.js, Bun 1.3.3 and 1.4.5, Deno 2.0.6 and 2.9.6, Cloudflare Workers (`wrangler dev`) | | Next.js, route handlers | 14.2.25, 15.5.29, 16.4.6 | | Next.js, middleware (`proxy.js` in 16) | 15.5.29, 16.4.6 | | NestJS | 10.0.0, 10.4.22, 11.2.12, 12.6.2 | Mount the SDK before your body parsers: the proof covers the body bytes exactly as received. The shared service (file: `sdks/js/examples/frameworks/notes.mjs`): ```js import { AllowedBy, route } from "@allowedby/sdk"; /** @param {Partial} [options] the settings of one deployment */ export function notesService({ origin = process.env.ALLOWEDBY_ORIGIN, node = process.env.ALLOWEDBY_NODE, ...options } = {}) { return new AllowedBy({ origin, node, org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ route("GET", "/me", undefined, { level: 0, summary: "Who is calling" }), route("GET", "/notes", "notes:read", { resource: "note:*", summary: "List your notes" }), route("POST", "/notes", "notes:write", { class: "write", resource: "note:new", summary: "Add a note", body: { text: "the note" } }), route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note" }), ], templates: { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}" }, ...options, }); } /** Each person's notes, by their id at this service (the context's `humanId`, never null here: the handlers answer 403 * without a person): nobody sees another person's. */ export class Notes { /** @type {Map} */ people = new Map(); next = 0; list(person) { return this.people.get(person) ?? []; } /** -> {id}, or null when the text is not one to keep. */ add(person, text) { if (typeof text !== "string" || text.length < 1 || text.length > 2000) return null; const note = { id: String(++this.next), text }; this.people.set(person, [...this.list(person), note]); return { id: note.id }; } remove(person, id) { this.people.set(person, this.list(person).filter((n) => n.id !== id)); } } ``` **Express** (file: `sdks/js/examples/frameworks/express/app.mjs`). The context is `req.allowedby`; the parsed body is `req.body` (the SDK reads it once and gives it back). ```js import express from "express"; import { allowedby } from "@allowedby/sdk/express"; import { Notes } from "../notes.mjs"; export function makeApp(aby, notes = new Notes()) { const app = express(); app.use(allowedby(aby)); // before the body parsers: the proof covers the body bytes app.use(express.json()); app.get("/health", (req, res) => res.json({ ok: true })); // not in the route map: no check app.get("/me", (req, res) => { const { agent, operator, level } = req.allowedby; res.json({ agent, operator, level }); }); app.get("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ notes: notes.list(person) }); }); app.post("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const note = notes.add(person, req.body?.text); if (!note) return res.status(400).json({ error: "text: a string of 1 to 2000 characters" }); res.status(201).json(note); }); app.delete("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); notes.remove(person, req.params.id); res.json({ deleted: req.params.id }); }); return app; } ``` **Fastify** (file: `sdks/js/examples/frameworks/fastify/app.mjs`). A plugin; the check runs in `preParsing`, so Fastify's parsers and schemas work unchanged. The context is `request.allowedby`. ```js import Fastify from "fastify"; import allowedby from "@allowedby/sdk/fastify"; import { Notes } from "../notes.mjs"; export async function makeApp(aby, notes = new Notes()) { const app = Fastify(); await app.register(allowedby, { aby }); app.get("/health", async () => ({ ok: true })); // not in the route map: no check app.get("/me", async ({ allowedby: { agent, operator, level } }) => ({ agent, operator, level })); app.get("/notes", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); // level 0: no person to key by return { notes: notes.list(person) }; }); app.post("/notes", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); const note = notes.add(person, req.body?.text); return note ? reply.code(201).send(note) : reply.code(400).send({ error: "text: a string of 1 to 2000 characters" }); }); app.delete("/notes/:id", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); notes.remove(person, req.params.id); return { deleted: req.params.id }; }); return app; } ``` **Hono** on Node, Bun, Deno and Cloudflare Workers (file: `sdks/js/examples/frameworks/hono/app.mjs`). The context is `c.get("allowedby")`. ```js import { Hono } from "hono"; import { allowedby } from "@allowedby/sdk/hono"; import { Notes } from "../notes.mjs"; export function makeApp(aby, notes = new Notes()) { const app = new Hono(); app.use(allowedby(aby, { app })); // the app: the SDK asks its router which handler serves each route of the map app.get("/health", (c) => c.json({ ok: true })); // not in the route map: no check app.get("/me", (c) => { const { agent, operator, level } = c.get("allowedby"); return c.json({ agent, operator, level }); }); app.get("/notes", (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); // level 0: no person to key by return c.json({ notes: notes.list(person) }); }); app.post("/notes", async (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); const note = notes.add(person, (await c.req.json()).text); return note ? c.json(note, 201) : c.json({ error: "text: a string of 1 to 2000 characters" }, 400); }); app.delete("/notes/:id", (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); notes.remove(person, c.req.param("id")); return c.json({ deleted: c.req.param("id") }); }); return app; } ``` On Cloudflare Workers no timer runs between requests: pass `autoRefresh: false` and refresh as requests come (file: `sdks/js/examples/frameworks/hono/worker.mjs`). This worker keeps notes and replay set in one isolate: for production, give a shared `store`. ```js import { notesService } from "../notes.mjs"; import { makeApp } from "./app.mjs"; let app; // made by the first request: Workers have no settings, random values or timers before it let aby; let first; // the first refresh: one for every request, also those that come while it runs let refreshed = 0; const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export default { async fetch(request, env, ctx) { aby ??= notesService({ origin: env.ALLOWEDBY_ORIGIN, node: env.ALLOWEDBY_NODE, autoRefresh: false }); app ??= makeApp(aby); first ??= aby.refresh(); // the node's keys and revocation lists // A few seconds at most: then the check runs without them and refuses (untrusted_node, or 503 with Retry-After) await Promise.race([first, pause(1000 * Number(env.ALLOWEDBY_FIRST_REFRESH_SECONDS ?? 5))]); const now = Date.now(); if (now - refreshed >= 1000 * Number(env.ALLOWEDBY_REFRESH_SECONDS ?? 5)) { if (refreshed) ctx.waitUntil(aby.refresh()); refreshed = now; } return app.fetch(request, env, ctx); }, }; ``` **Next.js, route handlers.** The shared service, once per process (file: `sdks/js/examples/frameworks/next/route/lib/allowedby.js`): ```js import { notesService, Notes } from "./notes.mjs"; // One instance per process, whatever Next.js bundles where const shared = (globalThis.notesApp ??= { aby: notesService({ keyFile: process.env.ALLOWEDBY_KEY_FILE ?? ".allowedby/keys.json", refreshSeconds: Number(process.env.ALLOWEDBY_REFRESH_SECONDS ?? 5), }), notes: new Notes(), }); export const { aby, notes } = shared; ``` Wrap each App Router handler; the context is its third argument (file: `sdks/js/examples/frameworks/next/route/app/notes/route.js`): ```js import { withAllowedBy } from "@allowedby/sdk/next"; import { aby, notes } from "../../lib/allowedby.js"; export const dynamic = "force-dynamic"; export const GET = withAllowedBy(aby, (req, ctx, allowedby) => { const person = allowedby.humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); // level 0: no person to key by return Response.json({ notes: notes.list(person) }); }, { route: "GET /notes" }); // the route this handler serves: a request checked for another runs nothing here export const POST = withAllowedBy(aby, async (req, ctx, allowedby) => { const person = allowedby.humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); const note = notes.add(person, (await req.json()).text); if (!note) return Response.json({ error: "text: a string of 1 to 2000 characters" }, { status: 400 }); return Response.json(note, { status: 201 }); }, { route: "POST /notes" }); ``` The discovery documents are three more routes: `app/.well-known/allowedby/route.js`, and the same for `app/openapi.json/route.js` and `app/.well-known/api-catalog/route.js` (file: `sdks/js/examples/frameworks/next/route/app/.well-known/allowedby/route.js`): ```js import { withAllowedBy } from "@allowedby/sdk/next"; import { aby } from "../../../lib/allowedby.js"; export const dynamic = "force-dynamic"; // What agents read first: the SDK answers, the handler is never reached export const GET = withAllowedBy(aby, () => new Response(null, { status: 404 })); ``` **Next.js, middleware** (file: `sdks/js/examples/frameworks/next/middleware/middleware.js`). One place for every route and the discovery documents. The middleware forwards the context to the handler in a request header MAC'd with a key derived from the service's private key (it drops any copy a client sent); use `keyFile` so the middleware and the handlers share the key, and the Node.js middleware runtime (stable from Next.js 15.5). ```js // middleware.js (Next.js 15.5+, Node.js runtime): the discovery documents and the check of every route of the map import { allowedByMiddleware } from "@allowedby/sdk/next"; import { aby } from "./lib/allowedby.js"; export const middleware = allowedByMiddleware(aby); export const config = { matcher: ["/((?!_next/).*)"], runtime: "nodejs" }; ``` In Next.js 16 the file is `proxy.js` (file: `sdks/js/examples/frameworks/next/middleware/proxy.js`): ```js // proxy.js (Next.js 16+): the same, under its new name import { allowedByMiddleware } from "@allowedby/sdk/next"; import { aby } from "./lib/allowedby.js"; export const proxy = allowedByMiddleware(aby); export const config = { matcher: ["/((?!_next/).*)"] }; ``` The handlers read the context (file: `sdks/js/examples/frameworks/next/middleware/app/notes/route.js`): ```js // app/notes/route.js: the handler reads what the middleware checked import { readContext } from "@allowedby/sdk/next"; import { aby, notes } from "../../lib/allowedby.js"; export const dynamic = "force-dynamic"; export async function GET(req) { // the route this handler serves: a context checked for another throws (a rewrite after the middleware) const person = (await readContext(aby, req, { route: "GET /notes" })).humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); // level 0: no person to key by return Response.json({ notes: notes.list(person) }); } export async function POST(req) { const person = (await readContext(aby, req, { route: "POST /notes" })).humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); const note = notes.add(person, (await req.json()).text); if (!note) return Response.json({ error: "text: a string of 1 to 2000 characters" }, { status: 400 }); return Response.json(note, { status: 201 }); } ``` **NestJS** on the Express platform (file: `sdks/js/examples/frameworks/nest/src/app.ts`): a guard, the `@AllowedBy()` parameter decorator, and a middleware for the discovery documents. Create the app with `rawBody: true`: the guard checks the body as received. Compile with `"experimentalDecorators": true` (the Nest CLI default). ```ts import "reflect-metadata"; import { BadRequestException, Body, Controller, Delete, ForbiddenException, Get, Module, Param, Post, type INestApplication } from "@nestjs/common"; import { NestFactory } from "@nestjs/core"; import type { AllowedBy as AllowedByService, Context } from "@allowedby/sdk"; import { AllowedBy, AllowedByGuard, allowedbyDiscovery } from "@allowedby/sdk/nest"; import { Notes } from "../../notes.mjs"; const notes = new Notes(); @Controller() class NotesController { @Get("health") health() { return { ok: true }; // not in the route map: no check } @Get("me") me(@AllowedBy() { agent, operator, level }: Context) { return { agent, operator, level }; } @Get("notes") list(@AllowedBy() ctx: Context) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); // level 0: no person to key by return { notes: notes.list(person) }; } @Post("notes") add(@AllowedBy() ctx: Context, @Body() body?: { text?: unknown }) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); const note = notes.add(person, body?.text); if (!note) throw new BadRequestException("text: a string of 1 to 2000 characters"); return note; } @Delete("notes/:id") remove(@Param("id") id: string, @AllowedBy() ctx: Context) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); notes.remove(person, id); return { deleted: id }; } } @Module({ controllers: [NotesController] }) class AppModule {} export async function makeApp(aby: AllowedByService): Promise { const app = await NestFactory.create(AppModule, { rawBody: true, logger: ["error"] }); // rawBody: the proof covers it app.use(allowedbyDiscovery(aby)); app.useGlobalGuards(new AllowedByGuard(aby)); return app; } ``` **Node.js http** is the quick start above (`allowedByNode`); the context is `req.allowedby` and the body bytes `req.rawBody`. The interop app is a complete example: `sdks/js/examples/interop.mjs`. **Any other framework**: call `aby.handle(method, path)` for the discovery documents, then `aby.check({ method, path, query, headers, body })` on the raw body bytes; it returns `{ context, refusal }` (both null outside the route map). Send `refusal.status`, `refusal.headers` and `JSON.stringify(refusal.body)`. What every adapter does, in this order (sdks/CONTRACT.md §2.10): the SDK's endpoints; paths outside the route map reach your app unchanged; on a route of the map, a non-empty body must be a JSON object sent as `application/json` (or without `Content-Type`) in UTF-8, without byte order mark, duplicate members, prototype members or `Content-Encoding`, else 400 before anything is charged, so the handler reads what the check read; then the headers are checked (431 above 8 KiB) before any signature work. Routers dispatch variants of a path to the same handler (`/Notes/`, `//notes`, `/notes;x`, `/notes.json`): the SDK checks such forms too, and the verifier then refuses them, instead of letting them through. A method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `?_method=`) on a route of the map is refused (400), and so is a `POST` with a body to a path the map lists for `PUT`, `PATCH` or `DELETE` but not `POST` (a form's `_method` field could turn it into one of them). **What the adapters refuse, and why.** The path that is checked must be the path the router uses, and a handler that serves a route of the map must run for that route only: - A request target that parsers read in different ways is refused (400) on every path, before any routing: a backslash, `#`, a space, control or non-ASCII character, dot segments, `//host/path`, `http://host/path`. With Express, for example, `/notes\7#` reaches the handler of `/notes/7`. - A wildcard, an optional parameter or an any-method handler that serves a route of the map is refused (400) for the other paths and methods it takes. - The handler of a route of the map runs for that route only (sdks/CONTRACT.md §2.10, rule 5). Express, Fastify, Hono and NestJS see the handler the router chose, and the SDK knows each route's: a rule of the route's own shape (`/notes/:id` for `/notes/{id}`), else the handler the router takes for sample values, then the one a checked request ran. That last one is learnt only when it serves the route's template, not only this value: the rule the framework says it matched has the route's own shape, or the router also takes it for the route's sample values (a page of its own at `/api/notes/export`, reached as `/api/notes/{id}`, is refused and never learnt). Short of the matched rule, the route must also be checked at least as strictly as every route of the map, of any method, whose handler is not known (a sample that reaches no handler tells nothing); the request is refused otherwise. Refused (400): - the same handler on another path, or for another method: `app.get("/n/:id", h)` next to `app.get("/notes/:id", h)`; - a request checked for one route that runs the handler of another, of any method: `/notes/x7`, checked as `/notes/{id}`, that the router gives to the handler of `/notes/pay` or of `DELETE /api/notes/{id}`; - a request checked for one method of a template whose handler also serves another method of it (`/items/{id}` and `/items/{item}` are one template), which the route does not cover: one function on `app.get` and `app.post` (or `app.all`) runs for the stricter route only, and the log names both at the first request. Map that method at the same capability and level, or give it its own handler; separate functions per method are separate handlers; - a checked request that would run a catch-all (a handler that also serves the route's path with a word replaced) next to the route's own known handler, unless the pattern the framework matched has the route's own shape: a catch-all is never learnt as a route's handler. That holds for a site-wide route that calls `next()` too (an Express `app.all("*", log)` before the routes): register such middleware with `app.use`, which is no route's handler. A request with a value the route's own handler does not take, which falls through to an SPA fallback, is refused, and the fallback keeps serving the site. While a catch-all is all a route has (an Express sub-app mounted with `app.use("/api", api)`, a front controller), checked requests run it, and unchecked ones that reach it are refused. It runs for a request checked for a route only if that route is checked at least as strictly as every other route, of any method, it is protected for (a level-1 route does not run the code of a level-3 one through a shared front controller); - any other catch-all, wherever else it serves: one under a route's prefix (`/notes/:id/*` for `/notes/{id}/archive`), or one the router did not take through a rule for the whole site (`/:version/notes/:id` next to `/api/notes/{id}`). It runs for that route, so the same handler on another path is an alias of it; - while a route's own handler is not known (none found for it, or only a catch-all), a request at or below the route, of any method, as received or decoded (`/%6Eotes/7/x` is `/notes/7/x` to Fastify and Hono): nobody can tell whether its handler is that route's. A handler shared by two routes of the map, whatever their templates, runs for a request checked for one of them only if that route is checked at least as strictly as the other: one function on `DELETE /notes/{id}` (write-hard) and `DELETE /items/{id}` (write) runs for the first only, and the log names both. So does a route of the map with no handler of its own that another route's handler serves: with `GET /notes/pay` mapped and only `/notes/:id` to serve it, a request checked for `GET /notes/{id}` is refused until `/notes/pay` has a handler. A handler that the router tries after `/notes/pay`'s own rule (it runs if that rule calls `next()`) stays protected for it, unless it is the own rule of another route (`/notes/:id` for `GET /notes/{id}`): with Express or Hono, a wildcard `/notes/*` or an optional `/notes/:id?` as the handler of `GET /notes/{id}` also serves `/notes/pay`, so a request checked for `GET /notes/{id}` is refused. Give `GET /notes/{id}` the rule `/notes/:id`. The refusal names the route and the fix: give each route of the map a handler of its own, registered with the router, and for another method, map that method too or give it a handler of its own. - A handler for the whole site (a rule for `*`, `/*` or `/{*rest}`: a single-page app, static files, a "not found" page) stays open while each route of the map has a handler of its own, for requests that are not checked. Middleware is no handler: Express `app.use(fn)` and Hono `app.use("*", mw)` pass every request on. When a site-wide handler is all a route has, it is that route's handler: protected wherever it serves (the site's other pages too), and the log names the route. - One limit, where this SDK differs from the text of CONTRACT §2.10 rule 5: the log lines that rule 5 puts at start (a route served only by a site-wide catch-all, one handler for two methods that do not cover each other, a route whose handler is not known) come at the first request. The SDK builds its table of handlers then, once the framework's routes are registered after the middleware. - A handler that dispatches protected actions itself (one handler for every path that deletes or pays, or a legacy controller on a path no route maps) is not something the SDK can see. A front controller shared by protected routes of different capabilities or resources runs for none of them. Give each protected route its own handler. With Hono, `app.all("*", h)` is registered as `app.use("*", mw)` is: it counts as a middleware, never as a route's handler. - Hono does not tell a middleware from a handler. A middleware (`app.use(path, mw)`, of any path: `/api/*` or a route's own `/notes/:id`) is no handler where a route of a method of its own also takes the path: that route is. It still runs, so where its function is the handler of a route of the map (`app.all("/files/*", del)` with `del` serving `DELETE /api/notes/{id}`), the request is refused all the same. Where nothing else takes the path, it counts as a handler, so unchecked requests that reach only it near a route of the map are refused. A middleware given with a route (`app.get(path, requireLogin, h)`) is not its handler: the last function is. For a checked request, the handlers Hono would run after the route's own handler (only through its `next()`) are not looked at. - Hono: pass the app, `allowedby(aby, { app })`, the one whose `fetch` serves (with `route`, the outer app): its router tells which handler serves each route of the map. Without it, `allowedby` throws. - Fastify (4.20 or later): register the plugin before your routes and hooks, as the SDK must see every handler. A route of the map registered before it stops the app at start; any other route registered before it is refused (500), since its handler could be an alias of a protected one. - What runs before the check: a request that is not checked is refused before Express runs its `app.param()` callbacks and before the `onRequest` hooks of Fastify registered after the plugin, so an alias runs none of the app's code. With NestJS, middleware and guards that run before `AllowedByGuard` (register it first, `app.useGlobalGuards`) see the request before the check: keep them free of effects. - `unprotected` never lets a handler of the map run unchecked, also not for another method at the route's very template: one handler for `GET` and `POST /notes` would run for an unchecked `GET`, its input read from the query. Map that method too, or give it a handler of its own; the refusal says which. - The map lists full paths, with the prefix of any mount (below). Below a mount prefix, a map without the prefix is refused (400), as are, with Express, routes of the map mounted before `allowedby()`. With Hono and Node.js `http`, the order is yours: `app.use(allowedby(...))` comes first. Put the SDK on the outer Hono app, not inside one given to `mount`: outside Node.js the prefix it cuts is lost, and paths that are the end of a route of the map are refused. - With Express a refusal at the last moment goes through your error handlers, with `err.status` 400. - Changed after the check. A step after the SDK could move an accepted request to another path or method (a rewrite of `req.url`, a method override, a framework's own rewrite): its handler would then act on values the person never approved. Where the adapter sees what the handler runs for, it compares the method and the path (normalised as the check normalises it: `/notes/%37` is `/notes/7`) with those that were checked, and refuses a request that changed (400 `invalid_request`, the path not repeated) before any handler runs: - Express: when the router dispatches the route, after any middleware (`req.url` rewritten, `method-override`). A router's prefix (`app.use("/notes", router)`) is no change. Express runs `app.param()` callbacks just before that: keep them free of effects. - Fastify: before the check, against what Fastify routed on: `rewriteUrl`, or a hook after the plugin's that changes `req.raw.url` or `req.raw.method`. Fastify routes before any hook, so a later change moves neither the handler nor `req.params`. - Hono: against the path Hono routed on (`c.req.path`, its `getPath`), and when a step after the SDK makes Hono run another request with the same proof (`methodOverride`, a rewrite through `app.fetch`). - NestJS: `AllowedByGuard` runs after Nest's middleware and Express's routing, so a middleware that rewrote `req.url` or overrode the method (method-override's `req.originalMethod`) is refused when either request is one the SDK checks. A method changed without a trace (`req.method` alone) is checked as it is, and its proof, made for the other method, is refused (401). - Next.js: after a rewrite (`rewrites` in `next.config.js`, or `NextResponse.rewrite` in a middleware after the SDK's), a route handler still gets the URL the client sent, which `withAllowedBy` and `readContext` check, while the route file and Next's `params` are the rewrite's: a request accepted for `/notes/7` could run `app/notes/[id]` with `id` 8, or another route's file. So each handler states the route it serves, always: `withAllowedBy(aby, handler, { route: "DELETE /notes/{id}" })`, or `readContext(aby, req, { route: "DELETE /notes/{id}", params })` with Next's `params`. A request checked for another route, unless that route covers the handler's (sdks/CONTRACT.md §2.10 rule 5), or with other values in Next's `params`, is refused: `withAllowedBy` answers 400, and `readContext` throws `RouteMismatchError`, whose `response` is that 400. Uncaught, Next answers 500, which still refuses the request; to answer the 400, catch it: `try { ctx = await readContext(aby, req, { route, params }); } catch (e) { if (e instanceof RouteMismatchError) return e.response; throw e; }`. For a clean 400 without the catch, prefer `withAllowedBy` (route handlers without the middleware). With a route stated, `readContextIfAny` is `readContext`: that handler serves a route of the map, so a request without a context (a rewrite from a path outside the map) throws `MissingContextError`. Name each dynamic segment of the route's folder as the template's `{name}` (`[id]` for `{id}`), so that the values can be compared; a folder named otherwise is refused (500). A route that is not one of the map is a `TypeError`: `withAllowedBy` throws it when the handler is made, at start; `readContext`, which runs per request, throws it on every call, before any context is read. Not covered: where the adapter does not see the route the handler runs for. Node.js `http` (route on `req.checkedPath`), `aby.check`, a Fastify hook registered before the plugin, a function mounted as Express middleware, and a Next.js handler that does not state its route. Put nothing that changes the method or the path after the SDK there, and read the values from `context.params`, never from the framework's own. - A Next.js handler in `withAllowedBy`, or that calls `readContext`, always has a context: other paths are refused, or `readContext` throws. `readContextIfAny` is for a handler that also serves paths outside the map. - Where the SDK does not see the route that is chosen (Node.js `http`, the Next.js middleware, `aby.check`), a path that would match a mapped template if a parameter took several segments is refused (400) for a mapped method: `DELETE /notes/7/x` with `DELETE /notes/{id}`. `GET /notes/7` with only `GET /notes` in the map is not. List your own such pages in `unprotected` (`["GET", "/notes/{id}/comments"]`, or `["DELETE", "/notes/7/x"]`); an entry that is or overlaps a route of the map is refused at construction, and an exact entry also lifts the checks on path variants for that very path (one that a router may take for a route of the map, such as a last `/` or another case: with the adapters that see the route only). It never lets a handler of the map run. These adapters do not see the handler, so rule 5 is out of their reach: give each route of the map a handler of its own. - A control character in the path of a route of the map, encoded or not, is refused (400). - A challenge names the resource the approval must cover (ABY-2 §6): the route's `resource` with the request's path values, normalised as for the proof (`%61b` is `ab`). Each value must be 1 to 64 of `A-Z a-z 0-9 . _ -`, and the whole scope at most 256 bytes, else the request is refused (400) instead of answered with a challenge no approval could satisfy: `a%20b`, `x%C3%A9`, `~`, `:`, `*`, sub-delimiters, a broken escape or one that decodes to a control character or `/`. A grant that covers such a path (`invoice:*`) is still checked as before. - With Node.js `http`, route on `req.checkedPath`, the path that was checked, not on your own reading of `req.url`. - The SDK cannot see a function mounted as middleware (`app.use("/notes", handler)`; an Express sub-app given to `app.use` is seen, as a catch-all of its prefix), a rewrite of `req.url` made before it, or what a proxy behind a catch-all makes of a path. **Routes below a prefix** (`app.use("/api", router)`, Fastify's `prefix`, Hono's `route` and `basePath`, Nest's global prefix, Next.js's `basePath`). The map lists `/api/notes/{id}`, not `/notes/{id}`: it is what agents call, what their proof signs, and what `/openapi.json` and the challenges show them. This differs from the SDKs of the other languages, where the map holds the paths without the mount prefix. Put the SDK on the app itself, so that it also serves the discovery documents at the root (file: `sdks/js/examples/mounted.mjs`). ```js // Routes below a prefix: the map lists the full paths, those agents call and sign. The SDK goes on the app itself, which // also serves /.well-known/allowedby and /openapi.json; only the routes are mounted. import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; export function notesService(options = {}) { return new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "http://localhost:3000", node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/api/notes/{id}", "notes:read", { resource: "note:{id}" })], // "/notes/{id}" is refused (400) templates: { "notes:read": "Read {scope}" }, ...options, }); } export function makeApp(aby) { const api = express.Router(); api.get("/notes/:id", (req, res) => res.json({ id: req.params.id, person: req.allowedby.humanId })); const app = express(); app.use(allowedby(aby)); // first, and not below /api app.use("/api", api); return app; } if (process.argv[1]?.endsWith("mounted.mjs")) { makeApp(notesService()).listen(Number(process.env.PORT ?? 3000), process.env.ALLOWEDBY_BIND || "127.0.0.1"); } ``` ## The context Your handler receives a frozen `Context` after the SDK accepted the request: who asked, for whom, at which level. | Field | Type | Meaning | |---|---|---| | `humanId` | `string \| null` | The person's pairwise id for your service (null at level 0: no person). Use it as the account key, after a null check: without a person, answer 403, never key by null or "". | | `level` | `number` | The identity level verified: 0 agent only, 1 passkey, 2 verified identity, 3 eIDAS high. | | `agent` | `string` | The agent (its passport `sub`). | | `operator` | `string` | The company running the agent (its verified domain, or a node-scoped id). | | `capabilities` | `string[]` | The capabilities of the grant. | | `display` | `{summary, lines, lang} \| null` | The words the person approved. | | `gid`, `rev`, `jti` | `string`, `number`, `string` | The grant id, its revision and its document id (audit). | | `chain` | `[gid, rev][]` | The grant chain, leaf first (a sub-agent's grant and its parent). | | `route` | `Route` | The line of the route map that matched, with the class resolved. | | `proofJti`, `run`, `call` | `string`, `string \| null`, `number \| null` | The proof's id and the agent's run and call numbers (audit). | | `humanIss` | `string \| null` | The person's home node. | | `params` | `Readonly>` | The route's path values as the SDK checked them: each `{name}` of the route's template, from the normalised path the verifier compared, percent-decoded once (`/t/acme%20co` gives `{ tenant: "acme co" }`, `%2520` gives `%20`, an encoded `/` stays in its value). Act on these, never on your own reading of the raw path, which can differ (`DELETE /notes/7/.` is checked as `/notes/7`). Frozen, with no prototype, so `__proto__` is an ordinary name; `{}` for a route without parameters. | | `linkedAccount` | `string | null` | On a route with `requireLink`, the account of yours the person is linked to ([Account linking](#account-linking)); null on other routes. | | `tenant` | `string \| null` | The tenant the path names (its `tenant` parameter, decoded once), on an accepted request with a grant ([Tenants](#tenants)); null otherwise. | | `actingFor` | `null` | Company mandates are not supported by this SDK yet. | Where it is: `req.allowedby` (Node http, Express, Fastify), `c.get("allowedby")` (Hono), the third argument of a `withAllowedBy` handler or `readContext(aby, req)` (Next.js), `@AllowedBy()` (NestJS), `context` from `aby.check`. ## Production Run with a key file, a shared store and, when you can, a signed trust list; the rest is automatic (file: `sdks/js/examples/production.mjs`). ```js // Production settings: keys kept across restarts, a store shared by every instance, optionally a signed trust list. // REDIS_URL=redis://localhost:6379 node examples/production.mjs import http from "node:http"; import Redis from "ioredis"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedByNode } from "@allowedby/sdk/node"; import { RedisStore } from "@allowedby/sdk/redis"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "https://notes.example", node: process.env.ALLOWEDBY_NODE ?? "https://node.example.org", org: { legal_name: "Notes Ltd", country: "FR", privacy_policy: "https://notes.example/privacy" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, keyFile: process.env.ALLOWEDBY_KEY_FILE ?? "/var/lib/notes/allowedby-keys.json", // mode 0600, shared by instances store: new RedisStore(new Redis(process.env.REDIS_URL ?? "redis://localhost:6379")), // trustList: { jws: process.env.ALLOWEDBY_TRUST_LIST, key: JSON.parse(process.env.ALLOWEDBY_TRUST_KEY) }, refreshSeconds: 5, log: (line) => process.stdout.write(line + "\n"), // codes only: never tokens, keys or bodies }); await aby.ready(); // keys loaded, node statement and status lists fetched once http.createServer(allowedByNode(aby, (req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ notes: [], person: req.allowedby?.humanId ?? null })); })).listen(Number(process.env.PORT ?? 8080), process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` - **Keys** (`keyFile`, Node.js): the signing key (Ed25519) and the disclosure key (P-256), created on first use with mode 0600, atomically (first writer wins), in the same JSON format as the Python SDK, so one file works for every SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `keyFile` at it, or write it from your secret manager. An existing file works anywhere. Without `keyFile` the keys are new at each start: agents then fetch `/.well-known/allowedby` again. On runtimes without a file system, load a key yourself: `keys: { signing: await SigningKey.fromPem(pem) }`. - **Store**: `MemoryStore` (the default) is for one process. With several instances behind a load balancer, every instance must share the replay set and the single-use set, or a proof replayed on another instance is accepted: use `RedisStore` (atomic Lua scripts; expiry follows the SDK's clock; cluster-safe with one hash tag) or your own `Store` (`add`, `get`, `charge`, each atomic). A store error refuses the request (`503 status_stale`). A refund (below) is a `charge` of negative increments with no max: your store applies it exactly, and keeps each key's `until`. - **Refunds** (sdks/CONTRACT.md, Refund on the SDK's own refusal; ABY-2 §5 step 9): the check consumes a single-use approval and adds to the grant's count and amount totals, as before. When the SDK then refuses that same request itself, before its handler starts (rule 5, a request changed after the check, a Next.js handler of another route), it gives back exactly what the check charged, once, from the check's receipt, before it answers: the approval is usable again on its own route. Express, Fastify, Hono, NestJS and `withAllowedBy` do this. A refund the store does not take leaves the approval spent, logged without request data (`refund not recorded: the approval stays spent`). Nothing is given back once the handler started, for a refusal of your own (a handler or a middleware that answers), or after the SDK handed the request on: Express's 404 for a request moved to no route, a layer that dispatches the request again through Hono (`app.fetch`), the Next.js middleware (`readContext` reads a copy of the context, which has no receipt), Node.js `http` and `aby.check`. Each accepted request is started or given back, never both: one given back never reaches a handler, even when a layer dispatches it again (an Express error handler that lets routing go on), and is refused (400). - **Trust**: by default the SDK trusts `node` on first use (it pins the node's key at the first fetch and refuses a later change). In production give a signed OAID-5 trust list: `trustList: { jws, key }`; it lists anchors, programs and vouching rules, and replaces `node` as the source of trust. - **Refresh**: node statements and status lists are fetched in the background every `refreshSeconds` (default 5 s, at most 60 s), never while handling a request. The first refresh starts at construction, and the first requests wait for it (done or failed, at most 5 s after construction), so a service that starts cold (a new instance, one that scales to zero) answers its first request from a filled cache, not with `untrusted_node` or `503 status_stale` (sdks/CONTRACT.md §2 item 4); `await aby.ready()` waits for the same. A failed refresh is logged (`[verifier] refresh failed`) and the cached lists stay; when a status list is older than the class allows (60 s for `write-hard` and `irreversible`, 1 hour otherwise), requests are refused with `503 status_stale` until a refresh succeeds. - **Logging**: one line per decision, `[host] METHOD /route/pattern -> code`, and refresh failures. No token, key, body or personal data is logged. `log: false` silences it; any function receives the lines. - **Several instances**: share `keyFile` (or `keys`) and the store; nothing else is shared. ## Agents An agent calls AllowedBy APIs with `new Agent({ node, tell })` and `agent.call(method, url, body, { action })`; the call pauses while the person approves and retries once (CONF-1 `runtime` profile, a port of the Python runtime). (file: `sdks/js/examples/agent.mjs`) ```js // An agent calling a service for its person: passport, approval when needed (the person taps a passkey), retry. // ALLOWEDBY_NODE=http://localhost:8700 APP_URL=http://localhost:3000 node examples/agent.mjs import { Agent } from "@allowedby/sdk/agent"; const agent = new Agent({ node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", tell: (m) => { if (m.type === "approval_needed") console.log(`Please approve "${m.summary}": ${m.link} (code ${m.code})`); }, }); const app = process.env.APP_URL ?? "http://localhost:3000"; const { status, body } = await agent.call("GET", `${app}/notes`, undefined, { action: "notes:read" }); console.log(status, body); ``` What `agent.call` does: it gets a tier-0 passport from the node (OAID-3; renewed before expiry), signs the request (a proof JWT, or RFC 9421 with `httpSig: true`), and on a `401` challenge either follows the service's own approval (write-hard and irreversible: the link must be on the agent's node and match the node's approval page) or asks its node for one (read and write); it tells the person the link and the 4-character code, long-polls the node, checks the grant (signed by its node, for its key and the site) and retries once. Standing grants are kept and reused. After "not me" it does not ask again for that action for 10 minutes. `agent.delegate(sub, capabilities)` gives a sub-agent an attenuated child grant: a chain is a root and one child (depth 1, ABY-1 §4), so only a root grant is narrowed (a child or a chain given as `allowedBy` throws before the node is asked), and `adopt` keeps a chain of exactly two grants. `agent.rebind(gid)` moves a grant to a new passport (with `operatorDomain` and `operatorKey`, OAID-2 §6). Options: `node`, `tell`, `operator`, `runtime`, `pollTimeout` (default 300 s), `operatorDomain`, `operatorKey`, `httpSig`, `renew`, `fetch`, `clock`; call options: `action`, `standing`, `limits` (the amount the agent may spend on amount routes), `notify`. **Agent frameworks**: one tool, "call an AllowedBy API", for MCP, the Vercel AI SDK, LangChain.js and the OpenAI Agents SDK; it only calls the `origins` you list (file: `sdks/js/examples/agent-tools.mjs`). ```js // One AllowedBy tool for each agent framework. Each call may pause while the person approves; only the listed // origins can be called. node examples/agent-tools.mjs import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Agent } from "@allowedby/sdk/agent"; import { allowedbyTool as aiSdkTool } from "@allowedby/sdk/agent/ai"; import { allowedbyTool as langchainTool } from "@allowedby/sdk/agent/langchain"; import { registerAllowedByTool } from "@allowedby/sdk/agent/mcp"; import { allowedbyTool as openaiAgentsTool } from "@allowedby/sdk/agent/openai"; const agent = new Agent({ node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", tell: (m) => console.log(m) }); const options = { agent, origins: [process.env.APP_URL ?? "http://localhost:3000"] }; // Model Context Protocol: the approval link reaches the client as a log message while the tool waits const server = new McpServer({ name: "notes-agent", version: "1.0.0" }, { capabilities: { logging: {} } }); registerAllowedByTool(server, options); // Vercel AI SDK: generateText({ model, tools: { notes: aiTool }, prompt }) const aiTool = aiSdkTool(options); // LangChain.js: model.bindTools([lcTool]) const lcTool = langchainTool(options); // OpenAI Agents SDK: new Agent({ name: "Assistant", tools: [oaTool] }) const oaTool = openaiAgentsTool(options); console.log("tools ready:", typeof aiTool.execute, lcTool.name, oaTool.name); ``` Each runs in CI with a scripted model in place of the LLM, through the framework's own agent loop, against a real node and a person: the tool refuses another site, the person refuses then approves, and a replay of the model's call is refused (`sdks/js/examples/frameworks/agents`): MCP 1.32.2, Vercel AI SDK 5.0.292, 6.0.336 and 7.0.181, LangChain.js 1.6.8, OpenAI Agents SDK 0.22.0. The tool's input is `{ method, url, body (JSON text or null), action (or null) }`, every member required and nullable, so the OpenAI strict mode accepts it; its output is `{"status", "body"}` as JSON text. On routes with an amount, set `limits` in the options (what the agent may ask to spend: yours to set, never the model's); `standing` sets the period to ask for. MCP clients time out a call after 60 s by default, less than a person may take: give the client a timeout of at least the agent's `pollTimeout` (300 s), or `resetTimeoutOnProgress: true` with `onprogress` (the tool sends progress every `progressSeconds`, default 15). The frameworks are optional peer dependencies (`@modelcontextprotocol/sdk`, `ai`, `@langchain/core`, `@openai/agents-core`, and `zod`). ## Errors Every refusal is an RFC 9457 `application/problem+json` body whose `type` ends with the code; challenges also carry `WWW-Authenticate: AllowedBy ...`. The same table in every language: | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a malformed `Allowed-By`, a body over 1 MiB (413). | Fix the request. | | `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and sends it. | | `invalid_signature` | 401 | A signature, proof, replay, URL, body hash or `human_sig` check failed. | Never retried as is; the agent signs a fresh request. | | `untrusted_node` | 401 | The document comes from a node this service does not trust. | Trust the node (trust list), or the agent uses another node. | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses (trust list `witnesses_min`). | Wait for the node's log to be witnessed. | | `grant_required` | 401 | The route needs a person's approval; the challenge says which. | The agent asks the person (its node, or the service's approval link) and retries. | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, single use). | Ask for an approval that covers it. | | `level_insufficient` | 401 | The person's identity level is below the route's. | The person verifies their identity at a higher level. | | `qes_required` | 401 | A qualified electronic signature is needed. | Not supported by this SDK: such routes are refused. | | `authority_required` | 401 | The organisation's co-approvers must approve. | Not supported by this SDK yet. | | `mandate_required` | 401 | The person must act for an organisation with its mandate. | Not supported by this SDK yet: a grant carrying a mandate is refused. | | `expired` | 401 | The grant has expired. | Ask again. | | `not_yet_valid` | 401 | The grant's `nbf` is in the future. | Check the clocks; retry later. | | `revoked` | 401 | The person withdrew the approval, or the passport or registration was revoked. | Ask again. | | `actor_expired` | 401 | The agent's key in the grant has expired. | The agent rebinds the grant to its new passport, or asks again. | | `class_lifetime_exceeded` | 401 | The grant lasts longer than the route's class allows. | Ask for a shorter approval. | | `single_use_consumed` | 401 | A one-time approval was already used. | Ask again for this request. | | `capability_denied` | 403 | No such route. | None: the service does not offer it. | | `tier_insufficient` | 403 | The agent's key custody, or the passkey class, is weaker than the route needs. | Use a stronger key or passkey. | | `human_not_linked` | 403 | The person's account is not linked. | Not used by this SDK yet. | | `budget_exceeded` | 403 | A budget is used up. | Not used by this SDK yet. | | `rate_limited` | 429 | Too many requests. | Wait (`Retry-After`). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain over four documents. | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old to decide, or the store (replay set) or the service keys are not available. | Retry after `Retry-After`; check that the service reaches the node and its store, and the key file. | ## Testing Run the conformance vectors, the unit tests and the interop test; test your own app with `TestNode`, no browser. Linux and macOS: ```sh cd sdks/js npm ci npm run lint && npm run typecheck npm test # unit tests, adapters, examples, and the vectors (prints N/N cases passed) npm run build cd ../.. pip install -r requirements.txt INTEROP_PORT_BASE=19200 python sdks/interop/interop.py --cmd "node sdks/js/examples/interop.mjs" # 26/26 INTEROP_PORT_BASE=19200 python sdks/interop/interop.py --agent-cmd "node sdks/js/examples/interop-agent.mjs" # 7/7 ``` Windows (PowerShell): ```powershell cd sdks/js npm ci npm run lint; npm run typecheck npm test npm run build cd ../.. python -m pip install -r requirements.txt $env:INTEROP_PORT_BASE = "19200"; python sdks/interop/interop.py --cmd "node sdks/js/examples/interop.mjs" python sdks/interop/interop.py --agent-cmd "node sdks/js/examples/interop-agent.mjs" ``` - **Vectors**: `test/vectors.test.ts` reads every case of the `verifier` profile from `vectors/` at run time and fails on any case it cannot run: `verifier profile: 481/481 cases passed`. It also runs every case of the `runtime` profile (122) with the agent SDK's helpers. - **Interop**: the app in `examples/interop.mjs` is the port of `sdks/interop/reference_app.py`; the harness runs a real node, the reference agent and a person with a software passkey (26 scenarios). In agent mode, `examples/interop-agent.mjs` (the port of `reference_agent.py`) drives the Python reference app, whose verifier checks every passport request, proof and body hash the agent SDK builds (7 scenarios). - **Your app**: `@allowedby/sdk/testing` (TEST ONLY) is a node in memory: passports, grants signed by a software passkey, approvals for serious actions, revocation (file: `sdks/js/examples/test-your-app.test.mjs`). ```js // Test your own service without a browser or a real node: TestNode issues passports and grants (TEST ONLY). // node --test examples/test-your-app.test.mjs import assert from "node:assert/strict"; import { test } from "node:test"; import { AllowedBy, route } from "@allowedby/sdk"; import { TestNode } from "@allowedby/sdk/testing"; test("an agent reads the person's notes with their approval", async () => { const node = await TestNode.create(); const aby = new AllowedBy({ origin: "https://notes.example", node: node.origin, org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, fetch: node.fetch, // the test node answers the SDK's background fetches autoRefresh: false, log: false, }); await aby.refresh(); const agent = await node.agent(); const grant = await node.grant(agent, { audience: "https://notes.example", capabilities: [{ cap: "notes:read", constraints: { scope: "note:*" } }], }); const headers = await agent.sign("GET", "https://notes.example/notes", { allowedBy: grant }); const { context, refusal } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(refusal, null); assert.equal(context.level, 1); assert.equal(context.humanId, await node.humanId("https://notes.example")); const without = await aby.check({ method: "GET", path: "/notes", headers: {} }); assert.equal(without.refusal.status, 401); }); ``` ## Reference Every public export, by import path. **`@allowedby/sdk`** | Export | What | |---|---| | `new AllowedBy(options)` | The service. Options: `origin`, `node`, `org` (`legal_name`, `country`, `website`, `support`, `privacy_policy`, `logo`, `exp`), `routes`, `templates`; optional `keyFile`, `keys`, `store`, `trustList`, `refreshSeconds`, `nodeMaxLevel`, `clock`, `title`, `version`, `description`, `rfc9421`, `fetch`, `log`, `autoRefresh`, `unprotected`, `linkAuthorize`, `nonce`, `rate`. Invalid options throw a `TypeError` saying what to fix. | | `aby.check(req)` | `{ method, path, query?, headers, body? }` -> `Promise<{ context, refusal }>`: `refusal` is the response to send instead of running a handler (a refusal, or the SDK's own answer to `POST /allowedby/link`). Never throws on hostile input. | | `aby.handle(method, path)` | The discovery documents (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), or null. | | `aby.needsCheck(req)`, `aby.isProtected(method, path)` | Whether a request needs `check` (a route of the map in any form a router dispatches, or a method override onto one): adapters read the body only then. | | `aby.ready()`, `aby.refresh()`, `aby.close()` | Wait for the keys and the first refresh (at most 5 s; checks wait for it too); refresh now; stop the background refresh. | | `aby.wellKnown()`, `aby.openapi()`, `aby.apiCatalog()`, `aby.publicKey()` | The documents and the public signing key. | | `aby.linkStart(account, ttl = 600)` | A one-time linking code for one of your accounts ([Account linking](#account-linking)). | | `route(method, path, capability?, options?)` | One line of the route map (see [Routes and templates](#routes-and-templates)). | | `MemoryStore`, `Store`, `Charge` | The in-process store and the store interface. | | `Context`, `Reject`, `STATUS`, `CHALLENGE_CODES` | The context type; the refusal type, codes and statuses. | | `SigningKey` | Ed25519 or P-256 signing key: `generate()`, `fromPem()`, `toPem()`, `kid`, `jwk`. | | `problem(code, status, title?)` | An RFC 9457 problem response. | | `SDK_VERSION`, `SPEC_VERSION`, `MAX_BODY` | `0.1.0`, `0.2.14`, 1 MiB. | **Adapters**: `@allowedby/sdk/node` (`allowedByNode`, `nodeGate`, `readBody`, `send`), `@allowedby/sdk/express` (`allowedby`), `@allowedby/sdk/fastify` (default plugin, `allowedby`), `@allowedby/sdk/hono` (`allowedby`, `AllowedByVariables`), `@allowedby/sdk/next` (`withAllowedBy`, `allowedByMiddleware`, `readContext`, `readContextIfAny`, `CONTEXT_HEADER`), `@allowedby/sdk/nest` (`AllowedByGuard`, `AllowedBy` parameter decorator, `AllowedByContext`, `allowedbyDiscovery`). **Agent**: `@allowedby/sdk/agent` (`Agent`: `call`, `ensurePassport`, `renewPassport`, `rebind`, `delegate`, `adopt`, `checkGrant`, `nodeUrl`, `waitFor`, `grantFor`, `grants`, `lastGrant`; `parseChallenge`, `pollOutcome`, `validApprovalIds`; types `AgentOptions`, `CallOptions`, `CallResult`, `AgentMessage`), and its tools `@allowedby/sdk/agent/mcp` (`registerAllowedByTool(server, options)`), `/agent/ai`, `/agent/langchain`, `/agent/openai` (`allowedbyTool(options)`); options `agent`, `origins`, `limits`, `standing`, `name`, `description`, `onApproval`. **Others**: `@allowedby/sdk/redis` (`RedisStore(client, prefix?)`), `@allowedby/sdk/keyfile` (`loadKeys(path)`), `@allowedby/sdk/testing` (`TestNode`, `TestAgent`; TEST ONLY). **Implemented** (sdks/CONTRACT.md). Core: configuration, route map with the reference's validation, discovery documents, ABY-2 §5 verification (proof JWT and RFC 9421, passports, grants and chains, every WebAuthn check, `human.reg`, `initiator`, status lists with per-class freshness, class lifetimes, ABY-3 constraints with counters, request digests and single use, the replay set, TOFU and OAID-5 trust lists with programs, vouching and witnesses, EdDSA and ES256 only), challenges and service-initiated approvals, background refresh, the context, `MemoryStore` and `RedisStore`, `keyFile`, six framework adapters. Agent: `Agent` (passports, proofs, challenges, approvals, standing grants, rebind, renewal, sub-agents) and four agent-framework tools. Extended: account linking, AllowedBy-Nonce, level profiles, rate limits, tenants and tenant budgets (below). Extended, not yet in this SDK (each refused at construction): the disclosure callback and JWE decryption, authority policies, company mandates, QES, the audit sink and the admin console. ### Account linking An extended feature (sdks/CONTRACT.md, Extended; ABY-3 §6). A person links their AllowedBy identity to one of your accounts once; routes with `requireLink` then accept their agent for that account only. 1. Your signed-in account page calls `aby.linkStart(account, ttl = 600)` and shows the code (96 random bits, valid `ttl` seconds, single use). The person gives it to their agent. A new code does not revoke the older ones. 2. The agent sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves this route itself, in `check` (every adapter; NestJS through `allowedbyDiscovery`; Next.js in a route handler, below): an unknown, spent, revoked or expired code is refused (400 `invalid_request`) before any approval is asked for. The request is then checked as the route `aby:link` (class `write`, level 1, resource `aby:link`), with single-use grants only; without one, the SDK creates that approval itself, bound to this request, and the challenge links it. Only that exact path is the endpoint (CONTRACT 1.13): a variant (`/allowedby/%6Cink`, `/allowedby/./link`) is refused (400) and `/allowedby/link/` or `//allowedby/link` go to your app as paths outside the map: none asks for an approval or links anything, whatever its code. 3. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home node and their pairwise id) is linked to the account, replacing any other pair: `200 {"linked": true}`, the answer `check` returns as its `refusal` (the response to send). A route with `requireLink` answers 403 `human_not_linked` unless the pair is linked; when its path names an account (`accountParam`, default `account`), linked to that account, compared as `context.params` has it (decoded once). The context's `linkedAccount` is that account. A route whose path names no account accepts any linked person: give `linkAuthorize: (account, route, params) => boolean` to `new AllowedBy` to say which of your accounts may act on it (only the literal `true` passes: any other value, a truthy one or a promise included, and a throw, are refused with 403 `human_not_linked`; it is never called for a person who is not linked; it is synchronous), as Python's `link_authorize`. Both members of the pair count: the same pairwise id from another home node is another person. An approval that names no person for this service (its `human.id` has no id, or an empty one, for your origin) is refused with 401 `grant_insufficient`, on `POST /allowedby/link` and on `requireLink` routes: an empty id never links nor matches. Approvals the SDK creates for an account that is linked name its person (`human_home`, `human_hint`). `/.well-known/allowedby` has `link` and the `aby:link` capability, `/openapi.json` the route; give `templates["aby:link"]` to word it your way. An app route at `POST /allowedby/link` or with the capability `aby:link` is refused at construction. Codes and links are kept in memory, for one process, bounded: with 10 000 codes pending (expired ones do not count), `linkStart` throws a `RangeError` rather than revoke a code another account was given; of 100 000 links, the oldest is dropped first. Behind several instances, the instance that gave a code must take its `POST /allowedby/link`, and every instance must see the links: until a shared store keeps them, run linking on one instance, or link again after a restart. Next.js: the middleware (`middleware.js`, `proxy.js`) runs apart from the route handlers, with its own `AllowedBy`, so it never sees the codes your account page made nor the links: behind `allowedByMiddleware`, linking does not work (it fails closed: the link answers 400, a `requireLink` route 403). Use route handlers with `withAllowedBy`, which share the instance of `lib/allowedby.js` with your account page: `app/allowedby/link/route.js` with `export const POST = withAllowedBy(aby, () => new Response(null, { status: 404 }))` (the SDK answers the link itself; that handler never runs), and `requireLink` routes in `withAllowedBy` too. If the app also has the middleware, leave those paths out of its matcher, or the middleware's own instance answers them first (400 for every link, 403 for every `requireLink` route): `export const config = { matcher: ["/((?!_next/|allowedby/link|accounts/).*)"] }`, with your `requireLink` paths in place of `accounts/`. In an Express app (file: `sdks/js/examples/linking.mjs`); the extended interop app, `sdks/js/examples/interop-ext.mjs`, is a test fixture that gives a code for any account it is asked for, never a pattern to copy: ```js // Account linking (ABY-3 §6) in an Express app. The account comes from your own login, never from the request: a code // for any account a caller names would let that caller link their identity to someone else's account. import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; export const routes = [ // needs the person linked to the account the path names (accountParam defaults to "account") route("GET", "/accounts/{account}/notes", "notes:read", { resource: "account:{account}", requireLink: true }), ]; /** `signedIn(req)`: your session's account id, or null when nobody is signed in. */ export function makeApp(aby, signedIn) { const app = express(); app.use(allowedby(aby)); // also answers the agent's POST /allowedby/link app.post("/account/agent-code", (req, res) => { const account = signedIn(req); if (account === null) return res.status(401).json({ error: "sign in first" }); res.json({ code: aby.linkStart(account) }); // shown on the account page; the person gives it to their agent }); app.get("/accounts/:account/notes", (req, res) => { res.json({ account: req.allowedby.params.account, notes: [] }); // its linked person only }); return app; } /** The service: `origin`, `node` and the rest of the options as usual. */ export function linkingService(options) { return new AllowedBy({ org: { legal_name: "Notes Ltd", country: "FR" }, routes, templates: { "notes:read": "Read your notes" }, ...options, }); } ``` ### AllowedBy-Nonce An extended feature (sdks/CONTRACT.md, Extended; ABY-2 §3.2). `new AllowedBy({ nonce: true })` turns it on (default off). Then every `irreversible` route, and every route with `nonce: true`, refuses a proof without a current service nonce with `401 invalid_signature` and a fresh nonce in its `AllowedBy-Nonce` response header; the agent sends the request again with it, once, whatever the route's class (`Agent` does). The nonce goes in the proof JWT's `nonce` claim, or, with RFC 9421, in the request's `AllowedBy-Nonce` header, covered by the signature (an uncovered one does not count; a covered value that is not base64url is refused, 401). A route with `nonce: true` while the service has nonces off is refused at construction. A nonce is current for 300 s from its issue. It is stateless: base64url(t ‖ HMAC-SHA256(nonce key, t)[0:16]), t its issue time as 8 bytes big-endian, and the nonce key is HKDF-SHA256 of the signing key's raw private key (no salt, info `allowedby/nonce/v1`, 32 bytes). So every instance that shares `keyFile` takes the others' nonces, and a restart keeps the ones it handed out current; SDKs of any language on one key file take each other's. ### Level profiles An extended feature (OAID-7 §5.3). `levelProfile: "eu"` or `"na"` on a level-3 route accepts only a person whose level-3 registration was verified under that profile (its `level_source.profile`); any other, or none, is refused with `401 level_insufficient`. A level-3 route without `levelProfile` takes either. `route()` refuses it on a route of another level. ### Rate limits An extended feature (sdks/CONTRACT.md, Extended). `new AllowedBy({ rate: { actor: [n, seconds], operator: [n, seconds] } })` caps the calls per agent (the passport's `sub`) and per operator (`operator.id`); by default 600 and 6000 calls per 60 s. A call over either is refused with `429 rate_limited` (`Retry-After: 60`). The window slides on the SDK's clock (a call at t sees those at x with t - x < seconds). A call counts once its proof is verified and is no replay, whatever is decided after it (a call refused as `grant_required` counts); a call refused by the limit itself counts for neither limit. Any other key, or a value that is not two positive integers, is refused at construction. The counts are kept in memory, per process (bounded: 10 000 agents and operators each); behind several instances each counts its own calls. ### Tenants An extended feature (sdks/CONTRACT.md, Extended; ORG-1 §3.3). A tenant is an account of your service (a customer company) that the path parameter `tenant` names: `new AllowedBy({ tenants: { acme: {...} } })`, on routes such as `/t/{tenant}/orders`. Each tenant has a `name` (1-200 characters), and may have an `org` (an https origin with no path), `membersOnly`, `routes` (overrides by capability) and `budgets` ([Tenant budgets](#tenant-budgets)). An override only tightens the provider's route, for that tenant: | Override | Effect | |---|---| | `level` | The higher of the route's and the tenant's: `401 level_insufficient` below it. | | `authn` | `hardware` or `synced`, the stronger counts: `403 tier_insufficient` with a weaker passkey. | | `maxLifetime` | Seconds: an approval that lasts longer is refused (`401 class_lifetime_exceeded`). | | `amountMax` | A decimal string: above it, or with no amount, `403 capability_denied`, whatever the person approved. | | `operators` | The operators (`operator.id`) that may act for the tenant: any other gets `403 capability_denied`. | | `requireLink` | [Account linking](#account-linking) on that route. | | `mandate` | A mandate from an organisation (ORG-1 §6). | `membersOnly` (with `org`) asks for a mandate on every route of the tenant, as `mandate` does on one route; a level-0 route of the tenant has no grant, so no mandate, and is refused too; until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with mandate_required (`401`, with no challenge: no approval could satisfy it, so no one is asked for one). The option is checked when the service is built, and the SDK keeps its own copy (a later change to your object changes nothing). A tenant id outside `[A-Za-z0-9_-]{1,64}`, any other key (`policy`, a misspelt override), a value of another shape, a capability the route map does not have, and `qes`, `authority` and `authorityPolicyRevision` (not in this SDK yet) throw a `TypeError`: a misspelt override would leave the route as loose as the provider's. So does an override or a budget on a capability with a route that has no `{tenant}` parameter (the error names it): there it would never apply. A tenant the map's routes name but the option does not list gets the provider's routes as they are. On an accepted request, `context.tenant` is the tenant's id. ### Tenant budgets An extended feature (ORG-1 §5.3). `tenants[t].budgets[capability]` is `{max, currency, per: "day" | "week" | "month", tz?}`: at most `max` in `currency` per calendar period in `tz` (an IANA zone, default UTC). Every route with that capability needs `amountField`, or the budget is refused at construction. The service counts the amounts it accepts, per tenant, capability, currency, tz and period, in the store (`store`): every instance that shares a `RedisStore` shares the count. A request with no amount in the budget's currency (amounts are never converted), or over what is left, is refused with `403 budget_exceeded`, before any challenge, so no approval is asked for. A refused request is not counted; a refund (an adapter's refusal after the check, `aby.release(context)`) gives the amount back. When the store does not answer, the request is refused with `503 status_stale` (`Retry-After: 5`), and what the check already charged is given back. The extended interop app (`sdks/js/examples/interop-ext.mjs`) has three tenants on `POST /t/{tenant}/orders`: one as the route map says, one with `amountMax: "50.00"`, and one with a budget of 100.00 EUR a day; `sdks/interop/ext/interop_ext.py` runs it against a real node. --- # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- # Recipes in JavaScript (each is run against a real node on every version) ## Quickstart A whole app that lets agents in with the person's approval. ```js import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN, // your app's public URL node: process.env.ALLOWEDBY_NODE, // the node you trust: people approve there org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { level: 1, resource: "note:*" })], templates: { "notes:read": "Read your notes" }, // what the person approves }); const app = express(); app.use(allowedby(aby)); app.get("/notes", (req, res) => { res.json({ notes: [], person: req.allowedby.humanId }); }); app.listen(process.env.PORT, process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` ## See which agent is calling Know the agent and its verified operator, before any person is involved. ```js routes.push(route("GET", "/me", undefined, { level: 0, summary: "Which agent is calling" })); api.get("/me", (req, res) => { res.json({ agent: req.allowedby.agent, operator: req.allowedby.operator }); }); ``` ## Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. ```js routes.push(route("GET", "/notes", "notes:read", { level: 1, resource: "note:*", summary: "List your notes" })); templates["notes:read"] = "Read your notes"; api.get("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ notes: notes.list(person) }); }); ``` ## Let an agent write A change the person can undo: one approval, reused like a read. ```js routes.push(route("POST", "/notes", "notes:write", { class: "write", level: 1, resource: "note:*", summary: "Add a note", body: { text: "the note" }, })); templates["notes:write"] = "Add and change your notes"; api.post("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.status(201).json(notes.add(person, String(req.body?.text ?? ""))); }); ``` ## Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. ```js routes.push(route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note", })); templates["notes:delete"] = "Delete {scope}"; api.delete("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by // The person approved this exact request, and it works once. if (!notes.delete(person, req.params.id)) { return res.status(404).json({ error: "no such note" }); } res.json({ deleted: req.params.id }); }); ``` ## Take a payment The person approves the amount and the payee; any other amount or payee is refused. ```js routes.push(route("POST", "/payees/{payee}/payments", "payments:send", { class: "irreversible", level: 2, resource: "payee:{payee}", amountField: "/amount", summary: "Pay someone", body: { amount: "a decimal string, e.g. 40.00", currency: "e.g. EUR" }, })); templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}"; api.post("/payees/:payee/payments", (req, res) => { // The payee, the amount and the currency are the ones the person approved. const { amount, currency } = req.body; res.status(201).json({ paid: amount, currency, to: req.params.payee }); }); ``` ## Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. ```js routes.push(route("POST", "/payees/{payee}/transfers", "transfers:send", { class: "irreversible", level: 3, authn: "hardware", resource: "payee:{payee}", amountField: "/amount", summary: "Send a bank transfer", body: { amount: "a decimal string, e.g. 4000.00", currency: "e.g. EUR" }, })); templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}"; api.post("/payees/:payee/transfers", (req, res) => { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. const { amount, currency } = req.body; res.status(201).json({ sent: amount, currency, to: req.params.payee, level: req.allowedby.level }); }); ``` ## Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. ```js routes.push(route("POST", "/orders", "orders:place", { class: "write", level: 1, resource: "order:new", amountField: "/total", summary: "Place an order", body: { total: "a decimal string, e.g. 60.00", currency: "e.g. EUR" }, })); templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"; api.post("/orders", (req, res) => { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. const { total, currency } = req.body; res.status(201).json({ ordered: total, currency }); }); ``` ## Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. ```js routes.push( route("POST", "/plans/{plan}/subscription", "plans:subscribe", { class: "write-hard", level: 1, resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan", body: { monthly: "the price per month, e.g. 12.00", currency: "EUR" }, }), route("GET", "/subscription", "plans:read", { level: 1, resource: "plan:*", summary: "Your subscription" }), route("DELETE", "/subscription", "plans:cancel", { class: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription", }), ); templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"; templates["plans:read"] = "See your subscription"; templates["plans:cancel"] = "Cancel your subscription"; api.post("/plans/:plan/subscription", (req, res) => { // Approved once, with the price: your billing charges it every month (subscriptions.mjs) until it is cancelled. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.status(201).json(subscriptions.start(person, req.params.plan, req.body.monthly)); }); api.get("/subscription", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const subscription = subscriptions.get(person); if (!subscription) return res.status(404).json({ error: "no subscription" }); res.json(subscription); }); api.delete("/subscription", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const subscription = subscriptions.cancel(person); if (!subscription) return res.status(404).json({ error: "no subscription" }); res.json(subscription); }); ``` ## Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. ```js routes.push(route("GET", "/notes/{id}/summary", "notes:read", { level: 1, resource: "note:{id}", summary: "Summarise one note", })); api.get("/notes/:id/summary", (req, res) => { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const note = notes.get(person, req.params.id); if (!note) return res.status(404).json({ error: "no such note" }); res.json({ words: note.text.split(/\s+/).length, delegated: req.allowedby.chain.length > 1 }); }); ``` ## Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. ```js routes.push(route("GET", "/export", "notes:export", { level: 1, resource: "note:*", summary: "Export your notes" })); templates["notes:export"] = "Export your notes"; api.get("/export", (req, res) => { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ approval: req.allowedby.gid, notes: notes.list(person) }); }); ``` ## Serve only the person's own data human_id is the same person every time at your app: look their data up with it. ```js routes.push(route("GET", "/notes/{id}", "notes:read", { level: 1, resource: "note:{id}", summary: "Read one note" })); api.get("/notes/:id", (req, res) => { // humanId is this person's id at your app, always the same. Look up with it, never by note id alone. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const note = notes.get(person, req.params.id); if (!note) return res.status(404).json({ error: "no such note" }); res.json(note); }); ``` ## Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. ```js routes.push(route("PUT", "/notes/{id}", "notes:write", { class: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: { text: "1 to 280 characters" }, })); api.put("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const text = String(req.body?.text ?? ""); const length = [...text].length; // characters, not UTF-16 units: an emoji counts as one if (length < 1 || length > 280) { return res.status(422).json({ error: "text: 1 to 280 characters" }); // the agent gets this status and this JSON } const note = notes.update(person, req.params.id, text); if (!note) return res.status(404).json({ error: "no such note" }); res.json(note); }); ``` ## Test your app Run your app's tests without a browser, a phone or a node. ```js import assert from "node:assert/strict"; import { test } from "node:test"; import { AllowedBy } from "@allowedby/sdk"; import { TestNode } from "@allowedby/sdk/testing"; import { routes, templates } from "./app.mjs"; const origin = "https://notes.example"; const node = await TestNode.create(); // a node in memory, whose people approve on demand const aby = new AllowedBy({ origin, node: node.origin, fetch: node.fetch, autoRefresh: false, org: { legal_name: "Notes Ltd", country: "FR" }, routes, templates, }); await aby.refresh(); const agent = await node.agent(); test("an agent the person did not approve is refused", async () => { const headers = await agent.sign("GET", `${origin}/notes`); const { refusal } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(refusal.status, 401); assert.match(refusal.headers["WWW-Authenticate"], /error="grant_required"/); }); test("an approved agent is accepted, and the app knows the person", async () => { const capabilities = [{ cap: "notes:read", constraints: { scope: "note:*" } }]; const grant = await node.grant(agent, { audience: origin, capabilities }); const headers = await agent.sign("GET", `${origin}/notes`, { allowedBy: grant }); const { context } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(context.humanId, await node.humanId(origin)); }); ```