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; 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.
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,TextEncoderandDecompressionStream, so the same code runs everywhere. - Modules: ES modules and CommonJS (
importorrequire), 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 anioredisclient you create. - Not published yet: until the package is on npm, build it from this repository:
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.tgzQuick start#
A service that accepts agents is one AllowedBy object and one wrapper around your server
(file: sdks/js/examples/quickstart.mjs).
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 containerSee 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:
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 passportWindows (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/notesThe whole flow (an agent asks, a person approves with a passkey, the agent retries) is what the interop test runs:
see Testing. In a container, see sdks/js/examples/Dockerfile:
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-notesRoutes 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).
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, 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 |
<namespace>:* |
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) |
none |
nonce |
The proof must carry a current service 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); 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):
import { AllowedBy, route } from "@allowedby/sdk";
/** @param {Partial<import("@allowedby/sdk").AllowedByOptions>} [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<string, {id: string, text: string}[]>} */
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).
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.
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").
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.
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):
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):
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):
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).
// 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):
// 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):
// 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).
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<INestApplication> {
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/:idfor/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 toapp.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/payor ofDELETE /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 onapp.getandapp.post(orapp.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 Expressapp.all("*", log)before the routes): register such middleware withapp.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 withapp.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/:idnext 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/xis/notes/7/xto 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) andDELETE /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: withGET /notes/paymapped and only/notes/:idto serve it, a request checked forGET /notes/{id}is refused until/notes/payhas a handler. A handler that the router tries after/notes/pay's own rule (it runs if that rule callsnext()) stays protected for it, unless it is the own rule of another route (/notes/:idforGET /notes/{id}): with Express or Hono, a wildcard/notes/*or an optional/notes/:id?as the handler ofGET /notes/{id}also serves/notes/pay, so a request checked forGET /notes/{id}is refused. GiveGET /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. - the same handler on another path, or for another method:
-
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: Expressapp.use(fn)and Honoapp.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 asapp.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)withdelservingDELETE /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 itsnext()) are not looked at. -
Hono: pass the app,
allowedby(aby, { app }), the one whosefetchserves (withroute, the outer app): its router tells which handler serves each route of the map. Without it,allowedbythrows. -
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 theonRequesthooks of Fastify registered after the plugin, so an alias runs none of the app's code. With NestJS, middleware and guards that run beforeAllowedByGuard(register it first,app.useGlobalGuards) see the request before the check: keep them free of effects. -
unprotectednever lets a handler of the map run unchecked, also not for another method at the route's very template: one handler forGETandPOST /noteswould run for an uncheckedGET, 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.jshttp, the order is yours:app.use(allowedby(...))comes first. Put the SDK on the outer Hono app, not inside one given tomount: 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.status400. -
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/%37is/notes/7) with those that were checked, and refuses a request that changed (400invalid_request, the path not repeated) before any handler runs:-
Express: when the router dispatches the route, after any middleware (
req.urlrewritten,method-override). A router's prefix (app.use("/notes", router)) is no change. Express runsapp.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 changesreq.raw.urlorreq.raw.method. Fastify routes before any hook, so a later change moves neither the handler norreq.params. -
Hono: against the path Hono routed on (
c.req.path, itsgetPath), and when a step after the SDK makes Hono run another request with the same proof (methodOverride, a rewrite throughapp.fetch). -
NestJS:
AllowedByGuardruns after Nest's middleware and Express's routing, so a middleware that rewrotereq.urlor overrode the method (method-override'sreq.originalMethod) is refused when either request is one the SDK checks. A method changed without a trace (req.methodalone) is checked as it is, and its proof, made for the other method, is refused (401). -
Next.js: after a rewrite (
rewritesinnext.config.js, orNextResponse.rewritein a middleware after the SDK's), a route handler still gets the URL the client sent, whichwithAllowedByandreadContextcheck, while the route file and Next'sparamsare the rewrite's: a request accepted for/notes/7could runapp/notes/[id]withid8, or another route's file. So each handler states the route it serves, always:withAllowedBy(aby, handler, { route: "DELETE /notes/{id}" }), orreadContext(aby, req, { route: "DELETE /notes/{id}", params })with Next'sparams. 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'sparams, is refused:withAllowedByanswers 400, andreadContextthrowsRouteMismatchError, whoseresponseis 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, preferwithAllowedBy(route handlers without the middleware). With a route stated,readContextIfAnyisreadContext: that handler serves a route of the map, so a request without a context (a rewrite from a path outside the map) throwsMissingContextError. 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 aTypeError:withAllowedBythrows 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 onreq.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 fromcontext.params, never from the framework's own. -
-
A Next.js handler in
withAllowedBy, or that callsreadContext, always has a context: other paths are refused, orreadContextthrows.readContextIfAnyis 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/xwithDELETE /notes/{id}.GET /notes/7with onlyGET /notesin the map is not. List your own such pages inunprotected(["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
resourcewith the request's path values, normalised as for the proof (%61bisab). Each value must be 1 to 64 ofA-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 onreq.checkedPath, the path that was checked, not on your own reading ofreq.url. -
The SDK cannot see a function mounted as middleware (
app.use("/notes", handler); an Express sub-app given toapp.useis seen, as a catch-all of its prefix), a rewrite ofreq.urlmade 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).
// 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<Record<string, string>> |
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` |
actingFor, tenant |
null |
Company mandates and tenants 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).
// 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 pointkeyFileat it, or write it from your secret manager. An existing file works anywhere. WithoutkeyFilethe keys are new at each start: agents then fetch/.well-known/allowedbyagain. 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: useRedisStore(atomic Lua scripts; expiry follows the SDK's clock; cluster-safe with one hash tag) or your ownStore(add,get,charge, each atomic). A store error refuses the request (503 status_stale). A refund (below) is achargeof negative increments with no max: your store applies it exactly, and keeps each key'suntil. - 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
withAllowedBydo 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 (readContextreads a copy of the context, which has no receipt), Node.jshttpandaby.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
nodeon 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 replacesnodeas 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 withuntrusted_nodeor503 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 forwrite-hardandirreversible, 1 hour otherwise), requests are refused with503 status_staleuntil 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: falsesilences it; any function receives the lines. - Several instances: share
keyFile(orkeys) 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)
// 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).
// 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:
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/7Windows (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.tsreads every case of theverifierprofile fromvectors/at run time and fails on any case it cannot run:verifier profile: 479/479 cases passed. It also runs every case of theruntimeprofile (122) with the agent SDK's helpers. - Interop: the app in
examples/interop.mjsis the port ofsdks/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 ofreference_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).
// 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). |
route(method, path, capability?, options?) |
One line of the route map (see 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 and rate
limits (below). Extended, not yet in this SDK (each refused at construction): the disclosure callback and JWE
decryption, tenants and budgets, 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.
- Your signed-in account page calls
aby.linkStart(account, ttl = 600)and shows the code (96 random bits, validttlseconds, single use). The person gives it to their agent. A new code does not revoke the older ones. - The agent sends
POST /allowedby/linkwith{"code": "..."}. The SDK serves this route itself, incheck(every adapter; NestJS throughallowedbyDiscovery; Next.js in a route handler, below): an unknown, spent, revoked or expired code is refused (400invalid_request) before any approval is asked for. The request is then checked as the routeaby:link(classwrite, level 1, resourceaby: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/linkgo to your app as paths outside the map: none asks for an approval or links anything, whatever its code. - 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 answercheckreturns as itsrefusal(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:
// 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.