TypeScript and JavaScript SDK#
The public API of sdks/js, with its doc comments. Guide: docs/sdk/js.md.
157 public declarations, 83 with a doc comment.
@allowedby/sdk#
sdks/js/src/allowedby.ts
export const SDK_VERSIONexport const SPEC_VERSIONexport const MAX_BODYBodies above this are refused before anything else (413), as the Python server does.
export interface Org {
/** The registered legal name, 1 to 200 characters. */
legal_name: string;
/** ISO 3166-1 alpha-2 country code, e.g. "FR". */
country: string;
website?: string;
support?: string;
privacy_policy?: string;
/** The logo: its URL and the base64url SHA-256 of the file. */
logo?: { uri: string; sha256: string };
/** Expiry of the signed profile (epoch seconds), at most one year ahead. Default: one year. */
exp?: number;
}The organisation that runs the service (ORG-1 §2), published signed in /.well-known/allowedby.
export type TemplateInput = string | { summary: Record<string, string>; lines: Record<string, string> };A template: one sentence for every language, or {summary: {lang: text}, lines: {lang: text}}.
export interface AllowedByOptions {
/** This service's public origin, as agents call it: "https://notes.example". */
origin: string;
/** The approval node this service trusts (trust on first use of its key): "https://node.example.org". */
node: string;
/** The organisation running the service (ORG-1 §2). */
org: Org;
/** The route map: `route(...)` lines. Paths outside it reach your app unchanged. */
routes: Route[];
/** The sentence the person signs for each capability (AMH-1 §4): {"notes:read": "Read your notes"}. */
templates: Record<string, TemplateInput>;
/** Node.js: a private JSON file keeping the keys across restarts and shared by every instance (mode 0600). */
keyFile?: string;
/** Keys you load yourself (e.g. from a secret manager), instead of keyFile. */
keys?: { signing: SigningKey };
/** The replay set, single use and counters. Default MemoryStore: one process only. */
store?: Store;
/** A signed OAID-5 trust list and the service key that signed it; replaces trust on first use of `node`. */
trustList?: { jws: string; key: Jwk };
/** Seconds between background refreshes of node statements and status lists (1 to 60, default 5). */
refreshSeconds?: number;
/** The highest identity level accepted from `node` (default 3). */
nodeMaxLevel?: number;
/** Epoch seconds now. Every time check uses it (tests move time). */
clock?: () => number;
/** OpenAPI title, version and description. */
title?: string;
version?: string;
description?: string;
/** Accept the RFC 9421 Web Bot Auth profile as well as the proof JWT (ABY-2 §3.1). */
rfc9421?: boolean;
/** Outbound HTTP (node statements, status lists, approvals). Default: globalThis.fetch. */
fetch?: FetchLike;
/** The app's own pages that the rules around the route map would refuse: a path, or [method, path]. Exact
* (`/notes/new/`: the path byte for byte), or a template of whole-segment parameters without a last "/"
* (`/notes/{id}/comments`: longer paths below a route that ends in a parameter; with the method when a route of the map,
* of any method, would reach it). An entry that is, or overlaps, a route of the map, or that a router may read as another
* path, is refused at construction. A path that a router may take for a route of the map (a last "/", another case, a
* suffix) counts with the Express, Fastify, Hono and NestJS adapters only, which see the handler that is chosen. No entry
* lets a handler of the map run. */
unprotected?: readonly Unprotected[];
/** Where the SDK logs one line per decision and refresh failures (codes only, no tokens or personal data).
* Default console.log; false: silent. */
log?: ((line: string) => void) | false;
/** Start the background refresh at construction (default true). With false, call `refresh()` yourself (e.g. a
* Cloudflare Workers Cron Trigger). */
autoRefresh?: boolean;
/** Account linking (ABY-3 §6): your own check of a linked person on a route with `requireLink`, after the SDK's
* (linked, to the account the path names if it names one): `(account, route, params) => boolean`, as Python's
* link_authorize. Only the literal true passes: any other value (a truthy one, a promise) and a throw are refused
* (403 human_not_linked); synchronous; never called for a person who is not linked. For a route whose path names no account: which of your accounts may act on it. */
linkAuthorize?: LinkAuthorize;
/** AllowedBy-Nonce (ABY-2 §3.2): on, every irreversible route, and every route with `nonce: true`, needs a current
* service nonce in the proof (or, with RFC 9421, in the covered AllowedBy-Nonce header). Default off. The nonce key is
* derived from the signing key: share `keyFile` and every instance takes the others' nonces, across restarts too. */
nonce?: boolean;
/** Rate limits: `{actor: [n, seconds], operator: [n, seconds]}`, per agent and per operator, in a sliding window on
* the SDK's clock; over either, 429 rate_limited. Default 600 and 6000 calls per 60 s. */
rate?: RateOption;
/** Tenants (ORG-1 §3.3): `{id: {name, org, membersOnly, routes: {capability: override}, budgets: {capability: budget}}}`,
* the accounts of your service that the path parameter `tenant` names. An override only tightens the route (`level`,
* `authn`, `mandate`, `requireLink`, `maxLifetime`, `amountMax`, `operators`); a budget (ORG-1 §5.3, `{max, currency,
* per, tz?}`) counts the amounts the service accepts for the tenant, in the store. Checked when the service is built:
* anything else, or an override or budget on a capability with a route without `{tenant}`, is refused. */
tenants?: Record<string, TenantOptions>;
}export interface SdkResponse {
status: number;
headers: Record<string, string>;
/** The JSON body (problem+json for refusals). */
body: unknown;
}An HTTP answer the SDK sends itself (a discovery document or a refusal).
export interface SdkRequest {
method: string;
/** The path without the query, as received. */
path: string;
/** The query string without "?", or "". */
query?: string;
headers: HeadersInit | Record<string, string | string[] | undefined> | ReadonlyMap<string, string>;
/** The body bytes exactly as received (empty or null when none). */
body?: Uint8Array | null;
/** The caller also checks the route its router selects (the Express, Fastify, Hono and NestJS adapters do): paths longer
* than a route of the map are left to that check. Otherwise they are refused, as a wildcard may serve them. */
seesRoute?: boolean;
}The request as the SDK needs it.
export interface CheckResult {
context: Context | null;
refusal: SdkResponse | null;
}The outcome of check: accepted (context), refused (the answer to send), or outside the route map (both null).
export function problem(code: string, status: number, title?: string | null, headers: Record<string, string> = {}, extra: Record<string, unknown> = {}): SdkResponseAn RFC 9457 problem (application/problem+json).
export class AllowedByAccept AI agents acting for a person (sdks/CONTRACT.md §2).
const aby = new AllowedBy({
origin: "https://notes.example", node: "https://node.example.org",
org: { legal_name: "Notes Ltd", country: "FR" },
routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })],
templates: { "notes:read": "Read your notes" },
}); readonly origin: string readonly node: string readonly host: string readonly routes: readonly Route[] readonly templates: Templates readonly title: string readonly version: string constructor(options: AllowedByOptions)@allowedby/sdk (routes.ts)#
sdks/js/src/routes.ts
export type ActionClass = "read" | "write" | "write-hard" | "irreversible"export const CLASSES: readonly ActionClass[]export interface ClassThreshold {
upTo?: string;
class: ActionClass;
}A class chosen by the request's amount: [{upTo: "1000.00", class: "write-hard"}, {class: "irreversible"}].
export interface RouteOptions {
/** read (default), write, write-hard, irreversible; or amount thresholds (needs `amountField`). */
class?: ActionClass | ClassThreshold[];
/** 0: the agent's passport is enough (no person); 1: passkey tap (default); 2: verified identity; 3: eIDAS high. */
level?: 0 | 1 | 2 | 3;
/** The resource the grant's `scope` must cover, with `{param}` from the path. Default `<namespace>:*`. */
resource?: string;
/** JSON Pointer to the amount in the body (e.g. "/total"): grants for this route must cap it. */
amountField?: string;
/** JSON Pointer to the ISO 4217 currency in the body. Default "/currency". */
currencyField?: string;
/** The weakest passkey class accepted: "synced" or "hardware". */
authn?: "synced" | "hardware";
/** Custody tier (OAID-6) the agent's key must have at least. Default 0. */
tier?: number;
/** Longest grant lifetime this route accepts, in seconds (60 s to 30 days). Default: the class maximum. */
maxLifetime?: number;
/** Level-3 profile (OAID-7 §5.3): "eu" or "na", on a level-3 route only. */
levelProfile?: "eu" | "na";
/** What the operation does, for agents (OpenAPI `summary`, well-known `description`). */
summary?: string;
/** The JSON body members, for agents (OpenAPI): {name: "description"} or {name: JSON Schema}. */
body?: Record<string, string | Record<string, unknown>>;
/** Account linking (ABY-3 §6): the person must have linked their identity to one of your accounts
* (`linkStart`, `POST /allowedby/link`); else 403 human_not_linked. A route of level 1 or more. */
requireLink?: boolean;
/** The path parameter that names one of your accounts (default "account"): with `requireLink`, the person must be
* linked to that very account; also the account whose linked person a service-created approval is for. */
accountParam?: string;
/** AllowedBy-Nonce (ABY-2 §3.2): a proof without a current service nonce is refused (401 invalid_signature, a fresh
* nonce in the AllowedBy-Nonce header). Needs `nonce: true` on the service; every irreversible route asks for one then. */
nonce?: boolean;
}Options of route(). Every option is enforced by the verifier (sdks/CONTRACT.md §2).
export interface Route {
readonly method: string;
readonly path: string;
readonly capability?: string;
readonly class: ActionClass | readonly ClassThreshold[];
readonly level: number;
readonly resource?: string;
readonly amountField?: string;
readonly currencyField?: string;
readonly authn?: "synced" | "hardware";
readonly tier?: number;
readonly maxLifetime?: number;
readonly levelProfile?: "eu" | "na";
readonly summary?: string;
readonly body?: Readonly<Record<string, string | Record<string, unknown>>>;
readonly requireLink?: boolean;
readonly accountParam?: string;
readonly nonce?: boolean;
/** Internal: a qualified signature is required (OAID-7 §10). Only the conformance vectors set it; with no EU
* trusted list in this SDK, such a route always refuses with qes_required (fail closed). */
readonly qes?: boolean;
/** Internal, from a tenant's override (ORG-1 §3.3; never a route option): a mandate is required. This SDK does not
* verify mandates yet, so such a route refuses every request with mandate_required (fail closed). */
readonly mandate?: boolean;
/** Internal, from a tenant's override: the tenant's lifetime cap, seconds. */
readonly tenantMaxLifetime?: number;
/** Internal, from a tenant's override: the amount ceiling (a decimal string); above it 403 capability_denied. */
readonly amountMax?: string;
/** Internal, from a tenant's override: the operators that may act; any other gets 403 capability_denied. */
readonly operators?: readonly string[];
}One line of the route map, as the verifier reads it. Frozen.
export interface ResolvedRoute extends Route {
readonly class: ActionClass;
readonly classes?: readonly ClassThreshold[];
}A route after the class was resolved from the request (amount thresholds).
export function route(method: string, path: string, capability?: string, options: RouteOptions = {}): RouteOne line of the route map (ABY-3 §4.1). Throws (TypeError) with what to fix for an invalid line.
route("GET", "/notes", "notes:read", { level: 1, resource: "note:*" })
route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}" })
route("GET", "/me", undefined, { level: 0 }) // the agent's passport only@allowedby/sdk (store.ts)#
sdks/js/src/store.ts
export interface Charge {
/** The counter's key (the SDK builds it). */
key: string;
/** What this request adds: 1 for a count, the amount in micro-units (1e-6) for an amount; negative, with no max, for
* a refund. */
inc: bigint;
/** The total must stay at or below this, or null for no limit. */
max: bigint | null;
/** Epoch seconds after which the counter is forgotten. */
until: number;
}export interface Store {
/** Add `key` unless present and live: false when it already was (a replay, a second use). Atomic. */
add(key: string, until: number, now: number): Promise<boolean> | boolean;
/** The live value of a counter, 0n when absent or expired. */
get(key: string, now: number): Promise<bigint> | bigint;
/** All or nothing: add every increment when every total stays within its max. Atomic. A refund (CONTRACT, Refund on
* the SDK's own refusal) is a charge of negative increments with no max, the exact opposite of what one request was
* charged: apply it exactly, never refuse it for a max, and keep each key's `until`. */
charge(charges: Charge[], now: number): Promise<boolean> | boolean;
}export class MemoryStore implements StoreFor one process only: every instance of a service behind a load balancer needs the same store, or a replayed proof
sent to another instance is accepted. Use RedisStore (@allowedby/sdk/redis) for more than one instance.
Bounded: when full of live entries it refuses rather than forgets (fail closed).
constructor(private readonly maxKeys = 200_000) add(key: string, until: number, now: number): boolean get(key: string, now: number): bigint charge(charges: Charge[], now: number): boolean@allowedby/sdk (linking.ts)#
sdks/js/src/linking.ts
export type LinkAuthorize = (account: string, route: Route, params: Readonly<Record<string, string>>) => booleanYour own check of a linked person on a route (linkAuthorize): anything but true refuses (human_not_linked).
@allowedby/sdk (verifier.ts)#
sdks/js/src/verifier.ts
export const CHALLENGE_CODES: ReadonlySet<string>Codes that come with a challenge (ABY-2 §6).
export const STATUS: Readonly<Record<string, number>>HTTP status of every refusal code: the same table in every SDK (Python verifier.STATUS). A store
that fails is status_stale too (refused, never accepted).
export class Reject extends ErrorA refusal: code (the spec error code), status (HTTP) and why (for logs, never secrets).
readonly status: number constructor( readonly code: string, readonly why = "", readonly route: ResolvedRoute | null = null, readonly actorSub: string | null = null, readonly extra: Record<string, unknown> = {}, )export interface Context {
/** The person's pairwise id for this service (null at level 0: no person). */
readonly humanId: string | null;
/** The identity level the request was verified at: 0 (agent only) to 3. */
readonly level: number;
/** The agent: its passport `sub`. */
readonly agent: string;
/** The agent's operator (the company running it). */
readonly operator: string;
/** The capabilities of the grant. */
readonly capabilities: readonly string[];
/** What the person read and approved (summary, lines, lang). */
readonly display: Display | null;
/** The grant id, its revision and its jti (audit). */
readonly gid: string | null;
readonly rev: number | null;
readonly jti: string | null;
/** The organisation the person acted for (company mandates: not supported by this SDK yet, always null). */
readonly actingFor: null;
/** The tenant the path names (its `tenant` parameter, ORG-1 §3.3), or null. */
readonly tenant: string | null;
/** The route of the map that matched. */
readonly route: ResolvedRoute;
/** The grant chain, leaf first: [gid, rev] pairs. */
readonly chain: readonly (readonly [string, number | null])[];
/** The proof's jti, and the agent's `run` and `call` (audit, ABY-2 §3). */
readonly proofJti: string;
readonly run: string | null;
readonly call: number | null;
/** The person's home node (the issuer of their registration). */
readonly humanIss: string | null;
/** The route's path values as the SDK checked them (CONTRACT §2 item 7): each `{name}` of the route's template, from
* the normalised path the verifier compared, percent-decoded once. Act on these, never on your own reading of the
* raw path (`DELETE /notes/7/.` is checked as `/notes/7`). Frozen, with no prototype: `__proto__` or `constructor` as
* a `{name}` is an ordinary key. Empty for a route without parameters. */
readonly params: Readonly<Record<string, string>>;
/** Account linking (ABY-3 §6): on a route with `requireLink`, the account of yours the person is linked to (the one
* the path names, when it names one); null on other routes. */
readonly linkedAccount: string | null;
}What the handler learns from an accepted request (ORG-1 §4.1, ABY-2 §5 step 10). Read-only.
@allowedby/sdk (crypto.ts)#
sdks/js/src/core/crypto.ts
export interface Jwk {
kty: string;
crv?: string;
x?: string;
y?: string;
n?: string;
e?: string;
kid?: string;
[k: string]: Json | undefined;
}export class SigningKeyA signing key: Ed25519 (EdDSA) or P-256 (ES256).
static async generate(kind: "Ed25519" | "P-256" = "Ed25519"): Promise<SigningKey> static async fromCryptoKeys(priv: CryptoKey, pub: CryptoKey): Promise<SigningKey> static async fromPem(pem: string): Promise<SigningKey>From a PKCS#8 PEM (the key file format shared by every SDK, as Python's Key.to_json).
static async fromPkcs8(der: Uint8Array): Promise<SigningKey>From PKCS#8 DER bytes (Ed25519 or P-256).
async rawPrivate(): Promise<Uint8Array>@internal The raw private key (Ed25519: its 32-byte seed; P-256: its scalar, 32 bytes big-endian), whatever the encoding it came in: the input of the keys the SDK derives from it (the nonce key, sdks/CONTRACT.md Extended).
async toPem(): Promise<string> async sign(data: Uint8Array): Promise<Uint8Array>@allowedby/sdk/node#
sdks/js/src/adapters/node.ts
export interface AllowedByRequest extends IncomingMessage {
/** The full target, set by routers that cut a prefix from `url` (Express, Connect). */
originalUrl?: string;
/** The accepted context on routes of the map; null elsewhere. */
allowedby?: Context | null;
/** The path that was checked, on every request the adapter lets through: route on it, not on your own reading of `url`. */
checkedPath?: string;
/** The body as received, on routes of the map (the stream is already read there). */
rawBody?: Buffer;
/** The body parsed as the check read it (a JSON object), or undefined when empty, on routes of the map. */
body?: unknown;
}The request your handler receives.
export function splitTarget(url: string | undefined):Split a request target into path and query. The path checked must be the one the router uses, so a target that URL
parsers read in different ways throws (the adapters answer 400 before any routing): see canonicalTarget.
export function readBody(req: IncomingMessage, limit = MAX_BODY): Promise<Buffer | null>Read the whole body, at most limit bytes. -> the bytes, or null when larger.
export function send(res: ServerResponse, r: SdkResponse, head = false): voidWrite an SDK answer (discovery document or refusal) on a Node response.
export async function nodeGate(aby: AllowedBy, req: AllowedByRequest, res: ServerResponse, preread?: Buffer): Promise<boolean>The SDK's part of a request on a Node request: discovery, or the check. -> true when it answered itself.
export function allowedByNode( aby: AllowedBy, handler: (req: AllowedByRequest, res: ServerResponse) => void | Promise<void>, ): (req: IncomingMessage, res: ServerResponse) => voidWrap a Node request listener.
http.createServer(allowedByNode(aby, (req, res) => {
const ctx = req.allowedby; // Context on routes of the map
switch (req.checkedPath) { ... }
})).listen(8080, "127.0.0.1");@allowedby/sdk/express#
sdks/js/src/adapters/express.ts
export interface AllowedByExpressRequest extends IncomingMessage {
allowedby?: Context | null;
rawBody?: Buffer;
body?: unknown;
originalUrl?: string;
_body?: boolean;
baseUrl?: string;
app?: { _router?: ExpressRouter; router?: ExpressRouter; get?: (setting: string) => unknown };
route?: unknown;
}What the middleware adds to the request.
export interface ExpressRoute {
path: Pattern;
methods: Record<string, boolean>;
/** Its handlers: a method each (`get`), or none for `all`. */
stack?: { method?: string; handle?: Handle }[];
_handles_method?: (method: string) => boolean;
}Express's Route, as it sets it on the request.
export interface ExpressRouter {
stack?: ExpressLayer[];
}export interface ExpressLayer {
route?: ExpressRoute;
handle?: ExpressRouter | ((...a: never[]) => unknown);
match?: (path: string) => boolean | { path?: string };
path?: string;
params?: unknown;
}export function servedInFull(router: ExpressRouter | undefined, line: Route, path = samplePath(line)): booleanWhether a handler of the app serves a route of the map at its full path (Express's own matching, layer by layer).
export function handlerOf(route: ExpressRoute, method: string): Handle | nullThe function that answers a method on a route: the last of its stack for that method (HEAD runs GET's when the route
has no head of its own, as Express's Route.dispatch does).
export function expressCandidates<K>(router: ExpressRouter | undefined, method: string, path: string, key: (r: ExpressRoute, method: string) => K | null, base = "", mount?: (l: ExpressLayer, at: string) => K, mounted = base): Candidate<K>[]The routes Express tries for a path, in order, as candidates of rule 5 (key: what identifies each one's handler).
A mounted sub-app is one candidate, its mount layer (mount): the SDK does not walk into it, so it is a catch-all of
the paths below its prefix. Other middleware (app.use(fn)) is not seen: a handler mounted so is a limit the guide
states. Throws when a layer cannot say (then nothing is known from this path).
export function selectedRoute(route: ExpressRoute):What a route of the app serves, as the map's check needs it. Also used by the NestJS guard.
export function movedSince(req: { method?: string; url?: string; baseUrl?: string }, checked: { method: string; path: string }): booleanWhether the method or the path Express routes the request on now is not the one checked. The path is the router's
prefix (req.baseUrl) and what is left of the URL: at the root of a mount, Express leaves /, which is not a change.
export function allowedby(aby: AllowedBy): (req: IncomingMessage, res: ServerResponse, next: Next) => void@allowedby/sdk/fastify#
sdks/js/src/adapters/fastify.ts
export interface AllowedByFastifyOptions {
aby: AllowedBy;
}export const allowedby@allowedby/sdk/hono#
sdks/js/src/adapters/hono.ts
export interface AllowedByVariables {
allowedby: Context | null;
}Add to your Hono generic: new Hono<{ Variables: AllowedByVariables }>().
export interface HonoAppLike {
routes: readonly { path: string; method: string; handler: unknown }[];
/** Hono 4's router: `match` gives [[[handler, route], params][], ...]. */
router: { match(method: string, path: string): unknown };
}The app the middleware is on (the outer one, whose fetch serves): its router and its routes.
export interface AllowedByHonoOptions {
/** The app: the SDK resolves each route of the map with its router, to know which handler runs (CONTRACT §2.10 rule 5). */
app: HonoAppLike;
}export function allowedby(aby: AllowedBy, options?: AllowedByHonoOptions): (c: HonoContextLike, next: () => Promise<void>) => Promise<Response | void>Hono middleware (structurally typed: works with Hono 4 without importing it):
app.use(allowedby(aby, { app })). Without the app it cannot know which handler runs: it refuses to start.
@allowedby/sdk/next#
sdks/js/src/adapters/next.ts
export const CONTEXT_HEADERexport interface HandlerOptions {
/** The route of the map this handler serves, as `"GET /notes/{id}"`: its method and its template, as in the map.
* A request checked for any other route, unless that route covers this one (CONTRACT §2.10 rule 5), is refused (400),
* and so is a value of Next's `params` that is not the one checked. Next keeps the URL the client sent after a rewrite
* (`next.config.js`, `NextResponse.rewrite`): only the route file and `params` show where the request went. */
route?: string;
}What a handler states about itself (plan 14).
export interface ReadContextOptions extends HandlerOptions {
params?: unknown;
}Options of readContext: the handler's route, and Next's params for it (a promise of them, as Next gives).
export function withAllowedBy<A extends unknown[]>( aby: AllowedBy, handler: (req: Request, routeContext: A[0], allowedby: Context) => Response | Promise<Response>, options: HandlerOptions = {}, ): (req: Request, ...rest: A) => Promise<Response>Wrap an App Router route handler: discovery and refusals are answered here, the handler gets the context. A wrapped
handler runs for routes of the map only: whatever path reaches it (a rewrite, a catch-all segment), it has a context.
Give it the route it serves ({ route: "GET /notes/{id}" }): a rewrite after the check leaves the URL as the client sent
it, and only the route stated tells that the request runs elsewhere (plan 14).
export function allowedByMiddleware(aby: AllowedBy): (req: Request) => Promise<Response>Next.js middleware: the SDK's endpoints and the check of every route of the map. Paths outside the map go on.
export class MissingContextError extends ErrorThrown by readContext on a route of the map without a verified context (fail closed: Next answers 500).
constructor()export class RouteMismatchError extends ErrorThrown by readContext when the handler states its route and the request was checked for another one, or with
other values (a rewrite after the middleware, plan 14). Next answers an error a route handler throws with 500 (fail
closed); response is the SDK's own answer (400, the path not repeated, or 500 for a route folder named otherwise),
for a handler that catches it.
constructor(readonly refusal: SdkResponse) get status(): number get response(): Responseexport async function readContext(aby: AllowedBy, req: Request, options: ReadContextOptions = {}): Promise<Context>In a route handler behind allowedByMiddleware: the accepted context. Without one it throws MissingContextError: the
middleware did not run, its matcher left the path out, a rewrite led here from a path outside the map, the header does
not verify or is older than 60 s. Give it the handler's route and Next's params
({ route: "DELETE /notes/{id}", params }): a request checked for another route or values throws RouteMismatchError.
A handler that also serves paths outside the map uses readContextIfAny.
export async function readContextIfAny(aby: AllowedBy, req: Request, options: ReadContextOptions = {}): Promise<Context | null>The accepted context, or null on a path outside the route map (MissingContextError on a route of the map). With the
handler's route stated, it is readContext: that handler serves a route of the map, so it never runs without a
context, whatever URL reaches it (a rewrite from a path outside the map).
@allowedby/sdk/nest#
sdks/js/src/adapters/nest.ts
export class AllowedByGuard implements CanActivateChecks every route of the map (CanActivate). Paths outside the map pass with allowedby null.
constructor(private readonly aby: AllowedByService) async canActivate(ctx: ExecutionContext): Promise<boolean>export const AllowedByThe accepted context of the request (null on paths outside the route map).
export const AllowedByContextexport function allowedbyDiscovery(aby: AllowedByService): (req: IncomingMessage, res: ServerResponse, next: () => void) => voidExpress-style middleware serving /.well-known/allowedby, /openapi.json and /.well-known/api-catalog, and the SDK's own POST /allowedby/link (account linking, ABY-3 §6).
@allowedby/sdk/redis#
sdks/js/src/redis.ts
export interface RedisLike {
eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
get(key: string): Promise<string | null>;
}The part of an ioredis client the store uses. node-redis: wrap client.eval(script, {keys, arguments}).
export class RedisStore implements Store constructor( private readonly redis: RedisLike, private readonly prefix = "{allowedby}:", ) async add(key: string, until: number, now: number): Promise<boolean> async get(key: string, now: number): Promise<bigint> async charge(charges: Charge[], now: number): Promise<boolean>@allowedby/sdk/keyfile#
sdks/js/src/keyfile.ts
export interface ServiceKeys {
signing: SigningKey;
/** The disclosure key pair (ORG-1 §4): personal data a node sends is encrypted to its public half. */
disclosure: CryptoKeyPair;
}export async function generateDisclosureKey(): Promise<CryptoKeyPair>export async function loadKeys(path: string): Promise<ServiceKeys>Load the keys from path, creating the file with fresh keys when it does not exist. Instances started together all
get the keys on disk; a file system without hard links is refused (create the file elsewhere).
@allowedby/sdk/testing#
sdks/js/src/testing.ts
export interface TestGrantOptions {
/** The service origin(s) the grant is for. */
audience: string | string[];
/** [{cap, constraints}] as ABY-3 §2 writes them. */
capabilities: { cap: string; constraints?: Record<string, unknown> }[];
/** The person's identity level (default 1). */
level?: number;
/** The grant's class (default "read"). */
class?: string;
/** Lifetime in seconds (default 3600). */
ttl?: number;
/** Bind the grant to one request: the request digest (ABY-1 §7). */
singleUse?: string;
/** The service key that asked for it (serious actions, ABY-2 §7). */
initiatorKid?: string;
/** Which person (default "person-1"). Each name has its own passkey and pairwise ids. */
person?: string;
/** Replace the person's registration (`human.reg`) by this JWS: to test what a verifier does with a bad one. */
reg?: string;
/** Members to set on the grant before it is signed: to test what a verifier does with a malformed one. */
extra?: JsonObject;
}export class TestAgentAn agent of the test node: its key and passport, and a signer for requests.
constructor( readonly key: SigningKey, readonly passport: string, readonly sub: string, private readonly clock: () => number, ) async sign(method: string, url: string, opts: { allowedBy?: string; body?: unknown } = {}): Promise<Record<string, string>>The AllowedBy headers of one request: Allowed-By (passport or grant) and a fresh proof.
export interface TestApproval {
aid: string;
request: JsonObject;
initiatorKid: string | null;
code: string;
summary: string;
state: "pending" | "approved" | "denied";
grant: string | null;
reason: string | null;
}An approval created at the node: by a service (ABY-2 §7, initiatorKid set) or by an agent's runtime.
export interface TestActor {
key: { jwk: Jwk };
passport: string;
sub: string;
}What a grant needs to know about its agent.
export class TestNode readonly name: string readonly origin: string readonly statusUri: string static async create(opts: { name?: string; clock?: () => number; approvalPage?: string } = {}): Promise<TestNode>A node named name (default "node.test"), on clock (epoch seconds; default the system clock). approvalPage:
an approval page on another host, as a node may publish (vectors/challenge.json uses askmyhuman.org).
revoke(doc: string): voidRevoke a passport, grant or registration (its status index; ABY-1 §6). The next status list says so.
async statusList(): Promise<string>The status list, signed now.
async agent(opts: { operator?: string; tier?: number; ttl?: number } = {}): Promise<TestAgent>A new agent with a tier-0 passport.
async humanId(origin: string, person = "person-1"): Promise<string>The person's pairwise id at an origin (what the service sees as humanId).
async grant(agent: TestActor, o: TestGrantOptions): Promise<string>A grant the person approved with a passkey tap, countersigned by the node, for agent.
async approve(aid: string, opts: { level?: number; person?: string } = {}): Promise<string>The person approves an approval (service- or runtime-initiated): the grant the agent's poll then receives.
deny(aid: string, reason = "denied"): voidThe person declines: the poll answers 410 with this reason ("not_me", "unknown_agent", "denied").
readonly fetch: FetchLikeA fetch for AllowedBy({fetch}) and Agent({fetch}): the node's statement, status list, passports, and the
approvals endpoints (create, page, poll). Approvals stay pending until approve or deny.
static originOf(url: string): stringThe origin of a URL, as grants name audiences.
@allowedby/sdk/agent#
sdks/js/src/agent.ts
export type AgentMessage =What the agent tells its person (through your chat or UI).
export interface AgentOptions {
/** The agent's node: "https://node.example.org". */
node: string;
/** The operator's short name (used in the node-scoped operator id when there is no domain). */
operator?: string;
/** The runtime id, e.g. "acme.example/assistant". */
runtime?: string;
/** How the agent talks to its person: receives approval links and outcomes. */
tell?: (m: AgentMessage) => void;
/** Longest wait for a person's decision, in seconds (default 300). */
pollTimeout?: number;
/** An operator with a verified domain (OAID-2 §6): its approvals survive a new passport (rebind, ABY-1 §6). */
operatorDomain?: string;
operatorKey?: SigningKey;
/** Sign requests to sites with RFC 9421 (Web Bot Auth profile) instead of the proof JWT (ABY-2 §3.1). */
httpSig?: boolean;
/** Ask the person to renew a standing grant when a quarter of its period remains (ABY-1 §8). Default true. */
renew?: boolean;
fetch?: FetchLike;
/** Epoch seconds now (tests). */
clock?: () => number;
}export interface CallOptions {
/** The capability the call needs, e.g. "notes:read" (none: the passport alone). */
action?: string;
/** Standing period asked for runtime-initiated approvals, seconds (default 7 days; 0: one-off). */
standing?: number;
/** For routes with an amount: what the agent may spend, e.g. {max: "300.00", currency: "EUR", per: "month"}. */
limits?: { max: string; currency: string; per?: string; tz?: string };
/** Also told of this call's approval (link and code) and outcome, besides the agent's `tell` (tool integrations). */
notify?: (m: AgentMessage) => void;
}export interface CallResult {
status: number;
body: Json;
}export function parseChallenge(h: string | null | undefined): Record<string, string> | nullA parsed WWW-Authenticate: AllowedBy ... challenge (ABY-2 §6), or null.
export function validApprovalIds(aid: unknown, code: unknown): booleanAMH-1 §3: an approval id is 26 Crockford base32 characters, a binding code 4.
export function pollOutcome(status: number): "approved" | "pending" | "refused"AMH-1 §5: what a poll answer means.
export class Agent readonly node: string readonly nodeName: string readonly operator: string readonly runtime: string readonly operatorId: string key: SigningKey | null passport: string | null grants: Held[]Standing grants: the Allowed-By value (one grant, or a chain leaf first) and its leaf payload.
lastGrant: string | nullThe last grant received (single use ones included).
constructor(o: AgentOptions) async ensurePassport(force = false, minLife = 120): Promise<string>A passport with more than minLife seconds left, issued (tier 0) or renewed when needed.
async renewPassport(): Promise<boolean>OAID-3 §6, tier 1 and 2: a new passport for the same key, chained by prev; live grants move without the
operator's signature. Tier 0 passports never renew. -> true when renewed.
async rebind(gid: string, operatorSig = true): Promise<string | null>ABY-1 §6: move a grant to the current passport: the operator signs the move, or (operatorSig false) the node
follows the passport's prev chain. -> the new revision, or null.
async delegate(sub: Agent, capabilities: JsonObject[], opts: { origin?: string; exp?: number; allowedBy?: string } = {}): Promise<string | null>Derive a narrower child grant for a sub-agent, which signs with its own key, and hand it the chain.
allowedBy: the root grant to narrow, by default our newest standing root grant for origin. A chain is a root
and one child (ABY-1 §4: depth 1), so a child is never narrowed again: by default none is chosen, and an explicit
one throws (TypeError) before the node is asked. -> the chain (child first), or null.
async adopt(chain: string): Promise<string | null>A chain from the runtime that delegated to us: its leaf is from our node, for our key, a child of the next grant. -> null when kept, else why. A chain is a root and one child (ABY-1 §4, ABY-2 §2: depth 1), so one a verifier would refuse is never kept.
nodeUrl(url: string | undefined, kind: "approve" | "poll"): string | nullAn approval link or poll URL from a site's challenge: only on our own node (or its signed approval page), https (http on this machine only), on the node's own paths. -> the approval id, or null: never opened.
async nodeKeys(refresh = false): Promise<Map<string, Jwk &The node's keys, from its signed statement (/.well-known/oaid), kept after the first fetch.
async checkGrant(t: string, origin?: string): Promise<string | null>A grant from the node, before we keep or use it: signed by our node, for our key (and the site). -> null when good, else why.
grantFor(origin: string, action: string, scope?: string, exclude?: string): string | nullThe newest live grant whose capability covers the action (and the resource scope, when known).
async call(method: string, url: string, body?: unknown, opts: CallOptions = {}): Promise<CallResult>Do the request; when a person's approval is missing, get it and retry once. -> {status, body}.
The call pauses while the person approves (up to pollTimeout seconds).
async waitFor(pollUrl: string, expires?: unknown, what?: [string, string], tell: (m: AgentMessage) => void = (m) => this.tell(m), passport = this.passport!): Promise<string | null>Long-poll the node: it answers the moment the person decides. A node that does not hold the request is asked
no more than every 5 s, never sooner than its Retry-After; polling stops at the approval's expires.
@allowedby/sdk/agent/mcp#
sdks/js/src/integrations/mcp.ts
export interface AllowedByMcpOptions extends AllowedByToolOptions {
/** Seconds between progress notifications while the tool waits (default 15). */
progressSeconds?: number;
}export function registerAllowedByTool(server: McpServer, o: AllowedByMcpOptions): void@allowedby/sdk/agent/mcp (common.ts)#
sdks/js/src/integrations/common.ts
export interface AllowedByToolOptions {
/** The agent that signs and sends the calls. */
agent: Agent;
/** The service origins the tool may call, e.g. ["https://notes.example"]. Required: nothing else is called. */
origins: string[];
/** On routes with an amount: what the agent may ask to spend. Set by you, never by the model; without it such
* calls are refused. */
limits?: CallOptions["limits"];
/** The standing period to ask for, in seconds (default 7 days; 0: one-off approvals). Set by you too. */
standing?: CallOptions["standing"];
/** The tool's name (default "allowedby_request"). */
name?: string;
/** What the model reads about the tool. */
description?: string;
/** Told of the approval link and code of each call that needs the person (besides the agent's `tell`). */
onApproval?: (m: AgentMessage) => void;
}@allowedby/sdk/agent/ai#
sdks/js/src/integrations/ai.ts
export function allowedbyTool(o: AllowedByToolOptions)@allowedby/sdk/agent/ai (common.ts)#
sdks/js/src/integrations/common.ts
export interface AllowedByToolOptions {
/** The agent that signs and sends the calls. */
agent: Agent;
/** The service origins the tool may call, e.g. ["https://notes.example"]. Required: nothing else is called. */
origins: string[];
/** On routes with an amount: what the agent may ask to spend. Set by you, never by the model; without it such
* calls are refused. */
limits?: CallOptions["limits"];
/** The standing period to ask for, in seconds (default 7 days; 0: one-off approvals). Set by you too. */
standing?: CallOptions["standing"];
/** The tool's name (default "allowedby_request"). */
name?: string;
/** What the model reads about the tool. */
description?: string;
/** Told of the approval link and code of each call that needs the person (besides the agent's `tell`). */
onApproval?: (m: AgentMessage) => void;
}@allowedby/sdk/agent/langchain#
sdks/js/src/integrations/langchain.ts
export function allowedbyTool(o: AllowedByToolOptions)@allowedby/sdk/agent/langchain (common.ts)#
sdks/js/src/integrations/common.ts
export interface AllowedByToolOptions {
/** The agent that signs and sends the calls. */
agent: Agent;
/** The service origins the tool may call, e.g. ["https://notes.example"]. Required: nothing else is called. */
origins: string[];
/** On routes with an amount: what the agent may ask to spend. Set by you, never by the model; without it such
* calls are refused. */
limits?: CallOptions["limits"];
/** The standing period to ask for, in seconds (default 7 days; 0: one-off approvals). Set by you too. */
standing?: CallOptions["standing"];
/** The tool's name (default "allowedby_request"). */
name?: string;
/** What the model reads about the tool. */
description?: string;
/** Told of the approval link and code of each call that needs the person (besides the agent's `tell`). */
onApproval?: (m: AgentMessage) => void;
}@allowedby/sdk/agent/openai#
sdks/js/src/integrations/openai.ts
export function allowedbyTool(o: AllowedByToolOptions)@allowedby/sdk/agent/openai (common.ts)#
sdks/js/src/integrations/common.ts
export interface AllowedByToolOptions {
/** The agent that signs and sends the calls. */
agent: Agent;
/** The service origins the tool may call, e.g. ["https://notes.example"]. Required: nothing else is called. */
origins: string[];
/** On routes with an amount: what the agent may ask to spend. Set by you, never by the model; without it such
* calls are refused. */
limits?: CallOptions["limits"];
/** The standing period to ask for, in seconds (default 7 days; 0: one-off approvals). Set by you too. */
standing?: CallOptions["standing"];
/** The tool's name (default "allowedby_request"). */
name?: string;
/** What the model reads about the tool. */
description?: string;
/** Told of the approval link and code of each call that needs the person (besides the agent's `tell`). */
onApproval?: (m: AgentMessage) => void;
}