# AllowedBy > AllowedBy lets AI agents act on web apps with a person's approval: the person taps a passkey on a page of their own node, and the app verifies that approval offline on every request. Agents never hold the person's password, API key or OAuth token. Every page is also Markdown: add `.md` to its address. A model that integrates AllowedBy in one language needs one file: the bundle of that language below. An MCP server with search is at https://docs.allowedby.com/mcp. --- Source: https://docs.allowedby.com/ # Let AI agents use your app, with a person's approval An agent asks, a person taps a passkey, and your app verifies that approval offline. No password, API key or OAuth token is ever shared with the agent. ## Choose your path | You want to | Start with | |---|---| | Accept agents in your app or API | [Quickstart](https://docs.allowedby.com/quickstart): a protected endpoint in about 20 lines | | See it work before reading anything | [Try it live](https://docs.allowedby.com/try): run an agent against the demo, approve with your own passkey | | Write an agent that asks for approval | [Build an agent](https://docs.allowedby.com/guides/build-an-agent) | | Use an agent yourself | [Use AllowedBy](https://docs.allowedby.com/guides/use-allowedby) | | Let your AI assistant do the integration | [Build with an AI assistant](https://docs.allowedby.com/ai) | ## Your language ## What you can build ## What stays true - **The person decides.** They see a sentence your app wrote, sign exactly that, and can withdraw it at any time. - **Your app verifies.** Every request carries a proof for that request only. There is no call to a third party to check it. - **Nothing is shared.** The agent holds no credential of the person. A stolen approval is useless without the agent's key. - **Serious actions are asked one by one.** The approval names the exact request and works once. Every example on this site runs on each version of the product before it is published. The [results](https://docs.allowedby.com/status) are public. --- Source: https://docs.allowedby.com/quickstart # Quickstart Protect an endpoint, see it refuse an agent that has no approval, then approve one yourself. ```python import os from flask import Flask, g from allowedby import route from allowedby.flask import AllowedBy app = Flask(__name__) app.config["ALLOWEDBY"] = { "origin": os.environ["ALLOWEDBY_ORIGIN"], # your app's public URL "node": os.environ["ALLOWEDBY_NODE"], # the node you trust: people approve there "org": {"legal_name": "Notes Ltd", "country": "FR"}, "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")], "templates": {"notes:read": "Read your notes"}, # what the person approves } AllowedBy(app) @app.get("/notes") def list_notes(): return {"notes": [], "person": g.allowedby.human_id} ``` ```js import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN, // your app's public URL node: process.env.ALLOWEDBY_NODE, // the node you trust: people approve there org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { level: 1, resource: "note:*" })], templates: { "notes:read": "Read your notes" }, // what the person approves }); const app = express(); app.use(allowedby(aby)); app.get("/notes", (req, res) => { res.json({ notes: [], person: req.allowedby.humanId }); }); app.listen(process.env.PORT, process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` ```go import ( "encoding/json" allowedby "github.com/yannUpTo/allowedby/sdks/go" "log" "net/http" "os" ) func main() { aby, err := allowedby.New(allowedby.Options{ Origin: os.Getenv("ALLOWEDBY_ORIGIN"), Node: os.Getenv("ALLOWEDBY_NODE"), // your URL; where people approve Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"}, Routes: []allowedby.Route{{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*"}}, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, // what they approve }) if err != nil { log.Fatal(err) } http.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) // a level-1 route: never run without a person w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"notes": []string{}, "person": who.HumanID}) }) log.Fatal(http.ListenAndServe("localhost:"+os.Getenv("PORT"), aby.Handler(http.DefaultServeMux))) } ``` ```java import java.util.*; import org.allowedby.*; import org.allowedby.spring.*; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.*; @SpringBootApplication @RestController public class Quickstart { @Bean AllowedByCustomizer agents() { // origin: your app's public URL; node: the node you trust, people approve there return aby -> aby.origin(System.getenv("ALLOWEDBY_ORIGIN")).node(System.getenv("ALLOWEDBY_NODE")) .org("Notes Ltd", "FR").route(Route.get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes"); // what the person approves } @GetMapping("/notes") Map listNotes(@AllowedByContext Context ctx) { return Map.of("notes", List.of(), "person", ctx.getHumanId()); } public static void main(String[] args) { SpringApplication.run(Quickstart.class, args); } } ``` ```dotnet using AllowedBy; using AllowedBy.AspNetCore; using static AllowedBy.Routes; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAllowedBy(o => { o.Origin = builder.Configuration["ALLOWEDBY_ORIGIN"]!; // your app's public URL o.Node = builder.Configuration["ALLOWEDBY_NODE"]!; // the node you trust: people approve there o.Org = new AllowedByOrg { LegalName = "Notes Ltd", Country = "FR" }; o.Routes = [Route("GET", "/notes", "notes:read", level: 1, resource: "note:*")]; o.Templates["notes:read"] = "Read your notes"; // what the person approves }); var app = builder.Build(); app.UseAllowedBy(); app.MapGet("/notes", (AllowedByContext ctx) => new { notes = Array.Empty(), person = ctx.HumanId }); app.Run(); ``` ```php require __DIR__.'/vendor/autoload.php'; use AllowedBy\AllowedBy; use function AllowedBy\route; $aby = new AllowedBy( origin: (string) getenv('ALLOWEDBY_ORIGIN'), // your app's public URL node: (string) getenv('ALLOWEDBY_NODE'), // the node you trust: people approve there org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'], routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')], templates: ['notes:read' => 'Read your notes'], // what the person approves keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'), // private ); $decision = $aby->processGlobals(); if (null !== $decision->response) { $decision->response->send(); // discovery documents, refusals and challenges exit; } if (null === $decision->context) { // not GET /notes: nothing was checked, so nothing is served http_response_code(404); exit; } header('Content-Type: application/json'); echo json_encode(['notes' => [], 'person' => $decision->context->humanId]); ``` ```ruby require "sinatra" require "allowedby" require "json" aby = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # your app's public URL node: ENV.fetch("ALLOWEDBY_NODE"), # the node you trust: people approve there org: { legal_name: "Notes Ltd", country: "FR" }, routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")], templates: { "notes:read" => "Read your notes" } # what the person approves ) use AllowedBy::Middleware, aby bind = ENV.fetch("ALLOWEDBY_BIND", "") # ALLOWEDBY_BIND=0.0.0.0 in a container; empty or unset: loopback only set :bind, bind.empty? ? "127.0.0.1" : bind unless ARGV.any? { |a| a.start_with?("-o") } # an explicit -o wins get "/notes" do content_type :json # no person (a level-0 route): refused, never a store keyed by nil person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json { notes: [], person: person }.to_json end ``` ```rust use allowedby::{AllowedByContext, Options, Org, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use std::env::var; async fn list_notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "person": ctx.human_id})) } #[tokio::main] async fn main() -> Result<(), Box> { // your app's public URL, and the node you trust: people approve there let aby = Options::new(&var("ALLOWEDBY_ORIGIN")?, &var("ALLOWEDBY_NODE")?) .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*")) .template("notes:read", "Read your notes"); // what the person approves let app = Router::new().route("/notes", get(list_notes)); let app = allowedby::axum::protect(app, Service::new(aby)?); let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", var("PORT")?)).await?; axum::serve(listener, app).await?; Ok(()) } ``` ## Install the SDK The packages are in private preview and not on public registries yet. The "Install" section of your language's guide has the commands for the preview: [Python](https://docs.allowedby.com/sdk/python#install), [JavaScript](https://docs.allowedby.com/sdk/js#install), [Go](https://docs.allowedby.com/sdk/go#install), [Java](https://docs.allowedby.com/sdk/java#install), [C#](https://docs.allowedby.com/sdk/dotnet#install), [PHP](https://docs.allowedby.com/sdk/php#install), [Ruby](https://docs.allowedby.com/sdk/ruby#install), [Rust](https://docs.allowedby.com/sdk/rust#install). ## Describe the endpoint One line says what the endpoint lets an agent do (`notes:read`), how serious it is, and which resource it touches. One sentence says what the person will sign. Only your app writes that sentence. ## Run it and call it without approval ```bash curl -i http://localhost:3000/notes ``` The answer is `401` with a problem document and a challenge that an agent understands: ```http HTTP/1.1 401 Unauthorized Content-Type: application/problem+json WWW-Authenticate: AllowedBy realm="localhost:3000", error="passport_required" ``` ## Let an agent call it An agent shows its passport, is told that an approval is missing, asks the person through its node, and tries again. You can watch that whole conversation, and take the person's place, on [Try it live](https://docs.allowedby.com/try). ## Next - [How it works](https://docs.allowedby.com/how-it-works), in five minutes. - [All recipes](https://docs.allowedby.com/recipes): write, delete, pay, personal data, tests. - [Before production](https://docs.allowedby.com/guides/accept-agents#14-going-live-checklist). --- Source: https://docs.allowedby.com/how-it-works # How it works Four parties take part: the **agent**, your **app**, the **person**, and a **node** that the person and your app trust. ## Three documents | Document | Who signs it | What it says | |---|---|---| | Passport | The node | Which agent this is, who operates it, and which key it holds | | Grant | The person (passkey) and the node | What the person approved, for which app, for how long, with which limits | | Proof | The agent | This request: method, address, body and time, with the agent's key | The agent sends the first two in `Allowed-By` and the proof in `AllowedBy-Proof`. ## What your app checks The SDK does all of this offline, on each request, in about a millisecond: 1. The passport or grant comes from a node you trust, is not expired, and is not withdrawn. 2. The person's passkey signed exactly this grant, and their identity level is enough for the route. 3. The proof is for this exact request, by the agent the grant names, and was never seen before. 4. The grant covers the action, the resource and the amount. 5. A serious action has an approval made for this request only, and it has not been used. Anything unknown, missing or unreadable is refused. See [error codes](https://docs.allowedby.com/errors) for each refusal. ## Levels: how sure you are of the person | Level | The person | Use it for | |---|---|---| | 0 | is not asked: only the agent is identified | Public or per-agent data | | 1 | tapped a passkey | Everyday actions | | 2 | has a verified legal identity, and tapped a passkey | Orders, contracts, anything hard to undo | | 3 | is verified at the highest level, with a hardware passkey | Payments and signatures of value | ## Classes: how serious the action is | Class | Example | Approval | |---|---|---| | `read` | List notes | Reused until it ends | | `write` | Add a note | Reused until it ends | | `write-hard` | Delete, publish | For that request, once | | `irreversible` | Pay, sign | For that request, once | For the last two, your app creates the approval itself. The agent cannot change what the person will read. ## The node A node issues passports, shows the approval page, and countersigns grants. It learns what was approved, never the data in your app. You choose which nodes to trust: one hosted node, your own, or a signed list. --- Source: https://docs.allowedby.com/try # Try it live These are real runs against the live demo, not recordings. Open any step to read the exact request and answer. ## A complete run, approved by a test passkey The agent gets a passport, asks to read notes, is told that an approval is missing, gets one, reads, and then tries to replay its request, which is refused. ## Approve it yourself The same run, but the person is you. The approval page opens in a new tab, on the demo node. Check that it shows the same code as here, then use your fingerprint, face or security key. A throwaway account is created for you. ## A serious action Deleting a note is hard to undo. The app creates the approval for that exact note, the person's identity must be verified (simulated in the demo), and the approval works once. ## From your own assistant Connect Claude, or any assistant that speaks MCP, to the demo and ask it: "Add a note 'Buy milk' on https://notes.demo.allowedby.com, then show my notes". The [setup](https://docs.allowedby.com/guides/use-allowedby) takes a minute. --- Source: https://docs.allowedby.com/ai # Build with an AI assistant Coding assistants integrate AllowedBy well when they read these pages rather than guess. Give them one of the following. ## The documentation as tools (MCP) ```bash claude mcp add --transport http allowedby-docs https://docs.allowedby.com/mcp ``` The assistant can then search the documentation, read a page, get a recipe in your language and look up an error. Any assistant that supports MCP over HTTP can use the same address. ## One file per language Everything needed to accept agents in one language, in one Markdown file: | Language | File | |---|---| | Python | [llms/python.txt](https://docs.allowedby.com/llms/python.txt) | | JavaScript | [llms/js.txt](https://docs.allowedby.com/llms/js.txt) | | Go | [llms/go.txt](https://docs.allowedby.com/llms/go.txt) | | Java | [llms/java.txt](https://docs.allowedby.com/llms/java.txt) | | C# | [llms/dotnet.txt](https://docs.allowedby.com/llms/dotnet.txt) | | PHP | [llms/php.txt](https://docs.allowedby.com/llms/php.txt) | | Ruby | [llms/ruby.txt](https://docs.allowedby.com/llms/ruby.txt) | | Rust | [llms/rust.txt](https://docs.allowedby.com/llms/rust.txt) | The index of every page is [llms.txt](https://docs.allowedby.com/llms.txt), and all guides together are [llms-full.txt](https://docs.allowedby.com/llms-full.txt). Any page is also Markdown at its own address with `.md` added. ## A prompt that works ```text Read https://docs.allowedby.com/llms/python.txt. Then add AllowedBy to this app: - list the routes an agent may call, and propose a capability, class and level for each; ask me before going on; - write the sentence a person will sign for each capability; - add the middleware, and key every query on the person's id from the context; - run the app, show me that a protected route answers 401, and write the tests from the "test" recipe. ``` Change `python` to your language. ## Rules an assistant must keep - Never take the person's identity from the agent's input: use the id in the verified context. - Never catch a refusal and continue. - Never log `Allowed-By`, `AllowedBy-Proof` or a request body. - Use a shared store as soon as there is more than one process, and a key file in production. - Put the middleware outside anything that rewrites the path or the method. A weekly test gives an assistant only these public pages, asks it to integrate AllowedBy in a new app, and runs the end-to-end scenarios on the result. --- Source: https://docs.allowedby.com/recipes # Recipes One task each, the same in every language. Choose your language once and it stays chosen. ## Every level, every class A use case is listed when an app proves it, in each language that says yes. | Level | Class | Use case | Python | JavaScript | Go | Java | C# | PHP | Ruby | Rust | |---|---|---|---|---|---|---|---|---|---|---| | 0 | `read` | [See which agent is calling](https://docs.allowedby.com/recipes/identify) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `read` | [Quickstart](https://docs.allowedby.com/recipes/quickstart) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `read` | [Let an agent read](https://docs.allowedby.com/recipes/read) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `read` | [Accept a sub-agent](https://docs.allowedby.com/recipes/delegate) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `read` | [Let the person withdraw](https://docs.allowedby.com/recipes/withdraw) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `read` | [Serve only the person's own data](https://docs.allowedby.com/recipes/own-data) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `write` | [Let an agent write](https://docs.allowedby.com/recipes/write) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `write` | [Set a spending limit](https://docs.allowedby.com/recipes/spend-limit) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `write` | [Refuse in your own handler](https://docs.allowedby.com/recipes/refuse) | yes | yes | yes | yes | yes | yes | yes | yes | | 1 | `write` | [Serve several customers](https://docs.allowedby.com/recipes/tenants) | yes | not yet | not yet | not yet | not yet | not yet | not yet | not yet | | 1 | `write-hard` | [Start and cancel a subscription](https://docs.allowedby.com/recipes/subscribe) | yes | yes | yes | yes | yes | yes | yes | yes | | 2 | `write-hard` | [Ask before deleting](https://docs.allowedby.com/recipes/delete) | yes | yes | yes | yes | yes | yes | yes | yes | | 2 | `write-hard` | [Sell to a company](https://docs.allowedby.com/recipes/mandate) | yes | not yet | not yet | not yet | not yet | not yet | not yet | not yet | | 2 | `write-hard` | [Ask for personal data](https://docs.allowedby.com/recipes/personal-data) | yes | not yet | not yet | not yet | not yet | not yet | not yet | not yet | | 2 | `write-hard` | [Require two people](https://docs.allowedby.com/recipes/two-approvers) | yes | not yet | not yet | not yet | not yet | not yet | not yet | not yet | | 2 | `irreversible` | [Take a payment](https://docs.allowedby.com/recipes/pay) | yes | yes | yes | yes | yes | yes | yes | yes | | 3 | `irreversible` | [Take a high-value payment](https://docs.allowedby.com/recipes/pay-high) | yes | yes | yes | yes | yes | yes | yes | yes | Each recipe is taken from an app that runs on every version, with a real node, a real agent and a test passkey, refusals included. See the [results](https://docs.allowedby.com/status). --- Source: https://docs.allowedby.com/recipes/quickstart # Quickstart A whole app that lets agents in with the person's approval. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - a plain request is refused: 401 passport_required, with the AllowedBy challenge - nothing else is served: another method or path is a 4xx - an agent asks, the person approves once with a passkey, and the app answers 200 ## Python ```python import os from flask import Flask, g from allowedby import route from allowedby.flask import AllowedBy app = Flask(__name__) app.config["ALLOWEDBY"] = { "origin": os.environ["ALLOWEDBY_ORIGIN"], # your app's public URL "node": os.environ["ALLOWEDBY_NODE"], # the node you trust: people approve there "org": {"legal_name": "Notes Ltd", "country": "FR"}, "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")], "templates": {"notes:read": "Read your notes"}, # what the person approves } AllowedBy(app) @app.get("/notes") def list_notes(): return {"notes": [], "person": g.allowedby.human_id} ``` ## JavaScript ```js import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN, // your app's public URL node: process.env.ALLOWEDBY_NODE, // the node you trust: people approve there org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { level: 1, resource: "note:*" })], templates: { "notes:read": "Read your notes" }, // what the person approves }); const app = express(); app.use(allowedby(aby)); app.get("/notes", (req, res) => { res.json({ notes: [], person: req.allowedby.humanId }); }); app.listen(process.env.PORT, process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` ## Go ```go import ( "encoding/json" allowedby "github.com/yannUpTo/allowedby/sdks/go" "log" "net/http" "os" ) func main() { aby, err := allowedby.New(allowedby.Options{ Origin: os.Getenv("ALLOWEDBY_ORIGIN"), Node: os.Getenv("ALLOWEDBY_NODE"), // your URL; where people approve Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"}, Routes: []allowedby.Route{{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*"}}, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, // what they approve }) if err != nil { log.Fatal(err) } http.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) // a level-1 route: never run without a person w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"notes": []string{}, "person": who.HumanID}) }) log.Fatal(http.ListenAndServe("localhost:"+os.Getenv("PORT"), aby.Handler(http.DefaultServeMux))) } ``` ## Java ```java import java.util.*; import org.allowedby.*; import org.allowedby.spring.*; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.*; @SpringBootApplication @RestController public class Quickstart { @Bean AllowedByCustomizer agents() { // origin: your app's public URL; node: the node you trust, people approve there return aby -> aby.origin(System.getenv("ALLOWEDBY_ORIGIN")).node(System.getenv("ALLOWEDBY_NODE")) .org("Notes Ltd", "FR").route(Route.get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes"); // what the person approves } @GetMapping("/notes") Map listNotes(@AllowedByContext Context ctx) { return Map.of("notes", List.of(), "person", ctx.getHumanId()); } public static void main(String[] args) { SpringApplication.run(Quickstart.class, args); } } ``` ## C# ```dotnet using AllowedBy; using AllowedBy.AspNetCore; using static AllowedBy.Routes; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAllowedBy(o => { o.Origin = builder.Configuration["ALLOWEDBY_ORIGIN"]!; // your app's public URL o.Node = builder.Configuration["ALLOWEDBY_NODE"]!; // the node you trust: people approve there o.Org = new AllowedByOrg { LegalName = "Notes Ltd", Country = "FR" }; o.Routes = [Route("GET", "/notes", "notes:read", level: 1, resource: "note:*")]; o.Templates["notes:read"] = "Read your notes"; // what the person approves }); var app = builder.Build(); app.UseAllowedBy(); app.MapGet("/notes", (AllowedByContext ctx) => new { notes = Array.Empty(), person = ctx.HumanId }); app.Run(); ``` ## PHP ```php require __DIR__.'/vendor/autoload.php'; use AllowedBy\AllowedBy; use function AllowedBy\route; $aby = new AllowedBy( origin: (string) getenv('ALLOWEDBY_ORIGIN'), // your app's public URL node: (string) getenv('ALLOWEDBY_NODE'), // the node you trust: people approve there org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'], routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')], templates: ['notes:read' => 'Read your notes'], // what the person approves keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'), // private ); $decision = $aby->processGlobals(); if (null !== $decision->response) { $decision->response->send(); // discovery documents, refusals and challenges exit; } if (null === $decision->context) { // not GET /notes: nothing was checked, so nothing is served http_response_code(404); exit; } header('Content-Type: application/json'); echo json_encode(['notes' => [], 'person' => $decision->context->humanId]); ``` ## Ruby ```ruby require "sinatra" require "allowedby" require "json" aby = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # your app's public URL node: ENV.fetch("ALLOWEDBY_NODE"), # the node you trust: people approve there org: { legal_name: "Notes Ltd", country: "FR" }, routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")], templates: { "notes:read" => "Read your notes" } # what the person approves ) use AllowedBy::Middleware, aby bind = ENV.fetch("ALLOWEDBY_BIND", "") # ALLOWEDBY_BIND=0.0.0.0 in a container; empty or unset: loopback only set :bind, bind.empty? ? "127.0.0.1" : bind unless ARGV.any? { |a| a.start_with?("-o") } # an explicit -o wins get "/notes" do content_type :json # no person (a level-0 route): refused, never a store keyed by nil person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json { notes: [], person: person }.to_json end ``` ## Rust ```rust use allowedby::{AllowedByContext, Options, Org, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use std::env::var; async fn list_notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "person": ctx.human_id})) } #[tokio::main] async fn main() -> Result<(), Box> { // your app's public URL, and the node you trust: people approve there let aby = Options::new(&var("ALLOWEDBY_ORIGIN")?, &var("ALLOWEDBY_NODE")?) .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*")) .template("notes:read", "Read your notes"); // what the person approves let app = Router::new().route("/notes", get(list_notes)); let app = allowedby::axum::protect(app, Service::new(aby)?); let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", var("PORT")?)).await?; axum::serve(listener, app).await?; Ok(()) } ``` --- Source: https://docs.allowedby.com/recipes/identify # See which agent is calling Know the agent and its verified operator, before any person is involved. | | | |---|---| | Level | 0: The agent identifies itself; no person is asked. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - without a passport: 401 passport_required - the app learns the agent and its verified operator; nobody is asked ## Python ```python routes.append(route("GET", "/me", level=0, summary="Which agent is calling")) @app.get("/me") def me(): return {"agent": g.allowedby.agent, "operator": g.allowedby.operator} ``` ## JavaScript ```js routes.push(route("GET", "/me", undefined, { level: 0, summary: "Which agent is calling" })); api.get("/me", (req, res) => { res.json({ agent: req.allowedby.agent, operator: req.allowedby.operator }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "GET", Path: "/me", Level: 0, Summary: "Which agent is calling"}) mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) writeJSON(w, http.StatusOK, map[string]string{"agent": who.Agent, "operator": who.Operator}) }) ``` ## Java ```java @Bean AllowedByCustomizer identify() { return aby -> aby.route(Route.get("/me").level(0).summary("Which agent is calling")); } @GetMapping("/me") Map me(@AllowedByContext Context ctx) { return Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator()); } ``` ## C# ```dotnet routes.Add(Route("GET", "/me", level: 0, summary: "Which agent is calling")); app.MapGet("/me", (AllowedByContext ctx) => new { agent = ctx.Agent, @operator = ctx.Operator }); ``` ## PHP ```php $routes[] = route('GET', '/me', level: 0, summary: 'Which agent is calling'); $app->get('/me', function (Request $request, Response $response) use ($json) { $context = $request->getAttribute('allowedby.context'); return $json($response, ['agent' => $context->agent, 'operator' => $context->operator]); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route("GET", "/me", level: 0, summary: "Which agent is calling") get "/me" do context = env["allowedby.context"] { agent: context.agent, operator: context.operator }.to_json end ``` ## Rust ```rust let aby = aby.route(Route::get("/me").level(0).summary("Which agent is calling")); let app = app.route("/me", get(me)); async fn me(ctx: AllowedByContext) -> Json { Json(json!({"agent": ctx.agent, "operator": ctx.operator})) } ``` --- Source: https://docs.allowedby.com/recipes/read # Let an agent read The person approves once with a passkey; the approval is reused until it expires or they withdraw it. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - an agent the person did not approve: 401 grant_required - the person approves the app's own sentence, then 200 - the approval is reused: nobody is asked again - the same signed request sent twice is refused ## Python ```python routes.append(route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes")) templates["notes:read"] = "Read your notes" @app.get("/notes") def list_notes(): return {"notes": notes.list(g.allowedby.human_id)} ``` ## JavaScript ```js routes.push(route("GET", "/notes", "notes:read", { level: 1, resource: "note:*", summary: "List your notes" })); templates["notes:read"] = "Read your notes"; api.get("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ notes: notes.list(person) }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "List your notes"}) templates["notes:read"] = allowedby.Text("Read your notes") mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } writeJSON(w, http.StatusOK, map[string][]Note{"notes": notes.List(me)}) }) ``` ## Java ```java @Bean AllowedByCustomizer read() { return aby -> aby .route(Route.get("/notes").capability("notes:read").level(1).resource("note:*") .summary("List your notes")) .template("notes:read", "Read your notes"); } @GetMapping("/notes") Map> listNotes(@AllowedByContext Context ctx) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } return Map.of("notes", notes.list(person)); } ``` ## C# ```dotnet routes.Add(Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes")); templates["notes:read"] = "Read your notes"; app.MapGet("/notes", (AllowedByContext ctx) => new { notes = notes.List(Person(ctx)) }); // The person the data belongs to. A level-0 route has no person (HumanId is null): stop here rather than key // anyone's data by a missing id. static string Person(AllowedByContext ctx) => ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); ``` ## PHP ```php $routes[] = route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*', summary: 'List your notes'); $templates['notes:read'] = 'Read your notes'; $app->get('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); return $json($response, ['notes' => $notes->list($person)]); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes") TEMPLATES["notes:read"] = "Read your notes" get "/notes" do # no person (a level-0 route): refused, never a store keyed by nil person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json { notes: notes.list(person) }.to_json end ``` ## Rust ```rust let aby = aby .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .template("notes:read", "Read your notes"); let app = app.route("/notes", get(list_notes)); async fn list_notes(ctx: AllowedByContext, State(notes): State) -> Json { Json(json!({"notes": notes.list(&ctx.human_id)})) } ``` --- Source: https://docs.allowedby.com/recipes/write # Let an agent write A change the person can undo: one approval, reused like a read. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `write`: Something changes and can be undone. The approval can be reused. | ## What the test proves - without an approval: 401 grant_required - the person approves, the note is added: 201 - a body changed on the way is refused and nothing is written ## Python ```python routes.append(route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:*", summary="Add a note", body={"text": "the note"})) templates["notes:write"] = "Add and change your notes" @app.post("/notes") def add_note(): return notes.add(g.allowedby.human_id, str(request.json.get("text", ""))), 201 ``` ## JavaScript ```js routes.push(route("POST", "/notes", "notes:write", { class: "write", level: 1, resource: "note:*", summary: "Add a note", body: { text: "the note" }, })); templates["notes:write"] = "Add and change your notes"; api.post("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.status(201).json(notes.add(person, String(req.body?.text ?? ""))); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:*", Summary: "Add a note", Body: map[string]string{"text": "the note"}}) templates["notes:write"] = allowedby.Text("Add and change your notes") mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } var input struct{ Text string } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "text: a string"}) return } writeJSON(w, http.StatusCreated, notes.Add(me, input.Text)) }) ``` ## Java ```java @Bean AllowedByCustomizer write() { return aby -> aby .route(Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1) .resource("note:*").summary("Add a note").body(Map.of("text", "the note"))) .template("notes:write", "Add and change your notes"); } @PostMapping("/notes") @ResponseStatus(HttpStatus.CREATED) Note addNote(@AllowedByContext Context ctx, @RequestBody NoteInput input) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } return notes.add(person, input.text() == null ? "" : input.text()); } ``` ## C# ```dotnet routes.Add(Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:*", summary: "Add a note", body: new Dictionary { ["text"] = "the note" })); templates["notes:write"] = "Add and change your notes"; app.MapPost("/notes", (NoteInput input, AllowedByContext ctx) => Results.Json(notes.Add(Person(ctx), input.Text ?? ""), statusCode: 201)); ``` ## PHP ```php $routes[] = route('POST', '/notes', 'notes:write', class: 'write', level: 1, resource: 'note:*', summary: 'Add a note', body: ['text' => 'the note']); $templates['notes:write'] = 'Add and change your notes'; $app->post('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $input = json_decode((string) $request->getBody(), true); return $json($response, $notes->add($person, (string) ($input['text'] ?? '')), 201); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:*", summary: "Add a note", body: { text: "the note" } ) TEMPLATES["notes:write"] = "Add and change your notes" post "/notes" do person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json text = JSON.parse(request.body.read)["text"].to_s [201, notes.add(person, text).to_json] end ``` ## Rust ```rust let aby = aby .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:*") .summary("Add a note") .body_field("text", "the note"), ) .template("notes:write", "Add and change your notes"); let app = app.route("/notes", post(add_note)); async fn add_note( ctx: AllowedByContext, State(notes): State, Json(input): Json, ) -> (StatusCode, Json) { (StatusCode::CREATED, Json(notes.add(&ctx.human_id, &input.text))) } ``` --- Source: https://docs.allowedby.com/recipes/delete # Ask before deleting A change that is hard to undo: your app asks the person for that exact request, and the approval works once. | | | |---|---| | Level | 2: A person whose identity is verified approves with a passkey. | | Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. | ## What the test proves - the approval to write does not delete: 401 - the app asks for this exact request; the person verifies their identity (level 2) and approves: 200 - the approval works once, and for no other note ## Python ```python routes.append(route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note")) templates["notes:delete"] = "Delete {scope}" @app.delete("/notes/") def delete_note(note_id): # The person approved this exact request, and it works once. if not notes.delete(g.allowedby.human_id, note_id): return {"error": "no such note"}, 404 return {"deleted": note_id} ``` ## JavaScript ```js routes.push(route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note", })); templates["notes:delete"] = "Delete {scope}"; api.delete("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by // The person approved this exact request, and it works once. if (!notes.delete(person, req.params.id)) { return res.status(404).json({ error: "no such note" }); } res.json({ deleted: req.params.id }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"}) templates["notes:delete"] = allowedby.Text("Delete {scope}") mux.HandleFunc("DELETE /notes/{id}", func(w http.ResponseWriter, r *http.Request) { // The person approved this exact request, and it works once. who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } if !notes.Delete(me, r.PathValue("id")) { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"}) return } writeJSON(w, http.StatusOK, map[string]string{"deleted": r.PathValue("id")}) }) ``` ## Java ```java @Bean AllowedByCustomizer delete() { return aby -> aby .route(Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD) .level(2).resource("note:{id}").summary("Delete a note")) .template("notes:delete", "Delete {scope}"); } @DeleteMapping("/notes/{id}") ResponseEntity> deleteNote(@AllowedByContext Context ctx, @PathVariable String id) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } // The person approved this exact request, and it works once. if (!notes.delete(person, id)) { return ResponseEntity.status(404).body(Map.of("error", "no such note")); } return ResponseEntity.ok(Map.of("deleted", id)); } ``` ## C# ```dotnet routes.Add(Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note")); templates["notes:delete"] = "Delete {scope}"; app.MapDelete("/notes/{id}", (string id, AllowedByContext ctx) => // The person approved this exact request, and it works once. notes.Delete(Person(ctx), id) ? Results.Json(new { deleted = id }) : Results.Json(new { error = "no such note" }, statusCode: 404)); ``` ## PHP ```php $routes[] = route('DELETE', '/notes/{id}', 'notes:delete', class: 'write-hard', level: 2, resource: 'note:{id}', summary: 'Delete a note'); $templates['notes:delete'] = 'Delete {scope}'; $app->delete('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { // The person approved this exact request, and it works once. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); if (!$notes->delete($person, $args['id'])) { return $json($response, ['error' => 'no such note'], 404); } return $json($response, ['deleted' => $args['id']]); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note" ) TEMPLATES["notes:delete"] = "Delete {scope}" delete "/notes/:id" do # The person approved this exact request, and it works once. person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json deleted = notes.delete(person, params["id"]) halt 404, { error: "no such note" }.to_json unless deleted { deleted: params["id"] }.to_json end ``` ## Rust ```rust let aby = aby .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:delete", "Delete {scope}"); let app = app.route("/notes/{id}", delete(delete_note)); async fn delete_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // The person approved this exact request, and it works once. match notes.delete(&ctx.human_id, &id) { Some(note) => Ok(Json(json!({"deleted": note.id}))), None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))), } } ``` --- Source: https://docs.allowedby.com/recipes/pay # Take a payment The person approves the amount and the payee; any other amount or payee is refused. | | | |---|---| | Level | 2: A person whose identity is verified approves with a passkey. | | Class | `irreversible`: Cannot be undone. The app creates the approval for that exact request, and it works once. | ## What the test proves - the person approves the amount and the payee, then 201 - another amount, another payee or a second payment needs another approval - an approval to pay is never kept by the agent ## Python ```python routes.append(route("POST", "/payees/{payee}/payments", "payments:send", cls="irreversible", level=2, resource="payee:{payee}", amount_field="/amount", summary="Pay someone", body={"amount": "a decimal string, e.g. 40.00", "currency": "e.g. EUR"})) templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}" @app.post("/payees//payments") def pay(payee): # The payee, the amount and the currency are the ones the person approved. payment = request.json return {"paid": payment["amount"], "currency": payment["currency"], "to": payee}, 201 ``` ## JavaScript ```js routes.push(route("POST", "/payees/{payee}/payments", "payments:send", { class: "irreversible", level: 2, resource: "payee:{payee}", amountField: "/amount", summary: "Pay someone", body: { amount: "a decimal string, e.g. 40.00", currency: "e.g. EUR" }, })); templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}"; api.post("/payees/:payee/payments", (req, res) => { // The payee, the amount and the currency are the ones the person approved. const { amount, currency } = req.body; res.status(201).json({ paid: amount, currency, to: req.params.payee }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "POST", Path: "/payees/{payee}/payments", Capability: "payments:send", Class: allowedby.Irreversible, Level: 2, Resource: "payee:{payee}", AmountField: "/amount", Summary: "Pay someone", Body: map[string]string{"amount": "a decimal string, e.g. 40.00", "currency": "e.g. EUR"}}) templates["payments:send"] = allowedby.Text("Pay {amount.max} {amount.currency} to {scope}") mux.HandleFunc("POST /payees/{payee}/payments", func(w http.ResponseWriter, r *http.Request) { // The payee, the amount and the currency are the ones the person approved. var payment struct{ Amount, Currency string } if err := json.NewDecoder(r.Body).Decode(&payment); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "amount, currency: strings"}) return } writeJSON(w, http.StatusCreated, map[string]string{ "paid": payment.Amount, "currency": payment.Currency, "to": r.PathValue("payee")}) }) ``` ## Java ```java @Bean AllowedByCustomizer pay() { return aby -> aby .route(Route.post("/payees/{payee}/payments").capability("payments:send") .actionClass(ActionClass.IRREVERSIBLE).level(2).resource("payee:{payee}") .amountField("/amount").summary("Pay someone") .body(Map.of("amount", "a decimal string, e.g. 40.00", "currency", "e.g. EUR"))) .template("payments:send", "Pay {amount.max} {amount.currency} to {scope}"); } @PostMapping("/payees/{payee}/payments") @ResponseStatus(HttpStatus.CREATED) Map pay(@PathVariable String payee, @RequestBody Payment payment) { // The payee, the amount and the currency are the ones the person approved. return Map.of("paid", payment.amount(), "currency", payment.currency(), "to", payee); } ``` ## C# ```dotnet routes.Add(Route("POST", "/payees/{payee}/payments", "payments:send", cls: "irreversible", level: 2, resource: "payee:{payee}", amountField: "/amount", summary: "Pay someone", body: new Dictionary { ["amount"] = "a decimal string, e.g. 40.00", ["currency"] = "e.g. EUR" })); templates["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}"; app.MapPost("/payees/{payee}/payments", (string payee, Payment payment) => // The payee, the amount and the currency are the ones the person approved. Results.Json(new { paid = payment.Amount, currency = payment.Currency, to = payee }, statusCode: 201)); ``` ## PHP ```php $routes[] = route('POST', '/payees/{payee}/payments', 'payments:send', class: 'irreversible', level: 2, resource: 'payee:{payee}', amountField: '/amount', summary: 'Pay someone', body: ['amount' => 'a decimal string, e.g. 40.00', 'currency' => 'e.g. EUR']); $templates['payments:send'] = 'Pay {amount.max} {amount.currency} to {scope}'; $app->post('/payees/{payee}/payments', function (Request $request, Response $response, array $args) use ($json) { // The payee, the amount and the currency are the ones the person approved. $payment = json_decode((string) $request->getBody(), true); return $json($response, ['paid' => $payment['amount'], 'currency' => $payment['currency'], 'to' => $args['payee']], 201); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "POST", "/payees/{payee}/payments", "payments:send", class: "irreversible", level: 2, resource: "payee:{payee}", amount_field: "/amount", summary: "Pay someone", body: { amount: "a decimal string, e.g. 40.00", currency: "e.g. EUR" } ) TEMPLATES["payments:send"] = "Pay {amount.max} {amount.currency} to {scope}" post "/payees/:payee/payments" do # The payee, the amount and the currency are the ones the person approved. payment = JSON.parse(request.body.read) [201, { paid: payment["amount"], currency: payment["currency"], to: params["payee"] }.to_json] end ``` ## Rust ```rust let aby = aby .route( Route::post("/payees/{payee}/payments") .capability("payments:send") .class(Class::Irreversible) .level(2) .resource("payee:{payee}") .amount_field("/amount") .summary("Pay someone") .body_field("amount", "a decimal string, e.g. 40.00") .body_field("currency", "e.g. EUR"), ) .template("payments:send", "Pay {amount.max} {amount.currency} to {scope}"); let app = app.route("/payees/{payee}/payments", post(pay)); async fn pay(Path(payee): Path, Json(payment): Json) -> (StatusCode, Json) { // The payee, the amount and the currency are the ones the person approved. (StatusCode::CREATED, Json(json!({"paid": payment.amount, "currency": payment.currency, "to": payee}))) } ``` --- Source: https://docs.allowedby.com/recipes/pay-high # Take a high-value payment Level 3: a verified identity and a hardware passkey. Anything weaker is refused. | | | |---|---| | Level | 3: A person verified at the highest level approves with a hardware passkey. | | Class | `irreversible`: Cannot be undone. The app creates the approval for that exact request, and it works once. | ## What the test proves - a passkey that is synced, or that no hardware vouches for, cannot reach level 3: refused - with a hardware passkey and an identity verified to level 3, the person approves: 201 - the approval works once ## Python ```python routes.append(route("POST", "/payees/{payee}/transfers", "transfers:send", cls="irreversible", level=3, authn="hardware", resource="payee:{payee}", amount_field="/amount", summary="Send a bank transfer", body={"amount": "a decimal string, e.g. 4000.00", "currency": "e.g. EUR"})) templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}" @app.post("/payees//transfers") def transfer(payee): # Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. order = request.json return {"sent": order["amount"], "currency": order["currency"], "to": payee, "level": g.allowedby.level}, 201 ``` ## JavaScript ```js routes.push(route("POST", "/payees/{payee}/transfers", "transfers:send", { class: "irreversible", level: 3, authn: "hardware", resource: "payee:{payee}", amountField: "/amount", summary: "Send a bank transfer", body: { amount: "a decimal string, e.g. 4000.00", currency: "e.g. EUR" }, })); templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}"; api.post("/payees/:payee/transfers", (req, res) => { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. const { amount, currency } = req.body; res.status(201).json({ sent: amount, currency, to: req.params.payee, level: req.allowedby.level }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "POST", Path: "/payees/{payee}/transfers", Capability: "transfers:send", Class: allowedby.Irreversible, Level: 3, Authn: "hardware", Resource: "payee:{payee}", AmountField: "/amount", Summary: "Send a bank transfer", Body: map[string]string{"amount": "a decimal string, e.g. 4000.00", "currency": "e.g. EUR"}}) templates["transfers:send"] = allowedby.Text("Transfer {amount.max} {amount.currency} to {scope}") mux.HandleFunc("POST /payees/{payee}/transfers", func(w http.ResponseWriter, r *http.Request) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. who, _ := allowedby.ContextFrom(r.Context()) var order struct{ Amount, Currency string } if err := json.NewDecoder(r.Body).Decode(&order); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "amount, currency: strings"}) return } writeJSON(w, http.StatusCreated, map[string]any{ "sent": order.Amount, "currency": order.Currency, "to": r.PathValue("payee"), "level": who.Level}) }) ``` ## Java ```java @Bean AllowedByCustomizer payHigh() { return aby -> aby .route(Route.post("/payees/{payee}/transfers").capability("transfers:send") .actionClass(ActionClass.IRREVERSIBLE).level(3).authn("hardware").resource("payee:{payee}") .amountField("/amount").summary("Send a bank transfer") .body(Map.of("amount", "a decimal string, e.g. 4000.00", "currency", "e.g. EUR"))) .template("transfers:send", "Transfer {amount.max} {amount.currency} to {scope}"); } @PostMapping("/payees/{payee}/transfers") @ResponseStatus(HttpStatus.CREATED) Map transfer(@AllowedByContext Context ctx, @PathVariable String payee, @RequestBody Payment order) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. return Map.of("sent", order.amount(), "currency", order.currency(), "to", payee, "level", ctx.getLevel()); } ``` ## C# ```dotnet routes.Add(Route("POST", "/payees/{payee}/transfers", "transfers:send", cls: "irreversible", level: 3, authn: "hardware", resource: "payee:{payee}", amountField: "/amount", summary: "Send a bank transfer", body: new Dictionary { ["amount"] = "a decimal string, e.g. 4000.00", ["currency"] = "e.g. EUR" })); templates["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}"; app.MapPost("/payees/{payee}/transfers", (string payee, Payment order, AllowedByContext ctx) => // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. Results.Json(new { sent = order.Amount, currency = order.Currency, to = payee, level = ctx.Level }, statusCode: 201)); ``` ## PHP ```php $routes[] = route('POST', '/payees/{payee}/transfers', 'transfers:send', class: 'irreversible', level: 3, authn: 'hardware', resource: 'payee:{payee}', amountField: '/amount', summary: 'Send a bank transfer', body: ['amount' => 'a decimal string, e.g. 4000.00', 'currency' => 'e.g. EUR']); $templates['transfers:send'] = 'Transfer {amount.max} {amount.currency} to {scope}'; $app->post('/payees/{payee}/transfers', function (Request $request, Response $response, array $args) use ($json) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. $level = $request->getAttribute('allowedby.context')->level; $order = json_decode((string) $request->getBody(), true); return $json($response, ['sent' => $order['amount'], 'currency' => $order['currency'], 'to' => $args['payee'], 'level' => $level], 201); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "POST", "/payees/{payee}/transfers", "transfers:send", class: "irreversible", level: 3, authn: "hardware", resource: "payee:{payee}", amount_field: "/amount", summary: "Send a bank transfer", body: { amount: "a decimal string, e.g. 4000.00", currency: "e.g. EUR" } ) TEMPLATES["transfers:send"] = "Transfer {amount.max} {amount.currency} to {scope}" post "/payees/:payee/transfers" do # Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. order = JSON.parse(request.body.read) level = env["allowedby.context"].level [201, { sent: order["amount"], currency: order["currency"], to: params["payee"], level: level }.to_json] end ``` ## Rust ```rust let aby = aby .route( Route::post("/payees/{payee}/transfers") .capability("transfers:send") .class(Class::Irreversible) .level(3) .authn(Authn::Hardware) .resource("payee:{payee}") .amount_field("/amount") .summary("Send a bank transfer") .body_field("amount", "a decimal string, e.g. 4000.00") .body_field("currency", "e.g. EUR"), ) .template("transfers:send", "Transfer {amount.max} {amount.currency} to {scope}"); let app = app.route("/payees/{payee}/transfers", post(transfer)); async fn transfer( ctx: AllowedByContext, Path(payee): Path, Json(order): Json, ) -> (StatusCode, Json) { // Level 3: an identity verified to eIDAS high, and a passkey that never leaves its device. let sent = json!({"sent": order.amount, "currency": order.currency, "to": payee, "level": ctx.level}); (StatusCode::CREATED, Json(sent)) } ``` --- Source: https://docs.allowedby.com/recipes/spend-limit # Set a spending limit The person approves an amount per month once; the SDK keeps the total and refuses what goes over. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `write`: Something changes and can be undone. The approval can be reused. | ## What the test proves - the person approves up to 100 EUR per month, and a first order of 60: 201 - 40.01 more is refused, 40.00 passes without asking, then not one cent more - another currency is refused, with room left under the limit - over the limit, the agent asks again: a new approval has its own total ## Python ```python routes.append(route("POST", "/orders", "orders:place", cls="write", level=1, resource="order:new", amount_field="/total", summary="Place an order", body={"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"})) templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}" @app.post("/orders") def place_order(): # The SDK keeps the total of the period: an order over the limit the person approved never gets here. order = request.json return {"ordered": order["total"], "currency": order["currency"]}, 201 ``` ## JavaScript ```js routes.push(route("POST", "/orders", "orders:place", { class: "write", level: 1, resource: "order:new", amountField: "/total", summary: "Place an order", body: { total: "a decimal string, e.g. 60.00", currency: "e.g. EUR" }, })); templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"; api.post("/orders", (req, res) => { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. const { total, currency } = req.body; res.status(201).json({ ordered: total, currency }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "POST", Path: "/orders", Capability: "orders:place", Class: allowedby.Write, Level: 1, Resource: "order:new", AmountField: "/total", Summary: "Place an order", Body: map[string]string{"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"}}) templates["orders:place"] = allowedby.Text("Order for up to {amount.max} {amount.currency} per {amount.per}") mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. var order struct{ Total, Currency string } if err := json.NewDecoder(r.Body).Decode(&order); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "total, currency: strings"}) return } writeJSON(w, http.StatusCreated, map[string]string{"ordered": order.Total, "currency": order.Currency}) }) ``` ## Java ```java @Bean AllowedByCustomizer spendLimit() { return aby -> aby .route(Route.post("/orders").capability("orders:place").actionClass(ActionClass.WRITE).level(1) .resource("order:new").amountField("/total").summary("Place an order") .body(Map.of("total", "a decimal string, e.g. 60.00", "currency", "e.g. EUR"))) .template("orders:place", "Order for up to {amount.max} {amount.currency} per {amount.per}"); } @PostMapping("/orders") @ResponseStatus(HttpStatus.CREATED) Map placeOrder(@RequestBody Order order) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. return Map.of("ordered", order.total(), "currency", order.currency()); } ``` ## C# ```dotnet routes.Add(Route("POST", "/orders", "orders:place", cls: "write", level: 1, resource: "order:new", amountField: "/total", summary: "Place an order", body: new Dictionary { ["total"] = "a decimal string, e.g. 60.00", ["currency"] = "e.g. EUR" })); templates["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}"; app.MapPost("/orders", (Order order) => // The SDK keeps the total of the period: an order over the limit the person approved never gets here. Results.Json(new { ordered = order.Total, currency = order.Currency }, statusCode: 201)); ``` ## PHP ```php $routes[] = route('POST', '/orders', 'orders:place', class: 'write', level: 1, resource: 'order:new', amountField: '/total', summary: 'Place an order', body: ['total' => 'a decimal string, e.g. 60.00', 'currency' => 'e.g. EUR']); $templates['orders:place'] = 'Order for up to {amount.max} {amount.currency} per {amount.per}'; $app->post('/orders', function (Request $request, Response $response) use ($json) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. $order = json_decode((string) $request->getBody(), true); return $json($response, ['ordered' => $order['total'], 'currency' => $order['currency']], 201); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "POST", "/orders", "orders:place", class: "write", level: 1, resource: "order:new", amount_field: "/total", summary: "Place an order", body: { total: "a decimal string, e.g. 60.00", currency: "e.g. EUR" } ) TEMPLATES["orders:place"] = "Order for up to {amount.max} {amount.currency} per {amount.per}" post "/orders" do # The SDK keeps the total of the period: an order over the limit the person approved never gets here. order = JSON.parse(request.body.read) [201, { ordered: order["total"], currency: order["currency"] }.to_json] end ``` ## Rust ```rust let aby = aby .route( Route::post("/orders") .capability("orders:place") .class(Class::Write) .level(1) .resource("order:new") .amount_field("/total") .summary("Place an order") .body_field("total", "a decimal string, e.g. 60.00") .body_field("currency", "e.g. EUR"), ) .template("orders:place", "Order for up to {amount.max} {amount.currency} per {amount.per}"); let app = app.route("/orders", post(place_order)); async fn place_order(Json(order): Json) -> (StatusCode, Json) { // The SDK keeps the total of the period: an order over the limit the person approved never gets here. (StatusCode::CREATED, Json(json!({"ordered": order.total, "currency": order.currency}))) } ``` --- Source: https://docs.allowedby.com/recipes/subscribe # Start and cancel a subscription The person approves the plan and its monthly price once; you charge it until they cancel. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. | ## What the test proves - the person approves the plan and its monthly price, once: 201, charged - another price needs another approval - a month later it is charged again, and nobody is asked - the person approves the cancellation: it is never charged again ## Python ```python routes.append(route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls="write-hard", level=1, resource="plan:{plan}", amount_field="/monthly", summary="Subscribe to a plan", body={"monthly": "the price per month, e.g. 12.00", "currency": "EUR"})) routes.append(route("GET", "/subscription", "plans:read", level=1, resource="plan:*", summary="Your subscription")) routes.append(route("DELETE", "/subscription", "plans:cancel", cls="write-hard", level=1, resource="plan:mine", summary="Cancel your subscription")) templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel" templates["plans:read"] = "See your subscription" templates["plans:cancel"] = "Cancel your subscription" @app.post("/plans//subscription") def subscribe(plan): # Approved once, with the price: your billing charges it every month (subscriptions.py) until it is cancelled. return subscriptions.start(g.allowedby.human_id, plan, request.json["monthly"]), 201 @app.get("/subscription") def subscription(): return subscriptions.get(g.allowedby.human_id) or ({"error": "no subscription"}, 404) @app.delete("/subscription") def cancel(): return subscriptions.cancel(g.allowedby.human_id) or ({"error": "no subscription"}, 404) ``` ## JavaScript ```js routes.push( route("POST", "/plans/{plan}/subscription", "plans:subscribe", { class: "write-hard", level: 1, resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan", body: { monthly: "the price per month, e.g. 12.00", currency: "EUR" }, }), route("GET", "/subscription", "plans:read", { level: 1, resource: "plan:*", summary: "Your subscription" }), route("DELETE", "/subscription", "plans:cancel", { class: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription", }), ); templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"; templates["plans:read"] = "See your subscription"; templates["plans:cancel"] = "Cancel your subscription"; api.post("/plans/:plan/subscription", (req, res) => { // Approved once, with the price: your billing charges it every month (subscriptions.mjs) until it is cancelled. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.status(201).json(subscriptions.start(person, req.params.plan, req.body.monthly)); }); api.get("/subscription", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const subscription = subscriptions.get(person); if (!subscription) return res.status(404).json({ error: "no subscription" }); res.json(subscription); }); api.delete("/subscription", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const subscription = subscriptions.cancel(person); if (!subscription) return res.status(404).json({ error: "no subscription" }); res.json(subscription); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "POST", Path: "/plans/{plan}/subscription", Capability: "plans:subscribe", Class: allowedby.WriteHard, Level: 1, Resource: "plan:{plan}", AmountField: "/monthly", Summary: "Subscribe to a plan", Body: map[string]string{"monthly": "the price per month, e.g. 12.00", "currency": "EUR"}}, allowedby.Route{Method: "GET", Path: "/subscription", Capability: "plans:read", Class: allowedby.Read, Level: 1, Resource: "plan:*", Summary: "Your subscription"}, allowedby.Route{Method: "DELETE", Path: "/subscription", Capability: "plans:cancel", Class: allowedby.WriteHard, Level: 1, Resource: "plan:mine", Summary: "Cancel your subscription"}) templates["plans:subscribe"] = allowedby.Text( "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel") templates["plans:read"] = allowedby.Text("See your subscription") templates["plans:cancel"] = allowedby.Text("Cancel your subscription") mux.HandleFunc("POST /plans/{plan}/subscription", func(w http.ResponseWriter, r *http.Request) { // Approved once, with the price: your billing charges it every month (subscriptions.go) until it is cancelled. who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } var input struct{ Monthly string } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "monthly: a string"}) return } writeJSON(w, http.StatusCreated, subscriptions.Start(me, r.PathValue("plan"), input.Monthly)) }) mux.HandleFunc("GET /subscription", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } subscription, found := subscriptions.Get(me) if !found { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no subscription"}) return } writeJSON(w, http.StatusOK, subscription) }) mux.HandleFunc("DELETE /subscription", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } subscription, found := subscriptions.Cancel(me) if !found { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no subscription"}) return } writeJSON(w, http.StatusOK, subscription) }) ``` ## Java ```java @Bean AllowedByCustomizer subscribe() { return aby -> aby .route(Route.post("/plans/{plan}/subscription").capability("plans:subscribe") .actionClass(ActionClass.WRITE_HARD).level(1).resource("plan:{plan}") .amountField("/monthly").summary("Subscribe to a plan") .body(Map.of("monthly", "the price per month, e.g. 12.00", "currency", "EUR"))) .route(Route.get("/subscription").capability("plans:read").level(1).resource("plan:*") .summary("Your subscription")) .route(Route.delete("/subscription").capability("plans:cancel").actionClass(ActionClass.WRITE_HARD) .level(1).resource("plan:mine").summary("Cancel your subscription")) .template("plans:subscribe", "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel") .template("plans:read", "See your subscription") .template("plans:cancel", "Cancel your subscription"); } @PostMapping("/plans/{plan}/subscription") @ResponseStatus(HttpStatus.CREATED) Subscription subscribe(@AllowedByContext Context ctx, @PathVariable String plan, @RequestBody Price price) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } // Approved once, with the price: your billing charges it every month (Subscriptions) until it is cancelled. return subscriptions.start(person, plan, price.monthly()); } @GetMapping("/subscription") ResponseEntity subscription(@AllowedByContext Context ctx) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } return subscriptions.get(person).>map(ResponseEntity::ok) .orElse(ResponseEntity.status(404).body(Map.of("error", "no subscription"))); } @DeleteMapping("/subscription") ResponseEntity cancel(@AllowedByContext Context ctx) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } return subscriptions.cancel(person).>map(ResponseEntity::ok) .orElse(ResponseEntity.status(404).body(Map.of("error", "no subscription"))); } ``` ## C# ```dotnet routes.Add(Route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls: "write-hard", level: 1, resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan", body: new Dictionary { ["monthly"] = "the price per month, e.g. 12.00", ["currency"] = "EUR" })); routes.Add(Route("GET", "/subscription", "plans:read", level: 1, resource: "plan:*", summary: "Your subscription")); routes.Add(Route("DELETE", "/subscription", "plans:cancel", cls: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription")); templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"; templates["plans:read"] = "See your subscription"; templates["plans:cancel"] = "Cancel your subscription"; app.MapPost("/plans/{plan}/subscription", (string plan, Price price, AllowedByContext ctx) => // Approved once, with the price: your billing charges it every month (Subscriptions.cs) until it is cancelled. Results.Json(subscriptions.Start(Person(ctx), plan, price.Monthly), statusCode: 201)); app.MapGet("/subscription", (AllowedByContext ctx) => subscriptions.Get(Person(ctx)) is { } subscription ? Results.Json(subscription) : Results.Json(new { error = "no subscription" }, statusCode: 404)); app.MapDelete("/subscription", (AllowedByContext ctx) => subscriptions.Cancel(Person(ctx)) is { } subscription ? Results.Json(subscription) : Results.Json(new { error = "no subscription" }, statusCode: 404)); ``` ## PHP ```php $routes[] = route('POST', '/plans/{plan}/subscription', 'plans:subscribe', class: 'write-hard', level: 1, resource: 'plan:{plan}', amountField: '/monthly', summary: 'Subscribe to a plan', body: ['monthly' => 'the price per month, e.g. 12.00', 'currency' => 'EUR']); $routes[] = route('GET', '/subscription', 'plans:read', level: 1, resource: 'plan:*', summary: 'Your subscription'); $routes[] = route('DELETE', '/subscription', 'plans:cancel', class: 'write-hard', level: 1, resource: 'plan:mine', summary: 'Cancel your subscription'); $templates['plans:subscribe'] = 'Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel'; $templates['plans:read'] = 'See your subscription'; $templates['plans:cancel'] = 'Cancel your subscription'; $app->post('/plans/{plan}/subscription', function (Request $request, Response $response, array $args) use ( $json, $subscriptions ) { // Approved once, with the price: your billing charges it every month (Subscriptions.php) until it is cancelled. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $input = json_decode((string) $request->getBody(), true); return $json($response, $subscriptions->start($person, $args['plan'], $input['monthly']), 201); }); $app->get('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) { $subscription = $subscriptions->get($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0')); return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404); }); $app->delete('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) { $subscription = $subscriptions->cancel($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0')); return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "POST", "/plans/{plan}/subscription", "plans:subscribe", class: "write-hard", level: 1, resource: "plan:{plan}", amount_field: "/monthly", summary: "Subscribe to a plan", body: { monthly: "the price per month, e.g. 12.00", currency: "EUR" } ) ROUTES << AllowedBy.route( "GET", "/subscription", "plans:read", level: 1, resource: "plan:*", summary: "Your subscription" ) ROUTES << AllowedBy.route( "DELETE", "/subscription", "plans:cancel", class: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription" ) TEMPLATES["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel" TEMPLATES["plans:read"] = "See your subscription" TEMPLATES["plans:cancel"] = "Cancel your subscription" post "/plans/:plan/subscription" do # Approved once, with the price: your billing charges it every month (subscriptions.rb) until it is cancelled. person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json monthly = JSON.parse(request.body.read)["monthly"] [201, subscriptions.start(person, params["plan"], monthly).to_json] end get "/subscription" do person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json subscription = subscriptions.get(person) halt 404, { error: "no subscription" }.to_json unless subscription subscription.to_json end delete "/subscription" do person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json subscription = subscriptions.cancel(person) halt 404, { error: "no subscription" }.to_json unless subscription subscription.to_json end ``` ## Rust ```rust let aby = aby .route( Route::post("/plans/{plan}/subscription") .capability("plans:subscribe") .class(Class::WriteHard) .level(1) .resource("plan:{plan}") .amount_field("/monthly") .summary("Subscribe to a plan") .body_field("monthly", "the price per month, e.g. 12.00") .body_field("currency", "EUR"), ) .route( Route::get("/subscription") .capability("plans:read") .level(1) .resource("plan:*") .summary("Your subscription"), ) .route( Route::delete("/subscription") .capability("plans:cancel") .class(Class::WriteHard) .level(1) .resource("plan:mine") .summary("Cancel your subscription"), ) .template( "plans:subscribe", "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel", ) .template("plans:read", "See your subscription") .template("plans:cancel", "Cancel your subscription"); let app = app .route("/plans/{plan}/subscription", post(subscribe)) .route("/subscription", get(subscription).delete(cancel)); async fn subscribe( ctx: AllowedByContext, State(subscriptions): State, Path(plan): Path, Json(price): Json, ) -> (StatusCode, Json) { // Approved once, with the price: your billing charges it every month (subscriptions.rs) until it is cancelled. (StatusCode::CREATED, Json(subscriptions.start(&ctx.human_id, plan, price.monthly))) } async fn subscription( ctx: AllowedByContext, State(subscriptions): State, ) -> Result, Refusal> { let found = subscriptions.get(&ctx.human_id); found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"})))) } async fn cancel( ctx: AllowedByContext, State(subscriptions): State, ) -> Result, Refusal> { let found = subscriptions.cancel(&ctx.human_id); found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"})))) } ``` --- Source: https://docs.allowedby.com/recipes/delegate # Accept a sub-agent An agent hands a sub-agent part of its approval, never more, and it ends when the person withdraws the first. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - the sub-agent reads the one note it was given, for the same person; nobody is asked - every note is out of its reach, and more than the agent has cannot be handed on - the chain works with the sub-agent's key only - the person withdraws the agent's approval: the sub-agent's ends with it ## Python ```python routes.append(route("GET", "/notes/{id}/summary", "notes:read", level=1, resource="note:{id}", summary="Summarise one note")) @app.get("/notes//summary") def summarise(note_id): # An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same. note = notes.get(g.allowedby.human_id, note_id) if not note: return {"error": "no such note"}, 404 return {"words": len(note["text"].split()), "delegated": len(g.allowedby.chain) > 1} ``` ## JavaScript ```js routes.push(route("GET", "/notes/{id}/summary", "notes:read", { level: 1, resource: "note:{id}", summary: "Summarise one note", })); api.get("/notes/:id/summary", (req, res) => { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const note = notes.get(person, req.params.id); if (!note) return res.status(404).json({ error: "no such note" }); res.json({ words: note.text.split(/\s+/).length, delegated: req.allowedby.chain.length > 1 }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "GET", Path: "/notes/{id}/summary", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:{id}", Summary: "Summarise one note"}) mux.HandleFunc("GET /notes/{id}/summary", func(w http.ResponseWriter, r *http.Request) { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and the person is the same. who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } note, found := notes.Get(me, r.PathValue("id")) if !found { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"}) return } writeJSON(w, http.StatusOK, map[string]any{ "words": len(strings.Fields(note.Text)), "delegated": len(who.Chain) > 1}) }) ``` ## Java ```java @Bean AllowedByCustomizer delegate() { return aby -> aby.route(Route.get("/notes/{id}/summary").capability("notes:read").level(1) .resource("note:{id}").summary("Summarise one note")); } @GetMapping("/notes/{id}/summary") ResponseEntity> summarise(@AllowedByContext Context ctx, @PathVariable String id) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and getHumanId is the same. return notes.get(person, id) .map(note -> ResponseEntity.ok(Map.of("words", note.text().split("\\s+").length, "delegated", ctx.getChain().size() > 1))) .orElse(ResponseEntity.status(404).body(Map.of("error", "no such note"))); } ``` ## C# ```dotnet routes.Add(Route("GET", "/notes/{id}/summary", "notes:read", level: 1, resource: "note:{id}", summary: "Summarise one note")); app.MapGet("/notes/{id}/summary", (string id, AllowedByContext ctx) => { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and HumanId is the same. if (notes.Get(Person(ctx), id) is not { } note) { return Results.Json(new { error = "no such note" }, statusCode: 404); } var words = note.Text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length; return Results.Json(new { words, delegated = ctx.Chain.Count > 1 }); }); ``` ## PHP ```php $routes[] = route('GET', '/notes/{id}/summary', 'notes:read', level: 1, resource: 'note:{id}', summary: 'Summarise one note'); $app->get('/notes/{id}/summary', function (Request $request, Response $response, array $args) use ($json, $notes) { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and humanId is the same. $context = $request->getAttribute('allowedby.context'); $note = $notes->get($context->humanId ?? throw new LogicException('no person at level 0'), $args['id']); if (null === $note) { return $json($response, ['error' => 'no such note'], 404); } $words = count(preg_split('/\s+/u', $note['text'])); return $json($response, ['words' => $words, 'delegated' => count($context->chain) > 1]); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "GET", "/notes/{id}/summary", "notes:read", level: 1, resource: "note:{id}", summary: "Summarise one note" ) get "/notes/:id/summary" do # An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same. context = env["allowedby.context"] person = context.human_id or halt 403, { error: "no person: this route needs one" }.to_json note = notes.get(person, params["id"]) halt 404, { error: "no such note" }.to_json unless note { words: note[:text].split.length, delegated: context.chain.length > 1 }.to_json end ``` ## Rust ```rust let aby = aby.route( Route::get("/notes/{id}/summary") .capability("notes:read") .level(1) .resource("note:{id}") .summary("Summarise one note"), ); let app = app.route("/notes/{id}/summary", get(summarise)); async fn summarise( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // An agent may hand a sub-agent part of its approval: the SDK checks the chain, and human_id is the same. match notes.get(&ctx.human_id, &id) { Some(note) => { let words = note.text.split_whitespace().count(); Ok(Json(json!({"words": words, "delegated": ctx.chain.len() > 1}))) } None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))), } } ``` --- Source: https://docs.allowedby.com/recipes/withdraw # Let the person withdraw The person takes an approval back on their node; your app refuses it from the next refresh. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - the person approves, and the app knows which approval it served - the person withdraws it: from the next refresh, 401 revoked - their other approvals still work - asked again, the person may approve again: a new approval, 200 ## Python ```python routes.append(route("GET", "/export", "notes:export", level=1, resource="note:*", summary="Export your notes")) templates["notes:export"] = "Export your notes" @app.get("/export") def export(): # Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. return {"approval": g.allowedby.gid, "notes": notes.list(g.allowedby.human_id)} ``` ## JavaScript ```js routes.push(route("GET", "/export", "notes:export", { level: 1, resource: "note:*", summary: "Export your notes" })); templates["notes:export"] = "Export your notes"; api.get("/export", (req, res) => { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ approval: req.allowedby.gid, notes: notes.list(person) }); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "GET", Path: "/export", Capability: "notes:export", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "Export your notes"}) templates["notes:export"] = allowedby.Text("Export your notes") mux.HandleFunc("GET /export", func(w http.ResponseWriter, r *http.Request) { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } writeJSON(w, http.StatusOK, map[string]any{"approval": who.GID, "notes": notes.List(me)}) }) ``` ## Java ```java @Bean AllowedByCustomizer withdraw() { return aby -> aby .route(Route.get("/export").capability("notes:export").level(1).resource("note:*") .summary("Export your notes")) .template("notes:export", "Export your notes"); } @GetMapping("/export") Map export(@AllowedByContext Context ctx) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. return Map.of("approval", ctx.getGid(), "notes", notes.list(person)); } ``` ## C# ```dotnet routes.Add(Route("GET", "/export", "notes:export", level: 1, resource: "note:*", summary: "Export your notes")); templates["notes:export"] = "Export your notes"; app.MapGet("/export", (AllowedByContext ctx) => // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. new { approval = ctx.Gid, notes = notes.List(Person(ctx)) }); ``` ## PHP ```php $routes[] = route('GET', '/export', 'notes:export', level: 1, resource: 'note:*', summary: 'Export your notes'); $templates['notes:export'] = 'Export your notes'; $app->get('/export', function (Request $request, Response $response) use ($json, $notes) { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. $context = $request->getAttribute('allowedby.context'); return $json($response, ['approval' => $context->gid, 'notes' => $notes->list($context->humanId ?? throw new LogicException('no person at level 0'))]); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route("GET", "/export", "notes:export", level: 1, resource: "note:*", summary: "Export your notes") TEMPLATES["notes:export"] = "Export your notes" get "/export" do # Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. context = env["allowedby.context"] person = context.human_id or halt 403, { error: "no person: this route needs one" }.to_json { approval: context.gid, notes: notes.list(person) }.to_json end ``` ## Rust ```rust let aby = aby .route( Route::get("/export").capability("notes:export").level(1).resource("note:*").summary("Export your notes"), ) .template("notes:export", "Export your notes"); let app = app.route("/export", get(export)); async fn export(ctx: AllowedByContext, State(notes): State) -> Json { // Once the person withdraws this approval, the SDK answers 401 revoked. Keep its id with what you do. Json(json!({"approval": ctx.gid, "notes": notes.list(&ctx.human_id)})) } ``` --- Source: https://docs.allowedby.com/recipes/own-data # Serve only the person's own data human_id is the same person every time at your app: look their data up with it. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - the person's own note is served, under the approval they already gave - someone else's agent, approved by its own person, gets 404 for that note and an empty list ## Python ```python routes.append(route("GET", "/notes/{id}", "notes:read", level=1, resource="note:{id}", summary="Read one note")) @app.get("/notes/") def get_note(note_id): # human_id is this person's id at your app, always the same. Look up with it, never by note_id alone. note = notes.get(g.allowedby.human_id, note_id) return note or ({"error": "no such note"}, 404) ``` ## JavaScript ```js routes.push(route("GET", "/notes/{id}", "notes:read", { level: 1, resource: "note:{id}", summary: "Read one note" })); api.get("/notes/:id", (req, res) => { // humanId is this person's id at your app, always the same. Look up with it, never by note id alone. const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const note = notes.get(person, req.params.id); if (!note) return res.status(404).json({ error: "no such note" }); res.json(note); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "GET", Path: "/notes/{id}", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:{id}", Summary: "Read one note"}) mux.HandleFunc("GET /notes/{id}", func(w http.ResponseWriter, r *http.Request) { // The person's id at your app is always the same. Look up with it, never by note id alone. who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } note, found := notes.Get(me, r.PathValue("id")) if !found { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"}) return } writeJSON(w, http.StatusOK, note) }) ``` ## Java ```java @Bean AllowedByCustomizer ownData() { return aby -> aby.route(Route.get("/notes/{id}").capability("notes:read").level(1).resource("note:{id}") .summary("Read one note")); } @GetMapping("/notes/{id}") ResponseEntity getNote(@AllowedByContext Context ctx, @PathVariable String id) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } // getHumanId is this person's id at your app, always the same. Look up with it, never by note id alone. return notes.get(person, id).>map(ResponseEntity::ok) .orElse(ResponseEntity.status(404).body(Map.of("error", "no such note"))); } ``` ## C# ```dotnet routes.Add(Route("GET", "/notes/{id}", "notes:read", level: 1, resource: "note:{id}", summary: "Read one note")); app.MapGet("/notes/{id}", (string id, AllowedByContext ctx) => // Person(ctx) is this person's id at your app, always the same. Look up with it, never by note id alone. notes.Get(Person(ctx), id) is { } note ? Results.Json(note) : Results.Json(new { error = "no such note" }, statusCode: 404)); ``` ## PHP ```php $routes[] = route('GET', '/notes/{id}', 'notes:read', level: 1, resource: 'note:{id}', summary: 'Read one note'); $app->get('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { // humanId is this person's id at your app, always the same. Look up with it, never by note id alone. $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $note = $notes->get($person, $args['id']); return null === $note ? $json($response, ['error' => 'no such note'], 404) : $json($response, $note); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "GET", "/notes/{id}", "notes:read", level: 1, resource: "note:{id}", summary: "Read one note" ) get "/notes/:id" do # human_id is this person's id at your app, always the same. Look up with it, never by note id alone. person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json note = notes.get(person, params["id"]) halt 404, { error: "no such note" }.to_json unless note note.to_json end ``` ## Rust ```rust let aby = aby.route( Route::get("/notes/{id}").capability("notes:read").level(1).resource("note:{id}").summary("Read one note"), ); let app = app.route("/notes/{id}", get(get_note)); async fn get_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, ) -> Result, Refusal> { // human_id is this person's id at your app, always the same. Look up with it, never by note id alone. let note = notes.get(&ctx.human_id, &id); note.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))) } ``` --- Source: https://docs.allowedby.com/recipes/refuse # Refuse in your own handler Your rules still apply: the agent receives your status and your JSON, and can correct itself. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `write`: Something changes and can be undone. The approval can be reused. | ## What the test proves - the app's own refusal reaches the agent as it is: 422 and its JSON; nothing changed - a body that is not a JSON object never reaches the app (400); no body at all is a 4xx - a note that is not there: the app's 404 - corrected, the same request is accepted under the same approval: 200 - 280 emoji are 280 characters in every language: 200; 281: 422 ## Python ```python routes.append(route("PUT", "/notes/{id}", "notes:write", cls="write", level=1, resource="note:{id}", summary="Change a note", body={"text": "1 to 280 characters"})) @app.put("/notes/") def change_note(note_id): text = str(request.json.get("text", "")) if not 1 <= len(text) <= 280: return {"error": "text: 1 to 280 characters"}, 422 # the agent gets this status and this JSON note = notes.update(g.allowedby.human_id, note_id, text) return note or ({"error": "no such note"}, 404) ``` ## JavaScript ```js routes.push(route("PUT", "/notes/{id}", "notes:write", { class: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: { text: "1 to 280 characters" }, })); api.put("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by const text = String(req.body?.text ?? ""); const length = [...text].length; // characters, not UTF-16 units: an emoji counts as one if (length < 1 || length > 280) { return res.status(422).json({ error: "text: 1 to 280 characters" }); // the agent gets this status and this JSON } const note = notes.update(person, req.params.id, text); if (!note) return res.status(404).json({ error: "no such note" }); res.json(note); }); ``` ## Go ```go routes = append(routes, allowedby.Route{Method: "PUT", Path: "/notes/{id}", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:{id}", Summary: "Change a note", Body: map[string]string{"text": "1 to 280 characters"}}) mux.HandleFunc("PUT /notes/{id}", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for if !ok { writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"}) return } var input struct{ Text string } err := json.NewDecoder(r.Body).Decode(&input) if n := utf8.RuneCountInString(input.Text); err != nil || n < 1 || n > 280 { // the agent gets this status and this JSON writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "text: 1 to 280 characters"}) return } note, found := notes.Update(me, r.PathValue("id"), input.Text) if !found { writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"}) return } writeJSON(w, http.StatusOK, note) }) ``` ## Java ```java @Bean AllowedByCustomizer refuse() { return aby -> aby.route(Route.put("/notes/{id}").capability("notes:write").actionClass(ActionClass.WRITE) .level(1).resource("note:{id}").summary("Change a note").body(Map.of("text", "1 to 280 characters"))); } @PutMapping("/notes/{id}") ResponseEntity changeNote(@AllowedByContext Context ctx, @PathVariable String id, @RequestBody NoteInput input) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } String text = input.text() == null ? "" : input.text(); int length = text.codePointCount(0, text.length()); // characters: an emoji counts as one if (length < 1 || length > 280) { // the agent gets this status and this JSON return ResponseEntity.status(422).body(Map.of("error", "text: 1 to 280 characters")); } return notes.update(person, id, text).>map(ResponseEntity::ok) .orElse(ResponseEntity.status(404).body(Map.of("error", "no such note"))); } ``` ## C# ```dotnet routes.Add(Route("PUT", "/notes/{id}", "notes:write", cls: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: new Dictionary { ["text"] = "1 to 280 characters" })); app.MapPut("/notes/{id}", (string id, NoteInput input, AllowedByContext ctx) => { var text = input.Text ?? ""; if (text.EnumerateRunes().Count() is < 1 or > 280) // characters: an emoji counts as one { return Results.Json(new { error = "text: 1 to 280 characters" }, statusCode: 422); // the agent gets this } return notes.Update(Person(ctx), id, text) is { } note ? Results.Json(note) : Results.Json(new { error = "no such note" }, statusCode: 404); }); ``` ## PHP ```php $routes[] = route('PUT', '/notes/{id}', 'notes:write', class: 'write', level: 1, resource: 'note:{id}', summary: 'Change a note', body: ['text' => '1 to 280 characters']); $app->put('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'); $text = (string) (json_decode((string) $request->getBody(), true)['text'] ?? ''); if (1 !== preg_match('/\A.{1,280}\z/su', $text)) { return $json($response, ['error' => 'text: 1 to 280 characters'], 422); // the agent gets this status and this JSON } $note = $notes->update($person, $args['id'], $text); return null === $note ? $json($response, ['error' => 'no such note'], 404) : $json($response, $note); }); ``` ## Ruby ```ruby ROUTES << AllowedBy.route( "PUT", "/notes/{id}", "notes:write", class: "write", level: 1, resource: "note:{id}", summary: "Change a note", body: { text: "1 to 280 characters" } ) put "/notes/:id" do text = JSON.parse(request.body.read)["text"].to_s # the agent gets this status and this JSON halt 422, { error: "text: 1 to 280 characters" }.to_json unless text.length.between?(1, 280) person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json note = notes.update(person, params["id"], text) halt 404, { error: "no such note" }.to_json unless note note.to_json end ``` ## Rust ```rust let aby = aby.route( Route::put("/notes/{id}") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:{id}") .summary("Change a note") .body_field("text", "1 to 280 characters"), ); let app = app.route("/notes/{id}", put(change_note)); async fn change_note( ctx: AllowedByContext, State(notes): State, Path(id): Path, Json(input): Json, ) -> Result, Refusal> { if !(1..=280).contains(&input.text.chars().count()) { // the agent gets this status and this JSON return Err((StatusCode::UNPROCESSABLE_ENTITY, Json(json!({"error": "text: 1 to 280 characters"})))); } let note = notes.update(&ctx.human_id, &id, &input.text); note.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))) } ``` --- Source: https://docs.allowedby.com/recipes/mandate # Sell to a company An employee approves for their company, within the mandate it gave them. **Python only today.** | | | |---|---| | Level | 2: A person whose identity is verified approves with a passkey. | | Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. | ## What the test proves - an employee approves for her company, within the mandate it gave her; the app sees the company: 201 - over her mandate (500 EUR), she cannot approve: refused - someone the company gave no mandate cannot approve: refused ## Python ```python routes.append(route("POST", "/t/{tenant}/purchases", "purchases:make", cls="write-hard", level=2, mandate=True, resource="tenant:{tenant}:purchase:new", amount_field="/total", summary="Buy for your company", body={"total": "a decimal string, e.g. 300.00", "currency": "e.g. EUR"})) templates["purchases:make"] = "Buy for {amount.max} {amount.currency}" tenants["initech"] = {"name": "Initech", "org": os.environ["INITECH"], "routes": {}} # the company's own site @app.post("/t//purchases") def purchase(tenant): # The person acts for the company, within the mandate it gave them. return {"bought": request.json["total"], "for": g.allowedby.acting_for["name"]}, 201 ``` --- Source: https://docs.allowedby.com/recipes/personal-data # Ask for personal data The person shares what they choose, encrypted to your app. The agent never sees it. **Python only today.** | | | |---|---| | Level | 2: A person whose identity is verified approves with a passkey. | | Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. | ## What the test proves - the person sees what is asked and for how long, shares both, and the app gets them: 201 - the agent never sees the data: only its hash is in the approval it carries - what is optional stays private unless the person says so: 201 without it ## Python ```python routes.append(route("POST", "/tickets", "tickets:buy", cls="write-hard", level=2, resource="ticket:new", disclose=["legal_name"], disclose_optional=["email"], summary="Buy a ticket in the person's name")) templates["tickets:buy"] = "Buy a ticket in your name" settings["disclosure"] = { # why you ask and how long you keep it: the person reads this before sharing "legal_name": {"purpose": {"en": "The name on the ticket"}, "retention_days": 30}, "email": {"purpose": {"en": "To send you the ticket"}, "retention_days": 30}, } @app.post("/tickets") def buy_ticket(): # Sent to your app encrypted, by the person's node. The agent never sees it. person = app.extensions["allowedby"].personal_data(g.allowedby) return {"ticket": "T-1", "named": "legal_name" in person, "emailed": "email" in person}, 201 ``` --- Source: https://docs.allowedby.com/recipes/tenants # Serve several customers Each customer account has its own approvals, and can tighten your rules. **Python only today.** | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `write`: Something changes and can be undone. The approval can be reused. | ## What the test proves - the person approves for one customer's account: 201 - that approval does not work on another customer's account - a customer's own ceiling (50 EUR) holds whatever the person approved ## Python ```python routes.append(route("POST", "/t/{tenant}/orders", "orders:place", cls="write", level=1, resource="tenant:{tenant}:order:new", amount_field="/total", summary="Order for a customer account", body={"total": "a decimal string, e.g. 60.00", "currency": "e.g. EUR"})) templates["orders:place"] = "Order for up to {amount.max} {amount.currency} on {scope}" tenants["umbrella"] = {"name": "Umbrella", "routes": {}} tenants["hooli"] = {"name": "Hooli", "routes": {"orders:place": {"amount_max": "50.00"}}} # can only tighten your rules @app.post("/t//orders") def place_order(tenant): # An approval for one customer's account never works on another's. if tenant not in tenants: return {"error": "no such customer"}, 404 return {"ordered": request.json["total"], "account": g.allowedby.tenant}, 201 ``` --- Source: https://docs.allowedby.com/recipes/two-approvers # Require two people Two people of a group approve the same action, each with their own passkey. **Python only today.** | | | |---|---| | Level | 2: A person whose identity is verified approves with a passkey. | | Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. | ## What the test proves - the first approval is not enough: it waits for a second person of the group - someone outside the group, or the first person again, cannot be the second: 403 - the second person approves the same wire with their passkey: 201 - both approvals are for that one wire ## Python ```python routes.append(route("POST", "/wires", "wires:send", cls="write-hard", level=2, authority=True, resource="wire:new", amount_field="/amount", summary="Wire money", body={"amount": "a decimal string, e.g. 9000.00", "currency": "e.g. EUR"})) templates["wires:send"] = "Wire {amount.max} {amount.currency}" settings["authority_policy"] = { "groups": {"finance": os.environ["FINANCE"].split(",")}, # the human_id of each member "rules": [{"cap": "wires:send", "group": "finance", "quorum": 2}], } @app.post("/wires") def wire(): # Two people of the group approved this same wire, each with their own passkey. return {"wired": request.json["amount"], "currency": request.json["currency"]}, 201 ``` --- Source: https://docs.allowedby.com/recipes/test # Test your app Run your app's tests without a browser, a phone or a node. | | | |---|---| | Level | 1: A person approves with a passkey. | | Class | `read`: Nothing changes. The approval can be reused until it ends or the person withdraws it. | ## What the test proves - the app's tests pass without a browser ## Python ```python from app import app client = app.test_client() def test_a_request_without_a_passport_is_refused(): r = client.get("/notes") assert r.status_code == 401 assert r.json["type"] == "https://allowedby.org/errors/passport_required" def test_agents_see_the_sentence_the_person_approves(): r = client.get("/.well-known/allowedby") assert r.json["templates"]["notes:read"]["summary"]["en"] == "Read your notes" def test_deleting_needs_an_approval_of_that_exact_request(): r = client.get("/openapi.json") assert r.json["paths"]["/notes/{id}"]["delete"]["x-allowedby"]["class"] == "write-hard" ``` ## JavaScript ```js import assert from "node:assert/strict"; import { test } from "node:test"; import { AllowedBy } from "@allowedby/sdk"; import { TestNode } from "@allowedby/sdk/testing"; import { routes, templates } from "./app.mjs"; const origin = "https://notes.example"; const node = await TestNode.create(); // a node in memory, whose people approve on demand const aby = new AllowedBy({ origin, node: node.origin, fetch: node.fetch, autoRefresh: false, org: { legal_name: "Notes Ltd", country: "FR" }, routes, templates, }); await aby.refresh(); const agent = await node.agent(); test("an agent the person did not approve is refused", async () => { const headers = await agent.sign("GET", `${origin}/notes`); const { refusal } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(refusal.status, 401); assert.match(refusal.headers["WWW-Authenticate"], /error="grant_required"/); }); test("an approved agent is accepted, and the app knows the person", async () => { const capabilities = [{ cap: "notes:read", constraints: { scope: "note:*" } }]; const grant = await node.grant(agent, { audience: origin, capabilities }); const headers = await agent.sign("GET", `${origin}/notes`, { allowedBy: grant }); const { context } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(context.humanId, await node.humanId(origin)); }); ``` ## Go ```go import ( "context" "net/http/httptest" "testing" "github.com/yannUpTo/allowedby/sdks/go/allowedbytest" ) const origin = "https://notes.example" func TestNotes(t *testing.T) { node := allowedbytest.NewNode(t) // a node on a local test server, whose people approve on demand aby, app, err := newApp(origin, node.URL()) if err != nil { t.Fatal(err) } defer aby.Close() if err := aby.Refresh(context.Background()); err != nil { t.Fatal(err) } agent := node.NewAgent() // An agent the person did not approve is refused. res := httptest.NewRecorder() app.ServeHTTP(res, agent.Request("GET", origin+"/notes", nil, agent.Passport)) if res.Code != 401 { t.Fatalf("without an approval: %d", res.Code) } // An approved agent gets the person's notes. grant := node.Grant(agent, allowedbytest.GrantSpec{Origin: origin, Capability: "notes:read", Scope: "note:*", Class: "read", Level: 1}) res = httptest.NewRecorder() app.ServeHTTP(res, agent.Request("GET", origin+"/notes", nil, grant)) if res.Code != 200 { t.Fatalf("with an approval: %d %s", res.Code, res.Body) } } ``` ## Java ```java class NotesAppTest { static final String ORIGIN = "https://notes.example"; static TestNode node; // a node on a local port, whose people approve on demand static AllowedBy aby; @BeforeAll static void start() throws Exception { node = TestNode.start(); AllowedBy.Builder builder = AllowedBy.builder().origin(ORIGIN).node(node.origin).org("Notes Ltd", "FR"); new NotesApp().read().customize(builder); // the app's own route and template aby = builder.build(); aby.refresh(); } @Test void anAgentThePersonDidNotApproveIsRefused() { TestNode.Agent agent = node.agent(); Map headers = agent.sign("GET", ORIGIN + "/notes", agent.passport, null); Outcome outcome = aby.process(Request.of("GET", "/notes", null, headers, null)); assertEquals(401, outcome.getResponse().getStatus()); } @Test void anApprovedAgentIsAccepted() { TestNode.Agent agent = node.agent(); String grant = node.grant(agent, ORIGIN).cap("notes:read", Map.of("scope", "note:*")).build(); Map headers = agent.sign("GET", ORIGIN + "/notes", grant, null); Outcome outcome = aby.process(Request.of("GET", "/notes", null, headers, null)); assertTrue(outcome.isAllowed()); } @AfterAll static void stop() { aby.close(); node.close(); } } ``` ## C# ```dotnet using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; public sealed class NotesTests(WebApplicationFactory app) : IClassFixture> { [Fact] public async Task A_request_without_a_passport_is_refused() { var response = await app.CreateClient().GetAsync("/notes"); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Contains("passport_required", response.Headers.WwwAuthenticate.ToString()); } [Fact] public async Task Agents_see_the_sentence_the_person_approves() { var json = await app.CreateClient().GetStringAsync("/.well-known/allowedby"); using var discovery = JsonDocument.Parse(json); var sentence = discovery.RootElement.GetProperty("templates").GetProperty("notes:read").GetProperty("summary"); Assert.Equal("Read your notes", sentence.GetProperty("en").GetString()); } } ``` ## PHP ```php use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Slim\Psr7\Factory\ServerRequestFactory; final class AppTest extends TestCase { public function testARequestWithoutAPassportIsRefused(): void { $response = $this->get('/notes'); self::assertSame(401, $response->getStatusCode()); self::assertStringContainsString('passport_required', $response->getHeaderLine('WWW-Authenticate')); } public function testAgentsSeeTheSentenceThePersonApproves(): void { $discovery = json_decode((string) $this->get('/.well-known/allowedby')->getBody(), true); self::assertSame('Read your notes', $discovery['templates']['notes:read']['summary']['en']); } private function get(string $path): ResponseInterface { $app = require __DIR__.'/../app.php'; return $app->handle((new ServerRequestFactory())->createServerRequest('GET', $path)); } } ``` ## Ruby ```ruby require "minitest/autorun" require "allowedby/testing" require_relative "app" class NotesTest < Minitest::Test ORIGIN = "https://notes.example" def setup @node = AllowedBy::Testing::Node.new # a node in memory, whose people approve on demand @aby = AllowedBy.new( origin: ORIGIN, node: @node.origin, http: @node, start: false, org: { legal_name: "Notes Ltd", country: "FR" }, routes: ROUTES, templates: TEMPLATES ) @aby.verifier.refresh @agent = @node.agent end def test_an_agent_the_person_did_not_approve_is_refused _, (status, headers) = @aby.check("GET", "/notes", @agent.headers("GET", "#{ORIGIN}/notes")) assert_equal 401, status assert_match(/error="grant_required"/, headers["www-authenticate"]) end def test_an_approved_agent_is_accepted_and_the_app_knows_the_person capabilities = [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }] grant = @node.grant(@agent, audience: ORIGIN, capabilities: capabilities) context, = @aby.check("GET", "/notes", @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant)) assert_equal @node.human_id(ORIGIN), context.human_id end end ``` ## Rust ```rust #[cfg(test)] mod tests { use super::*; use allowedby::{Outcome, Request}; fn service() -> Service { let (aby, _) = notes_app("https://notes.example", "https://node.example.org"); Service::new(aby.background_refresh(false)).expect("a valid configuration") } #[test] fn a_request_without_a_passport_is_refused() { let Outcome::Respond(refusal) = service().handle(&Request::new("GET", "/notes")) else { panic!("accepted"); }; assert_eq!(refusal.status, 401); assert!(refusal.header("WWW-Authenticate").is_some_and(|h| h.contains("passport_required"))); } #[test] fn agents_see_the_sentence_the_person_approves() { let discovery = service().well_known(); assert_eq!(discovery["templates"]["notes:read"]["summary"]["en"], "Read your notes"); } } ``` --- Source: https://docs.allowedby.com/guides/accept-agents # Deploy AllowedBy in your SaaS app For SaaS and API teams (the relying party) who want AI agents to call their API on behalf of a person, with that person's approval. You add the Python SDK to your app, describe your routes, and the SDK verifies every agent request offline. This guide is complete on its own. It describes the code in this repository (`sdks/python/src/allowedby/sdk.py`, specs 0.2.14-draft). --- ## 1. What you get - **Verification on every request.** Each agent request carries the agent's passport, the person's signed approval (the *grant*) and a proof for this exact request. The SDK checks all three offline, in about a millisecond. It makes no network call on the request path. - **The approval flow.** When the person's yes is missing, the SDK answers `401` with an `AllowedBy` challenge. The agent asks its node, the person taps a passkey on the node's approval page, and the agent retries. For serious actions (`write-hard`, `irreversible`) your app creates the approval itself, bound to the exact request and usable once. - **Levels per route.** You choose the assurance level for each route: | Level | Meaning | |---|---| | L0 | The agent's passport only. No person approves. | | L1 | The person taps a passkey. | | L2 | The person's legal identity was verified (eIDAS substantial). | | L3 | Verified at eIDAS high, on a hardware passkey. | - **Optional:** personal data with consent and a stated purpose, customers (tenants) with their own rules and budgets, company mandates, account linking. - **Published descriptions:** `/.well-known/allowedby`, `/openapi.json` (OpenAPI 3.1) and `/.well-known/api-catalog` (RFC 9727). An agent given only your address can find every operation. - **An admin console** at `/allowedby/admin`. You never handle passwords, API keys or OAuth tokens for agents. The person never gives the agent personal data. ## 2. Prerequisites - Your API served over **https** in production. - **Python 3.10+**. - The **`cryptography`** package. It is the SDK's only dependency. - A **node** you trust. The node issues agent passports, runs the approval page and countersigns grants (section 7). ## 3. Install the SDK The SDK is the `allowedby` package in `sdks/python/` (guide: `docs/sdk/python.md`). It is not published on PyPI yet: install it from a clone of this repository. ```bash pip install "./sdks/python" # from a clone of this repository (not on PyPI yet) ``` Then import it: ```python from allowedby import AllowedBy, SqliteStore, route ``` ## 4. Describe your routes Converting an API you already have? [Convert an existing API](https://docs.allowedby.com/guides/convert-an-api) sorts your endpoints first: which ones agents may call, their class and level, what to reshape, where the middleware goes and where it must not. One line per route. Each line gives the **capability** (`namespace:action`), its **class**, the **level** you require and the **resource** it acts on. ```python routes = [ route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}", summary="Delete a note"), ] ``` | Argument | Meaning | Default | |---|---|---| | `capability` | What the person allows, `namespace:action`. Leave it out (with `level=0`) for routes where the agent's passport is enough. | none | | `cls` | `read` (no visible change), `write` (reversible), `write-hard` (hard to undo, or visible to others), `irreversible` (payments, contracts, deletions). For `write-hard` and `irreversible`, the SDK creates the approval, bound to that exact request, used once. For payments, `cls` can be a list of amount thresholds: `[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]`, read at `amount_field`. | `read` | | `level` | 0, 1, 2 or 3 (table above). | `1` | | `resource` | The resource id, with `{param}` from the path. `note:{id}` means "this note". The person may widen it to `note:*` on the approval page. | `:*` | | `amount_field` | JSON Pointer to an amount in the body, e.g. `/total`. Approvals then carry a limit per call, day, week, month or in total. | none | | `authn` | `"hardware"` refuses synced passkeys. | any | | `mandate` | `True`: the person must approve **for their company**, under a mandate the company signed. | `False` | | `disclose`, `disclose_optional` | Personal data this route needs (section 9). | none | | `summary`, `body` | What the route does and each JSON body member. They go into `/openapi.json`. | none | | `max_lifetime` | Seconds an approval for this route may last, at most 30 days. | class default | | `require_link` | The person's account must be linked first (`aby:link`). | `False` | | `nonce` | Require an `AllowedBy-Nonce` on this route. | `False` | | `qes`, `authority`, `tier` | Qualified signature, co-approvers under an authority policy, minimum custody tier of the agent. Advanced; see the specs. | off | ### The sentence the person reads The person signs exactly this sentence. Only you write it, and it may use only values the approval enforces: ```python templates = { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}", } ``` Allowed placeholders: `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{count.max}`, `{fields}`. No free text from the agent. For several languages, use the long form: ```python templates["notes:read"] = {"summary": {"en": "Read your notes", "fr": "Lire vos notes"}, "lines": {"en": "Read your notes", "fr": "Lire vos notes"}} ``` ### Example route map | Route | Capability | Class | Level | Sentence | |---|---|---|---|---| | `GET /me` | none | read | 0 | none (agent only) | | `GET /notes` | `notes:read` | read | 1 | "Read your notes" | | `POST /notes` | `notes:write` | write | 1 | "Write new notes" | | `DELETE /notes/{id}` | `notes:delete` | write-hard | 2 | "Delete note {scope}" | | `POST /t/{tenant}/invoices/{id}/approve` | `invoices:approve` | write-hard | 2 | your sentence with `{amount.max} {amount.currency}` | | `POST /contracts/{id}/sign` | `contracts:sign` | irreversible | 2 or 3 | your sentence | The SDK also adds one route itself: `POST /allowedby/link` (`aby:link`, level 1) for account linking. ## 5. Wrap your app ```python aby = AllowedBy( origin=os.environ["ALLOWEDBY_ORIGIN"], # your public origin, https in production; no default: it fails to start node=os.environ["ALLOWEDBY_NODE"], # the node you trust, never guessed org={"legal_name": "Notes Ltd", "country": "FR"}, # country: ISO 3166-1 alpha-2 routes=routes, templates=templates, admin_token=os.environ["ALLOWEDBY_ADMIN_TOKEN"], # from your secret manager (section 11) title="Notes API", version="1.0.0", description="Notes for people and their agents", **options) # tenants, disclosure and store: sections 8, 9 and 12 ``` The wrapper: 1. serves its own endpoints: `/.well-known/allowedby`, `/.well-known/allowedby/tenants/`, `/openapi.json`, `/.well-known/api-catalog`, `/allowedby/callback`, `/allowedby/link`, `/allowedby/admin`, `/allowedby/admin/api*`; 2. checks every request whose method and path are in your route map, and answers `401`, `403`, `429` or `503` itself when needed; 3. calls your app only when the request is allowed. Paths outside the route map reach your app unchanged, with your own authentication. A path that only looks like a protected route is refused with 400, as a lenient router could run the protected handler for it: a variant (`/notes.json` next to `/notes`), or a longer path (`GET /notes/7/comments` next to `GET /notes/{id}`). Declare such pages of your own with `AllowedBy(..., unprotected=["/notes.json", ("GET", "/notes/{id}/comments")])`: exact paths, or templates with their method. With Flask, Django, Starlette and FastAPI a declared page never runs a protected handler, and one that differs from a protected route by its last `/` only (`/notes/new/` next to `/notes/{id}`) works. A bare WSGI or ASGI app passes a declared page to your app as it is, so no wildcard route of a protected handler may reach it, and a page that differs by its last `/` stays refused ([Python guide](https://docs.allowedby.com/sdk/python)). With Flask, Django, Starlette and FastAPI the handler of a protected route runs only for that route, whatever the path (an alias, a catch-all). A bare WSGI or ASGI app cannot tell: next to a protected route that ends in a word (`DELETE /notes/{id}/archive`), a catch-all of yours that also takes longer paths runs `DELETE /notes/7/archive/x` without a check. ### Plain WSGI ```python app = aby.wsgi(notes_app) ``` In your handler, read `environ["allowedby.context"]`. The whole app is `sdks/python/examples/frameworks/wsgi/app.py`. ### Frameworks | Framework | One line | Context | |---|---|---| | FastAPI | `allowedby.fastapi.install(app, aby)` | `Depends(allowedby_context)` | | Starlette, any ASGI app | `AllowedByMiddleware(app, aby)` | `request.state.allowedby` | | Flask | `allowedby.flask.AllowedBy(app, aby)` | `g.allowedby` | | Django | `"allowedby.django.AllowedByMiddleware"` and `settings.ALLOWEDBY` | `request.allowedby` | Whole apps: [the Python guide](https://docs.allowedby.com/sdk/python#framework-recipes). Each one is run against a real node, an agent and a person in CI. ### Use the context `ctx` is already verified: | Field | Meaning | |---|---| | `ctx.human_id` | The person, as a pseudonymous id: stable for your app, different in every app. Use it as the data owner, or link it to your account once (section 8). `None` on level 0 routes: never keep or read data under `None` or `""`, as every anonymous agent would share it. | | `ctx.level` | The level reached: 0 to 3. At 0 the request carries the agent's passport only: there is no person, and `ctx.human_id` is `None`. A handler that keeps one person's data refuses a request without a person, or keeps nothing for it. | | `ctx.agent`, `ctx.operator` | The agent's id and the company that runs it. | | `ctx.capabilities`, `ctx.display` | What was allowed, and the exact sentence the person signed. | | `ctx.gid`, `ctx.rev` | The approval id and its revision. Put them in your audit log. | | `ctx.acting_for` | `{"org", "name", "role"}` when the person approved for their company. | | `ctx.tenant` | Your customer, when the path has `{tenant}`. | If your handler refuses a request the SDK accepted (unknown invoice, wrong total), call `aby.refund(ctx)` so the tenant budget is given back. ## 6. Publish your discovery documents The wrapper serves these for you. Check that your reverse proxy forwards them and does not require your own authentication on them. | Address | What it is | |---|---| | `/.well-known/allowedby` | Capabilities, sentences, your signing key, your signed company profile, the disclosure key, links to `openapi` and `/allowedby/link`. Also sends an RFC 8631 `Link` header. Answers `GET` and `HEAD`. | | `/openapi.json` | OpenAPI 3.1 built from the route map. Each operation names its capability in `security` (`AllowedBy: ["notes:write"]`) and its level, class and amount field in `x-allowedby`. Served with `Access-Control-Allow-Origin: *`. | | `/.well-known/api-catalog` | RFC 9727 catalog that points to `/openapi.json` and `/.well-known/allowedby`. | | `/.well-known/allowedby/tenants/` | A tenant's signed authority policy, when it has one. | Check them after each deploy: ```bash curl -sS "$ORIGIN/.well-known/allowedby" | python -m json.tool curl -sS "$ORIGIN/openapi.json" | python -m json.tool curl -sSI "$ORIGIN/.well-known/api-catalog" ``` ## 7. Which node to trust The `node=` argument names the one node you trust. The SDK fetches its statement and keys and pins the node key on first fetch (trust on first use). It refreshes the node's revocation status list in the background (at most every 60 s). `node_max_level=` (default 3) caps the level you accept from that node. For a stricter setup, pass a signed trust list instead: `trust_list=verifier.TrustList(jws, key)` (OAID-5), where `key` is the public JWK you signed the list with. The trust list then replaces `node=` as the source of trusted nodes. **The hosted node** is https://demo.allowedby.com. It approves for its own demo sites (`https://NAME.demo.allowedby.com`) and for the services onboarded on it: their origins are listed in the node's `ALLOWEDBY_AUDIENCES`. Any other service gets `400 this demo node only approves for its own demo sites`. To onboard your app, send your production origin (for example `https://app.example.com`) to the node operator; it is added to that list and the node restarts. To run your own node, see the settings below. **How a node is configured.** A node is started by `demo/run.py`. The settings that matter to you: | Env var / flag | Effect | |---|---| | `--domain` / `ALLOWEDBY_DOMAIN` | Hosted mode: the node at `https://DOMAIN`, the example sites at `https://NAME.DOMAIN`. | | `ALLOWEDBY_ABOUT_DOMAIN` | Optional host name that also serves the presentation site at its root. Must not be a demo site's host name. | | `ALLOWEDBY_DOCS_DOMAIN` | Optional host name that serves the documentation, its live runs and its MCP endpoint. Must not be a demo site's or the presentation site's. | | `ALLOWEDBY_LIVE` | `off` closes the documentation's live runs. | | `ALLOWEDBY_ADMIN_TOKEN` | Required in hosted mode. Every console token is derived from it. | | `ALLOWEDBY_AUDIENCES` | Comma-separated origins of the services this hosted node approves for, besides its demo sites. `*` allows any https service. | | `ALLOWEDBY_MDS_ROOT` | PEM file of the pinned GlobalSign Root CA - R3. The node then fetches the FIDO MDS3 BLOB at start, verifies it, and caches it in its data folder: this is how passkeys are graded `hardware` in production. Fetching the BLOB means the node operator accepts the FIDO Alliance MDS terms. If the BLOB cannot be loaded, the node logs it and level 3 is unavailable (fail closed). | | `ALLOWEDBY_PASSKEY_ROOTS` | Local alternative to MDS3 for tests: JSON file `{aaguid: [root PEM]}` of authenticators that prove a hardware key. Without MDS3 or this file no passkey reaches L3. | | `ALLOWEDBY_SIGNICAT_DOMAIN`, `ALLOWEDBY_SIGNICAT_CLIENT_ID`, `ALLOWEDBY_SIGNICAT_CLIENT_SECRET` | Signicat eID Hub: national eIDs (OIDC). | | `ALLOWEDBY_SIGNICAT_NOTIFIED` | JSON file `{idp: {"country": "BE", "notified_loa": "high", "when": {claim: value}}}` from the Commission's list of notified schemes. A list of variants is allowed; `when` matches claims of the ID token, for eIDs whose `idp` also covers a non-notified variant (Norwegian BankID biometric, ID Austria basic). An eID not listed gives level 2 at most. The repository ships `demo/trust/signicat-notified.json`, with the source of each entry. | | `ALLOWEDBY_ASSURE_CLIENT_ID`, `ALLOWEDBY_ASSURE_CLIENT_SECRET` | Signicat Assure (ReadID + iProov): passport and ID-card chip with liveness. | | `ALLOWEDBY_ASSURE_LIVENESS` | `substantial` (default) or `high`. Use `high` only with the liveness certificate on file. | | `ALLOWEDBY_CSCA` | PEM file of CSCA certificates: the node re-checks chip data itself, as a shadow. | | `ALLOWEDBY_CROSSCHECK` | `log` (default) or `refuse` when the shadow check disagrees. | The redirect URI to register at Signicat is `/verify/return`. With no Signicat variable set, the node offers only its simulated identity provider. What the node grants, from Signicat results (`allowedby/idsources.py`): | Source | Level | |---|---| | National eID, notified at high, login at high | L3 (with a hardware passkey) | | National eID, substantial or high, notified | L2 | | Passport/ID chip + liveness `high` + chip authentication | L3 (with a hardware passkey) | | Passport/ID chip + liveness `substantial` | L2 | | Chip without liveness | none | ## 8. Tenants (multi-tenant SaaS) Put the tenant in the path and at the start of the resource. Each tenant can only **tighten** your rules, and may have budgets: ```python routes.append( route("POST", "/t/{tenant}/invoices/{id}/approve", "invoices:approve", cls="write-hard", level=2, resource="tenant:{tenant}:invoice:{id}", amount_field="/total", summary="Approve an invoice", body={"total": "invoice total", "currency": "EUR"})) templates["invoices:approve"] = "Approve {scope}, up to {amount.max} {amount.currency}" options["tenants"] = { "initech": {"name": "Initech SA", "org": os.environ.get("INITECH", "https://initech.example"), # who signs its staff's mandates "routes": {"invoices:approve": {"mandate": True, "level": 2}}, "budgets": {"invoices:approve": {"max": "6000.00", "currency": "EUR", "per": "month"}}}, } ``` - Because the tenant starts the resource id, an approval for one customer never works for another. - A tenant's `routes` override your route for one capability, and can only tighten it: - `level` and `authn` (the stricter one counts); - `mandate`, `qes`, `authority` and `require_link`; - a shorter `max_lifetime`, a lower `amount_max`; - `operators`, the agent operators allowed. `"members_only": True` with `org` needs a mandate from that organisation on every route of the tenant. Any other key, or a value of another shape, stops the app at start: a misspelt override would leave the route as loose as yours. - A budget, `{"max", "currency", "per": "day" | "week" | "month", "tz"}` (`tz` defaults to UTC), counts the amounts the SDK accepts on that capability, per calendar period: - Its route needs `amount_field`. - When the budget is used up, the SDK answers `403 budget_exceeded` before anyone is asked. It does the same for a request without an amount in the budget's currency, since amounts are never converted. - The count is kept in the verifier's store: give every instance the same `store` so they share it. - A tenant may carry its own authority policy under `"authority"`. The SDK signs it and publishes it at `/.well-known/allowedby/tenants/`. Your config is the source of truth: edit a policy there and redeploy, and it applies on the new instances, with nothing else to do; the instances of one config share one signed policy through the verifier's store, and old and new instances of a rolling deploy each keep their own. `aby.set_authority_policy(policy, tenant=None)` overrides yours, or a tenant's, while the app runs (`policy=None` leaves a tenant with no policy of its own), and `aby.revert_authority_policy(tenant=None)` removes the override. The instance that calls it holds it at once, every other instance that shares the store at its next refresh, within `refresh_seconds`, and it outlives restarts: approvals made under the old policy stop working everywhere within the refresh interval. To take control back from an override through your config, raise its revision, `authority_policy_revision=` for yours or `"authority_policy_revision"` in the tenant for a tenant's (both 0 by default): the config wins over an override set at a lower revision. The log says, at start, which one applies and why. A store that every instance shares (Redis, or SQLite on one machine), and a `key_file` they share, are what make it shared: a store of your own without `put_doc` and `get_doc` keeps policies per instance (the log says so once), and without a `key_file` a run-time change stays on the instance that made it and is lost on restart (the log says so at the first one). A policy is signed for 365 days and renewed by the SDK past half of that, the approvals made under the one it replaced staying valid, so it never lapses while the app runs or restarts. - Tenants are edited live in the admin console. **Account linking.** When agents act on accounts shared by several people, link the person to your account first. Your signed-in account page calls `aby.link_start(account)` and shows the code. The person gives the code to their agent, which sends it to `POST /allowedby/link`. Pass `require_link=("write-hard", "irreversible")` to `AllowedBy` to require it on those classes, and `link_authorize(account, route, params)` for your own check. When you delete an account, or the person asks to be forgotten, call `aby.unlink(account)`: the person links again with a new code. Users who sign in through Auth0, Okta, Cognito or another provider: read [Apps that use a sign-in provider](https://docs.allowedby.com/guides/existing-sign-in) for what changes, and how to keep the links in your database. ## 9. Personal data, purpose and the disclosure key A grant carries no name, email or phone. To get them, declare each attribute with a purpose and a retention period, then name them on the routes that need them: ```python options["disclosure"] = { "legal_name": {"purpose": {"en": "Name on the signed contract"}, "retention_days": 3650}, "email": {"purpose": {"en": "Send you the receipt"}, "retention_days": 365}, } routes.append( route("POST", "/contracts/{id}/sign", "contracts:sign", cls="irreversible", level=2, resource="contract:{id}", disclose=["legal_name"], disclose_optional=["email"])) templates["contracts:sign"] = "Sign {scope}" ``` How it works: 1. The SDK publishes `disclosure` and a `disclosure_key` (public encryption key) in `/.well-known/allowedby`. 2. The approval page shows each attribute, its purpose and how long you keep it. Optional ones start unticked. 3. The node encrypts what the person chooses to your `disclosure_key` (JWE, ECDH-ES+A256KW, A256GCM) and posts it to `/allowedby/callback`, signed, before the agent retries. 4. You read it in the handler: ```python who = aby.personal_data(ctx) # {"legal_name": "Claire Martin", "email": "..."} or {} ``` The agent never sees it. | Available from | Attributes | |---|---| | L1 | `email`, `phone` | | L2 | `legal_name`, `given_name`, `family_name`, `birth_date`, `age_over_18` (`age_over_13` to `age_over_99`), `nationality`, `address`, `verified_by` | Ask for `age_over_18` rather than `birth_date` when that is enough. Store what you receive under the retention you declared, and delete it on time. ## 10. Company mandates and budgets With `mandate=True` on a route, or on a tenant's route, the person must approve **for their company**. The company's organisation node gives them a mandate: signed by the company, tied to their passkey, at most 30 days, optionally capped (for example "invoices up to 10,000 EUR"). The SDK checks it offline against the keys the company publishes at its `org` origin (`https:///.well-known/allowedby`). You get: ```python company = ctx.acting_for # {"org": "https://initech.example", "name": "Initech SA", "role": "Accounts clerk"} ``` (`ctx` is the context of the accepted request.) Budgets can apply at several places. You control only the first one: | Budget | Set by | Enforced by | |---|---|---| | Tenant budget per capability | You, in `tenants[...]["budgets"]` | Your SDK: `403 budget_exceeded` before anyone is asked | | Organisation, team, member, operator budgets | The company, in its organisation console | The node: Allow is disabled on the approval page | | Personal budget | The person, in their wallet | The node | | Per-approval limit (`amount_field`) | The person, on the approval page | Your SDK, on every request | ## 11. Admin console and its token `/allowedby/admin` comes with the SDK. It shows and edits: - **Overview:** requests, new people, sign-ins, approvals asked and answered, per hour or per day. - **Access rules:** each route's rule in plain words. Class, level (0–3), passkey type and mandate per route. A change applies to the next request and to what you publish. - **Tenants:** overrides and budgets, with what is used this period. - **People** and **Agents:** pseudonymous ids, first and last seen. - **Activity log:** every request, accepted or refused, with filters and CSV export. - **Personal data:** what you may ask for, what you received, and when to delete it. - **Trust and keys:** the node you trust, how fresh its revocation list is, and your signing key. **The token.** 1. Generate a long random token and keep it in your secret manager (GCP Secret Manager, AWS Secrets Manager, Vault). 2. Pass it at start: `AllowedBy(..., admin_token=os.environ["ALLOWEDBY_ADMIN_TOKEN"])`. Without it, the SDK generates a random one at each start (`aby.admin_token`); do not rely on that in production. 3. Open the console with the token in the URL fragment, which browsers never send to the server: `https://notes.example/allowedby/admin#token=...`. 4. Never log it. The API accepts it only in the `X-Admin-Token` header, never in the query string. The console API, for scripts: ```bash curl -sS "$ORIGIN/allowedby/admin/api" -H "X-Admin-Token: $TOKEN" curl -sS -X POST "$ORIGIN/allowedby/admin/api/routes" -H "X-Admin-Token: $TOKEN" -H "Content-Type: application/json" \ -d '{"index": 0, "level": 2}' curl -sS -X POST "$ORIGIN/allowedby/admin/api/tenants" -H "X-Admin-Token: $TOKEN" -H "Content-Type: application/json" \ -d '{"tenant": "initech", "capability": "invoices:approve", "budget": {"max": "8000.00", "currency": "EUR", "per": "month"}}' ``` For a SIEM, pass `audit_sink="stdout-json"` (or a callable that takes a dict) to get every decision as a JSON line. ## 12. Storage for replay and single-use state By default the SDK keeps the replay set, the single-use set and the counters in memory. That is right for **one process only**. With several workers or instances, a replayed proof or a reused one-time approval could pass on another process. Use the SQLite store, shared by every process on a machine (or on a network file system that locks), or `RedisStore`: ```python options["store"] = SqliteStore(os.environ["ALLOWEDBY_DB"]) # an absolute path all processes share: /var/lib/notes/a.db ``` Each operation is one `BEGIN IMMEDIATE` transaction in WAL mode, so check-and-set is atomic. For instances on several machines, you need the same semantics in a shared database (Redis or a database with compare-and-set). The package also has `RedisStore` (extra `redis`). **What the store does not cover today.** These stay in each process's memory: tenant budget spend, the admin console's audit and activity, received personal data, account links and pending link codes, callback replay ids, and the signing and disclosure keys (section 13). With several processes, run one process per public origin, or plan to extend these before scaling out. Other per-route protections you can turn on: `rate={"actor": (600, 60), "operator": (6000, 60)}` (requests per seconds; these are the defaults), `nonce=True` (AllowedBy-Nonce on irreversible routes), `rfc9421=True` (accept the RFC 9421 Web Bot Auth profile). ## 13. Key management and rotation The SDK holds two keys: | Key | Used for | Published in | |---|---|---| | Signing key (`aby.key`) | Signs approval requests your app creates, your company profile and authority policies | `keys` in `/.well-known/allowedby` | | Disclosure key (`aby.enc`) | Personal data is encrypted to it | `disclosure_key` in `/.well-known/allowedby` | **Keep them with `key_file=`.** Pass `AllowedBy(..., key_file="/secrets/allowedby-keys.json")`. The SDK creates the file with fresh keys on first start (mode 0600; the folder needs hard links, so that instances starting together end up with the same keys, else the start fails) and loads it afterwards, so every restart and every instance uses the same keys. Put the file on a private volume, or write it from your secret manager before the app starts. Without `key_file`, both keys are **new at each start**: - every restart publishes new keys; - personal data encrypted to the old disclosure key, and approvals your app created but that were not yet used, are lost at restart, and the agent asks again; - each process has different keys, so callbacks with personal data must reach the process that published the key the node used. To rotate, start with a new file and keep the old app instance running for a short overlap. The node's own keys are rotated through the node admin API (`/oaid/v1/admin/...`, header `X-Admin-Token`); companies rotate their mandate key in their organisation console (`/org//api/keys/rotate`, needs a second admin). ## 14. Going-live checklist Change each of these before you accept real agents. Items marked *demo* are shortcuts the hosted demo takes. | # | Change | Why | |---|---|---| | 1 | Serve over **https**. *Demo: plain http on `*.localhost`.* | Proofs bind the exact URL; the approval page needs a secure origin. | | 2 | Trust a **production node**, or your own, and have your origin onboarded on it (`ALLOWEDBY_AUDIENCES`). | Section 7. | | 3 | Keep your signing and disclosure keys across restarts and instances with `key_file=` on a private volume or from your secret manager. *Demo: generated at start.* | Section 13. | | 4 | **Share the replay set, single-use set and counters** between instances (`SqliteStore`, or a shared database with compare-and-set). *Demo: memory, or SQLite.* | Section 12. | | 5 | Keep the **admin token** in a secret manager and pass `admin_token=`. | Section 11. | | 6 | Store **received personal data** under the retention you declared, and delete it on time. | Section 9. | | 7 | **Link accounts** (`aby:link`, `require_link=`) before accepting `write-hard` or `irreversible` actions on accounts shared by several people. | Section 8. | | 8 | Have your **organisation profile verified**, with a qualified seal or by your node. *Demo: verified by a node vouch.* Until then, the approval page shows only your hostname and "organisation not verified". | Trust on the approval page. | | 9 | Make sure your node does **real identity verification** (Signicat env vars, section 7). *Demo: the "Verify" buttons are simulated; the typed name becomes the legal name.* | L2/L3 mean nothing otherwise. | | 10 | Make sure your node verifies **passkey attestation** against the FIDO Metadata Service (`ALLOWEDBY_MDS_ROOT`). *Demo: a local allowlist, `ALLOWEDBY_PASSKEY_ROOTS`.* | Without it no passkey reaches L3. | | 11 | Do not rely on **unverified email**. *Demo: the node accepts the email typed.* | Treat `email` as user-supplied. | | 12 | Expect **independent witnesses** for the node's log. *Demo: one node is home, organisation and countersigning node, with no independent witness.* | Section 7, trust lists with `witnesses_min`. | | 13 | **Agents** in production should carry tier 1+ passports (TPM, Secure Enclave, cloud KMS). *Demo: tier 0; the operator key is a file in `demo/.data/`.* Use `tier=` on routes that need it. | Custody of agent keys. | | 14 | **QES** routes need a qualified trust service provider and an EU trusted-list snapshot (`qes_trusted_list=`). *Not built in the demo.* | Otherwise `qes_required`. | | 15 | Run the **conformance vectors** (`vectors/`) against your deployment. | CONF-1. | | 16 | Check that `/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog` and `/allowedby/callback` are reachable without your own auth. | Section 6. | ## 15. Testing with an agent ### Against the hosted node (to see the flow) Until your origin is in the node's `ALLOWEDBY_AUDIENCES`, use the hosted node to see the flow on its own sites: 1. Install the agent for Claude Code: ```bash claude mcp add allowedby -- allowedby-mcp --node https://demo.allowedby.com ``` 2. Ask Claude: "Add a note 'Buy milk' on https://notes.demo.allowedby.com, then show my notes." 3. Approve on the page that opens (see `docs/deploy-user.md`). ### Against your own app (locally) The local node accepts any service. 1. Start the demo node and sites: `python demo/run.py --reset`. The node is `http://localhost`. 2. Point your app at it: `AllowedBy(origin="http://myapp.localhost", node="http://localhost", ...)`. 3. Serve your app under a `*.localhost` name next to the demo, as `demo/run.py` does with `core.serve_hosts` and `core.WsgiApp`. Or run it on its own port. 4. Call it from Python: ```python import os from allowedby import Agent agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=print) # prints the link and the code app = os.environ.get("APP_URL", "http://myapp.localhost") status, body = agent.call("POST", app + "/notes", {"text": "Buy milk"}, action="notes:write") print(status, body) ``` Or give the address to Claude with the MCP agent (default node `http://localhost`). 5. For automated tests without a browser, copy `SoftPasskey` and `Human` from `demo/e2e.py`. Run the full suite with `python demo/e2e.py`. **Agent vendors:** publish `https:///.well-known/oaid-operator` with your keys and nodes (see `demo/agent_operator.py`), and pass `operator_domain=` and `operator_key=` to `Agent`. Your agents' approvals then survive their hourly key change. Without a verified domain, the person is asked again every hour. ## 16. Troubleshooting Refusals are `application/problem+json` with `type: https://allowedby.org/errors/`. Challenges also carry `WWW-Authenticate: AllowedBy ...`. The admin console's Activity log shows the same code in plain words. | Status | Code | Meaning | What to do | |---|---|---|---| | 400 | `invalid_request` | Malformed request, or the body is not a JSON object. | Send a JSON object body. | | 401 | `passport_required` | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. | | 401 | `grant_required` | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. | | 401 | `grant_insufficient` | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. | | 401 | `level_insufficient` | The person's level is below the route's. | The person verifies their identity on the approval page. | | 401 | `mandate_required` | The route needs a company mandate, or the mandate does not cover this. | The person approves "for" their company; check the tenant's `org`. | | 401 | `expired`, `actor_expired` | The approval, or the agent's passport, expired. | The agent rebinds or asks again. | | 401 | `revoked` | The person withdrew the approval. | The agent asks again. | | 401 | `single_use_consumed` | A one-time approval was already used. | Expected on retries of a serious action. | | 401 | `class_lifetime_exceeded` | The approval lasts longer than this class allows. | Lower the requested period. | | 401 | `invalid_signature` | Bad, expired or replayed proof; tampered grant; or bad admin token. | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match `origin`). | | 401 | `untrusted_node` | The approval comes from a node you do not trust. | Check `node=` or your trust list. | | 401 | `qes_required`, `authority_required` | A qualified signature, or the organisation's co-approvers, are needed. | See the specs. | | 403 | `budget_exceeded` | A tenant budget is used up. Nobody is asked. | Raise the budget in the admin console, or wait for the next period. | | 403 | `capability_denied` | No such route, or the account refuses this operator or amount. | Check the route map. | | 403 | `tier_insufficient` | The passkey is not of the required kind (e.g. `authn="hardware"`). | The person uses a hardware passkey. | | 403 | `human_not_linked` | The route needs a linked account. | Section 8, account linking. | | 429 | `rate_limited` | Too many requests from this agent or operator. `Retry-After: 60`. | Wait, or raise `rate=`. | | 431 | `envelope_too_large` | The `Allowed-By` header is too large. | Usually a delegation chain too deep. | | 503 | `status_stale` | Your copy of the node's revocation list is too old; serious actions are paused. `Retry-After: 5`. | Check that your app can reach the node; look for `[verifier] refresh failed` in your logs. | Other common issues: - **"organisation not verified" on the approval page.** Your profile is not verified by a seal or by the node. - **`400 this demo node only approves for its own demo sites`.** Your origin is not onboarded on the node. Ask the node operator to add it to `ALLOWEDBY_AUDIENCES`, or use a local node. - **Proof fails behind a proxy.** The SDK rebuilds the URL from `origin` and the path your app sees. Make sure the proxy does not rewrite the path. - **Personal data is empty.** The callback did not reach `/allowedby/callback`, or reached another process whose disclosure key differs (section 13). ## Reference - SDK: `sdks/python/src/allowedby/sdk.py`; verifier and stores: `sdks/python/src/allowedby/verifier.py`; agent runtime: `sdks/python/src/allowedby/agent.py`. Python guide: `docs/sdk/python.md`. - Example apps: `demo/examples/notes_app.py`, `shop_app.py` (B2C), `supply_app.py` (B2B, tenants and mandates), `saas_app.py` (plans). - Walkthrough: `demo/INTEGRATE.md`. Specs: `specs/README.md`; for services read OAID-1, ABY-2, ABY-1, OAID-7 §4, OAID-5, ABY-3, and ORG-1 §2–§3. --- Source: https://docs.allowedby.com/guides/convert-an-api # Convert an existing API For a team that has an API today and wants AI agents to use it with a person's approval. This page is the method: go through your endpoints one by one and decide, for each, what agents may do and what the person approves. The code for each step is in [Accept AI agents in your app](https://docs.allowedby.com/guides/accept-agents) and in your [language guide](https://docs.allowedby.com/). ## 1. Sort every endpoint into one of three groups List your endpoints (your OpenAPI file, or your router's table) and put each one in exactly one group: | Group | What it means | In the route map | |---|---|---| | **Approved by a person** | An agent does it for someone, and that person agrees first. Most endpoints that read or change a person's data. | A line with a capability, a class and a level 1 to 3 | | **Agent identity only** | No person is involved, but you want to know which agent calls: public catalogue, search, prices, availability. | A line with no capability, `level=0` | | **Not for agents** | Agents never call it through AllowedBy (section 6). | Not in the map; keep your own authentication on it | A route of the map is for agents only: a request to it without AllowedBy headers is answered `401`. Endpoints that people's browsers or your other clients also call stay on their own paths (section 5). ## 2. Give each approved endpoint a class The class says how serious the action is. Ask one question per endpoint: **if the agent got it wrong, what would it take to undo?** | Class | When | Examples | What the SDK does | |---|---|---|---| | `read` | Nothing changes for anyone | list orders, get an invoice, download a statement, search the person's files | An approval can be reused, for up to 30 days | | `write` | A change the person can undo themselves | create a draft, add to a basket, edit a note, tag, archive | An approval can be reused, for up to 7 days | | `write-hard` | Hard to undo, or someone else sees it | send a message or an email, submit an order, publish, invite a user, approve an invoice, change who has access | Your app creates the approval for this exact request, usable once, for up to 24 hours | | `irreversible` | Cannot be undone, or has legal effect | pay, transfer, sign a contract, delete for good, close an account | Your app creates the approval for this exact request, usable once, for up to 1 hour | - **Choose by the worst case of the endpoint, not the usual one.** `PATCH /orders/{id}` that can also cancel a shipped order is `write-hard`. If one endpoint does harmless and serious things, split it (section 4). - **Money: class by amount.** One payment route can be `write-hard` up to a threshold and `irreversible` above it, read from the body: `cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]` with `amount_field="/total"`. The person can then set a limit per call, day, week, month or in total. - **Deletion:** `write` when it goes to a bin the person can restore from, `irreversible` when it is gone. - **Serious routes need a linked account.** A service MUST link the person to its own account before it accepts `write-hard` or `irreversible` approvals, and for anything several users share (ABY-3 §6). Python has `require_link=True`, but keeps the links in one process's memory: after a restart, or on another instance, those routes are refused until the person links again. The other SDKs have no linking yet. In production, build the link route and keep the links in your database ([account linking](https://docs.allowedby.com/guides/existing-sign-in#2-link-the-person-to-their-account)). - **Levels follow the class.** The specs give level 2 as the default for `write-hard` and `irreversible` (ABY-3 §4), but `route()` defaults to `level=1` for every class: write `level=2` on those routes yourself, and go lower only with a reason you can write down. ## 3. Give each endpoint a level, a capability and a resource **Level**: how sure you need to be of the person, not of the agent. | Level | Use it for | |---|---| | 0 | Agent identity only (group 2). No person. | | 1 | The person's own data and reversible actions (`read`, `write`): a passkey tap. Most routes. | | 2 | A verified legal identity: what the specs set for `write-hard` and `irreversible` (write it: `route()` defaults to 1), and anything you would ask ID for. | | 3 | A legal identity verified at the highest level, on a hardware passkey: high-value or legally binding acts. | **Capability**: `namespace:action`, what the person allows, in their words. One capability per thing a person would want to allow on its own. - **Group by what the person decides, not by HTTP method.** `GET /invoices` and `GET /invoices/{id}` are both `invoices:read`. `POST /invoices/{id}/approve` and `POST /invoices/{id}/pay` are two capabilities: people allow the first more easily than the second. - **Namespaces are your domains**: `orders`, `invoices`, `messages`, `files`. Keep them stable: approvals name them. `aby` is reserved. - **Never one capability for everything** (`api:all`). The person would approve without knowing what for. **Resource**: what the action acts on, built from the path: `invoice:{id}`, `project:{project}/file:{file}`. The person approves a scope (this invoice, or every invoice: `invoice:*`), and each request must fall inside it. - **The id must be in the path.** The resource takes `{param}` from path segments only, never from the query or the body. `GET /invoice?id=7` cannot be scoped to invoice 7: add `GET /invoices/{id}`. - **A parameter is a whole segment.** `/files/{id}` works; `/files/report-{id}.pdf` does not. - **Collections**: `GET /invoices` acts on `invoice:*`; creating one acts on a fixed name such as `invoice:new`. - **Multi-tenant**: start the path and the resource with the tenant (`/t/{tenant}/invoices/{id}`, resource `{tenant}:invoice:{id}`), so an approval for one customer never works for another ([tenants](https://docs.allowedby.com/guides/accept-agents#8-tenants-multi-tenant-saas)). **Sentence**: each capability has the sentence the person signs, written by you, with only the values the approval enforces (`{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{count.max}`, `{fields}`). If you cannot write a short, true sentence for an endpoint, it is doing too much. ## 4. Reshape what does not fit Some API designs cannot be scoped or approved as they are. Add a small agent-facing route next to them instead of weakening the check. | Your API has | Why it does not fit | Do instead | |---|---|---| | **GraphQL or JSON-RPC** on one `POST /graphql` | One route, one capability, one sentence for every query and mutation | One agent route per operation the agent needs (`GET /agent/orders`, `POST /agent/orders/{id}/cancel`), calling the same resolvers | | **Ids in the query or the body** (`?id=7`, `{"invoiceId": 7}`) | The scope cannot name the object | The id in the path | | **Batch endpoints** (`POST /invoices/batch-approve`) | One approval for many objects, one amount | One request per object, or a batch whose scope is a named container (`run:{id}`) with `amount_field` on the total | | **A `PATCH` that can do anything** | The class must be the worst case | Split: `PATCH /orders/{id}` for safe fields, `POST /orders/{id}/cancel` for the serious one | | **`GET` with side effects** (`GET /unsubscribe?...`, `GET /export` that emails) | Readers approve reads | Make it a `POST` with the right class | | **File uploads** (multipart, raw bytes) | A route of the map accepts only a JSON object body, at most 1 MiB by default (`max_body`) | An approved JSON route that returns a short-lived upload URL, outside the map, bound to that upload | | **Forms** (`application/x-www-form-urlencoded`) | Same: JSON only | A JSON route for agents | | **WebSockets, streaming input** | The middleware lets WebSocket connections through without any check | A JSON route per action; server-sent events or streaming responses on an approved `GET` are fine | | **Long jobs** | The request returns before the work is done | Approve the start (`POST /exports`), then `GET /exports/{id}` as `read` | | **Retries of serious actions** | A `write-hard` or `irreversible` approval works once: a retry after a timeout needs a new one | Make the handler idempotent: a client reference in the body, and the existing result for a repeat | ## 5. Where the middleware goes **In your stack:** ```text TLS / load balancer / reverse proxy forwards Allowed-By and AllowedBy-Proof unchanged, up to 8 KiB └─ AllowedBy middleware outermost layer of your app └─ anything that rewrites the path or the method (mounts, rewrites, method override) └─ your router └─ your handler reads the context: who approved, what, at which level ``` - **Outermost in your app**, before anything that changes the path or the method, and before your own authentication middleware: that middleware would refuse agent requests, which carry no token of yours. - **Mounted under a prefix?** Tell the SDK where (`SCRIPT_NAME`, ASGI `root_path`, or the `prefix` argument): the agent signs the full URL. - **One shared store** for the replay and single-use sets when you run more than one instance ([storage](https://docs.allowedby.com/guides/accept-agents#12-storage-for-replay-and-single-use-state)). - **The SDK's own endpoints** (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`, `/allowedby/...`) must be reachable without your authentication. **Per framework**, one line, from the [language guides](https://docs.allowedby.com/): | Language | Where | |---|---| | Python | WSGI/ASGI middleware; FastAPI `install(app, aby)`; Flask extension; Django `MIDDLEWARE` | | TypeScript / JavaScript | Node `http`, Express, Fastify, Hono, Next.js middleware, NestJS | | Go | `net/http` handler wrapper; Gin, Echo, chi middleware | | Java / Kotlin | Servlet filter; Spring Boot starter | | C# / .NET | ASP.NET Core middleware | | PHP | PSR-15 middleware; Laravel; Symfony | | Ruby | Rack middleware; Rails; Sinatra | | Rust | `tower` layer (axum); actix-web | **Agents and people on the same API.** A method and path is either for agents (in the map) or for your other clients (not in the map), never both. Serve agents on their own prefix or host (`/agent/...`, `agents.api.example.com`) with the same handlers behind them. If your users sign in through a provider, read [Apps that use Auth0, Okta, Cognito or another sign-in provider](https://docs.allowedby.com/guides/existing-sign-in). **In your handlers:** - **Own data by the person**, from the context (`human_id`, or your user after [linking](https://docs.allowedby.com/guides/existing-sign-in)), never by an id the agent sends. - **Keep your own authorisation.** The approval says the person agreed; your rules still say whether that person may touch that object. - **Log** the agent, its operator, the approval id and revision, with the action. ## 6. Where not to put AllowedBy | Endpoint | Why not | Keep | |---|---|---| | Sign-up, login, password reset, MFA, OAuth and SSO endpoints | They create or prove your own sessions; an agent must not act there for a person | Your current flow | | Webhooks and callbacks from other companies (payment provider, e-mail service) | The caller is a company, not an agent acting for a person | Their signatures (HMAC, mTLS) | | Your own service-to-service calls, cron jobs, queues | No agent, no person | Your internal authentication | | Back-office and admin tools | Staff actions, not agents | Your staff authentication | | Health checks, metrics, status pages | No person's data | Open, or your monitoring's credentials | | Static files, the web app itself, public pages | Nothing to approve | Untouched; your CDN | | Public data where you do not need to know the agent | Nothing to approve | Untouched, or level 0 if you want the agent's identity and rate limits per agent | | Endpoints that move data in bulk out of your system (full exports, admin dumps) | Too much for one sentence | A narrower agent route, or none | | Anything not ready for an agent's mistakes | An approval does not make an agent careful | Nothing, until it is | And never: - **An agent route that also accepts your old token** as a fallback: it skips the person's approval. - **Catching a refusal** from the SDK and serving the request anyway. - **The same handler under a path outside the map** (an alias, a catch-all, `/v2/...`) that agents can reach without a check. The adapters refuse paths that only look like a protected route; declare your own such pages with `unprotected=` ([wrap your app](https://docs.allowedby.com/guides/accept-agents#5-wrap-your-app)). ## 7. A worked example An invoicing API before and after. | Endpoint today | Group | Class | Level | Capability | Resource | |---|---|---|---|---|---| | `POST /login`, `POST /oauth/token` | not for agents | | | | | | `POST /webhooks/stripe` | not for agents | | | | | | `GET /health` | not for agents | | | | | | `GET /catalogue` | agent identity only | read | 0 | none | | | `GET /invoices` | approved | read | 1 | `invoices:read` | `invoice:*` | | `GET /invoices/{id}` | approved | read | 1 | `invoices:read` | `invoice:{id}` | | `POST /invoices` (draft) | approved | write | 1 | `invoices:write` | `invoice:new` | | `POST /invoices/{id}/send` | approved | write-hard | 2 | `invoices:send` | `invoice:{id}` | | `POST /invoices/{id}/pay` | approved | by amount | 2 | `invoices:pay` | `invoice:{id}` | | `DELETE /invoices/{id}` (bin) | approved | write | 1 | `invoices:delete` | `invoice:{id}` | | `POST /graphql` | reshaped | | | | as the rows above | | `POST /invoices/import` (CSV upload) | not yet | | | | | ```python from allowedby import route routes = [ route("GET", "/agent/catalogue", level=0, summary="The catalogue"), route("GET", "/agent/invoices", "invoices:read", level=1, resource="invoice:*", summary="List your invoices"), route("GET", "/agent/invoices/{id}", "invoices:read", level=1, resource="invoice:{id}", summary="One invoice"), route("POST", "/agent/invoices", "invoices:write", cls="write", level=1, resource="invoice:new", summary="Create a draft invoice", body={"customer": "customer id", "lines": "the lines"}), route("POST", "/agent/invoices/{id}/send", "invoices:send", cls="write-hard", level=2, resource="invoice:{id}", require_link=True, summary="Send an invoice to its customer"), # links in memory: see section 2 route("POST", "/agent/invoices/{id}/pay", "invoices:pay", level=2, resource="invoice:{id}", cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}], amount_field="/total", require_link=True, summary="Pay an invoice", body={"total": "the amount", "currency": "EUR"}), route("DELETE", "/agent/invoices/{id}", "invoices:delete", cls="write", level=1, resource="invoice:{id}", summary="Move an invoice to the bin"), ] templates = { "invoices:read": "Read your invoices", "invoices:write": "Create draft invoices", "invoices:send": "Send invoice {scope} to its customer", "invoices:pay": "Pay {scope}, up to {amount.max} {amount.currency}", "invoices:delete": "Move invoice {scope} to the bin", } ``` ## 8. Roll it out 1. **Start with reads.** Map the `read` routes, try them with an agent against your staging app ([testing](https://docs.allowedby.com/guides/accept-agents#15-testing-with-an-agent)), watch the admin console. 2. **Then reversible writes**, then the serious routes one by one, each with its sentence reviewed by someone who has not seen the code. 3. **Test the refusals**: each agent route without headers answers `401`; with your old token alone, `401`; a variant of a protected path (`/agent/invoices/7/`, `/agent/invoices.json`) does not reach the handler. 4. **Go live** with the [going-live checklist](https://docs.allowedby.com/guides/accept-agents#14-going-live-checklist). When you change the map later, keep capability names and resources stable: existing approvals name them. A new name means people approve again. --- Source: https://docs.allowedby.com/guides/existing-sign-in # Apps that use Auth0, Okta, Cognito or another sign-in provider For teams whose users sign in through a provider: Auth0, Okta, Amazon Cognito, Microsoft Entra ID, Keycloak, Clerk, Firebase Authentication, or any OpenID Connect or SAML service. Read [Accept AI agents in your app](https://docs.allowedby.com/guides/accept-agents) first; this page explains what changes for you, and what you have to build. ## In one minute - **Your provider never sees agent requests.** An agent does not sign in. It sends `Allowed-By` and `AllowedBy-Proof`, the SDK checks them, and your handler receives a context. No login, no access token from your provider, no session, no cookie. - **The person arrives with a new identifier.** `human_id` is pseudonymous and different for every app. It is not your provider's user id (`sub`), and nothing in the request connects the two. You connect them once, while the person is signed in to your app: **account linking**. - **AllowedBy proves who approved what. Your app still decides what that person may touch.** After linking, run the same authorisation as for a signed-in user: their account, their role, their organisation. - **Your provider's controls do not apply to agent requests.** Signing out, resetting a password or MFA, blocking a user, and your provider's login rules and logs all act on sign-ins only. Check your own user record on every agent request instead. ## What happens to an agent request ```text agent ── Allowed-By + AllowedBy-Proof ──▶ AllowedBy middleware ──▶ your handler (ctx) checks the agent, the person's approval and this exact request person ── browser or app, provider token ──▶ your provider's middleware ──▶ your handler (user) ``` | | A signed-in user | An agent through AllowedBy | |---|---|---| | Who checks the caller | Your provider (token, session) | The SDK, offline | | Who the person is | The provider's user id | `ctx.human_id` (pseudonymous, this app only), `ctx.human_iss` (their node) | | How sure you are of the person | Your provider's login and MFA | `ctx.level`: a passkey tap at the person's node (1), a verified legal identity (2, 3) | | What they allowed | Everything their role allows | Only the capabilities they approved, with their limits (`ctx.capabilities`, `ctx.display`) | | Ended by | Sign-out, session expiry, blocking the user | The person withdrawing the approval in their wallet, or its expiry | | Seen in | Your provider's logs | Your logs: `ctx.agent`, `ctx.operator`, `ctx.gid`, `ctx.rev` | The SDK never reads the `Authorization` header or your cookies, and never calls your provider. ## 1. Keep agent routes apart from your users' routes A route of the map is for agents only: a request without AllowedBy headers gets `401` with a challenge, even when it has a valid token from your provider. And your provider's middleware refuses an agent request, which has no token. So the two must not share a method and path. - **Recommended: a path prefix or a host for agents.** Serve the same handlers twice: `/api/...` with your provider's middleware, `/agent/...` (or `agents.api.example.com`) with AllowedBy's. Mount the app under the prefix so the SDK sees it (`SCRIPT_NAME`, ASGI `root_path`, or `prefix` in `check()`). - **Your provider's middleware or gateway must not cover the agent paths**, nor the SDK's own endpoints: `/.well-known/allowedby` (and `/.well-known/allowedby/tenants/...`), `/openapi.json`, `/.well-known/api-catalog`, `/allowedby/callback`, `/allowedby/link`, and `/allowedby/admin` (it has its own token). A JWT authoriser on the whole API (an API gateway's Cognito or JWT authoriser, `app.use(auth())`, a gateway plugin) answers `401` before AllowedBy sees the request. - **Do not choose by the presence of a header** (`Authorization` present, so skip AllowedBy). That works only as well as your provider's check behind it, and an agent holding a token of your provider then skips the person's approval. - **Let the headers through.** Proxies must forward `Allowed-By` and `AllowedBy-Proof` unchanged and accept them up to 8 KiB together (nginx: `large_client_header_buffers`). ## 2. Link the person to their account Without linking, the only identity you have is `ctx.human_id`. That is enough when the agent's data is its own (notes the person writes through their agent). It is not enough to reach an account that already exists in your app: the customer's orders, their organisation's invoices. Linking pairs `(ctx.human_iss, ctx.human_id)` with your user id, once, while the person is signed in to your app: 1. On a page behind your provider's login, your app makes a one-time code for the signed-in user and shows it with the account's handle (a username or account name the person recognises, not a secret). 2. The person gives both to their agent. 3. The agent sends the code to your link route for that account. The person approves that request with their passkey; the sentence they sign names the account. 4. Your app checks that the code belongs to that account and stores the pair against the user. From then on, every agent request of that person resolves to your user: look up `(ctx.human_iss, ctx.human_id)` and treat the request as theirs. **Where the link is kept.** In the Python SDK, `link_start()` and `require_link=` do steps 1 to 4 for you, but keep the links in the memory of one process today: they are lost on restart and not shared between instances. Its link route (`aby:link`) is also a `write` route whose sentence does not name the account (see the rules below). The other SDKs do not have linking yet and refuse `requireLink`. In production, in any language, make the link route yourself and keep the pairs in your database, as below. ```python """Account linking for an app whose users sign in through a provider (Flask; the same in any framework). current_user() is your provider's session; db is your database.""" import hashlib import os import secrets import time from flask import Flask, abort, g, request import allowedby.flask from allowedby import AllowedBy, route routes = [ # `write`, as linking is in ABY-3 §6; the handler checks that the sentence the person signed names the account route("POST", "/agent/accounts/{account}/link", "account:link", cls="write", level=1, resource="account:{account}", summary="Link your AllowedBy identity to your account", body={"code": "the code shown in your settings"}), route("GET", "/agent/orders", "orders:read", level=1, resource="order:*", summary="List your orders"), ] LINK = "Link your AllowedBy identity to the Example {scope}" # {scope} is account: templates = {"account:link": LINK, "orders:read": "Read your orders"} app = Flask(__name__) aby = AllowedBy(origin=os.environ["ALLOWEDBY_ORIGIN"], node=os.environ["ALLOWEDBY_NODE"], org={"legal_name": "Example Ltd", "country": "FR"}, routes=routes, templates=templates) allowedby.flask.AllowedBy(app, aby) def digest(code): return hashlib.sha256(code.encode()).hexdigest() @app.post("/settings/agents/code") # behind your provider's login, never under /agent def new_link_code(): user = current_user() # your provider's session code = secrets.token_urlsafe(12) db.link_codes.put(digest(code), user_id=user.id, expires=time.time() + 600) # one at a time per user return {"account": user.handle, "code": code} # the person gives both to their agent @app.post("/agent/accounts//link") def link(account): ctx = g.allowedby # verified: the person approved with their passkey... if LINK.replace("{scope}", "account:" + account) not in (ctx.display or {}).get("lines", []): abort(403) # ...but not a sentence naming this account (an approval for account:*, say) row = db.link_codes.take(digest(str((request.get_json(silent=True) or {}).get("code", "")))) # deleted when read if row is None or row.expires < time.time() or db.users.get(row.user_id).handle != account: abort(400) # unknown, expired, or the code of another account than the one approved db.agent_links.put((ctx.human_iss, ctx.human_id), user_id=row.user_id, linked_at=time.time()) notify(row.user_id, "An AI agent identity was linked to your account") return {"linked": True} @app.get("/agent/orders") def orders(): ctx = g.allowedby user = db.users.get(db.agent_links.user_for((ctx.human_iss, ctx.human_id))) if user is None or user.blocked: # not linked, or blocked in your app or your provider abort(403) return {"orders": db.orders.for_user(user.id)} ``` Rules for the link: - **The code is for the signed-in user only.** Short-lived (minutes), used once, stored hashed, one per user at a time. Show it on your own page, never by email or in a URL. - **The approval names the account.** Put the account's handle in the link route's path and `{scope}` in its sentence, and accept the link only when the sentence the person signed (`ctx.display`) names that account. The agent asks for this approval itself (the route is `write`, as linking is in ABY-3 §6), so it could ask for every account at once (`account:*`): the sentence would then not name one, and the handler refuses it. A handle is 1 to 64 letters, digits, `.`, `_` or `-`, and not `.` or `..` (no email address), or the challenge cannot name it. Otherwise anyone who slips their own code to the person's agent (a message, a web page the agent reads) gets that person's agent requests, and what the agent writes, in their own account. Tell your users to give their agent only a code from their own settings page. - **A wrong code still costs a tap.** Your handler sees the code only after the person approved. Rate-limit the link route per agent and per person, and tell the person when a code was refused. - **Say what happened.** Notify the user when an identity is linked, list the linked identities in their settings, and let them remove one. Whoever gets a user's code can link their own passkey to that account. - **Never link by email.** The same email at your provider and at the person's node does not prove the same person controls both. Ask for the code even when the node discloses a verified email. - **Key on both values.** `human_id` is only unique together with `human_iss`, the person's node. - **One person can have several identities.** A person who uses two nodes, or who loses every passkey and starts again without recovering their identity, arrives with a new `human_id`: they link again. - **Each of your origins sees a different `human_id`.** If agents call `api.example.com` and `eu.api.example.com`, the same person has two ids. Link per origin, or give agents one origin. ## 3. Sign-out, blocking and deletion Approvals live at the person's node, not in your provider. Nothing your provider does ends them. | In your provider | What happens to agent requests | What to do | |---|---|---| | The user signs out, or their session expires | Nothing: they continue | Nothing. Approvals are withdrawn in the person's wallet. | | Password or MFA reset | Nothing | Nothing. | | User blocked or suspended | Nothing, unless your app checks | Check your user's status on every agent request (the `orders()` handler above). | | User deleted | Nothing, unless your app checks | Delete their links. Unlinked requests no longer reach the account. | | Role or organisation changed | Your authorisation decides | Read the role from your database at request time, never from a copy made at linking. | ## 4. Levels are not your provider's MFA `ctx.level` says how the person's node knows them: a passkey tap with user verification (1), a legal identity checked at eIDAS substantial (2) or high, on a hardware passkey (3). Your provider's MFA, social logins and passwordless flows do not count, and your own customer checks do not raise it. Choose each route's level as if you knew nothing else about the person. A route that needs your own checks too (a verified customer, a signed contract) requires the link, then checks your record. ## 5. Companies: SSO, organisations, tenants If your provider handles organisations (enterprise SSO, Auth0 Organizations, Okta or Entra tenants, Cognito groups): - **The tenant in the path is not proof of membership.** An approval for `/t/{tenant}/...` means the person approved that action for that tenant. It does not mean they belong to it. Your authorisation checks it, from the link, as for a signed-in user. In the Python SDK: `link_authorize(account, route, params)`. - **Company mandates** (`ctx.acting_for`) come from the company's own node, which signs who may act for it. A company can feed that node from its identity provider: SCIM for members and teams, OpenID Connect sign-in at enrolment ([Use AllowedBy as a company](https://docs.allowedby.com/guides/use-allowedby)). Its provider is not yours: compare `acting_for.org` with the organisation you know, never a name. ## 6. Tokens agents already have If agents already reach your API with tokens from your provider (machine-to-machine clients, personal API keys, OAuth tokens a user granted), those requests keep working and never ask the person: AllowedBy does not see them. Decide for each: - **Keep them** for integrations that do not act for a person. - **Narrow them** to what may run without a person's approval. - **Retire them** for actions a person must approve: point those agents to the agent routes. ## 7. Personal data Your provider holds your user's profile. An agent request carries none of it: no name, email or phone. Once linked, read your own record. Without a link, ask the person through disclosure, with a purpose ([Personal data](https://docs.allowedby.com/guides/accept-agents#9-personal-data-purpose-and-the-disclosure-key)). Never copy one into the other without the person's consent. ## 8. Audit and limits - **Logs.** Your provider's logs show no agent request. Log in your app: `ctx.agent`, `ctx.operator`, `ctx.human_id`, `ctx.gid`, `ctx.rev`, the route and your user id once linked. The SDK's audit sink can do it. - **Attack protection.** Your provider's brute-force and bot protection does not see agent requests. Rate-limit the agent routes yourself, by `ctx.agent` and by user. - **Tests.** Test the agent routes without a browser or a node (the "Testing" section of each language guide), and test that each agent route refuses a request with only your provider's token. ## Checklist | # | Before agents reach real accounts | Section | |---|---|---| | 1 | Agent routes on their own prefix or host; your provider's middleware off those paths and off the SDK's endpoints. | 1 | | 2 | Proxies forward `Allowed-By` and `AllowedBy-Proof`, up to 8 KiB. | 1 | | 3 | Link route and link codes in your database, keyed on `(human_iss, human_id)`; the approval names the account; notify, list, unlink. | 2 | | 4 | Every agent handler looks up the linked user and refuses when there is none or when the user is blocked. | 2, 3 | | 5 | Deleting a user deletes their links. | 3 | | 6 | Authorisation (account, role, tenant) from your database, exactly as for a signed-in user. | 2, 5 | | 7 | Levels chosen without counting your provider's MFA. | 4 | | 8 | Each existing agent token kept, narrowed or retired. | 6 | | 9 | Agent requests logged and rate-limited in your app. | 8 | --- Source: https://docs.allowedby.com/guides/build-an-agent # Build an agent Your agent calls an app as usual. When an approval is missing, the SDK asks the person through a node, waits for their passkey, and tries again. ## In Python ```python import os from allowedby import Agent agent = Agent(os.environ.get("ALLOWEDBY_NODE", "https://demo.allowedby.com"), tell=print) # tell: show it to the person app = os.environ.get("APP_URL", "https://notes.demo.allowedby.com") status, notes = agent.call("GET", app + "/notes", action="notes:read") print(status, notes) ``` `tell` receives the approval link and a short code. Show both to the person: they check that the page shows the same code. Full details are in the [Python guide](https://docs.allowedby.com/sdk/python#agents). ## In JavaScript The same agent, in Node.js, is in the [JavaScript guide](https://docs.allowedby.com/sdk/js#agents). ## In an agent framework | Framework | Python | JavaScript | |---|---|---| | MCP server | [Yes](https://docs.allowedby.com/sdk/python#agents) | [Yes](https://docs.allowedby.com/sdk/js#agents) | | LangChain | [Yes](https://docs.allowedby.com/sdk/python#agents) | [Yes](https://docs.allowedby.com/sdk/js#agents) | | OpenAI Agents SDK | [Yes](https://docs.allowedby.com/sdk/python#agents) | [Yes](https://docs.allowedby.com/sdk/js#agents) | | Vercel AI SDK | | [Yes](https://docs.allowedby.com/sdk/js#agents) | Each one becomes a tool that pauses while the person decides. ## What a good agent does - **Asks for the least.** One resource, one action, a limit on the amount. - **Shows the code.** A person who sees the code in two places cannot be sent to another request. - **Takes no for an answer.** After a refusal, it does not ask again for the same action. - **Keeps approvals.** A standing approval is reused, so that the person is not asked twice. --- Source: https://docs.allowedby.com/guides/use-allowedby # Use AllowedBy as a person or a company For people who let an AI agent (Claude, or any MCP client) act for them on websites, and for companies that let staff use agents under company rules. It covers setting up the agent, approving with a passkey, verifying your identity, your wallet, and the organisation console. This guide is complete on its own. It describes the code in this repository and the hosted demo at https://demo.allowedby.com. --- ## 1. What it is AllowedBy lets an AI agent use a website for you, but only with your yes. - The agent never gets your password, a token or your personal data. - When the agent needs your approval, a page opens on your **node** (your home server for approvals). The page shows the website, the exact sentence you are approving and a 4-character code. - You approve with a **passkey** tap: Face ID, Touch ID, Windows Hello, your phone or a security key. - The website checks every request the agent makes against what you approved. - Your **wallet** lists everything you approved. You can withdraw any approval at any time. Some actions need more than a passkey. The website chooses a **level** for each action: | Level | What you need | |---|---| | L0 | Nothing. The agent acts alone (for example, reading a public catalogue). | | L1 | A passkey tap. | | L2 | Your identity verified once (eIDAS substantial), plus a passkey tap. | | L3 | Your identity verified at eIDAS high, on a hardware passkey (a security key or the secure chip of your device; a synced passkey is not enough). | **Hosted addresses.** | What | Address | |---|---| | Node: approval pages and your wallet | https://demo.allowedby.com, wallet at https://demo.allowedby.com/wallet | | Example sites | https://NAME.demo.allowedby.com: `shop`, `supply`, `beacon`, `globex`, `notes` | | Demo company (Initech SA) console | https://demo.allowedby.com/org/initech | | Presentation | https://allowedby.com | The hosted node approves for its example sites and for the services onboarded on it. ## 2. Set up the agent To try the hosted demo from ChatGPT or Claude.ai with nothing to install, add one URL: see [Use it from ChatGPT or Claude.ai](#use-it-from-chatgpt-or-claudeai) below. To run the agent yourself, it is `demo/mcp_agent.py`, an MCP server over stdio. You need: - **Python 3.10+** and the `cryptography` package: `pip install cryptography`; - a copy of this repository (the agent imports the `allowedby` package from `sdks/python/src/`). ### Options | Flag | Env var | Default | Meaning | |---|---|---|---| | `--node URL` | `ALLOWEDBY_NODE` | `http://localhost` | Your node. Use `https://demo.allowedby.com` for the hosted demo. | | `--operator-domain NAME` | `ALLOWEDBY_OPERATOR` | `acme.localhost` with a local node, none otherwise | The agent vendor's verified domain. Lets approvals survive the agent's hourly key change. | | `--operator-key PATH` | none | `demo/.data/operator-acme.json` | The vendor's signing key. Used only if the file exists. | | `--state PATH` | none | `demo/.data/claude-agent.json` | Where your approvals are saved between sessions. | | `--no-browser` | none | off | Do not open approval pages; the agent only gives you the link. | With the hosted node the agent runs without a vendor by default: the demo vendor `acme.localhost` and its key file exist only on your own machine. ### Claude Code Run once (adjust the path): ```bash claude mcp add allowedby -- python /path/to/Network/demo/mcp_agent.py --node https://demo.allowedby.com ``` For the local demo, leave out the flags: ```bash claude mcp add allowedby -- python /path/to/Network/demo/mcp_agent.py ``` If you open Claude Code in the repository's `Network` folder, it finds the agent in `.mcp.json` and asks once to enable it. That file uses the local node. ### Claude Desktop, or any MCP client Add the server under `mcpServers` in the client's configuration. For Claude Desktop the file is `claude_desktop_config.json` (Settings → Developer → Edit Config): ```json { "mcpServers": { "allowedby": { "command": "python", "args": ["/path/to/Network/demo/mcp_agent.py", "--node", "https://demo.allowedby.com"] } } } ``` Restart the client. ### Use it from ChatGPT or Claude.ai The demo's agent also runs as a hosted MCP server (streamable HTTP, no sign-in). Its URL is: ```text https://acme.demo.allowedby.com/mcp ``` It is the agent of Acme AI, the demo's agent vendor, and it uses the hosted node. Each conversation gets its own agent: a new key, held in memory only, and the approvals you give it. Nothing is installed or saved. **Limits, honestly.** - It is a demo. The sites are fictional (`shop`, `supply`, `beacon`, `globex`, `notes` on `demo.allowedby.com`): nothing is delivered and no money moves. It cannot reach any other website. - There is no vendor key, so approvals end with the agent's key: at the latest after an hour, or when the session ends (an hour without use). A new conversation asks again. - The approval page does not open by itself. The assistant shows you a sentence with a link and a 4-character code: open the link, check the code, and tap your passkey on the node's page. The assistant never sees your passkey. - It is shared by every visitor, so it is rate-limited. When it is busy it says so; try again a few minutes later. #### Use it from ChatGPT Checked on 2026-11-26 against OpenAI's help page "Developer mode and full MCP connectors in ChatGPT" and its developer guide: custom MCP servers are for ChatGPT **Business** and **Enterprise/Edu** on the web. **Pro** can add one with read/fetch permissions only, so `allowedby_call` (which acts) may not be offered there. Free and Plus are not listed. On Business, only admins and owners can add one (permission "Create plugins with MCPs"). 1. On the web, open **Plugins** (https://chatgpt.com/plugins). Developer mode no longer needs to be turned on. 2. Select **+**, then **Add custom MCP server**. 3. Name it `AllowedBy demo`. Under **Connection**, enter the server URL `https://acme.demo.allowedby.com/mcp`. 4. Authentication: **No authentication**. 5. Read the risk warning, check **I understand and want to continue**, then select **Create as a plugin**, and review the four tools it found. 6. Install the plugin. In a new chat, type `@`, choose it, and ask, for example: "Use AllowedBy demo: on https://shop.demo.allowedby.com, put two bags of coffee and a mug in my basket." ChatGPT asks you to confirm `allowedby_call` before it runs (it is the only tool that acts). That is ChatGPT's own check; the approval that counts is your passkey tap on the node's page. #### Use it from Claude.ai Checked on 2026-11-26 against Anthropic's "Get started with custom connectors using remote MCP" and "Add a connector that isn't in the directory": custom connectors work on Free (one custom connector), Pro, Max, Team and Enterprise. Claude connects from Anthropic's cloud, not from your device. On Free, Pro or Max: 1. Open **Customize > Connectors** (https://claude.ai/customize/connectors). 2. Select **Add**, then **Add custom connector**. 3. Name it `AllowedBy demo`, enter the URL `https://acme.demo.allowedby.com/mcp`, then **Continue**. 4. Authentication: **No sign-in**. Select **Add**. 5. In a chat, click **+**, find the connector under **Connectors**, and turn it on. Then ask, for example: "On https://notes.demo.allowedby.com, add a note 'Buy milk', then show my notes." On Team or Enterprise, an Owner adds it under **Organization settings > Connectors** (**Add**, **Custom**, **Web**, then the same name, URL and **No sign-in**); each member then finds it in **Customize > Connectors** and selects **Connect**. These menus change often: if a label differs, look for "custom MCP server" (ChatGPT) or "custom connector" (Claude). The local demo serves the same endpoint at `http://acme.localhost/mcp`, which only an MCP client on your own machine can reach (for example `claude mcp add --transport http allowedby-local http://acme.localhost/mcp`). ### What the agent can do It gives Claude four tools: | Tool | What it does | |---|---| | `allowedby_discover(url)` | Reads what a site offers: who runs it, every operation, the level each needs, the personal data it may ask for. | | `allowedby_call(method, url, body, spend_limit)` | Makes a request as your agent. When your yes is missing, opens the approval page and waits for your tap (90 s by default). | | `allowedby_wait(job)` | Keeps waiting for an approval you have not given yet. | | `allowedby_approvals()` | Lists the approvals the agent holds. | You only give the site's address. For example: - "On https://shop.demo.allowedby.com, buy two bags of the Ethiopian coffee and a mug, delivered to me." - "On https://beacon.demo.allowedby.com, monitor https://example.com, and move me to the Team plan for 4 people." - "Add a note 'Buy milk' on https://notes.demo.allowedby.com, then show my notes." - "What approvals do you hold?" There is also a terminal agent for the local demo: `python demo/agent_cli.py` (flags `--service`, `--node`, `--operator`, `--operator-domain`, `--no-browser`). Type `help` for its commands. ## 3. Your first approval 1. Ask the agent to do something that needs your yes. 2. The approval page opens in your browser. The agent also tells you, word for word: *Your agent asks for your approval: "…". Check that the page shows the code XXXX, then approve with your passkey: *. 3. **Check the code.** The 4-character code on the page must match the one the agent gave you. If it does not, deny. 4. **Check the service.** The page shows the website as "Legal name · country · verified", or only its hostname with "organisation not verified". 5. **Create a passkey** (first time only). Enter a name (shown only to you) and, if you like, an email (shared only when you tick it on a request). Click **Create passkey** and follow your device's prompt. The passkey stays on your device. 6. **Choose how much to allow**, under *What may the agent do?*: - only what was asked; - all of this type (for example, all notes); - everything of this kind (for example, read and write notes; never payments or deletions). Wider means fewer questions later. 7. **Choose how long**: 1 hour, 1 day, 7 days or 30 days, as far as the action allows. The shortest is selected by default. Serious actions (deleting, paying) are approved for that exact request, once. 8. If the site asks for **personal data**, the page lists each item, why it is needed and how long it is kept. Required items are ticked; optional ones start unticked. 9. Tap **Allow**, then your passkey. The agent continues at once. To refuse, pick a reason and tap **Deny**. "This was not me" or "I don't know this agent" also stops the agent asking again for 10 minutes. If a request is "not addressed to a named person", anyone with a passkey on this node who opens the link may approve it. Do not forward approval links. ## 4. Verify your identity (level 2 and 3) When an action needs level 2 or 3, the approval page says so and offers the identity checks the node supports. You verify once; it is kept for **12 months**. On the hosted node, verification is done by **Signicat**: | Button | What happens | Level you can reach | |---|---|---| | **Verify with your national eID** | You are sent to Signicat and sign in with your country's eID (for example itsme, BankID, FranceConnect+, depending on what the node offers). You come back to the page. | L2; L3 if the eID is notified at "high" and you signed in at "high" | | **Scan your passport or ID card** | Your phone reads the chip of your passport or ID card, then takes a short selfie video (liveness). | L2; L3 only if the node's liveness check is rated "high" and the chip authenticates | Steps for the passport scan: 1. Tap **Scan your passport or ID card**, then your passkey. 2. **On a computer**, the page shows a **QR code**. Scan it with your phone. Your phone opens the passport reader. If you are already on your phone, it opens directly. 3. Hold your passport or ID card against the back of your phone and follow the steps. 4. The computer page continues by itself when the scan is done (it waits about 10 minutes). On the phone you see "Done on this phone. If you started on a computer, go back to it". **Level 3 also needs a hardware passkey.** A synced passkey (iCloud Keychain, Google Password Manager) cannot reach level 3, whatever your ID. The node must also recognise your authenticator's maker; if it does not, no passkey reaches level 3. **Demo only.** The page also has a collapsed "Demo: simulated identity provider" section with **Verify (substantial)** and **Verify (high)**. These are simulated: the name you type becomes your verified name. On a local demo with no Signicat setup, these are the only options. ## 5. Your wallet Open https://demo.allowedby.com/wallet (or `http://localhost/wallet` locally). Each change takes a passkey tap. | Section | What you can do | |---|---| | **You** | See your level and how it was verified (and until when), and the data the node holds. **Erase my identity check**: deletes your verified identity; you are level 1 again. | | **Your passkeys** | See your passkeys and their kind (software, synced, hardware). **Add a passkey**, optionally for one service only, so two services cannot match you by your key. | | **Your budgets** | Set a spending limit per day, week or month (EUR or USD). Every approval reserves the most it could spend. Past your budget, Allow is disabled. | | **Companies** | For each company you belong to: your role, your mandate and its end date, what it allows, which agents, your budget, what you may never share for work. | | **Grants** | Every approval: what it allows, for which site, which agent, level, until when. **Revoke** one, **Revoke everything for** a site, or **Revoke everything from** an agent vendor. Sites refuse revoked approvals within seconds. | | **What you shared** | Each time you shared personal data: what, to whom, when, how long they keep it, and their privacy policy. | **Lost your passkey?** With no passkey in this browser, the wallet offers recovery: verify your identity again and, if it matches your verified record, the new passkey replaces the lost one. *Demo: this uses the simulated provider.* ## 6. Approvals that last across sessions The agent saves your approvals in its state file (`demo/.data/claude-agent.json` by default) and reloads them when Claude starts again. The agent's key changes every hour. An approval is tied to that key, so it must be moved to the new key: - **With a verified agent vendor** (the local demo's "Acme AI", `--operator-domain acme.localhost`), the vendor signs the move. Your approvals continue until they expire, across hours and new Claude sessions, with no question. - **Without one** (the hosted demo), approvals end with the agent's key, after at most one hour, and you are asked again. In both cases, your wallet is the reference. Revoking there always wins. ## 7. For companies A company has an **organisation** on its node. Staff join it with their passkey and receive a **mandate**: signed by the company, tied to their passkey, valid 30 days, renewed while they work there. Websites then know the person approves **for the company**, within its rules. **Hosted demo:** only the demo company *Initech SA* exists (https://demo.allowedby.com/org/initech). There is no self-service creation of a new organisation in this code; an organisation is configured when the node starts. ### The organisation console Open `https:///org/`. Admins sign in with their own passkey. Before the first owner or admin joins, a bootstrap token opens it once. Console roles: | Role | Can | |---|---| | Owner | Everything, including giving or taking the owner and admin roles, and keys. | | Admin | Members, teams, policy, revoke, secrets. | | Team manager | See and revoke for their own team. | | Auditor | Read and export. | Every change takes a fresh level 2 passkey tap. Changes to rules, budgets, authority and keys also need a **second admin** to approve. ### Invite staff Three ways: 1. **From the console.** Invite a person with a name, email and job role. The console gives a join link, `https:///org//join#`. Send it to them. They open it, create or use their passkey, and tap **Join with my passkey**. 2. **SCIM 2.0 directory sync.** Your identity provider creates users and groups (teams) at `https:///org//scim/v2/Users` and `/Groups`, with the SCIM token from the console: ```bash curl -X POST https:///org//scim/v2/Users \ -H "Authorization: Bearer " -H "Content-Type: application/json" \ -d '{"userName":"bob@initech.example","displayName":"Bob","title":"Finance manager"}' ``` `title` is the job role. Each user gets a join link. 3. **Company sign-in (SSO).** On the join page, **Sign in with your company account** (OpenID Connect), then create a passkey. *Demo: the company identity provider is a mock on Initech's site.* ### Job roles and mandates Each job role lists what staff may let an agent do, with limits. For example, in the demo: | Job role | Allows | |---|---| | Accounts payable clerk | Read and comment invoices; approve invoices up to 10,000 EUR; pay up to 5,000 EUR; submit expenses | | Finance manager | Everything on invoices; expenses; supplies | | Buyer | Read supplies, get quotes, order up to 15,000 EUR | On an approval page, a member chooses **As yourself** or **For Initech SA (role)**. If the mandate does not cover the request, the page says "Your mandate from … does not allow: …". ### Company rules | Rule | Effect | |---|---| | **Vendor allowlist** | Only agents from listed vendors (verified domains), each with a minimum custody tier. Others are blocked on the page: "… does not allow agents from …". | | **Services** | Optionally, only listed websites. | | **Minimum levels** | For example level 2 for hard-to-undo actions and level 3 for irreversible ones. | | **Longest approval** | For example 7 days. | | **Budgets** | Organisation, team, member and agent-vendor budgets. Each approval reserves its maximum; past a budget, Allow is disabled. Websites can also hold a budget for your company (`403 budget_exceeded`). | | **Never share** | Personal data staff may never share for work, for example `birth_date`. | | **Retention** | How many days after leaving a leaver's record is erased (the log keeps only commitments). | ### What the console shows - What each role lets an agent do, and the rules in one sentence. - Every live approval per member. Withdraw one, or block a vendor. - History in sentences, exported as JSON lines for a SIEM: `https:///org//events.jsonl`. - Reports and signed evidence packs per approval (check them with `python tools/check_evidence.py`). ### Leavers Click **Remove (leaver)** on the member, or deactivate them from your directory by SCIM (`PATCH` with `active: false`, or `DELETE`). At once: - all their approvals for the company are revoked; - they can no longer approve for the company. Their record is erased after the retention period. ## 8. Privacy What the agent never sees: - your passkey, password or any token for the website; - your personal data. You choose what to share on the approval page; it is encrypted to the website and sent directly to it; - your verified identity record. It stays on your node. What the website learns: - a **pseudonymous id** for you, different on every website, so websites cannot match you with each other; - your level, the sentence you approved, and which agent acted; - for work approvals, your company and job role; - only the personal data you ticked, with the purpose and retention it declared. Other protections: - Approval links preview as "An AI agent is asking for your approval", with no detail. - Your wallet, approval links and consoles are kept out of search engines. - You can erase your identity check from the wallet at any time. ## 9. Troubleshooting | Message or symptom | What it means | What to do | |---|---|---| | The code on the page does not match the agent's | It may not be your agent's request. | Deny with "This was not me". | | "organisation not verified" | The node has not verified the company behind the website. | Approve only if you trust the hostname. | | "Unknown approval." | The link is wrong or the request no longer exists. | Ask the agent to try again. | | "This request is approved / denied / expired." | It was already answered or ran out. | Ask the agent to try again if needed. | | "Cannot be approved: …" | A rule blocks it. The text says which: a budget ("this reserves … but only … remains"), a company rule, your mandate, or missing data ("Your identity has no …"). | Change your budget, ask your company admin, or add the data. | | "This needs L2 · verified identity …" | The action needs a verified identity. | Section 4. | | "Your identity check is more than 12 months old: verify again." | Your verification expired. | Verify again. | | "level 3 needs a hardware passkey …" | Your passkey is synced or software. | Add a hardware passkey in your wallet. | | "Passkey creation failed" / "Passkey check cancelled or failed" | The device prompt was cancelled or is unavailable. | Try again; use another passkey or device. | | "The scan was not finished in time." | The passport scan took more than about 10 minutes. | Start again. | | "The provider has not answered yet." | Signicat has not returned a result. | Try again in a few minutes. | | "This browser knows a passkey the node does not (node data was reset)." | The node's data was reset (demo). | Click **Forget it** and create a new passkey. | | "This invitation is unknown, used or withdrawn." | The join link was already used or revoked. | Ask your admin for a new one. | | "… does not allow agents from …" | Your company does not allow this agent vendor. | Use an allowed agent, or ask your admin. | | The agent says `waiting_for_approval` | You have not tapped yet. | Open the link it gives, then tell it to continue. | | The page did not open | The agent was started with `--no-browser`, or only opens links on its own node. | Open the link the agent gives you. | | `this demo node only approves for its own demo sites` | The site is not onboarded on this node yet. | Use one of the example sites, or ask the site to onboard. | | Asked again every hour on the hosted demo | Normal without a verified agent vendor (section 6). | Approve again, or use the local demo. | | You approved "This was not me" by mistake | The agent may not ask again for 10 minutes. | Wait 10 minutes. | --- Source: https://docs.allowedby.com/errors # Error codes Every SDK answers the same codes with the same statuses; `tools/docs.py` checks this table and every language guide against the verifier. A refusal is `application/problem+json` with `type: https://allowedby.org/errors/`. A `401` that the agent can resolve also carries a challenge in `WWW-Authenticate: AllowedBy ...` (ABY-2 §6). `429` and `503` carry `Retry-After`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | ## How an agent reacts - **Asks the person, then retries once:** `grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`. - **Gets a new passport or rebinds:** `passport_required`, `actor_expired`. - **Waits, then retries:** `rate_limited`, `status_stale`. - **Signs again, once:** `invalid_signature` (a fresh proof; check the clock and the URL). - **Stops:** every other code. Retrying cannot succeed until someone changes something. --- Source: https://docs.allowedby.com/sdk/python # AllowedBy Python SDK The `allowedby` package is the Python SDK and the reference implementation of every AllowedBy SDK. A service uses it to accept AI agents (the **service SDK**); an agent uses it to call those services (the **agent SDK**). The concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in Python. The rules every SDK follows are in `sdks/CONTRACT.md`. Terms used below: a **node** issues agent passports and asks the person for approval (a passkey tap); a **grant** is the person's signed approval; a **proof** is the agent's signature over one request; **ABY-2** is the specification of how a service verifies a request (in `specs/`). ## Install Install the package from a clone of this repository with `pip install "./sdks/python"`; add the extra of your framework. The package is not on PyPI yet. Python 3.10 or later. Its only dependencies are `cryptography` (Ed25519, P-256, AES key wrap and AES-GCM, which the standard library lacks) and `tzdata` (time zones on systems without a zone database); each integration is an optional extra. Linux and macOS: ```bash git clone https://github.com/yannUpTo/allowedby.git python3 -m venv .venv && . .venv/bin/activate pip install "./allowedby/sdks/python[fastapi]" ``` Windows (PowerShell): ```powershell git clone https://github.com/yannUpTo/allowedby.git python -m venv .venv; .venv\Scripts\Activate.ps1 pip install "./allowedby/sdks/python[fastapi]" ``` Docker (in your image's Dockerfile, with the repository next to it): ```dockerfile FROM python:3.13-slim COPY allowedby/sdks/python /tmp/allowedby RUN pip install --no-cache-dir "/tmp/allowedby[fastapi]" uvicorn ``` | Extra | Installs | For | |---|---|---| | (none) | `cryptography`, `tzdata` | WSGI, the agent, MCP | | `asgi` | `starlette` | ASGI middleware | | `fastapi` | `fastapi`, `starlette` | FastAPI | | `django` | `django` 5.2 to 6 | Django | | `flask` | `flask` | Flask | | `redis` | `redis` | `RedisStore`, shared by every machine | | `langchain` | `langchain-core` | `AllowedByRequestsTool` | | `openai-agents` | `openai-agents` | `allowedby_tools` | ## Quick start A WSGI app that accepts agents is 25 lines with the standard library's server; run it next to the local node. From `sdks/python/examples/quickstart.py`: ```python """Quick start: a WSGI app that accepts AI agents with the person's approval (standard library server).""" import json import os from wsgiref.simple_server import make_server from allowedby import AllowedBy, route aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Ltd", "country": "FR"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*")], templates={"notes:read": "Read your notes"}, ) def notes(environ, start_response): ctx = environ["allowedby.context"] # None outside the route map status, body = ("200 OK", {"notes": [], "person": ctx.human_id}) if ctx else ("404 Not Found", {}) start_response(status, [("Content-Type", "application/json")]) return [json.dumps(body).encode()] app = aby.wsgi(notes) if __name__ == "__main__": make_server("localhost", 8000, app).serve_forever() ``` See it work against the local node (from the repository root): ```bash python demo/run.py # the node on http://localhost, the demo sites python sdks/python/examples/quickstart.py # your app on http://localhost:8000 curl -i http://localhost:8000/notes # 401, WWW-Authenticate: AllowedBy ... passport_required curl http://localhost:8000/.well-known/allowedby # what agents read: templates, keys, signed profile ``` Then let an agent call it, approving on the page that opens (from another terminal): ```bash ALLOWEDBY_NODE=http://localhost APP_URL=http://localhost:8000 python sdks/python/examples/agent_quickstart.py ``` ```powershell $env:ALLOWEDBY_NODE = "http://localhost"; $env:APP_URL = "http://localhost:8000" python sdks/python/examples/agent_quickstart.py ``` With the hosted node, set `ALLOWEDBY_NODE=https://demo.allowedby.com`; the node approves only for origins onboarded on it (see `docs/deploy-saas.md`). ## Routes and templates Each route says which capability, class and identity level a request needs; each capability has a sentence the person reads before approving. ```python from allowedby import AllowedBy, route routes = [ route("GET", "/me", level=0, summary="Who is calling"), # the agent's passport is enough route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}"), route("POST", "/invoices/{id}/pay", "invoices:pay", level=2, resource="invoice:{id}", amount_field="/total", cls=[{"up_to": "1000.00", "class": "write-hard"}, {"class": "irreversible"}]), ] 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}, up to {amount.max} {amount.currency}"}}, } ``` | Argument | Meaning | |---|---| | `method`, `path` | `GET` (also checks `HEAD`), `POST`, `PUT`, `PATCH`, `DELETE`; `{param}` matches one path segment; other segments are ASCII, percent-encoded where a URL needs it (`/caf%C3%A9`). The first match decides: a literal route comes before the parameter route it overlaps, else construction fails | | `capability` | `namespace:action`; none means level 0 (the agent's passport only) | | `cls` | `read`, `write` (approved once, reused), `write-hard`, `irreversible` (the service asks for this exact request, used once), or amount thresholds | | `level` | 0 passport only, 1 passkey, 2 verified identity, 3 eIDAS high | | `resource` | the scope the grant must cover; `{param}` is replaced from the path | | `amount_field`, `currency_field` | JSON pointers to the amount and currency in the body; the grant must cap them | | `authn` | `hardware` or `synced`: the kind of passkey | | `tier` | 0 to 2: the agent's key custody (OAID-3) | | `max_lifetime` | seconds, 60 s to 30 days: shorter than the class maximum | | `summary`, `body` | what agents read in `/openapi.json` | | `mandate`, `disclose`, `disclose_optional`, `authority`, `qes`, `require_link`, `nonce`, `level_profile` | extended features (see Reference) | A bad route or configuration raises `ValueError` at start, saying what to fix: an origin that is not https (http only for localhost), a capability without a template, a route listed twice, a level outside 0-3. A template is a sentence (`"Read your notes"`) or `{"summary": {lang: ...}, "lines": {lang: ...}}` with `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}` and `{fields}`. The node renders it; the person signs exactly that text. ## Framework recipes Every app below is whole, and CI runs it against a real node, an agent and a person (26 scenarios: levels 0 to 2 and all refusals). Each framework has a thin adapter; every adapter serves the SDK's endpoints, checks every route of the map, and lets other paths through untouched. The SDK's endpoints: `GET /.well-known/allowedby`, `GET /openapi.json`, `GET /.well-known/api-catalog`, `POST /allowedby/callback`, `POST /allowedby/link`. On a route of the map the body (at most `max_body`, 1 MiB by default) is read once and given back to your handler intact; it must be a JSON object. Variants of a protected route never reach your handler unchecked (sdks/CONTRACT.md §2.10): a trailing or doubled `/`, a format suffix (`/notes.json`), a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method` in the query or a form) and a path that only decodes to a route (`%2F`) are refused with 400 `invalid_request`. The method and the path are checked again where the framework runs your handler (Flask, Django, Starlette and FastAPI do it by themselves): whatever a layer behind the SDK changed (a `_method` form field, a header, a rewritten path), a handler of a route of the map runs only for the very request the SDK accepted, else the client gets 400. A form POST on a path protected under another method only is your own, streamed and with no size limit. For a bare WSGI or ASGI app the SDK does not know where the router is and refuses such forms; put the guard right around the router to accept them: `aby.wsgi(layer(aby.wsgi_guard(router)), guarded=True)`, or `AllowedByMiddleware(layer(DispatchGuard(router, aby)), aby, guarded=True)`. An app mounted inside the router, with layers of its own that change the method, needs its own guard. **Changed after the check.** A step after the SDK that moves an accepted request, to another value of the same route (`/invoices/4711` rewritten to `/invoices/9`) or to another method (a method override after the middleware), gets 400 `invalid_request`, and its handler never runs: it would act on values the person never approved. The refusal names route templates at most, never a value of the request. Another spelling of the same path (`/invoices/%34711`) is the same request and runs. If the check spent a single-use approval, the SDK gives it back (`release`). Limits: a bare WSGI or ASGI app routes where the SDK cannot see it, so put the guard right around the router as above; where you cannot, put nothing that changes the method or the path after the SDK, and read the path values from `ctx.params`. A wildcard (`/notes/` for `/notes/{id}`), an open pattern or a last newline never runs the handler of a protected route unchecked. Flask, Django, Starlette and FastAPI check what their router chose: a static catch-all and your longer routes run. A bare WSGI or ASGI app (Falcon, Bottle) refuses with 400 a path that would match a route of the map if a parameter took several segments (`DELETE /notes/7/x`). Write the route map without the prefix your app is mounted at; a proxy that strips a prefix must set `SCRIPT_NAME` or `root_path`. A page of your own that looks like one of these is refused too, and the message says so. Declare it, as an exact path (`/notes.json` next to `/notes`) or a template with its method (`("DELETE", "/notes/{id}/comments")`), with the routes above. On Flask, Django, Starlette and FastAPI, which see the handler, a declared page never runs the handler of a protected route, and a page that differs from a protected route by its last `/` only (`/notes/new/` next to `/notes/{id}`, usual in Django) can be declared. A bare WSGI or ASGI app passes a declared page to your app as it is: no wildcard route of a protected handler (Bottle ``, Falcon `{id:path}`) may reach it. There, a page that differs by its last `/` stays refused, and the log says so once. **The handler of a protected route runs only for that route.** Flask, Django, Starlette and FastAPI know, for each route of the map, the handler their router runs for it, and refuse with 400 any other request that would reach it: an alias (`/old/notes/7/archive`), a catch-all that also serves `DELETE /notes/7/archive/x`, a static catch-all that also answers a route of the map, for any method: one view that serves a protected `DELETE` and an unmapped `POST` is refused for the `POST` too, as it runs the same code (and reads its input, the query string included). `unprotected` never lifts this. Split the view, one per method, or map the other method at the same capability and level; the refusal names both. One function that serves two mapped methods of a template (Flask `methods=["GET", "POST"]`) runs the same code for both, so a request checked for one runs it only if that route covers the other: a `GET` mapped at level 1 next to a `POST` at level 3 is refused, and the log names both routes. One function on two routes of other paths (`DELETE /notes/` at level 3 and `DELETE /items/` at level 1) runs for a request checked for one only if that route covers the other: the level-1 request is refused. A `MethodView` (or a Django or Starlette class view) with separate `get()` and `post()` dispatches by method, and each runs for its own route, on any path the view serves (a route of the same method on another path still needs covering). A handler that is protected as a catch-all for another route (a front controller bound to `/home` and to `/`) never runs for a request checked for a route that does not cover that other route. Give each route of the map a handler of its own. A CORS preflight `OPTIONS` that the framework answers itself (Flask's automatic `OPTIONS`, a Starlette route without `OPTIONS`, and a Django class-based view or a Starlette endpoint whose classes, Django's or Starlette's own aside, define only their HTTP handlers, as plain functions, and plain data) is not refused. Anything that runs your code for it ends that: a function view, a decorator or wrapper around `as_view()`, `as_view()` arguments other than plain data (`as_view(dispatch=f)`), a property or a metaclass, route middleware, a `Route` class of your own with its own `handle()`, a `functools.partial` of the endpoint. Then `OPTIONS` is refused. Middleware, error handlers and converters are not the view: they run for every request, on any path. When the router has no handler for a route of the map, requests near it are refused, whatever their method (a `GET` near a `POST` route may run its handler): map only the routes your app serves. A checked request whose matched rule (Flask's `request.url_rule`, Django's `resolver_match`) has the route's own shape names the route's handler at once. Otherwise the SDK finds a route's handler in the router's own rules (Flask's URL map, Starlette's routes and mounts, Django's `path()` patterns, and `re_path()` patterns that are literal text and one-segment named groups, such as `^notes/(?P[0-9a-f]{24})/archive$`): a rule of the route's shape, its converters aside, names it, even when the converter refuses every sample value (``). Where there is no such rule (a regular expression with alternatives, optional parts or a group that may take a `/`), it resolves sample values (`1`, `a`, a UUID); when a catch-all answers them instead, the log says the handler is not known, and requests near the route are refused until its own handler is found. A checked request teaches a handler as the route's only when the rule that matched has the route's own shape, or the router also chooses it for the route's sample values: a literal page (`/api/notes/export` next to `/api/notes/{id}`) serves one value, not the route, so a request checked for the route that reaches it is refused and nothing is learnt. Two routes of one shape, parameter names aside (`/items/{id}` and `/items/{item}`), are one template. A catch-all is never learnt: next to the route's own handler, a checked request that would run one is refused; when the route's own handler is not known and the catch-all is the only handler found for it (a front controller, a router mounted at `/`), it runs for that checked request if the route covers every other route for which that catch-all is protected (every route whose own handler is not known and among whose handlers it is found, and every route for which it is a catch-all under the prefix: a request checked at level 1 never runs a front controller that is also one of a level-3 route's handlers), and the route stays not known. A site-wide or SPA fallback (a `/` rule at the root, as the router shows) is protected for a route only while that route's own handler is not known, so its pages run once every route of the map has a handler of its own (if a route's only handler is the fallback, a front controller, the fallback is that route's handler, protected, and the log names the route); a catch-all under the route's prefix (`/notes//`, or `/notes//` for `/notes/{id}/archive`) stays protected and keeps the route unknown, until the route's own handler is known (a rule of its own shape, which also frees an SPA fallback next to a tenant route `/{org}/notes/{id}`): give the route a rule of its own shape. Limit: a site-wide catch-all that dispatches protected actions on paths no route maps (a legacy `/` controller that deletes at `/legacy/delete?id=7`) is not something the SDK can see, and a front controller shared by routes of different capabilities or resources runs for none of them (covering needs the same capability and resource): give each protected route its own handler. A view class is one handler per set of arguments: `Item.as_view("users", User)` is not the handler of a route served by `Item.as_view("notes", Note)`, and two views of one class with the same arguments are the same handler. A bare WSGI or ASGI app cannot tell: there, next to a protected route that ends in a word (`DELETE /notes/{id}/archive`), a catch-all of yours that also takes longer paths runs `DELETE /notes/7/archive/x` without a check. ```python aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Ltd", "country": "FR"}, routes=routes, templates=templates, unprotected=[("DELETE", "/notes/{id}/comments"), ("GET", "/notes.json")], # your own pages: the app's, unchanged ) ``` A path that is a route of the map cannot be declared. An encoded `?` or `#` in a path segment stays part of the segment. The URL a proof is checked against is the path as the client sent it (ASGI `raw_path`); WSGI and Django give only the decoded path, which the SDK encodes again, so there an encoded reserved character (`%40` for `@`) in a path segment is refused: send it unencoded or serve the API with an ASGI server. ### WSGI `app = aby.wsgi(app)`; the Context is `environ["allowedby.context"]`. See the quick start above (`sdks/python/examples/quickstart.py`). Falcon and Bottle work the same way: their apps, and a plain one with every route, are in `sdks/python/examples/frameworks/`. ### FastAPI From `sdks/python/examples/frameworks/fastapi/app.py`: ```python """FastAPI: the middleware, the Context as a dependency, and FastAPI's OpenAPI with the AllowedBy members. Run: uvicorn app:app --port 8000""" import itertools import os from fastapi import Depends, FastAPI from pydantic import BaseModel, Field from allowedby import AllowedBy, Context, route from allowedby.fastapi import allowedby_context, install aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Interop Ltd", "country": "FR"}, routes=[ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="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}"}, refresh_seconds=float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), ) app = FastAPI(title="Notes") install(app, aby) notes: dict[str, list[dict[str, str]]] = {} # person -> their notes ids = itertools.count(1) def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id class Note(BaseModel): text: str = Field(min_length=1, max_length=2000) @app.get("/health") def health() -> dict[str, bool]: return {"ok": True} # not in the route map: yours, unchanged @app.get("/me") def me(ctx: Context = Depends(allowedby_context)) -> dict[str, object]: return {"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level} @app.get("/notes") def list_notes(ctx: Context = Depends(allowedby_context)) -> dict[str, object]: return {"notes": notes.get(person(ctx), [])} @app.post("/notes", status_code=201) def add_note(note: Note, ctx: Context = Depends(allowedby_context)) -> dict[str, str]: nid = str(next(ids)) notes.setdefault(person(ctx), []).append({"id": nid, "text": note.text}) return {"id": nid} @app.delete("/notes/{id}") def delete_note(id: str, ctx: Context = Depends(allowedby_context)) -> dict[str, str]: mine = notes.get(person(ctx), []) for note in [n for n in mine if n["id"] == id]: # in place: a note added meanwhile stays mine.remove(note) return {"deleted": id} ``` `install(app, aby)` adds the middleware and serves FastAPI's own `/openapi.json` with `security` and `x-allowedby` on every operation of the route map (readable from any origin). At start-up it checks that every route of the map has a FastAPI operation with the same method and path; a missing one stops the start. `allowedby_context` answers 403 on a route outside the map; `optional_allowedby_context` returns None there. ### Starlette and any ASGI app From `sdks/python/examples/frameworks/starlette/app.py`: ```python """Starlette: AllowedByMiddleware; the Context is request.state.allowedby. Run: uvicorn app:app --port 8000""" import itertools import json import os from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.responses import JSONResponse from starlette.routing import Route from allowedby import AllowedBy, route from allowedby.asgi import AllowedByMiddleware aby = AllowedBy( origin=os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), node=os.environ.get("ALLOWEDBY_NODE", "http://localhost"), org={"legal_name": "Notes Interop Ltd", "country": "FR"}, routes=[ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="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}"}, refresh_seconds=float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), ) notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None async def health(request): return JSONResponse({"ok": True}) # not in the route map: yours, unchanged async def me(request): ctx = request.state.allowedby return JSONResponse({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level}) async def list_notes(request): return JSONResponse({"notes": notes.get(person(request.state.allowedby), [])}) async def add_note(request): text = text_of(await request.body()) if not isinstance(text, str) or not 0 < len(text) <= 2000: return JSONResponse({"error": "text: a string of 1 to 2000 characters"}, 400) note = {"id": str(next(ids)), "text": text} notes.setdefault(person(request.state.allowedby), []).append(note) return JSONResponse({"id": note["id"]}, 201) async def delete_note(request): mine = notes.get(person(request.state.allowedby), []) for note in [n for n in mine if n["id"] == request.path_params["id"]]: # in place: a note added meanwhile stays mine.remove(note) return JSONResponse({"deleted": request.path_params["id"]}) app = Starlette( routes=[ Route("/health", health), Route("/me", me), Route("/notes", list_notes, methods=["GET"]), Route("/notes", add_note, methods=["POST"]), Route("/notes/{id}", delete_note, methods=["DELETE"]), ], middleware=[Middleware(AllowedByMiddleware, aby=aby)], ) ``` For a bare ASGI app: `app = AllowedByMiddleware(app, aby)`; the Context is also in `scope["allowedby.context"]` (`sdks/python/examples/frameworks/asgi/app.py`). The check never blocks the event loop: it runs in a worker thread (about 0.3 ms of hand-off, measured). ### Flask From `sdks/python/examples/frameworks/flask/app.py`: ```python """Flask: the AllowedBy extension; the Context is g.allowedby. Run: flask --app app run --port 8000""" import itertools import json import os from flask import Flask, g, request from allowedby import route from allowedby.flask import AllowedBy app = Flask(__name__) app.config["ALLOWEDBY"] = { "origin": os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), "node": os.environ.get("ALLOWEDBY_NODE", "http://localhost"), "org": {"legal_name": "Notes Interop Ltd", "country": "FR"}, "routes": [ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="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}"}, "refresh_seconds": float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), } AllowedBy(app) notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None @app.get("/health") def health(): return {"ok": True} # not in the route map: yours, unchanged @app.get("/me") def me(): return {"agent": g.allowedby.agent, "operator": g.allowedby.operator, "level": g.allowedby.level} @app.get("/notes") def list_notes(): return {"notes": notes.get(person(g.allowedby), [])} @app.post("/notes") def add_note(): text = text_of(request.get_data()) if not isinstance(text, str) or not 0 < len(text) <= 2000: return {"error": "text: a string of 1 to 2000 characters"}, 400 note = {"id": str(next(ids)), "text": text} notes.setdefault(person(g.allowedby), []).append(note) return {"id": note["id"]}, 201 @app.delete("/notes/") def delete_note(note_id): mine = notes.get(person(g.allowedby), []) for note in [n for n in mine if n["id"] == note_id]: # in place: a note added meanwhile stays mine.remove(note) return {"deleted": note_id} ``` `AllowedBy(app, aby=...)` takes an instance instead; `ext.init_app(app)` works for app factories. ### Django From `sdks/python/examples/frameworks/django/app.py`: ```python """Django in one file: settings.ALLOWEDBY and the middleware; the Context is request.allowedby. Run: python app.py runserver 8000""" import itertools import json import os import sys from django.conf import settings from allowedby import route settings.configure( DEBUG=False, ALLOWED_HOSTS=["localhost", "127.0.0.1", "testserver"], ROOT_URLCONF=__name__, SECRET_KEY=os.environ.get("DJANGO_SECRET_KEY", "change-me"), MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware", "allowedby.django.AllowedByMiddleware"], ALLOWEDBY={ "origin": os.environ.get("ALLOWEDBY_ORIGIN", "http://localhost:8000"), "node": os.environ.get("ALLOWEDBY_NODE", "http://localhost"), "org": {"legal_name": "Notes Interop Ltd", "country": "FR"}, "routes": [ route("GET", "/me", level=0, summary="Who is calling"), route("GET", "/notes", "notes:read", level=1, resource="note:*", summary="List your notes"), route("POST", "/notes", "notes:write", cls="write", level=1, resource="note:new", summary="Add a note", body={"text": "the note"}), route("DELETE", "/notes/{id}", "notes:delete", cls="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}"}, "refresh_seconds": float(os.environ.get("ALLOWEDBY_REFRESH_SECONDS", "5")), }, ) from django.http import JsonResponse # noqa: E402 - after settings.configure from django.urls import path # noqa: E402 from django.views import View # noqa: E402 from django.views.decorators.http import require_http_methods # noqa: E402 notes, ids = {}, itertools.count(1) # person -> their notes def person(ctx) -> str: """The person of a level 1 or 2 route (the key of their notes); level 0 has none, and none is invented.""" if ctx is None or ctx.human_id is None: raise LookupError("no person at level 0") return ctx.human_id def text_of(raw: bytes) -> object: """The body's "text", or None when the body is not a JSON object (the request then gets a 400).""" try: body = json.loads(raw or b"{}") except ValueError: return None return body.get("text") if isinstance(body, dict) else None def health(request): return JsonResponse({"ok": True}) # not in the route map: yours, unchanged def me(request): ctx = request.allowedby return JsonResponse({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level}) class Notes(View): """One view class, one method each: GET /notes (read) and POST /notes (write) are routes of their own, so each runs only for a request checked for it (a single function for both would run the write for a read check: refused).""" def get(self, request): return JsonResponse({"notes": notes.setdefault(person(request.allowedby), [])}) def post(self, request): mine = notes.setdefault(person(request.allowedby), []) text = text_of(request.body) if not isinstance(text, str) or not 0 < len(text) <= 2000: return JsonResponse({"error": "text: a string of 1 to 2000 characters"}, status=400) note = {"id": str(next(ids)), "text": text} mine.append(note) return JsonResponse({"id": note["id"]}, status=201) @require_http_methods(["DELETE"]) def note_view(request, note_id): mine = notes.get(person(request.allowedby), []) for note in [n for n in mine if n["id"] == note_id]: # in place: a note added meanwhile stays mine.remove(note) return JsonResponse({"deleted": note_id}) urlpatterns = [ path("health", health), path("me", me), path("notes", Notes.as_view()), path("notes/", note_view), ] if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ``` In a project, put `ALLOWEDBY = {...}` in `settings.py` (or a dotted path to an `AllowedBy` instance) and add `"allowedby.django.AllowedByMiddleware"` to `MIDDLEWARE`. A request the SDK accepted is exempt from Django's CSRF check: it carries no cookie credential, and the agent signed this exact method, URL and body. ## The context An accepted request gives the handler a read-only `Context`; setting a field raises `AttributeError`. | Field | Type | Meaning | |---|---|---| | `human_id` | `str \| None` | The person, as a pseudonym specific to your origin (None on level 0 routes) | | `level` | `int` | The identity level actually proven: 0 to 3 | | `agent` | `str` | The agent's passport subject (`did:oaid:...`) | | `operator` | `str \| None` | Who runs the agent: a verified domain, or a node-scoped id | | `capabilities` | `list[str]` | The capabilities of the grant used | | `display` | `dict \| None` | What the person saw and signed: `summary`, `lines`, `lang` | | `gid`, `rev`, `jti` | `str`, `int`, `str` | The grant's id, revision and document id (audit) | | `acting_for` | `dict \| None` | The organisation the person acts for, with its mandate (`org`, `name`, `role`) | | `tenant` | `str \| None` | The `{tenant}` path parameter, when tenants are configured | | `linked_account` | `str \| None` | On a `require_link` route, the account the person is linked to (ABY-3 §6); `None` elsewhere | | `route` | `dict` | The route of the map that matched, after tenant overrides | | `chain` | `list[tuple[str, int]]` | `(gid, rev)` of each grant, leaf first (sub-agents) | | `run`, `call` | `str \| None`, `int \| None` | The agent's run id and call counter from the proof (audit) | | `proof_jti` | `str` | The proof's id (audit) | | `params` | `dict[str, str]` | The route's path values as checked (`{"id": "7"}`): from the normalised path, decoded once. Act on these, never on your own reading of the raw path (`DELETE /notes/7/.` is checked as `/notes/7`) | `ctx.as_dict()` returns the fields as a dict; `repr(ctx)` shows ids only. `aby.personal_data(ctx)` returns the attributes the person chose to share for this grant (extended feature `disclose`). ## Production Keep the keys in one file, share the store between instances, and let the background refresh run. From `sdks/python/examples/production.py`: ```python """Production settings: keys kept across restarts and shared by instances, a Redis store shared by every machine, JSON audit lines on stdout. Several instances behind a load balancer run this same code.""" import os from allowedby import AllowedBy, route from allowedby.redis_store import RedisStore aby = AllowedBy( origin=os.environ["ALLOWEDBY_ORIGIN"], # https://api.example.com, as agents call it node=os.environ["ALLOWEDBY_NODE"], # the node you trust org={"legal_name": "Notes Ltd", "country": "FR", "website": "https://notes.example"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*"), route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}")], templates={"notes:read": "Read your notes", "notes:delete": "Delete note {scope}"}, key_file=os.environ.get("ALLOWEDBY_KEY_FILE", "/run/secrets/allowedby-keys.json"), # one file, every instance store=RedisStore.from_url(os.environ["REDIS_URL"]), # replay set, single use and counters, shared refresh_seconds=5, # node statement and status lists, fetched in the background audit_sink="stdout-json", # one JSON line per decision: codes and ids, no personal data ) ``` - **Keys** (`key_file`): the signing key (Ed25519) and the disclosure key (P-256). Created on first use with mode 0600, atomically, first writer wins (the folder needs hard links, else the start fails with a message); every SDK reads the same JSON format. Without it, both keys are new at each start. Keep the file in a secret store (a mounted secret on Kubernetes or Cloud Run). - **Store**: `MemoryStore` (the default) holds the replay set, single-use consumption and counters for **one process only**. With several processes or machines, use `RedisStore` (atomic with WATCH/MULTI, amounts added as decimals) or `SqliteStore(path)` (one machine, several processes). Expiry follows the SDK's clock. A store that fails refuses the request (503 `status_stale`); it never accepts it. - **Refunds** (sdks/CONTRACT.md, Refund on the SDK's own refusal): the check consumes a single-use approval and adds to the grant's totals and the tenant budget. When the SDK then refuses that request itself before the view (the Flask extension, `wsgi_guard()`, Django's middleware, the ASGI guard's first check: rule 5, a method or path changed after the check), `AllowedBy.release(ctx)` gives back exactly what the check spent, once, so the approval stays usable. A refund the store does not take leaves it spent. Nothing is given back once the view started (the adapters call `started(ctx)` as they hand the request on, so a second dispatch of the same request gets nothing back, and refuse a request already given back, which `started(ctx)` answers with False: it never reaches a view), nor for a refusal of your own (use `refund(ctx)` to give a tenant budget back). - **Trust**: by default the SDK pins the node's key on first fetch (TOFU). For a fixed list of nodes, pass `trust_list=TrustList(jws, service_key)` (OAID-5). - **Refresh**: node statements and status lists are fetched in the background every `refresh_seconds` (status lists at least every 60 s), never on the request path. A failure logs `[verifier] refresh failed` and the SDK keeps serving from its cache within the freshness rules (stale lists refuse with 503). - **Logging**: one line per decision on stdout (method, path, code; never tokens, keys or bodies); `audit_sink="stdout-json"` or a callable adds JSON events (ORG-1 §7.6). - **Origin**: `origin` is the public URL agents call. Behind a proxy, the SDK builds URLs from `origin` and the path the app sees: the proxy must not rewrite the path. Mounted under a prefix (ASGI `root_path`, a Starlette `Mount`, WSGI `SCRIPT_NAME`), the route map is matched on the path without the prefix, and proofs are checked against the full URL the agent called (`origin` + prefix + path). The callback URL, the link route and the links in the discovery documents carry the prefix too. Nodes and agents read `/.well-known/allowedby` at the origin's root: serve it there as well (route it to the same app). ## Agents `Agent` calls AllowedBy APIs for a person; `Wallet` turns it into tools for MCP, LangChain and the OpenAI Agents SDK, which pause while the person approves. From `sdks/python/examples/agent_quickstart.py`: ```python """Agent quick start: call an AllowedBy API as a person's agent. The person approves on their own device.""" import os from allowedby import Agent def tell(message): if message["type"] == "approval_needed": print("Approve on your device. Check the code %s: %s" % (message["code"], message["link"])) agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=tell) if __name__ == "__main__": status, body = agent.call("GET", os.environ.get("APP_URL", "http://notes.localhost") + "/notes", action="notes:read") print(status, body) ``` `agent.call(method, url, body, action)` gets a passport (tier 0) from the node, signs the request with a proof, and on a challenge asks the node for an approval, tells the person the link and the binding code, waits for the tap (long polling), and retries once. Standing grants (read and write) are reused while they cover the action. `operator_domain` and `operator_key` let approvals survive a new passport (rebind, ABY-1 §6); `agent.delegate(...)` gives a sub-agent an attenuated grant (ABY-1 §4). A tier 0 passport comes with a new key. The agent keeps the previous key in memory until its passport expires, so a standing grant or a pending approval that names it stays usable. The wait for the person ends before the passport that asked expires. An approval link is shown only when it is on the agent's node, or on the approval page the node names in its signed statement (OAID-2 §3). `node_origin` must be an `https` origin (`http` on this machine only), else `ValueError`. ### MCP The `allowedby-mcp` command is an MCP server over stdio with four tools: `allowedby_discover`, `allowedby_call`, `allowedby_wait`, `allowedby_approvals`. ```bash claude mcp add allowedby -- allowedby-mcp --node https://demo.allowedby.com allowedby-mcp --node http://localhost --no-browser --allow https://notes.example ``` The approval page opens in the person's browser; when the tap takes longer than the call's wait, the tool returns the sentence to show the person verbatim (`tell_the_person`), with a job id for `allowedby_wait`. Approvals are kept in `~/.allowedby/mcp-approvals.json` (`--state`). ### LangChain From `sdks/python/examples/frameworks/langchain/agent.py`: ```python """LangChain: the AllowedBy tools for any LangChain agent. `tell` posts the approval link and code into the conversation; the request tool waits for the person's tap.""" import os from allowedby import Agent from allowedby.langchain import AllowedByDiscoverTool, AllowedByRequestsTool from allowedby.tools import Wallet def tell(message): if message["type"] == "approval_needed": print(message["text"]) # the sentence to show the person, verbatim (link and code) wallet = Wallet(Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost")), tell=tell) tools = [AllowedByDiscoverTool(wallet=wallet), AllowedByRequestsTool(wallet=wallet, wait_seconds=300)] # Give `tools` to your agent: langchain.agents.create_agent(model, tools=tools). ``` ### OpenAI Agents SDK From `sdks/python/examples/frameworks/openai-agents/agent.py`: ```python """OpenAI Agents SDK: the AllowedBy tools as FunctionTools.""" import os from agents import Agent as Assistant from allowedby import Agent from allowedby.openai_agents import INSTRUCTIONS, allowedby_tools from allowedby.tools import Wallet def tell(message): if message["type"] == "approval_needed": print(message["text"]) # the sentence to show the person, verbatim (link and code) wallet = Wallet(Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost")), tell=tell) assistant = Assistant(name="assistant", instructions=INSTRUCTIONS, tools=allowedby_tools(wallet)) # Run: agents.Runner.run_sync(assistant, "Read my notes on https://notes.example") ``` `Wallet(agent, tell, allowed_origins=[...])` restricts the sites the tools may call; `state=path` keeps approvals across restarts in a private file. ## Errors Every refusal is `application/problem+json` with `type: https://allowedby.org/errors/`; 401 answers carry `WWW-Authenticate: AllowedBy ...`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a header is repeated or unreadable | Fix the request | | `passport_required` | 401 | No `Allowed-By` header | The agent gets a passport from its node and retries | | `invalid_signature` | 401 | A signature, proof, chain or `human_sig` check failed, or the proof was replayed | The agent signs a fresh proof; check its clock (-120 s to +60 s) | | `untrusted_node` | 401 | The grant or passport comes from a node this service does not trust | Use a trusted node, or add it (trust list) | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses | Retry later; the node operator fixes its witnesses | | `grant_required` | 401 | The route needs a person's approval and the agent showed only its passport | The agent asks the person (the challenge says what) | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator) | The agent asks for a grant that covers it | | `level_insufficient` | 401 | The person's identity level is below the route's | The person verifies their identity to that level | | `qes_required` | 401 | The route needs a qualified electronic signature | The person signs with a qualified signature | | `authority_required` | 401 | The organisation's co-approvers have not approved | The co-approvers approve | | `mandate_required` | 401 | The route needs a company mandate | The person acts with their company's mandate | | `expired` | 401 | The grant has expired | The agent asks again | | `not_yet_valid` | 401 | The grant's `nbf` is in the future | Check clocks; retry | | `revoked` | 401 | The person or the node withdrew the grant | The agent asks again; respect the person's choice | | `actor_expired` | 401 | The agent's key (passport) expired | The agent gets a new passport and rebinds its grants | | `class_lifetime_exceeded` | 401 | The grant lives longer than the route's class allows | The agent asks for a shorter grant | | `single_use_consumed` | 401 | A one-time grant was already used | The agent asks again for this request | | `capability_denied` | 403 | Not allowed at all (route unknown, operator not accepted, over a ceiling) | Do not retry | | `tier_insufficient` | 403 | The agent's key custody or the passkey kind is too weak | Use a stronger custody tier or passkey | | `human_not_linked` | 403 | The person has not linked their account here | The person links their account (`aby:link`) | | `budget_exceeded` | 403 | The organisation's budget for this action is used up | Wait for the next period or raise the budget | | `rate_limited` | 429 | Too many requests from this agent or operator | Wait (`Retry-After`) | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two grants (depth 1) | Send a shorter chain | | `status_stale` | 503 | The revocation list is too old to decide, or the replay store is unavailable | Retry after `Retry-After` | `allowedby.STATUS` maps every code to its status. ## Testing Run the vectors and the interop test from the repository root, and test your own app offline with `aby.check()`. ```bash pip install -r requirements.txt -e "sdks/python[asgi,fastapi,django,flask,redis,langchain,openai-agents,dev]" python sdks/python/tests/conformance.py # verifier profile: 481/481, runtime profile: 122/122 (cd sdks/python && python -m pytest -q) # unit tests, every adapter, stores, agent tools python sdks/interop/interop.py --cmd "python sdks/interop/reference_app.py" # 26/26 python sdks/python/examples/frameworks/run.py flask fastapi # 26/26 each python sdks/interop/interop.py --agent-cmd "python sdks/python/examples/interop_agent.py" # 7/7 ``` On Windows (PowerShell) the commands are the same; set the interop ports with `$env:INTEROP_PORT_BASE = "19100"` when another run uses the defaults. `REDIS_URL=redis://localhost:6379/0` runs the store tests on a real Redis (`docker run -p 6379:6379 redis:7.4-alpine`); without it they use `fakeredis`. Testing your own app needs no browser and no node: `background_refresh=False` keeps the SDK offline, and `aby.check(method, path, headers, body)` returns its decision. From `sdks/python/examples/testing.py`: ```python """Testing your own app without a browser or a node: `aby.check()` gives the SDK's answer to any request, and `background_refresh=False` keeps the test offline. A request without a passport gets the challenge an agent sees. Run: python testing.py (or with pytest: the test_* functions)""" from allowedby import AllowedBy, route aby = AllowedBy( origin="https://notes.example", node="https://node.example.org", org={"legal_name": "Notes Ltd", "country": "FR"}, routes=[route("GET", "/notes", "notes:read", level=1, resource="note:*"), route("GET", "/health", level=0)], templates={"notes:read": "Read your notes"}, background_refresh=False, # no thread, no fetch: the node is never contacted ) def test_a_request_without_passport_gets_the_challenge(): ctx, refusal = aby.check("GET", "/notes", headers={}) status, problem, headers = refusal assert ctx is None and status == 401 and problem["type"].endswith("/passport_required") assert headers["WWW-Authenticate"] == 'AllowedBy realm="notes.example", error="passport_required"' def test_paths_outside_the_route_map_are_yours(): assert aby.check("GET", "/about", headers={}) == (None, None) def test_discovery_documents(): assert aby.openapi()["paths"]["/notes"]["get"]["x-allowedby"]["capability"] == "notes:read" assert aby.well_known()["templates"]["notes:read"]["summary"]["en"] == "Read your notes" if __name__ == "__main__": for name, fn in list(globals().items()): if name.startswith("test_"): fn() print("ok", name) ``` For an accepted request end to end, run your app under the interop harness (`interop.py --cmd`): it starts a real node, an agent and a person with a software passkey. `sdks/python/tests/conftest.py` shows how the SDK's own tests verify real signed requests offline, with the vectors' node and clock. ## Reference The public API is `allowedby` (service and agent), plus one module per integration. | Name | What | |---|---| | `AllowedBy(origin, node, routes, templates, org, ...)` | The service SDK. Options: `key_file`, `store`, `trust_list`, `refresh_seconds`, `node_max_level`, `clock`, `title`, `version`, `description`, `max_body`, `background_refresh`, `serve_openapi`, `unprotected`, and the extended ones below | | `AllowedBy.check(method, path, headers, body, query)` | `(Context, None)` accepted; `(None, response)` refused; `(None, None)` outside the map | | `AllowedBy.process(...)` | `handle()` then `check()`: what every adapter calls | | `AllowedBy.handle(method, path, headers, body)` | The SDK's own endpoints, or None | | `AllowedBy.wsgi(app, guarded=False)`, `wsgi_guard(app)`, `may_dispatch(method, path, checked)` | WSGI middleware; the check again at dispatch | | `AllowedBy.openapi()`, `well_known()`, `api_catalog()`, `describe(method, path)` | The discovery documents; one operation's OpenAPI members | | `AllowedBy.personal_data(ctx)`, `refund(ctx)`, `release(ctx)`, `started(ctx)`, `link_start(account)`, `unlink(account)` | Disclosed attributes; give a tenant budget back; give back what the check spent for a request the SDK refused itself; mark the request as handed to its handler (no refund after that; False for a request given back, which the adapter refuses); account linking code; remove an account's link (and its pending codes), for an account deleted or a person who asks to be forgotten | | `route(method, path, capability, cls, level, resource, ...)` | One route of the map | | `render(response)` | A response as `(status, headers, bytes)` | | `load_keys(path)` | The key file: `(signing Key, disclosure key)` | | `Context` | The accepted request (read-only) | | `Store` (protocol), `MemoryStore`, `SqliteStore`, `redis_store.RedisStore` | Replay set, single use, counters | | `TrustList(jws, key)` | A signed OAID-5 trust list | | `Reject`, `STATUS` | A refusal (`code`, `status`, `why`); code to status | | `Agent(node, operator, runtime, tell, poll_timeout, operator_domain, operator_key, http_sig)` | The agent SDK: `call`, `delegate`, `adopt`, `rebind`, `ensure_passport`, `wait_for` | | `asgi.AllowedByMiddleware(app, aby, guarded=False)`, `asgi.DispatchGuard(app, aby)` | ASGI middleware; the check again at dispatch | | `fastapi.install(app, aby)`, `allowedby_context`, `optional_allowedby_context`, `enrich_openapi`, `check_routes` | FastAPI | | `django.AllowedByMiddleware`, `django.from_settings()` | Django | | `flask.AllowedBy(app, aby=None)` | Flask extension | | `tools.Wallet(agent, tell, state, allowed_origins)`, `tools.TOOLS`, `tools.INSTRUCTIONS` | Agent tools shared by the integrations | | `mcp.main()`, `mcp.Server`, `mcp.wallet_for(node, ...)` | MCP server (`allowedby-mcp`) | | `langchain.AllowedByRequestsTool`, `langchain.AllowedByDiscoverTool` | LangChain tools | | `openai_agents.allowedby_tools(wallet)` | OpenAI Agents SDK tools | What is implemented (sdks/CONTRACT.md): - **Core** (§2, all of it): configuration checked at construction, the route map, discovery (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), verification ABY-2 §5 steps 1-10 (proof JWT and RFC 9421, passports, grant chains, `human_sig`, status lists, trust on first use and OAID-5 trust lists, EdDSA and ES256 only), challenges with service-initiated approvals, background refresh, the Context, the stores (memory, SQLite, Redis), the key file, middleware for WSGI, ASGI, FastAPI, Django and Flask. - **Extended** (all of them, as the reference): disclosure callback and JWE decryption (`disclosure`), tenants and tenant budgets (`tenants`), authority policies (`authority_policy`), account linking (`require_link`, `link_start`), AllowedBy-Nonce (`nonce`), company mandates (`mandate`), level profiles (`level_profile`), rate limits (`rate`), the audit sink (`audit_sink`), the admin console (`/allowedby/admin`). - **Agent** (§3): passports, proofs, challenges, approvals, rebind, renewal, sub-agents, and the MCP, LangChain and OpenAI Agents SDK integrations. Version: package 0.1.0, specification set 0.2.14. The full source is `sdks/python/src/allowedby/`. --- Source: https://docs.allowedby.com/sdk/js # AllowedBy SDK for TypeScript and JavaScript `@allowedby/sdk` lets AI agents use your API for a person, with that person's approval (a passkey tap on their AllowedBy node). Your service publishes what each operation needs; the SDK verifies every agent request offline (ABY-2 §5), answers with a challenge when an approval is missing, and creates the approval itself for serious actions. The concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in TypeScript and JavaScript. Terms used here: an **agent passport** is the agent's signed identity from its node; a **grant** is the person's signed approval; a **proof** is a JWT the agent signs for each request; **JWS** is a signed JSON document (RFC 7515); **JCS** is canonical JSON (RFC 8785). ## Install Install the package with npm (or pnpm, yarn, bun); it has no runtime dependency. ```sh npm install @allowedby/sdk ``` - **Runtimes**: Node.js 20, 22 and 24; Bun 1.3.3+; Deno 2; Cloudflare Workers (through the Hono adapter). The core uses only WebCrypto (`globalThis.crypto.subtle`: Ed25519, P-256 ECDSA, HMAC), `fetch`, `TextEncoder` and `DecompressionStream`, so the same code runs everywhere. - **Modules**: ES modules and CommonJS (`import` or `require`), with TypeScript types. - **Dependencies**: none at run time. Frameworks are optional peer dependencies: the adapter for a framework is under its own import path (`@allowedby/sdk/express`, `/fastify`, `/hono`, `/next`, `/nest`, `/node`) and loads nothing else. The shared Redis store (`@allowedby/sdk/redis`) takes an `ioredis` client you create. - **Not published yet**: until the package is on npm, build it from this repository: ```sh cd sdks/js npm ci npm run build npm pack # -> allowedby-sdk-0.1.0.tgz, then: npm install /path/to/allowedby-sdk-0.1.0.tgz ``` ## Quick start A service that accepts agents is one `AllowedBy` object and one wrapper around your server (file: `sdks/js/examples/quickstart.mjs`). ```js import http from "node:http"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedByNode } from "@allowedby/sdk/node"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "http://localhost:3000", node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, }); http.createServer(allowedByNode(aby, (req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ notes: [], person: req.allowedby?.humanId ?? null })); })).listen(Number(process.env.PORT ?? 3000), process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` See it work against a local node. The node and its demo sites run from the repository (Python 3.10+ with the packages of `requirements.txt`): Linux and macOS: ```sh python demo/run.py --port 8700 & # the node on http://localhost:8700 node sdks/js/examples/quickstart.mjs & sleep 5 # both have started curl -s http://localhost:3000/.well-known/allowedby # what agents read curl -si http://localhost:3000/notes # 401 passport_required: an agent must present a passport ``` Windows (PowerShell): ```powershell Start-Process python -ArgumentList "demo/run.py", "--port", "8700" Start-Process node sdks/js/examples/quickstart.mjs Start-Sleep 5 Invoke-RestMethod http://localhost:3000/.well-known/allowedby curl.exe -si http://localhost:3000/notes ``` The whole flow (an agent asks, a person approves with a passkey, the agent retries) is what the interop test runs: see [Testing](#testing). In a container, see `sdks/js/examples/Dockerfile`: ```sh docker build -f sdks/js/examples/Dockerfile -t allowedby-notes sdks/js docker run -p 3000:3000 -e ALLOWEDBY_ORIGIN=http://localhost:3000 -e ALLOWEDBY_NODE=https://node.example.org allowedby-notes ``` ## Routes and templates Each operation agents may call is one `route(method, path, capability, options)` line, and each capability has a template: the sentence the person reads and signs (file: `sdks/js/examples/routes.mjs`). ```js import { route } from "@allowedby/sdk"; export const routes = [ route("GET", "/me", undefined, { level: 0 }), // the agent's passport is enough route("GET", "/notes", "notes:read", { resource: "note:*" }), // read, level 1 (a passkey tap) route("POST", "/notes", "notes:write", { class: "write", resource: "note:new", body: { text: "the note" } }), route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}" }), route("POST", "/invoices/{id}/pay", "invoices:pay", { class: [{ upTo: "1000.00", class: "write-hard" }, { class: "irreversible" }], // the class by amount amountField: "/total", currencyField: "/currency", level: 2, authn: "hardware", resource: "invoice:{id}", }), ]; export const templates = { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}", "invoices:pay": { summary: { en: "Pay {scope}, up to {amount.max} {amount.currency}" }, lines: { en: "Pay {scope}" } }, }; ``` | Option | Meaning | Default | |---|---|---| | `class` | `read`, `write`, `write-hard` (hard to undo), `irreversible`; or amount thresholds `[{upTo, class}, ..., {class}]` | `read` | | `level` | 0 agent only, 1 passkey tap, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey | 1 | | `resource` | What the grant's `scope` must cover; `{param}` from the path | `:*` | | `amountField`, `currencyField` | JSON Pointers to the amount and its currency in the body; the grant must cap the amount | none, `/currency` | | `authn` | The weakest passkey accepted: `synced` or `hardware` | any | | `tier` | Custody tier of the agent's key (OAID-6), 0 to 3 | 0 | | `maxLifetime` | Longest grant lifetime accepted, 60 s to 30 days | the class maximum (30 d, 7 d, 1 d, 1 h) | | `levelProfile` | `eu` or `na`, on a level-3 route ([Level profiles](#level-profiles)) | none | | `nonce` | The proof must carry a current service nonce ([AllowedBy-Nonce](#allowedby-nonce)); needs the service option `nonce` | false | | `summary`, `body` | Describe the operation to agents (OpenAPI) | none | | `requireLink` | The person must have linked their identity to one of your accounts ([Account linking](#account-linking)); else 403 `human_not_linked`. A route of level 1 or more | false | | `accountParam` | The path parameter that names one of your accounts: with `requireLink`, the person must be linked to that account | `account` | `write-hard` and `irreversible` routes are approved every time, for the exact request: the SDK creates that approval itself (a signed `POST {approvals}` to the node, ABY-2 §7) and the grant works once. `read` and `write` approvals are standing: the agent reuses them until they expire or the person withdraws them. The Python options `mandate`, `disclose`, `discloseOptional`, `authority` and `qes` are not enforced by this SDK yet: `route()` refuses them, so a route never accepts what it cannot check. ## Framework recipes Each recipe is the same notes service on one framework. CI runs each on every version below against a real node, agent and person, all the interop scenarios (`examples/frameworks.json`): | Framework | Versions run in CI | |---|---| | Node.js http | Node.js 20.20.2, 22.23.5, 24.22.3 | | Express | 4.18.0, 4.22.3, 5.0.0, 5.3.0 | | Fastify | 4.20.0, 4.29.1, 5.0.0, 5.12.8 | | Hono 4.0.6 (Node.js) and 4.13.22 | on Node.js, Bun 1.3.3 and 1.4.5, Deno 2.0.6 and 2.9.6, Cloudflare Workers (`wrangler dev`) | | Next.js, route handlers | 14.2.25, 15.5.29, 16.4.6 | | Next.js, middleware (`proxy.js` in 16) | 15.5.29, 16.4.6 | | NestJS | 10.0.0, 10.4.22, 11.2.12, 12.6.2 | Mount the SDK before your body parsers: the proof covers the body bytes exactly as received. The shared service (file: `sdks/js/examples/frameworks/notes.mjs`): ```js import { AllowedBy, route } from "@allowedby/sdk"; /** @param {Partial} [options] the settings of one deployment */ export function notesService({ origin = process.env.ALLOWEDBY_ORIGIN, node = process.env.ALLOWEDBY_NODE, ...options } = {}) { return new AllowedBy({ origin, node, org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ route("GET", "/me", undefined, { level: 0, summary: "Who is calling" }), route("GET", "/notes", "notes:read", { resource: "note:*", summary: "List your notes" }), route("POST", "/notes", "notes:write", { class: "write", resource: "note:new", summary: "Add a note", body: { text: "the note" } }), route("DELETE", "/notes/{id}", "notes:delete", { class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note" }), ], templates: { "notes:read": "Read your notes", "notes:write": "Write new notes", "notes:delete": "Delete note {scope}" }, ...options, }); } /** Each person's notes, by their id at this service (the context's `humanId`, never null here: the handlers answer 403 * without a person): nobody sees another person's. */ export class Notes { /** @type {Map} */ people = new Map(); next = 0; list(person) { return this.people.get(person) ?? []; } /** -> {id}, or null when the text is not one to keep. */ add(person, text) { if (typeof text !== "string" || text.length < 1 || text.length > 2000) return null; const note = { id: String(++this.next), text }; this.people.set(person, [...this.list(person), note]); return { id: note.id }; } remove(person, id) { this.people.set(person, this.list(person).filter((n) => n.id !== id)); } } ``` **Express** (file: `sdks/js/examples/frameworks/express/app.mjs`). The context is `req.allowedby`; the parsed body is `req.body` (the SDK reads it once and gives it back). ```js import express from "express"; import { allowedby } from "@allowedby/sdk/express"; import { Notes } from "../notes.mjs"; export function makeApp(aby, notes = new Notes()) { const app = express(); app.use(allowedby(aby)); // before the body parsers: the proof covers the body bytes app.use(express.json()); app.get("/health", (req, res) => res.json({ ok: true })); // not in the route map: no check app.get("/me", (req, res) => { const { agent, operator, level } = req.allowedby; res.json({ agent, operator, level }); }); app.get("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by res.json({ notes: notes.list(person) }); }); app.post("/notes", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); const note = notes.add(person, req.body?.text); if (!note) return res.status(400).json({ error: "text: a string of 1 to 2000 characters" }); res.status(201).json(note); }); app.delete("/notes/:id", (req, res) => { const person = req.allowedby.humanId; if (person === null) return res.status(403).json({ error: "no person at level 0" }); notes.remove(person, req.params.id); res.json({ deleted: req.params.id }); }); return app; } ``` **Fastify** (file: `sdks/js/examples/frameworks/fastify/app.mjs`). A plugin; the check runs in `preParsing`, so Fastify's parsers and schemas work unchanged. The context is `request.allowedby`. ```js import Fastify from "fastify"; import allowedby from "@allowedby/sdk/fastify"; import { Notes } from "../notes.mjs"; export async function makeApp(aby, notes = new Notes()) { const app = Fastify(); await app.register(allowedby, { aby }); app.get("/health", async () => ({ ok: true })); // not in the route map: no check app.get("/me", async ({ allowedby: { agent, operator, level } }) => ({ agent, operator, level })); app.get("/notes", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); // level 0: no person to key by return { notes: notes.list(person) }; }); app.post("/notes", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); const note = notes.add(person, req.body?.text); return note ? reply.code(201).send(note) : reply.code(400).send({ error: "text: a string of 1 to 2000 characters" }); }); app.delete("/notes/:id", async (req, reply) => { const person = req.allowedby.humanId; if (person === null) return reply.code(403).send({ error: "no person at level 0" }); notes.remove(person, req.params.id); return { deleted: req.params.id }; }); return app; } ``` **Hono** on Node, Bun, Deno and Cloudflare Workers (file: `sdks/js/examples/frameworks/hono/app.mjs`). The context is `c.get("allowedby")`. ```js import { Hono } from "hono"; import { allowedby } from "@allowedby/sdk/hono"; import { Notes } from "../notes.mjs"; export function makeApp(aby, notes = new Notes()) { const app = new Hono(); app.use(allowedby(aby, { app })); // the app: the SDK asks its router which handler serves each route of the map app.get("/health", (c) => c.json({ ok: true })); // not in the route map: no check app.get("/me", (c) => { const { agent, operator, level } = c.get("allowedby"); return c.json({ agent, operator, level }); }); app.get("/notes", (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); // level 0: no person to key by return c.json({ notes: notes.list(person) }); }); app.post("/notes", async (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); const note = notes.add(person, (await c.req.json()).text); return note ? c.json(note, 201) : c.json({ error: "text: a string of 1 to 2000 characters" }, 400); }); app.delete("/notes/:id", (c) => { const person = c.get("allowedby").humanId; if (person === null) return c.json({ error: "no person at level 0" }, 403); notes.remove(person, c.req.param("id")); return c.json({ deleted: c.req.param("id") }); }); return app; } ``` On Cloudflare Workers no timer runs between requests: pass `autoRefresh: false` and refresh as requests come (file: `sdks/js/examples/frameworks/hono/worker.mjs`). This worker keeps notes and replay set in one isolate: for production, give a shared `store`. ```js import { notesService } from "../notes.mjs"; import { makeApp } from "./app.mjs"; let app; // made by the first request: Workers have no settings, random values or timers before it let aby; let first; // the first refresh: one for every request, also those that come while it runs let refreshed = 0; const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export default { async fetch(request, env, ctx) { aby ??= notesService({ origin: env.ALLOWEDBY_ORIGIN, node: env.ALLOWEDBY_NODE, autoRefresh: false }); app ??= makeApp(aby); first ??= aby.refresh(); // the node's keys and revocation lists // A few seconds at most: then the check runs without them and refuses (untrusted_node, or 503 with Retry-After) await Promise.race([first, pause(1000 * Number(env.ALLOWEDBY_FIRST_REFRESH_SECONDS ?? 5))]); const now = Date.now(); if (now - refreshed >= 1000 * Number(env.ALLOWEDBY_REFRESH_SECONDS ?? 5)) { if (refreshed) ctx.waitUntil(aby.refresh()); refreshed = now; } return app.fetch(request, env, ctx); }, }; ``` **Next.js, route handlers.** The shared service, once per process (file: `sdks/js/examples/frameworks/next/route/lib/allowedby.js`): ```js import { notesService, Notes } from "./notes.mjs"; // One instance per process, whatever Next.js bundles where const shared = (globalThis.notesApp ??= { aby: notesService({ keyFile: process.env.ALLOWEDBY_KEY_FILE ?? ".allowedby/keys.json", refreshSeconds: Number(process.env.ALLOWEDBY_REFRESH_SECONDS ?? 5), }), notes: new Notes(), }); export const { aby, notes } = shared; ``` Wrap each App Router handler; the context is its third argument (file: `sdks/js/examples/frameworks/next/route/app/notes/route.js`): ```js import { withAllowedBy } from "@allowedby/sdk/next"; import { aby, notes } from "../../lib/allowedby.js"; export const dynamic = "force-dynamic"; export const GET = withAllowedBy(aby, (req, ctx, allowedby) => { const person = allowedby.humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); // level 0: no person to key by return Response.json({ notes: notes.list(person) }); }, { route: "GET /notes" }); // the route this handler serves: a request checked for another runs nothing here export const POST = withAllowedBy(aby, async (req, ctx, allowedby) => { const person = allowedby.humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); const note = notes.add(person, (await req.json()).text); if (!note) return Response.json({ error: "text: a string of 1 to 2000 characters" }, { status: 400 }); return Response.json(note, { status: 201 }); }, { route: "POST /notes" }); ``` The discovery documents are three more routes: `app/.well-known/allowedby/route.js`, and the same for `app/openapi.json/route.js` and `app/.well-known/api-catalog/route.js` (file: `sdks/js/examples/frameworks/next/route/app/.well-known/allowedby/route.js`): ```js import { withAllowedBy } from "@allowedby/sdk/next"; import { aby } from "../../../lib/allowedby.js"; export const dynamic = "force-dynamic"; // What agents read first: the SDK answers, the handler is never reached export const GET = withAllowedBy(aby, () => new Response(null, { status: 404 })); ``` **Next.js, middleware** (file: `sdks/js/examples/frameworks/next/middleware/middleware.js`). One place for every route and the discovery documents. The middleware forwards the context to the handler in a request header MAC'd with a key derived from the service's private key (it drops any copy a client sent); use `keyFile` so the middleware and the handlers share the key, and the Node.js middleware runtime (stable from Next.js 15.5). ```js // middleware.js (Next.js 15.5+, Node.js runtime): the discovery documents and the check of every route of the map import { allowedByMiddleware } from "@allowedby/sdk/next"; import { aby } from "./lib/allowedby.js"; export const middleware = allowedByMiddleware(aby); export const config = { matcher: ["/((?!_next/).*)"], runtime: "nodejs" }; ``` In Next.js 16 the file is `proxy.js` (file: `sdks/js/examples/frameworks/next/middleware/proxy.js`): ```js // proxy.js (Next.js 16+): the same, under its new name import { allowedByMiddleware } from "@allowedby/sdk/next"; import { aby } from "./lib/allowedby.js"; export const proxy = allowedByMiddleware(aby); export const config = { matcher: ["/((?!_next/).*)"] }; ``` The handlers read the context (file: `sdks/js/examples/frameworks/next/middleware/app/notes/route.js`): ```js // app/notes/route.js: the handler reads what the middleware checked import { readContext } from "@allowedby/sdk/next"; import { aby, notes } from "../../lib/allowedby.js"; export const dynamic = "force-dynamic"; export async function GET(req) { // the route this handler serves: a context checked for another throws (a rewrite after the middleware) const person = (await readContext(aby, req, { route: "GET /notes" })).humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); // level 0: no person to key by return Response.json({ notes: notes.list(person) }); } export async function POST(req) { const person = (await readContext(aby, req, { route: "POST /notes" })).humanId; if (person === null) return Response.json({ error: "no person at level 0" }, { status: 403 }); const note = notes.add(person, (await req.json()).text); if (!note) return Response.json({ error: "text: a string of 1 to 2000 characters" }, { status: 400 }); return Response.json(note, { status: 201 }); } ``` **NestJS** on the Express platform (file: `sdks/js/examples/frameworks/nest/src/app.ts`): a guard, the `@AllowedBy()` parameter decorator, and a middleware for the discovery documents. Create the app with `rawBody: true`: the guard checks the body as received. Compile with `"experimentalDecorators": true` (the Nest CLI default). ```ts import "reflect-metadata"; import { BadRequestException, Body, Controller, Delete, ForbiddenException, Get, Module, Param, Post, type INestApplication } from "@nestjs/common"; import { NestFactory } from "@nestjs/core"; import type { AllowedBy as AllowedByService, Context } from "@allowedby/sdk"; import { AllowedBy, AllowedByGuard, allowedbyDiscovery } from "@allowedby/sdk/nest"; import { Notes } from "../../notes.mjs"; const notes = new Notes(); @Controller() class NotesController { @Get("health") health() { return { ok: true }; // not in the route map: no check } @Get("me") me(@AllowedBy() { agent, operator, level }: Context) { return { agent, operator, level }; } @Get("notes") list(@AllowedBy() ctx: Context) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); // level 0: no person to key by return { notes: notes.list(person) }; } @Post("notes") add(@AllowedBy() ctx: Context, @Body() body?: { text?: unknown }) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); const note = notes.add(person, body?.text); if (!note) throw new BadRequestException("text: a string of 1 to 2000 characters"); return note; } @Delete("notes/:id") remove(@Param("id") id: string, @AllowedBy() ctx: Context) { const person = ctx.humanId; if (person === null) throw new ForbiddenException("no person at level 0"); notes.remove(person, id); return { deleted: id }; } } @Module({ controllers: [NotesController] }) class AppModule {} export async function makeApp(aby: AllowedByService): Promise { const app = await NestFactory.create(AppModule, { rawBody: true, logger: ["error"] }); // rawBody: the proof covers it app.use(allowedbyDiscovery(aby)); app.useGlobalGuards(new AllowedByGuard(aby)); return app; } ``` **Node.js http** is the quick start above (`allowedByNode`); the context is `req.allowedby` and the body bytes `req.rawBody`. The interop app is a complete example: `sdks/js/examples/interop.mjs`. **Any other framework**: call `aby.handle(method, path)` for the discovery documents, then `aby.check({ method, path, query, headers, body })` on the raw body bytes; it returns `{ context, refusal }` (both null outside the route map). Send `refusal.status`, `refusal.headers` and `JSON.stringify(refusal.body)`. What every adapter does, in this order (sdks/CONTRACT.md §2.10): the SDK's endpoints; paths outside the route map reach your app unchanged; on a route of the map, a non-empty body must be a JSON object sent as `application/json` (or without `Content-Type`) in UTF-8, without byte order mark, duplicate members, prototype members or `Content-Encoding`, else 400 before anything is charged, so the handler reads what the check read; then the headers are checked (431 above 8 KiB) before any signature work. Routers dispatch variants of a path to the same handler (`/Notes/`, `//notes`, `/notes;x`, `/notes.json`): the SDK checks such forms too, and the verifier then refuses them, instead of letting them through. A method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `?_method=`) on a route of the map is refused (400), and so is a `POST` with a body to a path the map lists for `PUT`, `PATCH` or `DELETE` but not `POST` (a form's `_method` field could turn it into one of them). **What the adapters refuse, and why.** The path that is checked must be the path the router uses, and a handler that serves a route of the map must run for that route only: - A request target that parsers read in different ways is refused (400) on every path, before any routing: a backslash, `#`, a space, control or non-ASCII character, dot segments, `//host/path`, `http://host/path`. With Express, for example, `/notes\7#` reaches the handler of `/notes/7`. - A wildcard, an optional parameter or an any-method handler that serves a route of the map is refused (400) for the other paths and methods it takes. - The handler of a route of the map runs for that route only (sdks/CONTRACT.md §2.10, rule 5). Express, Fastify, Hono and NestJS see the handler the router chose, and the SDK knows each route's: a rule of the route's own shape (`/notes/:id` for `/notes/{id}`), else the handler the router takes for sample values, then the one a checked request ran. That last one is learnt only when it serves the route's template, not only this value: the rule the framework says it matched has the route's own shape, or the router also takes it for the route's sample values (a page of its own at `/api/notes/export`, reached as `/api/notes/{id}`, is refused and never learnt). Short of the matched rule, the route must also be checked at least as strictly as every route of the map, of any method, whose handler is not known (a sample that reaches no handler tells nothing); the request is refused otherwise. Refused (400): - the same handler on another path, or for another method: `app.get("/n/:id", h)` next to `app.get("/notes/:id", h)`; - a request checked for one route that runs the handler of another, of any method: `/notes/x7`, checked as `/notes/{id}`, that the router gives to the handler of `/notes/pay` or of `DELETE /api/notes/{id}`; - a request checked for one method of a template whose handler also serves another method of it (`/items/{id}` and `/items/{item}` are one template), which the route does not cover: one function on `app.get` and `app.post` (or `app.all`) runs for the stricter route only, and the log names both at the first request. Map that method at the same capability and level, or give it its own handler; separate functions per method are separate handlers; - a checked request that would run a catch-all (a handler that also serves the route's path with a word replaced) next to the route's own known handler, unless the pattern the framework matched has the route's own shape: a catch-all is never learnt as a route's handler. That holds for a site-wide route that calls `next()` too (an Express `app.all("*", log)` before the routes): register such middleware with `app.use`, which is no route's handler. A request with a value the route's own handler does not take, which falls through to an SPA fallback, is refused, and the fallback keeps serving the site. While a catch-all is all a route has (an Express sub-app mounted with `app.use("/api", api)`, a front controller), checked requests run it, and unchecked ones that reach it are refused. It runs for a request checked for a route only if that route is checked at least as strictly as every other route, of any method, it is protected for (a level-1 route does not run the code of a level-3 one through a shared front controller); - any other catch-all, wherever else it serves: one under a route's prefix (`/notes/:id/*` for `/notes/{id}/archive`), or one the router did not take through a rule for the whole site (`/:version/notes/:id` next to `/api/notes/{id}`). It runs for that route, so the same handler on another path is an alias of it; - while a route's own handler is not known (none found for it, or only a catch-all), a request at or below the route, of any method, as received or decoded (`/%6Eotes/7/x` is `/notes/7/x` to Fastify and Hono): nobody can tell whether its handler is that route's. A handler shared by two routes of the map, whatever their templates, runs for a request checked for one of them only if that route is checked at least as strictly as the other: one function on `DELETE /notes/{id}` (write-hard) and `DELETE /items/{id}` (write) runs for the first only, and the log names both. So does a route of the map with no handler of its own that another route's handler serves: with `GET /notes/pay` mapped and only `/notes/:id` to serve it, a request checked for `GET /notes/{id}` is refused until `/notes/pay` has a handler. A handler that the router tries after `/notes/pay`'s own rule (it runs if that rule calls `next()`) stays protected for it, unless it is the own rule of another route (`/notes/:id` for `GET /notes/{id}`): with Express or Hono, a wildcard `/notes/*` or an optional `/notes/:id?` as the handler of `GET /notes/{id}` also serves `/notes/pay`, so a request checked for `GET /notes/{id}` is refused. Give `GET /notes/{id}` the rule `/notes/:id`. The refusal names the route and the fix: give each route of the map a handler of its own, registered with the router, and for another method, map that method too or give it a handler of its own. - A handler for the whole site (a rule for `*`, `/*` or `/{*rest}`: a single-page app, static files, a "not found" page) stays open while each route of the map has a handler of its own, for requests that are not checked. Middleware is no handler: Express `app.use(fn)` and Hono `app.use("*", mw)` pass every request on. When a site-wide handler is all a route has, it is that route's handler: protected wherever it serves (the site's other pages too), and the log names the route. - One limit, where this SDK differs from the text of CONTRACT §2.10 rule 5: the log lines that rule 5 puts at start (a route served only by a site-wide catch-all, one handler for two methods that do not cover each other, a route whose handler is not known) come at the first request. The SDK builds its table of handlers then, once the framework's routes are registered after the middleware. - A handler that dispatches protected actions itself (one handler for every path that deletes or pays, or a legacy controller on a path no route maps) is not something the SDK can see. A front controller shared by protected routes of different capabilities or resources runs for none of them. Give each protected route its own handler. With Hono, `app.all("*", h)` is registered as `app.use("*", mw)` is: it counts as a middleware, never as a route's handler. - Hono does not tell a middleware from a handler. A middleware (`app.use(path, mw)`, of any path: `/api/*` or a route's own `/notes/:id`) is no handler where a route of a method of its own also takes the path: that route is. It still runs, so where its function is the handler of a route of the map (`app.all("/files/*", del)` with `del` serving `DELETE /api/notes/{id}`), the request is refused all the same. Where nothing else takes the path, it counts as a handler, so unchecked requests that reach only it near a route of the map are refused. A middleware given with a route (`app.get(path, requireLogin, h)`) is not its handler: the last function is. For a checked request, the handlers Hono would run after the route's own handler (only through its `next()`) are not looked at. - Hono: pass the app, `allowedby(aby, { app })`, the one whose `fetch` serves (with `route`, the outer app): its router tells which handler serves each route of the map. Without it, `allowedby` throws. - Fastify (4.20 or later): register the plugin before your routes and hooks, as the SDK must see every handler. A route of the map registered before it stops the app at start; any other route registered before it is refused (500), since its handler could be an alias of a protected one. - What runs before the check: a request that is not checked is refused before Express runs its `app.param()` callbacks and before the `onRequest` hooks of Fastify registered after the plugin, so an alias runs none of the app's code. With NestJS, middleware and guards that run before `AllowedByGuard` (register it first, `app.useGlobalGuards`) see the request before the check: keep them free of effects. - `unprotected` never lets a handler of the map run unchecked, also not for another method at the route's very template: one handler for `GET` and `POST /notes` would run for an unchecked `GET`, its input read from the query. Map that method too, or give it a handler of its own; the refusal says which. - The map lists full paths, with the prefix of any mount (below). Below a mount prefix, a map without the prefix is refused (400), as are, with Express, routes of the map mounted before `allowedby()`. With Hono and Node.js `http`, the order is yours: `app.use(allowedby(...))` comes first. Put the SDK on the outer Hono app, not inside one given to `mount`: outside Node.js the prefix it cuts is lost, and paths that are the end of a route of the map are refused. - With Express a refusal at the last moment goes through your error handlers, with `err.status` 400. - Changed after the check. A step after the SDK could move an accepted request to another path or method (a rewrite of `req.url`, a method override, a framework's own rewrite): its handler would then act on values the person never approved. Where the adapter sees what the handler runs for, it compares the method and the path (normalised as the check normalises it: `/notes/%37` is `/notes/7`) with those that were checked, and refuses a request that changed (400 `invalid_request`, the path not repeated) before any handler runs: - Express: when the router dispatches the route, after any middleware (`req.url` rewritten, `method-override`). A router's prefix (`app.use("/notes", router)`) is no change. Express runs `app.param()` callbacks just before that: keep them free of effects. - Fastify: before the check, against what Fastify routed on: `rewriteUrl`, or a hook after the plugin's that changes `req.raw.url` or `req.raw.method`. Fastify routes before any hook, so a later change moves neither the handler nor `req.params`. - Hono: against the path Hono routed on (`c.req.path`, its `getPath`), and when a step after the SDK makes Hono run another request with the same proof (`methodOverride`, a rewrite through `app.fetch`). - NestJS: `AllowedByGuard` runs after Nest's middleware and Express's routing, so a middleware that rewrote `req.url` or overrode the method (method-override's `req.originalMethod`) is refused when either request is one the SDK checks. A method changed without a trace (`req.method` alone) is checked as it is, and its proof, made for the other method, is refused (401). - Next.js: after a rewrite (`rewrites` in `next.config.js`, or `NextResponse.rewrite` in a middleware after the SDK's), a route handler still gets the URL the client sent, which `withAllowedBy` and `readContext` check, while the route file and Next's `params` are the rewrite's: a request accepted for `/notes/7` could run `app/notes/[id]` with `id` 8, or another route's file. So each handler states the route it serves, always: `withAllowedBy(aby, handler, { route: "DELETE /notes/{id}" })`, or `readContext(aby, req, { route: "DELETE /notes/{id}", params })` with Next's `params`. A request checked for another route, unless that route covers the handler's (sdks/CONTRACT.md §2.10 rule 5), or with other values in Next's `params`, is refused: `withAllowedBy` answers 400, and `readContext` throws `RouteMismatchError`, whose `response` is that 400. Uncaught, Next answers 500, which still refuses the request; to answer the 400, catch it: `try { ctx = await readContext(aby, req, { route, params }); } catch (e) { if (e instanceof RouteMismatchError) return e.response; throw e; }`. For a clean 400 without the catch, prefer `withAllowedBy` (route handlers without the middleware). With a route stated, `readContextIfAny` is `readContext`: that handler serves a route of the map, so a request without a context (a rewrite from a path outside the map) throws `MissingContextError`. Name each dynamic segment of the route's folder as the template's `{name}` (`[id]` for `{id}`), so that the values can be compared; a folder named otherwise is refused (500). A route that is not one of the map is a `TypeError`: `withAllowedBy` throws it when the handler is made, at start; `readContext`, which runs per request, throws it on every call, before any context is read. Not covered: where the adapter does not see the route the handler runs for. Node.js `http` (route on `req.checkedPath`), `aby.check`, a Fastify hook registered before the plugin, a function mounted as Express middleware, and a Next.js handler that does not state its route. Put nothing that changes the method or the path after the SDK there, and read the values from `context.params`, never from the framework's own. - A Next.js handler in `withAllowedBy`, or that calls `readContext`, always has a context: other paths are refused, or `readContext` throws. `readContextIfAny` is for a handler that also serves paths outside the map. - Where the SDK does not see the route that is chosen (Node.js `http`, the Next.js middleware, `aby.check`), a path that would match a mapped template if a parameter took several segments is refused (400) for a mapped method: `DELETE /notes/7/x` with `DELETE /notes/{id}`. `GET /notes/7` with only `GET /notes` in the map is not. List your own such pages in `unprotected` (`["GET", "/notes/{id}/comments"]`, or `["DELETE", "/notes/7/x"]`); an entry that is or overlaps a route of the map is refused at construction, and an exact entry also lifts the checks on path variants for that very path (one that a router may take for a route of the map, such as a last `/` or another case: with the adapters that see the route only). It never lets a handler of the map run. These adapters do not see the handler, so rule 5 is out of their reach: give each route of the map a handler of its own. - A control character in the path of a route of the map, encoded or not, is refused (400). - A challenge names the resource the approval must cover (ABY-2 §6): the route's `resource` with the request's path values, normalised as for the proof (`%61b` is `ab`). Each value must be 1 to 64 of `A-Z a-z 0-9 . _ -`, and the whole scope at most 256 bytes, else the request is refused (400) instead of answered with a challenge no approval could satisfy: `a%20b`, `x%C3%A9`, `~`, `:`, `*`, sub-delimiters, a broken escape or one that decodes to a control character or `/`. A grant that covers such a path (`invoice:*`) is still checked as before. - With Node.js `http`, route on `req.checkedPath`, the path that was checked, not on your own reading of `req.url`. - The SDK cannot see a function mounted as middleware (`app.use("/notes", handler)`; an Express sub-app given to `app.use` is seen, as a catch-all of its prefix), a rewrite of `req.url` made before it, or what a proxy behind a catch-all makes of a path. **Routes below a prefix** (`app.use("/api", router)`, Fastify's `prefix`, Hono's `route` and `basePath`, Nest's global prefix, Next.js's `basePath`). The map lists `/api/notes/{id}`, not `/notes/{id}`: it is what agents call, what their proof signs, and what `/openapi.json` and the challenges show them. This differs from the SDKs of the other languages, where the map holds the paths without the mount prefix. Put the SDK on the app itself, so that it also serves the discovery documents at the root (file: `sdks/js/examples/mounted.mjs`). ```js // Routes below a prefix: the map lists the full paths, those agents call and sign. The SDK goes on the app itself, which // also serves /.well-known/allowedby and /openapi.json; only the routes are mounted. import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; export function notesService(options = {}) { return new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "http://localhost:3000", node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/api/notes/{id}", "notes:read", { resource: "note:{id}" })], // "/notes/{id}" is refused (400) templates: { "notes:read": "Read {scope}" }, ...options, }); } export function makeApp(aby) { const api = express.Router(); api.get("/notes/:id", (req, res) => res.json({ id: req.params.id, person: req.allowedby.humanId })); const app = express(); app.use(allowedby(aby)); // first, and not below /api app.use("/api", api); return app; } if (process.argv[1]?.endsWith("mounted.mjs")) { makeApp(notesService()).listen(Number(process.env.PORT ?? 3000), process.env.ALLOWEDBY_BIND || "127.0.0.1"); } ``` ## The context Your handler receives a frozen `Context` after the SDK accepted the request: who asked, for whom, at which level. | Field | Type | Meaning | |---|---|---| | `humanId` | `string \| null` | The person's pairwise id for your service (null at level 0: no person). Use it as the account key, after a null check: without a person, answer 403, never key by null or "". | | `level` | `number` | The identity level verified: 0 agent only, 1 passkey, 2 verified identity, 3 eIDAS high. | | `agent` | `string` | The agent (its passport `sub`). | | `operator` | `string` | The company running the agent (its verified domain, or a node-scoped id). | | `capabilities` | `string[]` | The capabilities of the grant. | | `display` | `{summary, lines, lang} \| null` | The words the person approved. | | `gid`, `rev`, `jti` | `string`, `number`, `string` | The grant id, its revision and its document id (audit). | | `chain` | `[gid, rev][]` | The grant chain, leaf first (a sub-agent's grant and its parent). | | `route` | `Route` | The line of the route map that matched, with the class resolved. | | `proofJti`, `run`, `call` | `string`, `string \| null`, `number \| null` | The proof's id and the agent's run and call numbers (audit). | | `humanIss` | `string \| null` | The person's home node. | | `params` | `Readonly>` | The route's path values as the SDK checked them: each `{name}` of the route's template, from the normalised path the verifier compared, percent-decoded once (`/t/acme%20co` gives `{ tenant: "acme co" }`, `%2520` gives `%20`, an encoded `/` stays in its value). Act on these, never on your own reading of the raw path, which can differ (`DELETE /notes/7/.` is checked as `/notes/7`). Frozen, with no prototype, so `__proto__` is an ordinary name; `{}` for a route without parameters. | | `linkedAccount` | `string | null` | On a route with `requireLink`, the account of yours the person is linked to ([Account linking](#account-linking)); null on other routes. | | `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`). ```js // Production settings: keys kept across restarts, a store shared by every instance, optionally a signed trust list. // REDIS_URL=redis://localhost:6379 node examples/production.mjs import http from "node:http"; import Redis from "ioredis"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedByNode } from "@allowedby/sdk/node"; import { RedisStore } from "@allowedby/sdk/redis"; const aby = new AllowedBy({ origin: process.env.ALLOWEDBY_ORIGIN ?? "https://notes.example", node: process.env.ALLOWEDBY_NODE ?? "https://node.example.org", org: { legal_name: "Notes Ltd", country: "FR", privacy_policy: "https://notes.example/privacy" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, keyFile: process.env.ALLOWEDBY_KEY_FILE ?? "/var/lib/notes/allowedby-keys.json", // mode 0600, shared by instances store: new RedisStore(new Redis(process.env.REDIS_URL ?? "redis://localhost:6379")), // trustList: { jws: process.env.ALLOWEDBY_TRUST_LIST, key: JSON.parse(process.env.ALLOWEDBY_TRUST_KEY) }, refreshSeconds: 5, log: (line) => process.stdout.write(line + "\n"), // codes only: never tokens, keys or bodies }); await aby.ready(); // keys loaded, node statement and status lists fetched once http.createServer(allowedByNode(aby, (req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ notes: [], person: req.allowedby?.humanId ?? null })); })).listen(Number(process.env.PORT ?? 8080), process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container ``` - **Keys** (`keyFile`, Node.js): the signing key (Ed25519) and the disclosure key (P-256), created on first use with mode 0600, atomically (first writer wins), in the same JSON format as the Python SDK, so one file works for every SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `keyFile` at it, or write it from your secret manager. An existing file works anywhere. Without `keyFile` the keys are new at each start: agents then fetch `/.well-known/allowedby` again. On runtimes without a file system, load a key yourself: `keys: { signing: await SigningKey.fromPem(pem) }`. - **Store**: `MemoryStore` (the default) is for one process. With several instances behind a load balancer, every instance must share the replay set and the single-use set, or a proof replayed on another instance is accepted: use `RedisStore` (atomic Lua scripts; expiry follows the SDK's clock; cluster-safe with one hash tag) or your own `Store` (`add`, `get`, `charge`, each atomic). A store error refuses the request (`503 status_stale`). A refund (below) is a `charge` of negative increments with no max: your store applies it exactly, and keeps each key's `until`. - **Refunds** (sdks/CONTRACT.md, Refund on the SDK's own refusal; ABY-2 §5 step 9): the check consumes a single-use approval and adds to the grant's count and amount totals, as before. When the SDK then refuses that same request itself, before its handler starts (rule 5, a request changed after the check, a Next.js handler of another route), it gives back exactly what the check charged, once, from the check's receipt, before it answers: the approval is usable again on its own route. Express, Fastify, Hono, NestJS and `withAllowedBy` do this. A refund the store does not take leaves the approval spent, logged without request data (`refund not recorded: the approval stays spent`). Nothing is given back once the handler started, for a refusal of your own (a handler or a middleware that answers), or after the SDK handed the request on: Express's 404 for a request moved to no route, a layer that dispatches the request again through Hono (`app.fetch`), the Next.js middleware (`readContext` reads a copy of the context, which has no receipt), Node.js `http` and `aby.check`. Each accepted request is started or given back, never both: one given back never reaches a handler, even when a layer dispatches it again (an Express error handler that lets routing go on), and is refused (400). - **Trust**: by default the SDK trusts `node` on first use (it pins the node's key at the first fetch and refuses a later change). In production give a signed OAID-5 trust list: `trustList: { jws, key }`; it lists anchors, programs and vouching rules, and replaces `node` as the source of trust. - **Refresh**: node statements and status lists are fetched in the background every `refreshSeconds` (default 5 s, at most 60 s), never while handling a request. The first refresh starts at construction, and the first requests wait for it (done or failed, at most 5 s after construction), so a service that starts cold (a new instance, one that scales to zero) answers its first request from a filled cache, not with `untrusted_node` or `503 status_stale` (sdks/CONTRACT.md §2 item 4); `await aby.ready()` waits for the same. A failed refresh is logged (`[verifier] refresh failed`) and the cached lists stay; when a status list is older than the class allows (60 s for `write-hard` and `irreversible`, 1 hour otherwise), requests are refused with `503 status_stale` until a refresh succeeds. - **Logging**: one line per decision, `[host] METHOD /route/pattern -> code`, and refresh failures. No token, key, body or personal data is logged. `log: false` silences it; any function receives the lines. - **Several instances**: share `keyFile` (or `keys`) and the store; nothing else is shared. ## Agents An agent calls AllowedBy APIs with `new Agent({ node, tell })` and `agent.call(method, url, body, { action })`; the call pauses while the person approves and retries once (CONF-1 `runtime` profile, a port of the Python runtime). (file: `sdks/js/examples/agent.mjs`) ```js // An agent calling a service for its person: passport, approval when needed (the person taps a passkey), retry. // ALLOWEDBY_NODE=http://localhost:8700 APP_URL=http://localhost:3000 node examples/agent.mjs import { Agent } from "@allowedby/sdk/agent"; const agent = new Agent({ node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", tell: (m) => { if (m.type === "approval_needed") console.log(`Please approve "${m.summary}": ${m.link} (code ${m.code})`); }, }); const app = process.env.APP_URL ?? "http://localhost:3000"; const { status, body } = await agent.call("GET", `${app}/notes`, undefined, { action: "notes:read" }); console.log(status, body); ``` What `agent.call` does: it gets a tier-0 passport from the node (OAID-3; renewed before expiry), signs the request (a proof JWT, or RFC 9421 with `httpSig: true`), and on a `401` challenge either follows the service's own approval (write-hard and irreversible: the link must be on the agent's node and match the node's approval page) or asks its node for one (read and write); it tells the person the link and the 4-character code, long-polls the node, checks the grant (signed by its node, for its key and the site) and retries once. Standing grants are kept and reused. After "not me" it does not ask again for that action for 10 minutes. `agent.delegate(sub, capabilities)` gives a sub-agent an attenuated child grant: a chain is a root and one child (depth 1, ABY-1 §4), so only a root grant is narrowed (a child or a chain given as `allowedBy` throws before the node is asked), and `adopt` keeps a chain of exactly two grants. `agent.rebind(gid)` moves a grant to a new passport (with `operatorDomain` and `operatorKey`, OAID-2 §6). Options: `node`, `tell`, `operator`, `runtime`, `pollTimeout` (default 300 s), `operatorDomain`, `operatorKey`, `httpSig`, `renew`, `fetch`, `clock`; call options: `action`, `standing`, `limits` (the amount the agent may spend on amount routes), `notify`. **Agent frameworks**: one tool, "call an AllowedBy API", for MCP, the Vercel AI SDK, LangChain.js and the OpenAI Agents SDK; it only calls the `origins` you list (file: `sdks/js/examples/agent-tools.mjs`). ```js // One AllowedBy tool for each agent framework. Each call may pause while the person approves; only the listed // origins can be called. node examples/agent-tools.mjs import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Agent } from "@allowedby/sdk/agent"; import { allowedbyTool as aiSdkTool } from "@allowedby/sdk/agent/ai"; import { allowedbyTool as langchainTool } from "@allowedby/sdk/agent/langchain"; import { registerAllowedByTool } from "@allowedby/sdk/agent/mcp"; import { allowedbyTool as openaiAgentsTool } from "@allowedby/sdk/agent/openai"; const agent = new Agent({ node: process.env.ALLOWEDBY_NODE ?? "http://localhost:8700", tell: (m) => console.log(m) }); const options = { agent, origins: [process.env.APP_URL ?? "http://localhost:3000"] }; // Model Context Protocol: the approval link reaches the client as a log message while the tool waits const server = new McpServer({ name: "notes-agent", version: "1.0.0" }, { capabilities: { logging: {} } }); registerAllowedByTool(server, options); // Vercel AI SDK: generateText({ model, tools: { notes: aiTool }, prompt }) const aiTool = aiSdkTool(options); // LangChain.js: model.bindTools([lcTool]) const lcTool = langchainTool(options); // OpenAI Agents SDK: new Agent({ name: "Assistant", tools: [oaTool] }) const oaTool = openaiAgentsTool(options); console.log("tools ready:", typeof aiTool.execute, lcTool.name, oaTool.name); ``` Each runs in CI with a scripted model in place of the LLM, through the framework's own agent loop, against a real node and a person: the tool refuses another site, the person refuses then approves, and a replay of the model's call is refused (`sdks/js/examples/frameworks/agents`): MCP 1.32.2, Vercel AI SDK 5.0.292, 6.0.336 and 7.0.181, LangChain.js 1.6.8, OpenAI Agents SDK 0.22.0. The tool's input is `{ method, url, body (JSON text or null), action (or null) }`, every member required and nullable, so the OpenAI strict mode accepts it; its output is `{"status", "body"}` as JSON text. On routes with an amount, set `limits` in the options (what the agent may ask to spend: yours to set, never the model's); `standing` sets the period to ask for. MCP clients time out a call after 60 s by default, less than a person may take: give the client a timeout of at least the agent's `pollTimeout` (300 s), or `resetTimeoutOnProgress: true` with `onprogress` (the tool sends progress every `progressSeconds`, default 15). The frameworks are optional peer dependencies (`@modelcontextprotocol/sdk`, `ai`, `@langchain/core`, `@openai/agents-core`, and `zod`). ## Errors Every refusal is an RFC 9457 `application/problem+json` body whose `type` ends with the code; challenges also carry `WWW-Authenticate: AllowedBy ...`. The same table in every language: | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object, a malformed `Allowed-By`, a body over 1 MiB (413). | Fix the request. | | `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and sends it. | | `invalid_signature` | 401 | A signature, proof, replay, URL, body hash or `human_sig` check failed. | Never retried as is; the agent signs a fresh request. | | `untrusted_node` | 401 | The document comes from a node this service does not trust. | Trust the node (trust list), or the agent uses another node. | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses (trust list `witnesses_min`). | Wait for the node's log to be witnessed. | | `grant_required` | 401 | The route needs a person's approval; the challenge says which. | The agent asks the person (its node, or the service's approval link) and retries. | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, single use). | Ask for an approval that covers it. | | `level_insufficient` | 401 | The person's identity level is below the route's. | The person verifies their identity at a higher level. | | `qes_required` | 401 | A qualified electronic signature is needed. | Not supported by this SDK: such routes are refused. | | `authority_required` | 401 | The organisation's co-approvers must approve. | Not supported by this SDK yet. | | `mandate_required` | 401 | The person must act for an organisation with its mandate. | Not supported by this SDK yet: a grant carrying a mandate is refused. | | `expired` | 401 | The grant has expired. | Ask again. | | `not_yet_valid` | 401 | The grant's `nbf` is in the future. | Check the clocks; retry later. | | `revoked` | 401 | The person withdrew the approval, or the passport or registration was revoked. | Ask again. | | `actor_expired` | 401 | The agent's key in the grant has expired. | The agent rebinds the grant to its new passport, or asks again. | | `class_lifetime_exceeded` | 401 | The grant lasts longer than the route's class allows. | Ask for a shorter approval. | | `single_use_consumed` | 401 | A one-time approval was already used. | Ask again for this request. | | `capability_denied` | 403 | No such route. | None: the service does not offer it. | | `tier_insufficient` | 403 | The agent's key custody, or the passkey class, is weaker than the route needs. | Use a stronger key or passkey. | | `human_not_linked` | 403 | The person's account is not linked. | Not used by this SDK yet. | | `budget_exceeded` | 403 | A budget is used up. | Not used by this SDK yet. | | `rate_limited` | 429 | Too many requests. | Wait (`Retry-After`). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain over four documents. | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old to decide, or the store (replay set) or the service keys are not available. | Retry after `Retry-After`; check that the service reaches the node and its store, and the key file. | ## Testing Run the conformance vectors, the unit tests and the interop test; test your own app with `TestNode`, no browser. Linux and macOS: ```sh cd sdks/js npm ci npm run lint && npm run typecheck npm test # unit tests, adapters, examples, and the vectors (prints N/N cases passed) npm run build cd ../.. pip install -r requirements.txt INTEROP_PORT_BASE=19200 python sdks/interop/interop.py --cmd "node sdks/js/examples/interop.mjs" # 26/26 INTEROP_PORT_BASE=19200 python sdks/interop/interop.py --agent-cmd "node sdks/js/examples/interop-agent.mjs" # 7/7 ``` Windows (PowerShell): ```powershell cd sdks/js npm ci npm run lint; npm run typecheck npm test npm run build cd ../.. python -m pip install -r requirements.txt $env:INTEROP_PORT_BASE = "19200"; python sdks/interop/interop.py --cmd "node sdks/js/examples/interop.mjs" python sdks/interop/interop.py --agent-cmd "node sdks/js/examples/interop-agent.mjs" ``` - **Vectors**: `test/vectors.test.ts` reads every case of the `verifier` profile from `vectors/` at run time and fails on any case it cannot run: `verifier profile: 479/479 cases passed`. It also runs every case of the `runtime` profile (122) with the agent SDK's helpers. - **Interop**: the app in `examples/interop.mjs` is the port of `sdks/interop/reference_app.py`; the harness runs a real node, the reference agent and a person with a software passkey (26 scenarios). In agent mode, `examples/interop-agent.mjs` (the port of `reference_agent.py`) drives the Python reference app, whose verifier checks every passport request, proof and body hash the agent SDK builds (7 scenarios). - **Your app**: `@allowedby/sdk/testing` (TEST ONLY) is a node in memory: passports, grants signed by a software passkey, approvals for serious actions, revocation (file: `sdks/js/examples/test-your-app.test.mjs`). ```js // Test your own service without a browser or a real node: TestNode issues passports and grants (TEST ONLY). // node --test examples/test-your-app.test.mjs import assert from "node:assert/strict"; import { test } from "node:test"; import { AllowedBy, route } from "@allowedby/sdk"; import { TestNode } from "@allowedby/sdk/testing"; test("an agent reads the person's notes with their approval", async () => { const node = await TestNode.create(); const aby = new AllowedBy({ origin: "https://notes.example", node: node.origin, org: { legal_name: "Notes Ltd", country: "FR" }, routes: [route("GET", "/notes", "notes:read", { resource: "note:*" })], templates: { "notes:read": "Read your notes" }, fetch: node.fetch, // the test node answers the SDK's background fetches autoRefresh: false, log: false, }); await aby.refresh(); const agent = await node.agent(); const grant = await node.grant(agent, { audience: "https://notes.example", capabilities: [{ cap: "notes:read", constraints: { scope: "note:*" } }], }); const headers = await agent.sign("GET", "https://notes.example/notes", { allowedBy: grant }); const { context, refusal } = await aby.check({ method: "GET", path: "/notes", headers }); assert.equal(refusal, null); assert.equal(context.level, 1); assert.equal(context.humanId, await node.humanId("https://notes.example")); const without = await aby.check({ method: "GET", path: "/notes", headers: {} }); assert.equal(without.refusal.status, 401); }); ``` ## Reference Every public export, by import path. **`@allowedby/sdk`** | Export | What | |---|---| | `new AllowedBy(options)` | The service. Options: `origin`, `node`, `org` (`legal_name`, `country`, `website`, `support`, `privacy_policy`, `logo`, `exp`), `routes`, `templates`; optional `keyFile`, `keys`, `store`, `trustList`, `refreshSeconds`, `nodeMaxLevel`, `clock`, `title`, `version`, `description`, `rfc9421`, `fetch`, `log`, `autoRefresh`, `unprotected`, `linkAuthorize`, `nonce`, `rate`. Invalid options throw a `TypeError` saying what to fix. | | `aby.check(req)` | `{ method, path, query?, headers, body? }` -> `Promise<{ context, refusal }>`: `refusal` is the response to send instead of running a handler (a refusal, or the SDK's own answer to `POST /allowedby/link`). Never throws on hostile input. | | `aby.handle(method, path)` | The discovery documents (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), or null. | | `aby.needsCheck(req)`, `aby.isProtected(method, path)` | Whether a request needs `check` (a route of the map in any form a router dispatches, or a method override onto one): adapters read the body only then. | | `aby.ready()`, `aby.refresh()`, `aby.close()` | Wait for the keys and the first refresh (at most 5 s; checks wait for it too); refresh now; stop the background refresh. | | `aby.wellKnown()`, `aby.openapi()`, `aby.apiCatalog()`, `aby.publicKey()` | The documents and the public signing key. | | `aby.linkStart(account, ttl = 600)` | A one-time linking code for one of your accounts ([Account linking](#account-linking)). | | `route(method, path, capability?, options?)` | One line of the route map (see [Routes and templates](#routes-and-templates)). | | `MemoryStore`, `Store`, `Charge` | The in-process store and the store interface. | | `Context`, `Reject`, `STATUS`, `CHALLENGE_CODES` | The context type; the refusal type, codes and statuses. | | `SigningKey` | Ed25519 or P-256 signing key: `generate()`, `fromPem()`, `toPem()`, `kid`, `jwk`. | | `problem(code, status, title?)` | An RFC 9457 problem response. | | `SDK_VERSION`, `SPEC_VERSION`, `MAX_BODY` | `0.1.0`, `0.2.14`, 1 MiB. | **Adapters**: `@allowedby/sdk/node` (`allowedByNode`, `nodeGate`, `readBody`, `send`), `@allowedby/sdk/express` (`allowedby`), `@allowedby/sdk/fastify` (default plugin, `allowedby`), `@allowedby/sdk/hono` (`allowedby`, `AllowedByVariables`), `@allowedby/sdk/next` (`withAllowedBy`, `allowedByMiddleware`, `readContext`, `readContextIfAny`, `CONTEXT_HEADER`), `@allowedby/sdk/nest` (`AllowedByGuard`, `AllowedBy` parameter decorator, `AllowedByContext`, `allowedbyDiscovery`). **Agent**: `@allowedby/sdk/agent` (`Agent`: `call`, `ensurePassport`, `renewPassport`, `rebind`, `delegate`, `adopt`, `checkGrant`, `nodeUrl`, `waitFor`, `grantFor`, `grants`, `lastGrant`; `parseChallenge`, `pollOutcome`, `validApprovalIds`; types `AgentOptions`, `CallOptions`, `CallResult`, `AgentMessage`), and its tools `@allowedby/sdk/agent/mcp` (`registerAllowedByTool(server, options)`), `/agent/ai`, `/agent/langchain`, `/agent/openai` (`allowedbyTool(options)`); options `agent`, `origins`, `limits`, `standing`, `name`, `description`, `onApproval`. **Others**: `@allowedby/sdk/redis` (`RedisStore(client, prefix?)`), `@allowedby/sdk/keyfile` (`loadKeys(path)`), `@allowedby/sdk/testing` (`TestNode`, `TestAgent`; TEST ONLY). **Implemented** (sdks/CONTRACT.md). Core: configuration, route map with the reference's validation, discovery documents, ABY-2 §5 verification (proof JWT and RFC 9421, passports, grants and chains, every WebAuthn check, `human.reg`, `initiator`, status lists with per-class freshness, class lifetimes, ABY-3 constraints with counters, request digests and single use, the replay set, TOFU and OAID-5 trust lists with programs, vouching and witnesses, EdDSA and ES256 only), challenges and service-initiated approvals, background refresh, the context, `MemoryStore` and `RedisStore`, `keyFile`, six framework adapters. Agent: `Agent` (passports, proofs, challenges, approvals, standing grants, rebind, renewal, sub-agents) and four agent-framework tools. Extended: account linking, AllowedBy-Nonce, level profiles 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. 1. Your signed-in account page calls `aby.linkStart(account, ttl = 600)` and shows the code (96 random bits, valid `ttl` seconds, single use). The person gives it to their agent. A new code does not revoke the older ones. 2. The agent sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves this route itself, in `check` (every adapter; NestJS through `allowedbyDiscovery`; Next.js in a route handler, below): an unknown, spent, revoked or expired code is refused (400 `invalid_request`) before any approval is asked for. The request is then checked as the route `aby:link` (class `write`, level 1, resource `aby:link`), with single-use grants only; without one, the SDK creates that approval itself, bound to this request, and the challenge links it. Only that exact path is the endpoint (CONTRACT 1.13): a variant (`/allowedby/%6Cink`, `/allowedby/./link`) is refused (400) and `/allowedby/link/` or `//allowedby/link` go to your app as paths outside the map: none asks for an approval or links anything, whatever its code. 3. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home node and their pairwise id) is linked to the account, replacing any other pair: `200 {"linked": true}`, the answer `check` returns as its `refusal` (the response to send). A route with `requireLink` answers 403 `human_not_linked` unless the pair is linked; when its path names an account (`accountParam`, default `account`), linked to that account, compared as `context.params` has it (decoded once). The context's `linkedAccount` is that account. A route whose path names no account accepts any linked person: give `linkAuthorize: (account, route, params) => boolean` to `new AllowedBy` to say which of your accounts may act on it (only the literal `true` passes: any other value, a truthy one or a promise included, and a throw, are refused with 403 `human_not_linked`; it is never called for a person who is not linked; it is synchronous), as Python's `link_authorize`. Both members of the pair count: the same pairwise id from another home node is another person. An approval that names no person for this service (its `human.id` has no id, or an empty one, for your origin) is refused with 401 `grant_insufficient`, on `POST /allowedby/link` and on `requireLink` routes: an empty id never links nor matches. Approvals the SDK creates for an account that is linked name its person (`human_home`, `human_hint`). `/.well-known/allowedby` has `link` and the `aby:link` capability, `/openapi.json` the route; give `templates["aby:link"]` to word it your way. An app route at `POST /allowedby/link` or with the capability `aby:link` is refused at construction. Codes and links are kept in memory, for one process, bounded: with 10 000 codes pending (expired ones do not count), `linkStart` throws a `RangeError` rather than revoke a code another account was given; of 100 000 links, the oldest is dropped first. Behind several instances, the instance that gave a code must take its `POST /allowedby/link`, and every instance must see the links: until a shared store keeps them, run linking on one instance, or link again after a restart. Next.js: the middleware (`middleware.js`, `proxy.js`) runs apart from the route handlers, with its own `AllowedBy`, so it never sees the codes your account page made nor the links: behind `allowedByMiddleware`, linking does not work (it fails closed: the link answers 400, a `requireLink` route 403). Use route handlers with `withAllowedBy`, which share the instance of `lib/allowedby.js` with your account page: `app/allowedby/link/route.js` with `export const POST = withAllowedBy(aby, () => new Response(null, { status: 404 }))` (the SDK answers the link itself; that handler never runs), and `requireLink` routes in `withAllowedBy` too. If the app also has the middleware, leave those paths out of its matcher, or the middleware's own instance answers them first (400 for every link, 403 for every `requireLink` route): `export const config = { matcher: ["/((?!_next/|allowedby/link|accounts/).*)"] }`, with your `requireLink` paths in place of `accounts/`. In an Express app (file: `sdks/js/examples/linking.mjs`); the extended interop app, `sdks/js/examples/interop-ext.mjs`, is a test fixture that gives a code for any account it is asked for, never a pattern to copy: ```js // Account linking (ABY-3 §6) in an Express app. The account comes from your own login, never from the request: a code // for any account a caller names would let that caller link their identity to someone else's account. import express from "express"; import { AllowedBy, route } from "@allowedby/sdk"; import { allowedby } from "@allowedby/sdk/express"; export const routes = [ // needs the person linked to the account the path names (accountParam defaults to "account") route("GET", "/accounts/{account}/notes", "notes:read", { resource: "account:{account}", requireLink: true }), ]; /** `signedIn(req)`: your session's account id, or null when nobody is signed in. */ export function makeApp(aby, signedIn) { const app = express(); app.use(allowedby(aby)); // also answers the agent's POST /allowedby/link app.post("/account/agent-code", (req, res) => { const account = signedIn(req); if (account === null) return res.status(401).json({ error: "sign in first" }); res.json({ code: aby.linkStart(account) }); // shown on the account page; the person gives it to their agent }); app.get("/accounts/:account/notes", (req, res) => { res.json({ account: req.allowedby.params.account, notes: [] }); // its linked person only }); return app; } /** The service: `origin`, `node` and the rest of the options as usual. */ export function linkingService(options) { return new AllowedBy({ org: { legal_name: "Notes Ltd", country: "FR" }, routes, templates: { "notes:read": "Read your notes" }, ...options, }); } ``` ### AllowedBy-Nonce An extended feature (sdks/CONTRACT.md, Extended; ABY-2 §3.2). `new AllowedBy({ nonce: true })` turns it on (default off). Then every `irreversible` route, and every route with `nonce: true`, refuses a proof without a current service nonce with `401 invalid_signature` and a fresh nonce in its `AllowedBy-Nonce` response header; the agent sends the request again with it, once, whatever the route's class (`Agent` does). The nonce goes in the proof JWT's `nonce` claim, or, with RFC 9421, in the request's `AllowedBy-Nonce` header, covered by the signature (an uncovered one does not count; a covered value that is not base64url is refused, 401). A route with `nonce: true` while the service has nonces off is refused at construction. A nonce is current for 300 s from its issue. It is stateless: base64url(t ‖ HMAC-SHA256(nonce key, t)[0:16]), t its issue time as 8 bytes big-endian, and the nonce key is HKDF-SHA256 of the signing key's raw private key (no salt, info `allowedby/nonce/v1`, 32 bytes). So every instance that shares `keyFile` takes the others' nonces, and a restart keeps the ones it handed out current; SDKs of any language on one key file take each other's. ### Level profiles An extended feature (OAID-7 §5.3). `levelProfile: "eu"` or `"na"` on a level-3 route accepts only a person whose level-3 registration was verified under that profile (its `level_source.profile`); any other, or none, is refused with `401 level_insufficient`. A level-3 route without `levelProfile` takes either. `route()` refuses it on a route of another level. ### Rate limits An extended feature (sdks/CONTRACT.md, Extended). `new AllowedBy({ rate: { actor: [n, seconds], operator: [n, seconds] } })` caps the calls per agent (the passport's `sub`) and per operator (`operator.id`); by default 600 and 6000 calls per 60 s. A call over either is refused with `429 rate_limited` (`Retry-After: 60`). The window slides on the SDK's clock (a call at t sees those at x with t - x < seconds). A call counts once its proof is verified and is no replay, whatever is decided after it (a call refused as `grant_required` counts); a call refused by the limit itself counts for neither limit. Any other key, or a value that is not two positive integers, is refused at construction. The counts are kept in memory, per process (bounded: 10 000 agents and operators each); behind several instances each counts its own calls. --- Source: https://docs.allowedby.com/sdk/go # AllowedBy Go SDK The Go SDK lets AI agents call your Go service with a person's approval. The person approves with a passkey tap on their node's approval page; your service checks every agent request offline (no network call on the request path) and answers with a challenge when an approval is missing. Concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in Go. Terms used here: a **node** issues agent passports and runs the approval page; a **grant** is a person's signed approval; a **proof** (JWS, JSON Web Signature) signs each request; **JCS** is RFC 8785 canonical JSON. ## Install `go get github.com/yannUpTo/allowedby/sdks/go` adds the SDK; it needs Go 1.22 or later and nothing but the standard library. The SDK is not published yet (publishing is a separate step). Until then, point Go at a clone of the repository. Linux and macOS: ```bash git clone https://github.com/yannUpTo/allowedby.git cd your-app go mod edit -replace github.com/yannUpTo/allowedby/sdks/go=../allowedby/sdks/go go get github.com/yannUpTo/allowedby/sdks/go ``` Windows (PowerShell): ```powershell git clone https://github.com/yannUpTo/allowedby.git cd your-app go mod edit -replace github.com/yannUpTo/allowedby/sdks/go=../allowedby/sdks/go go get github.com/yannUpTo/allowedby/sdks/go ``` Framework adapters and the Redis store are separate modules, so the core stays dependency-free. Add only the one you use, with the same `-replace` for its directory: | Module | For | Dependency (pinned, why) | |---|---|---| | `github.com/yannUpTo/allowedby/sdks/go` | `net/http` | none: `crypto/ed25519`, `crypto/ecdsa`, `crypto/ecdh`, `compress/zlib` cover every algorithm | | `.../sdks/go/allowedbygin` | Gin | `github.com/gin-gonic/gin v1.12.0`: the framework itself | | `.../sdks/go/allowedbyecho` | Echo | `github.com/labstack/echo/v4 v4.16.3`: the framework itself | | `.../sdks/go/allowedbychi` | chi | `github.com/go-chi/chi/v5 v5.5.0`: the framework itself | | `.../sdks/go/allowedbyredis` | several instances | `github.com/redis/go-redis/v9 v9.23.0`: the shared replay set and counters | With Docker, nothing is installed on the machine: ```bash docker run --rm -v "$PWD":/src -w /src/sdks/go golang:1.27.2@sha256:820153096fda4de6ac1b7194d12e416b7dd8f4e9a33d17e0345b111b945162d8 go test ./... ``` ```powershell docker run --rm -v "${PWD}:/src" -w /src/sdks/go golang:1.27.2@sha256:820153096fda4de6ac1b7194d12e416b7dd8f4e9a33d17e0345b111b945162d8 go test ./... ``` ## Quick start `allowedby.New` with your origin, your node, your organisation, a route map and a sentence per capability, then `aby.Handler(mux)`: that is a service that accepts agents. ```go package main import ( "fmt" "log" "net/http" allowedby "github.com/yannUpTo/allowedby/sdks/go" ) func main() { aby, err := allowedby.New(allowedby.Options{ Origin: "http://localhost:8081", // your public origin, as agents call it Node: "http://localhost:8080", // the AllowedBy node you trust (here: python demo/run.py) Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1}, }, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) // the person's pairwise id, level, agent... person, ok := who.Human() // false at level 0: an agent, no person if !ok { http.Error(w, "no person", http.StatusForbidden) return } fmt.Fprintf(w, `{"notes": [], "for": %q}`, person) }) log.Fatal(http.ListenAndServe("127.0.0.1:8081", aby.Handler(mux))) } ``` From `sdks/go/examples/quickstart/main.go`. See it work against the local demo node: ```bash pip install -r requirements.txt ./sdks/python # once python demo/run.py --reset --port 8080 # terminal 1: the node on http://localhost:8080 cd sdks/go && go run ./examples/quickstart # terminal 2: the service on http://localhost:8081 python -c "from allowedby.agent import Agent; print(Agent('http://localhost:8080', tell=print).call('GET', 'http://localhost:8081/notes', action='notes:read'))" ``` ```powershell pip install -r requirements.txt ./sdks/python # once python demo/run.py --reset --port 8080 # terminal 1: the node on http://localhost:8080 cd sdks/go; go run ./examples/quickstart # terminal 2: the service on http://localhost:8081 python -c "from allowedby.agent import Agent; print(Agent('http://localhost:8080', tell=print).call('GET', 'http://localhost:8081/notes', action='notes:read'))" ``` The agent prints the approval link and its code (terminal 3); open the link, approve with the demo passkey, and the call returns `200`. Without a passport the service answers `401 passport_required`; with a passport and no approval, `401 grant_required` and a challenge; the agent asks the node, the person taps the passkey, the agent retries and gets `200`. Against a hosted node, set `Node` to its origin and `Origin` to your public https origin. ## Routes and templates Each `allowedby.Route` says what an agent needs before it may call one method and path; the person signs the sentence of the capability's `Template`. A `Route` is a struct literal, not a function with options: it reads like the route map table of ABY-3 §4.1, every field is named at the call site, and `New` validates the whole map at once (what `route()` checks in Python). Zero values are never silently weaker than meant: a route with a `Capability` must set `Class` and `Level` 1 to 3, or `New` fails. | Field | Meaning | Default | |---|---|---| | `Method`, `Path` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`; `/notes/{id}` (a `{param}` is one segment, whatever the router's syntax: `New` refuses `:id`, `*` and `{path...}`). `HEAD` uses the `GET` route. | required | | `Capability` | What the person allows, `namespace:action`. Empty: an identity route, the passport is enough (level 0). | none | | `Class` | `allowedby.Read`, `Write`, `WriteHard`, `Irreversible`. For `WriteHard` and `Irreversible` the SDK creates the approval itself, bound to the exact request, used once. | required with a capability | | `Classes` | A class by amount: `[]allowedby.Threshold{{UpTo: "1000.00", Class: allowedby.WriteHard}, {Class: allowedby.Irreversible}}`, read at `AmountField`. | none | | `Level` | 1 passkey, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. | required with a capability | | `Resource` | What the route acts on, with path parameters: `note:{id}`. The grant's `scope` must cover it; `New` refuses a character a scope cannot hold (a space, a quote, non-ASCII). | `:*` | | `AmountField`, `CurrencyField` | JSON Pointers to the amount (a decimal string) and currency in the body; the grant must cap the amount. | none, `/currency` | | `Authn` | `"synced"` or `"hardware"`: the passkey class required. | any | | `Tier` | The agent key custody tier required (OAID-6). | 0 | | `MaxLifetime` | How long an approval for this route may last, 60 s to 30 days. | the class's | | `LevelProfile` | `"eu"` or `"na"` on level-3 routes (OAID-7 §5.3, see Reference): a grant whose registration has another profile, or none, is refused with `401 level_insufficient`. | none: any level 3 | | `Nonce` | An AllowedBy-Nonce on this route (ABY-2 §3.2, see Reference). Needs `Options.Nonce`, or `New` fails. | off | | `Summary`, `Body` | What the route does and each JSON body member, for `/openapi.json`. | none | | `RequireLink` | The person must be linked to one of your accounts (account linking, see Reference): `403 human_not_linked` otherwise; when the path has the `AccountParam` parameter, linked to that account. Routes with a capability only: `New` refuses it on a level-0 route. | off | | `AccountParam` | The path parameter that names one of your accounts. With `RequireLink`, the person must be linked to it; approvals the service asks for on a linked account name its person (`human_hint`, AMH-1 §7). | `account` | | `Mandate`, `Disclose`, `DiscloseOptional`, `Authority`, `QES` | Options of the Python SDK the Go SDK does not enforce yet: `New` refuses them, naming the option. | off | Templates: `allowedby.Text("Read your notes")` is English only. For several languages, give the full form, `allowedby.Template{Summary: map[string]string{"en": "...", "fr": "..."}, Lines: map[string]string{...}}`. Placeholders: `{scope}`, `{fields}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{count.max}`; nothing else from the agent reaches the sentence. `New` refuses a route map whose capabilities have no template. ## Framework recipes `aby.Handler` is `net/http` middleware; Gin, Echo and chi have adapters (`allowedbygin.Middleware`, `allowedbyecho.Middleware`, `allowedbychi.Middleware`). In every framework: register the middleware for all routes (so it also serves `/.well-known/allowedby`, `/openapi.json` and `/.well-known/api-catalog`), write paths in the route map with `{param}` whatever the router's own syntax, and read the context in handlers. The middleware reads the body once and gives it back intact. Each app below is complete: the notes API of the interop test, at levels 0, 1 and 2. CI runs all of them against a real node, agent and person (26 of 26 scenarios), on the oldest Go version claimed for the framework and on the current one (`sdks/go/examples/frameworks.json`, `python sdks/go/examples/run_frameworks.py`). `net/http` (Go 1.22 patterns): ```go // Command nethttp is the notes app of sdks/interop/reference_app.py on net/http. CI runs it against a real node, agent // and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py nethttp`. // // GET /me the agent's passport is enough (level 0) // GET /health outside the route map: the app's own // GET /notes read, level 1: the person's own notes // POST /notes write, level 1: body {"text": string} // DELETE /notes/{id} write-hard, level 2: one approval for exactly this request package main import ( "encoding/json" "log" "net/http" "os" "slices" "strconv" "sync" "time" "unicode/utf8" allowedby "github.com/yannUpTo/allowedby/sdks/go" ) func main() { aby, err := service() if err != nil { log.Fatal(err) } notes := &store{by: map[string][]note{}} mux := http.NewServeMux() mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusOK, map[string]bool{"ok": true}) }) // the routes of the map: registered with the SDK, which then knows each one's handler (rule 5) aby.HandleFunc(mux, "GET /me", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level}) }) aby.HandleFunc(mux, "GET /notes", func(w http.ResponseWriter, r *http.Request) { me, ok := person(w, r) if !ok { return } reply(w, http.StatusOK, map[string]any{"notes": notes.list(me)}) }) aby.HandleFunc(mux, "POST /notes", func(w http.ResponseWriter, r *http.Request) { me, ok := person(w, r) if !ok { return } var in struct { Text string `json:"text"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || !validText(in.Text) { reply(w, http.StatusBadRequest, map[string]string{"error": badText}) return } reply(w, http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)}) }) aby.HandleFunc(mux, "DELETE /notes/{id}", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) me, ok := person(w, r) if !ok { return } id := who.Params["id"] // the id as the SDK checked it, never the app's own reading of the raw path notes.remove(me, id) reply(w, http.StatusOK, map[string]string{"deleted": id}) }) mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusNotFound, map[string]string{"error": "not found"}) }) srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second} log.Fatal(srv.ListenAndServe()) } // service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability. func service() (*allowedby.Service, error) { refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s") if err != nil { return nil, err } return allowedby.New(allowedby.Options{ Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"), Node: getenv("ALLOWEDBY_NODE", "http://localhost:8080"), Org: allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/me", Summary: "Who is calling"}, {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "List your notes"}, {Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}}, {Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"}, }, Templates: map[string]allowedby.Template{ "notes:read": allowedby.Text("Read your notes"), "notes:write": allowedby.Text("Write new notes"), "notes:delete": allowedby.Text("Delete note {scope}"), }, Title: "Notes Interop API", RefreshInterval: refresh, }) } func getenv(k, def string) string { if v := os.Getenv(k); v != "" { return v } return def } type note struct { ID string `json:"id"` Text string `json:"text"` } // store keeps each person's notes, by the pairwise id AllowedBy gives this service for them. type store struct { mu sync.Mutex last int by map[string][]note } func (s *store) list(person string) []note { s.mu.Lock() defer s.mu.Unlock() return append([]note{}, s.by[person]...) } func (s *store) add(person, text string) string { s.mu.Lock() defer s.mu.Unlock() s.last++ id := strconv.Itoa(s.last) s.by[person] = append(s.by[person], note{ID: id, Text: text}) return id } func (s *store) remove(person, id string) { s.mu.Lock() defer s.mu.Unlock() s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id }) } const badText = "text: a string of 1 to 2000 characters" // noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for. const noPerson = "this route has no person: map it at level 1 or more" // person is the id of the person the notes belong to, or a 403: never notes kept under an empty id. func person(w http.ResponseWriter, r *http.Request) (string, bool) { who, _ := allowedby.ContextFrom(r.Context()) id, ok := who.Human() if !ok { reply(w, http.StatusForbidden, map[string]string{"error": noPerson}) } return id, ok } func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 } func reply(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } ``` From `sdks/go/examples/frameworks/nethttp/main.go`. Gin: ```go // Command gin is the notes app of sdks/interop/reference_app.py on Gin. CI runs it against a real node, agent // and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py gin`. // // GET /me the agent's passport is enough (level 0) // GET /health outside the route map: the app's own // GET /notes read, level 1: the person's own notes // POST /notes write, level 1: body {"text": string} // DELETE /notes/{id} write-hard, level 2: one approval for exactly this request package main import ( "log" "net/http" "os" "slices" "strconv" "sync" "time" "unicode/utf8" "github.com/gin-gonic/gin" allowedby "github.com/yannUpTo/allowedby/sdks/go" "github.com/yannUpTo/allowedby/sdks/go/allowedbygin" ) func main() { aby, err := service() if err != nil { log.Fatal(err) } notes := &store{by: map[string][]note{}} gin.SetMode(gin.ReleaseMode) r := gin.New() r.Use(gin.Recovery(), allowedbygin.Middleware(aby, r)) // with Use, it also serves /.well-known/allowedby r.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) }) r.GET("/me", func(c *gin.Context) { who, _ := allowedbygin.Context(c) c.JSON(http.StatusOK, gin.H{"agent": who.Agent, "operator": who.Operator, "level": who.Level}) }) r.GET("/notes", func(c *gin.Context) { me, ok := person(c) if !ok { return } c.JSON(http.StatusOK, gin.H{"notes": notes.list(me)}) }) r.POST("/notes", func(c *gin.Context) { me, ok := person(c) if !ok { return } var in struct { Text string `json:"text"` } if err := c.ShouldBindJSON(&in); err != nil || !validText(in.Text) { c.JSON(http.StatusBadRequest, gin.H{"error": badText}) return } c.JSON(http.StatusCreated, gin.H{"id": notes.add(me, in.Text)}) }) r.DELETE("/notes/:id", func(c *gin.Context) { // the route map writes it /notes/{id} me, ok := person(c) if !ok { return } notes.remove(me, c.Param("id")) c.JSON(http.StatusOK, gin.H{"deleted": c.Param("id")}) }) r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"error": "not found"}) }) srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: r, ReadHeaderTimeout: 10 * time.Second} log.Fatal(srv.ListenAndServe()) } // service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability. func service() (*allowedby.Service, error) { refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s") if err != nil { return nil, err } return allowedby.New(allowedby.Options{ Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"), Node: getenv("ALLOWEDBY_NODE", "http://localhost:8080"), Org: allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/me", Summary: "Who is calling"}, {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "List your notes"}, {Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}}, {Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"}, }, Templates: map[string]allowedby.Template{ "notes:read": allowedby.Text("Read your notes"), "notes:write": allowedby.Text("Write new notes"), "notes:delete": allowedby.Text("Delete note {scope}"), }, Title: "Notes Interop API", RefreshInterval: refresh, }) } func getenv(k, def string) string { if v := os.Getenv(k); v != "" { return v } return def } type note struct { ID string `json:"id"` Text string `json:"text"` } // store keeps each person's notes, by the pairwise id AllowedBy gives this service for them. type store struct { mu sync.Mutex last int by map[string][]note } func (s *store) list(person string) []note { s.mu.Lock() defer s.mu.Unlock() return append([]note{}, s.by[person]...) } func (s *store) add(person, text string) string { s.mu.Lock() defer s.mu.Unlock() s.last++ id := strconv.Itoa(s.last) s.by[person] = append(s.by[person], note{ID: id, Text: text}) return id } func (s *store) remove(person, id string) { s.mu.Lock() defer s.mu.Unlock() s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id }) } const badText = "text: a string of 1 to 2000 characters" // noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for. const noPerson = "this route has no person: map it at level 1 or more" // person is the id of the person the notes belong to, or a 403: never notes kept under an empty id. func person(c *gin.Context) (string, bool) { who, _ := allowedbygin.Context(c) id, ok := who.Human() if !ok { c.JSON(http.StatusForbidden, gin.H{"error": noPerson}) } return id, ok } func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 } ``` From `sdks/go/examples/frameworks/gin/main.go`; tested in `sdks/go/allowedbygin/allowedbygin_test.go`. Echo: ```go // Command echo is the notes app of sdks/interop/reference_app.py on Echo. CI runs it against a real node, agent // and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py echo`. // // GET /me the agent's passport is enough (level 0) // GET /health outside the route map: the app's own // GET /notes read, level 1: the person's own notes // POST /notes write, level 1: body {"text": string} // DELETE /notes/{id} write-hard, level 2: one approval for exactly this request package main import ( "log" "net/http" "os" "slices" "strconv" "sync" "time" "unicode/utf8" "github.com/labstack/echo/v4" allowedby "github.com/yannUpTo/allowedby/sdks/go" "github.com/yannUpTo/allowedby/sdks/go/allowedbyecho" ) func main() { aby, err := service() if err != nil { log.Fatal(err) } notes := &store{by: map[string][]note{}} e := echo.New() e.HideBanner = true e.Use(allowedbyecho.Middleware(aby)) // Use also runs for /.well-known/allowedby e.GET("/health", func(c echo.Context) error { return c.JSON(http.StatusOK, map[string]bool{"ok": true}) }) e.GET("/me", func(c echo.Context) error { who, _ := allowedbyecho.Context(c) return c.JSON(http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level}) }) e.GET("/notes", func(c echo.Context) error { me, err := person(c) if err != nil { return err } return c.JSON(http.StatusOK, map[string]any{"notes": notes.list(me)}) }) e.POST("/notes", func(c echo.Context) error { me, err := person(c) if err != nil { return err } var in struct { Text string `json:"text"` } if err := c.Bind(&in); err != nil || !validText(in.Text) { return c.JSON(http.StatusBadRequest, map[string]string{"error": badText}) } return c.JSON(http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)}) }) e.DELETE("/notes/:id", func(c echo.Context) error { // the route map writes it /notes/{id} me, err := person(c) if err != nil { return err } notes.remove(me, c.Param("id")) return c.JSON(http.StatusOK, map[string]string{"deleted": c.Param("id")}) }) e.RouteNotFound("/*", func(c echo.Context) error { return c.JSON(http.StatusNotFound, map[string]string{"error": "not found"}) }) e.Server.ReadHeaderTimeout = 10 * time.Second log.Fatal(e.Start("127.0.0.1:" + getenv("PORT", "8081"))) } // service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability. func service() (*allowedby.Service, error) { refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s") if err != nil { return nil, err } return allowedby.New(allowedby.Options{ Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"), Node: getenv("ALLOWEDBY_NODE", "http://localhost:8080"), Org: allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/me", Summary: "Who is calling"}, {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "List your notes"}, {Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}}, {Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"}, }, Templates: map[string]allowedby.Template{ "notes:read": allowedby.Text("Read your notes"), "notes:write": allowedby.Text("Write new notes"), "notes:delete": allowedby.Text("Delete note {scope}"), }, Title: "Notes Interop API", RefreshInterval: refresh, }) } func getenv(k, def string) string { if v := os.Getenv(k); v != "" { return v } return def } type note struct { ID string `json:"id"` Text string `json:"text"` } // store keeps each person's notes, by the pairwise id AllowedBy gives this service for them. type store struct { mu sync.Mutex last int by map[string][]note } func (s *store) list(person string) []note { s.mu.Lock() defer s.mu.Unlock() return append([]note{}, s.by[person]...) } func (s *store) add(person, text string) string { s.mu.Lock() defer s.mu.Unlock() s.last++ id := strconv.Itoa(s.last) s.by[person] = append(s.by[person], note{ID: id, Text: text}) return id } func (s *store) remove(person, id string) { s.mu.Lock() defer s.mu.Unlock() s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id }) } const badText = "text: a string of 1 to 2000 characters" // noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for. const noPerson = "this route has no person: map it at level 1 or more" // person is the id of the person the notes belong to, or a 403: never notes kept under an empty id. func person(c echo.Context) (string, error) { who, _ := allowedbyecho.Context(c) id, ok := who.Human() if !ok { return "", echo.NewHTTPError(http.StatusForbidden, noPerson) } return id, nil } func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 } ``` From `sdks/go/examples/frameworks/echo/main.go`; tested in `sdks/go/allowedbyecho/allowedbyecho_test.go`. chi: ```go // Command chi is the notes app of sdks/interop/reference_app.py on chi. CI runs it against a real node, agent // and person (26 interop scenarios): `python sdks/go/examples/run_frameworks.py chi`. // // GET /me the agent's passport is enough (level 0) // GET /health outside the route map: the app's own // GET /notes read, level 1: the person's own notes // POST /notes write, level 1: body {"text": string} // DELETE /notes/{id} write-hard, level 2: one approval for exactly this request package main import ( "encoding/json" "log" "net/http" "os" "slices" "strconv" "sync" "time" "unicode/utf8" "github.com/go-chi/chi/v5" allowedby "github.com/yannUpTo/allowedby/sdks/go" "github.com/yannUpTo/allowedby/sdks/go/allowedbychi" ) func main() { aby, err := service() if err != nil { log.Fatal(err) } notes := &store{by: map[string][]note{}} r := chi.NewRouter() r.Use(allowedbychi.Middleware(aby)) r.Get("/health", func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusOK, map[string]bool{"ok": true}) }) // the routes of the map: registered with the SDK, which then knows each one's handler (rule 5) r.Method("GET", "/me", aby.Registered("GET /me", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level}) }))) r.Method("GET", "/notes", aby.Registered("GET /notes", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { me, ok := person(w, r) if !ok { return } reply(w, http.StatusOK, map[string]any{"notes": notes.list(me)}) }))) r.Method("POST", "/notes", aby.Registered("POST /notes", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { me, ok := person(w, r) if !ok { return } var in struct { Text string `json:"text"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || !validText(in.Text) { reply(w, http.StatusBadRequest, map[string]string{"error": badText}) return } reply(w, http.StatusCreated, map[string]string{"id": notes.add(me, in.Text)}) }))) r.Method("DELETE", "/notes/{id}", aby.Registered("DELETE /notes/{id}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { me, ok := person(w, r) if !ok { return } notes.remove(me, chi.URLParam(r, "id")) reply(w, http.StatusOK, map[string]string{"deleted": chi.URLParam(r, "id")}) }))) r.NotFound(func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusNotFound, map[string]string{"error": "not found"}) }) srv := &http.Server{Addr: "127.0.0.1:" + getenv("PORT", "8081"), Handler: r, ReadHeaderTimeout: 10 * time.Second} log.Fatal(srv.ListenAndServe()) } // service describes the API to AllowedBy: its routes, and the sentence a person approves for each capability. func service() (*allowedby.Service, error) { refresh, err := time.ParseDuration(getenv("ALLOWEDBY_REFRESH_SECONDS", "5") + "s") if err != nil { return nil, err } return allowedby.New(allowedby.Options{ Origin: getenv("ALLOWEDBY_ORIGIN", "http://localhost:8081"), Node: getenv("ALLOWEDBY_NODE", "http://localhost:8080"), Org: allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/me", Summary: "Who is calling"}, {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*", Summary: "List your notes"}, {Method: "POST", Path: "/notes", Capability: "notes:write", Class: allowedby.Write, Level: 1, Resource: "note:new", Summary: "Add a note", Body: map[string]string{"text": "the note"}}, {Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete", Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"}, }, Templates: map[string]allowedby.Template{ "notes:read": allowedby.Text("Read your notes"), "notes:write": allowedby.Text("Write new notes"), "notes:delete": allowedby.Text("Delete note {scope}"), }, Title: "Notes Interop API", RefreshInterval: refresh, }) } func getenv(k, def string) string { if v := os.Getenv(k); v != "" { return v } return def } type note struct { ID string `json:"id"` Text string `json:"text"` } // store keeps each person's notes, by the pairwise id AllowedBy gives this service for them. type store struct { mu sync.Mutex last int by map[string][]note } func (s *store) list(person string) []note { s.mu.Lock() defer s.mu.Unlock() return append([]note{}, s.by[person]...) } func (s *store) add(person, text string) string { s.mu.Lock() defer s.mu.Unlock() s.last++ id := strconv.Itoa(s.last) s.by[person] = append(s.by[person], note{ID: id, Text: text}) return id } func (s *store) remove(person, id string) { s.mu.Lock() defer s.mu.Unlock() s.by[person] = slices.DeleteFunc(s.by[person], func(n note) bool { return n.ID == id }) } const badText = "text: a string of 1 to 2000 characters" // noPerson: a level-0 route proves an agent, not a person, so it has no one to keep notes for. const noPerson = "this route has no person: map it at level 1 or more" // person is the id of the person the notes belong to, or a 403: never notes kept under an empty id. func person(w http.ResponseWriter, r *http.Request) (string, bool) { who, _ := allowedby.ContextFrom(r.Context()) id, ok := who.Human() if !ok { reply(w, http.StatusForbidden, map[string]string{"error": noPerson}) } return id, ok } func validText(s string) bool { return s != "" && utf8.RuneCountInString(s) <= 2000 } func reply(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } ``` From `sdks/go/examples/frameworks/chi/main.go`; tested in `sdks/go/allowedbychi/allowedbychi_test.go`. The SDK checks a request when its path names a route of the map either as decoded (how Gin routes) or segment by segment as escaped (how `ServeMux`, chi and Echo route), after RFC 3986 normalisation; a mapped route reached through an encoded `/` or `\` in a segment (`/notes/a%2Fb`) is refused with `400 invalid_request`, and so is a `.` or `..` segment (`/notes/.`, `%2E` included) where the path before dot removal names a route (those routers do not clean paths), and so is a path whose readings name two different routes, or that still holds a `%` once decoded (double encoding, `/notes/%2564rafts`). Variants of a protected route are refused too (CONTRACT §2.10): a doubled or trailing `/` (`/notes/`, `//notes`) and a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method` in the query or a form body) that would turn the request into a mapped one. After that, the middleware asks the router which of its routes and handlers the request goes to, and refuses (`400`) a request it did not verify that would run the handler of any route of the map, wherever the router uses that handler (another path, a catch-all), or a protected route: Echo gives the rest of the path to a last `:param` (`/notes/7/x` is `/notes/:id` for it), and a wildcard may serve a protected route (`/notes/{id...}`, `/notes/*`). The handler of each route of the map is found once with sample values (and from chi's own routes), then learnt from checked requests (CONTRACT §2.10 rule 5). A handler that also serves the route's path with a word replaced is a catch-all, not the route's own handler, and the route counts as not known until a checked request runs a handler of its own. A site-wide catch-all (the router chose it for the route's path with a word replaced through a site-wide wildcard rule: `/*`, an SPA fallback) is the site's own, never protected, while the routes it reaches have known handlers of their own; a route served only by it makes it that route's handler (a `/` handler that dispatches itself, a mounted router): protected, and the log names the route at the first request. A prefix catch-all (`/notes/{id}/{rest...}`) that the route's samples reach stays protected, its own handler known or not: it can only be another handler of that route, so an alias of it on another path is refused. A fallback the router chose through a site-wide wildcard rule is protected only while the route's own handler is not known (this is what keeps a tenant-first app's fallback pages working, under `/{org}/notes/{id}` too). Neither is ever learnt. A checked request runs a catch-all of its route only while the route has no known handler of its own (a dispatcher, a mounted router: it is the route's handler); next to the route's own handler it is refused, unless the router names a matched rule of the route's own shape (the pattern each adapter reports: Gin's `FullPath`, Echo's `Path`, the ServeMux pattern, chi's route pattern). Near a route whose handler is not known, a request the SDK did not check is refused (it cannot tell). A site-wide catch-all that is a protected route's only handler refuses every request the SDK did not check that it would serve. 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. One handler for several mapped methods of a route, such as the pre-1.22 pattern of one `HandlerFunc` for `/notes/{id}` that switches on `r.Method`, runs only for a request checked as a method that covers the others: the weaker method is refused (`400`), and the log names both routes at the first request. Register one handler per method instead: Go 1.22 method patterns (`mux.HandleFunc("GET /notes/{id}", get)` and `mux.HandleFunc("DELETE /notes/{id}", del)`), or the router's per-method registration (`r.Get` and `r.Delete` on chi, `e.GET` and `e.DELETE` on Echo, `r.GET` and `r.DELETE` on Gin). Closures made by one wrapper count as one handler (see below): `requireLogin(get)` on GET and `requireLogin(del)` on DELETE of `/notes/{id}` refuse checked requests to the method that does not cover the other, so give each method a named handler, register the handlers (below), or apply the wrapper as router middleware (`r.Use`, or a `http.Handler` around the mux). What checked requests teach lives in the process: it is lost on restart and not shared between instances, so until an instance has served a checked request for a route whose handler the samples miss, an alias of that handler far from the route is not refused there. The handlers are resolved, and these warnings logged, at the first request for each router (an adapter's routes are registered until then), not when the service is built. Make every protected route's handler known from the first request: patterns its sample values reach (`0` or `a` in each parameter), or chi, whose routes the adapter lists. A func handler is known by its code (Echo: by its default name; a route given a `Name` of its own hides its handler, so a request the SDK did not check is refused on that route, and on every route when it is a route of the map), a pointer by its address: a method value written twice (`h.Archive`) is one handler, and so is every closure made by one wrapper or factory (a `handle(fn)` helper, `echo.WrapHandler`; a wrapper the compiler inlines, such as `gin.WrapF`, may give each call its own code). A route whose handler shares that code with a protected route's is refused when the SDK did not verify the request (fail closed), and so is a checked request for a route whose handler is also another route's (any template, any method) that it does not cover: one `del` on a level-3 `DELETE /notes/{id}` and a level-1 `DELETE /items/{id}` refuses `DELETE /items/7`. Give protected routes handlers of their own, not a wrapper your other routes use, or register them (below). Where the SDK does not see the router (`aby.Handler` around anything but a `*http.ServeMux`), every path that goes on below a protected parameter is refused, for the methods the map uses there. **Registered handlers** (CONTRACT §2.10 rule 5, 1.9). Rather than let the SDK infer each route's handler, you can register it with the method and path it serves: - `aby.HandleFunc(mux, "GET /notes/{id}", get)` and `aby.Handle(mux, pattern, h)` register on a `ServeMux`; - `aby.Registered("GET /notes/{id}", h)` is the handler for a router that takes an `http.Handler`, such as chi: `r.Method("GET", "/notes/{id}", aby.Registered("GET /notes/{id}", h))`. The pattern is `METHOD /path` (HEAD is read as GET), or a path alone for every method. The path is the route's path as the map writes it, with `{param}` and any mount prefix included, and no host. A pattern with a method must name a route of the map: one that names none (a host before the path, a chi path without its mount prefix) panics when it is registered, naming the nearest route. Register a page of your own with its path alone, or through the router. A registered handler of a route of the map runs only for a request the SDK checked for that route. Every other request is refused with `400 invalid_request`: - one the SDK did not check (the SDK is not in front, or another method); - one checked for another route; - one checked for a route that does not cover every other route of the map the handler is registered on (the weaker is refused, and the log names the two routes once). A registered closure is known by its value, so `aby.HandleFunc(mux, "GET /notes/{id}", requireLogin(get))` and `aby.HandleFunc(mux, "DELETE /notes/{id}", requireLogin(del))` no longer count as one handler, while one closure registered on two routes is one handler. (Telling closures apart by value reads how the Go toolchain represents a func value, which the language does not specify: a self-test at start-up checks it, and if it ever fails, a closure is known by its code as without registration, which refuses rather than allows, and the log says so once.) A named function, or one handler value, registered twice is one handler. A method value (`store.Del`) is a new value each time it is written, so it is known by its code, as the router checks know it: two method values of one method are one handler, whatever their receivers (give each route a closure or a function of its own). On a path the map does not have, a route's handler is its alias and is refused there. A registered handler that serves no route of the map runs as before. The router checks above still run, and see each registration as its handler. A use registered through the router's own API (`mux.HandleFunc`, or `r.Get` with the bare handler) is known by its code, as without registration: a bare use of a registered closure stays protected (an unchecked request to it is refused, and so is one checked for a route that does not cover the registered one's), and so does a bare closure of the same wrapper. Gin and Echo, whose handlers are not `http.Handler`, have no registration yet. A refusal names the fix, never the request. `Options.Unprotected` lists your own pages that these rules refuse: `{Method: "GET", Path: "/notes/{id}/comments"}` (a template, for pages below a protected route: it has a word of its own, and names its method when it lies below a route of the map), or `{Method: "GET", Path: "/notes/new/"}` (an exact path, with no `;`, encoded or control character); where the SDK sees the router, a declared page never opens a protected handler; elsewhere the entry is your word that the router runs your page for that path, except an exact path that is a protected route but for its last `/` (`/notes/new/` next to `/notes/{id}`): that one has no effect there, the request stays refused, and the log says so once. A protected handler never runs unchecked, for any method, and no entry lifts that: the refusal says to map that method too, or to give it a handler of its own. Also refused: a control character in a protected path, and a protected path seen without its prefix (below `http.StripPrefix`): write the map with the paths the SDK sees, and mount it where those are the paths agents call. Do not give one handler to every method (`Any`) unless it checks the method: the map protects the methods it lists. Put the SDK after any middleware that rewrites the path (Echo `Pre` rewrites, chi `StripSlashes`). Make sure your router does not serve a protected handler under another spelling of a mapped path (a trailing slash, other letter case). `HEAD` is read as `GET` in all these rules: a ServeMux, chi's `GetHead` or an explicit `HEAD` route given a `GET` handler run it for `HEAD`. A refusal names no part of the request (path, query, headers), and the log names only the route template and the code: paths may hold personal data or tokens. (An approval challenge on a mapped route carries its `scope`, the route's `Resource` with its parameters, built from the path normalised as for `htu` (`/notes/%61b` gives `note:ab`), as ABY-2 §6 defines it, and only when each value is 1 to 64 of `A-Z a-z 0-9 . _ -` and the whole at most 256 bytes, so it is safe in a header and an approval of it satisfies the route; otherwise the request is refused with `400`, and the scope is never logged.) On a ServeMux, a protected handler registered only under a host pattern (`notes.example/notes/{id}`) is known as protected for requests to that host; give it to no hostless pattern. ## The context `allowedby.ContextFrom(r.Context())` returns who called and with which approval; `ok` is false on paths outside the route map. | Field | Type | Meaning | |---|---|---| | `HumanID` | `string` | The person's pairwise id for your service: stable here, different at every other service. Empty at level 0 (identity routes), where an agent calls with no person. | | `Level` | `int` | The identity level proven: 0 (agent only) to 3. | | `Agent` | `string` | The agent's passport subject, `did:oaid::`. | | `Operator` | `string` | Who runs the agent: its verified domain, or a node-scoped id. | | `Capabilities` | `[]string` | What the approval allows. | | `Display` | `*allowedby.Display` | The sentence the person signed: `Summary`, `Lines`, `Lang`. | | `GID`, `Rev`, `JTI` | `string`, `int64`, `string` | The approval's id, revision and document id. | | `Chain` | `[]allowedby.ChainLink` | The grant chain, leaf first (`GID`, `Rev`). | | `HumanIssuer` | `string` | The person's home node. | | `Route` | `string` | The route that matched, e.g. `DELETE /notes/{id}`. | | `ProofJTI`, `Run`, `Call` | `string`, `string`, `*int64` | The request proof's id and the agent's own audit labels. | | `ActingFor` | `*allowedby.ActingFor` | Company mandates: always nil in the Go SDK for now. | | `Tenant` | `string` | The `{tenant}` path parameter when the route has one, decoded once as in `Params` (`Options.Tenants` tightens the route for it, and caps its amounts). | | `Params` | `map[string]string` | The route's path values as the SDK checked them: each `{name}` of the route, from the normalised path, decoded once. Empty, never nil, without parameters. | | `LinkedAccount` | `string` | On a `RequireLink` route, the account of yours the person is linked to (account linking). Empty elsewhere. | The context is a copy: changing it changes nothing else. Key a person's data by `who.Human()`, which returns the id and `false` when there is no person (a level-0 route proves an agent only, and `HumanID` is then empty). When it is false, refuse or store nothing: never keep data under an empty id, which every level-0 caller would share. The examples answer `403` (their `person` helper). Act on `Params`, never on your own reading of the raw path: the two can differ (`/notes/%37` is checked as note `7`, `DELETE /notes/7/.` as `/notes/7`). Each value is decoded once (`acme%20co` gives `acme co`), and the SDK refuses a path that a router could read another way: an encoded `/`, or a value that still holds a `%` once decoded (`%2561`). A router hands your handler the values it matched (`r.PathValue` on a ServeMux, `c.Param` on Gin and Echo, `chi.URLParam`); a handler with no router behind `aby.Handler` or `aby.Check` sees only the raw path, and takes the values from `Params` (`examples/frameworks/nethttp/main.go` uses it for the note id). **Changed after the check.** A step after the SDK (a middleware, a wrapper inside a handler) that rewrites an accepted request's path or method, or passes on another request (`r.WithContext` or `r.Clone` with another URL), would have the handler act on values the person never approved. The SDK records the method and the normalised path it accepted (another spelling of the same path, or `HEAD` for `GET`, is the same request), and: - `allowedbygin.Context(c)` and `allowedbyecho.Context(c)` refuse a changed request (`400 invalid_request`, the path never repeated) and give no context: return when `ok` is false. Gin, and Echo with `Use`, route before their middleware runs, so the handler and its `c.Param` are the ones checked; only the request was changed. With `e.Pre`, a `Pre` middleware after the SDK's (`middleware.Rewrite`) makes Echo route the rewritten request to another route or value: `allowedbyecho.Context(c)` refuses it there too, since it compares the request the handler got. - On chi, `allowedby.ContextFrom` gives no context to a handler that chi routed to another method, route or value (the route context tells), and `allowedby.RequireUnchanged` as the router's last `Use` refuses the request with `400`: it asks chi how it would route the request now, so a middleware that sets the route context's `RoutePath` (chi's own rewrite) is refused too. - On a ServeMux (`aby.Handler(mux)` runs the mux right after the check), `allowedby.ContextFrom` gives no context when the accepted request was changed in place, and `allowedby.ContextOf(r)` also compares the request the handler got. Behind a step of your own, put the step and `allowedby.RequireUnchanged` around the handler, inside the mux: `mux.Handle("GET /notes/{id}", step(allowedby.RequireUnchanged(h)))`. Never put anything between `aby.Handler` and the mux (`aby.Handler(step(mux))`): the SDK then no longer sees the mux, and its router checks (CONTRACT §2.10 rules 2 and 5) are off. The SDK sees through `RequireUnchanged`: `h` is still known as itself, and `aby.Handler(allowedby.RequireUnchanged(mux))` still checks the mux. Limits: where the SDK does not see the router (`aby.Handler` or `aby.Check` around anything but a ServeMux), and in a handler that reads `allowedby.ContextFrom` behind a step that passes on another request, nothing tells the SDK which request the handler runs for: use `allowedby.ContextOf(r)` or `allowedby.RequireUnchanged`, or put nothing that changes the method or the path after the SDK. `http.StripPrefix` after the SDK passes on another path: there, `ContextOf` and `RequireUnchanged` refuse, and `ContextFrom` still answers. ## Production In production, keep the keys in a key file shared by every instance, share the replay set in Redis, and close the service on shutdown. ```go // Command production is the production recipe of docs/sdk/go.md: keys kept in a key file, the replay set shared // in Redis by every instance, and a clean shutdown. // // In a container, next to a Redis service named redis (ALLOWEDBY_BIND is the address to listen on: 127.0.0.1, loopback // only, when it is unset or empty; 0.0.0.0 in a container, so that its port mapping reaches the service): // // ALLOWEDBY_ORIGIN=https://notes.example ALLOWEDBY_NODE=https://node.example.org ALLOWEDBY_BIND=0.0.0.0 PORT=8080 \ // ALLOWEDBY_KEY_FILE=/var/lib/notes/allowedby-keys.json REDIS_URL=redis://redis:6379/0 ./production package main import ( "cmp" "context" "errors" "log" "net" "net/http" "os" "os/signal" "syscall" "time" "github.com/redis/go-redis/v9" allowedby "github.com/yannUpTo/allowedby/sdks/go" "github.com/yannUpTo/allowedby/sdks/go/allowedbyredis" ) func main() { ropts, err := redis.ParseURL(os.Getenv("REDIS_URL")) if err != nil { log.Fatal("REDIS_URL: ", err) } aby, err := allowedby.New(allowedby.Options{ Origin: os.Getenv("ALLOWEDBY_ORIGIN"), // your public https origin Node: os.Getenv("ALLOWEDBY_NODE"), // the node you trust Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR", PrivacyPolicy: "https://notes.example/privacy"}, KeyFile: os.Getenv("ALLOWEDBY_KEY_FILE"), // the same file on every instance (a secret volume) Store: allowedbyredis.New(redis.NewClient(ropts), "notes:allowedby:"), Routes: []allowedby.Route{ {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*"}, }, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, }) if err != nil { log.Fatal(err) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"notes": []}`)) }) srv := &http.Server{Addr: net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "8080")), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second} go func() { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } }() <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = srv.Shutdown(shutdown) _ = aby.Close() } ``` From `sdks/go/examples/production/main.go`. CI runs two instances of it with a real Redis and one key file (`sdks/go/examples/prove_examples.py`), and the trust-list app below. - **Keys** (`KeyFile`): the Ed25519 signing key (it signs your organisation profile and the approvals you ask for; its `kid` is the `initiator` of serious grants) and the P-256 disclosure key. The file is created on first use with mode 0600, atomically, first writer wins, in the same JSON format as every other SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `KeyFile` at it, or write it from your secret manager. An existing file works anywhere. Without `KeyFile`, keys are new at each start and agents re-read `/.well-known/allowedby`. - **Listening**: the examples listen on `ALLOWEDBY_BIND` (default `127.0.0.1`, loopback only) and `PORT` (default `8080`); an empty value counts as unset (`cmp.Or`). A container sets `ALLOWEDBY_BIND=0.0.0.0` so that its port mapping reaches the service. - **Store**: `MemoryStore` (the default) is for one process only. With several instances, a proof replayed to another instance would be accepted there: use `allowedbyredis.New(client, prefix)`. Expiry follows the SDK's clock; with Redis Cluster put a hash tag in the prefix (`"allowedby:{aby}:"`). Any store error refuses the request (`503`). - **Handlers**: what the adapters learn from checked requests (rule 5) is per process, like `MemoryStore`: make each protected route's handler known at start-up (see Framework recipes). - **Refunds** (CONTRACT §2 item 10): the check spends the approval (a single-use grant's mark, its `count` and `amount` totals). When the SDK itself then refuses that accepted request before any handler started, it gives back exactly what the request spent, once, so the approval serves the request on its own route afterwards. That covers a router check (rule 5) in `aby.Handler(mux)` and the Gin, Echo and chi middleware, and, on chi, `allowedby.RequireUnchanged` in front of the routing (a request moved by a middleware after the SDK's). `RequireUnchanged` as the handler a ServeMux chooses, or around the mux, also refunds, and so does a registered handler that refuses (Framework recipes), behind a ServeMux or any other router: behind a router the SDK does not see, `aby.Handler` starts the request once the router returns. Nothing is refunded once the request was handed to its handler, for a refusal of your own (a handler or a middleware that answers), or for `allowedbygin.Context` and `allowedbyecho.Context`, which run inside the handler. A refunded request never reaches a handler, even dispatched again. A refund the store does not take leaves the approval spent, and is logged without request data. A store refunds with a `Charge` of negative increments and no maximum, which it applies exactly (`Store.Charge`). - **Trust**: by default the SDK trusts `Node` on first use and pins its node key; a changed key is refused and logged. With a signed OAID-5 trust list, `allowedby.ParseTrustList(jws, signerJWK)` and `Options.TrustList` decide which nodes count (anchors, program lists, vouching, witnesses): ```go // Command trustlist is the trust-list recipe of docs/sdk/go.md: trust the nodes of a signed OAID-5 trust list // instead of trust on first use of one node. // // On one host (ALLOWEDBY_BIND is the address to listen on: 127.0.0.1, loopback only, when it is unset or empty; 0.0.0.0 // in a container): // // ALLOWEDBY_ORIGIN=https://notes.example ALLOWEDBY_NODE=https://node.example.org ALLOWEDBY_BIND=127.0.0.1 PORT=8080 \ // ALLOWEDBY_TRUST_LIST=trust-list.jws ALLOWEDBY_TRUST_LIST_KEY='{"kty":"OKP","crv":"Ed25519","kid":"...","x":"..."}' ./trustlist package main import ( "cmp" "encoding/json" "log" "net" "net/http" "os" "time" allowedby "github.com/yannUpTo/allowedby/sdks/go" ) func main() { jws, err := os.ReadFile(os.Getenv("ALLOWEDBY_TRUST_LIST")) // the signed list (oaid-trust+jwt) if err != nil { log.Fatal(err) } var signer map[string]any // the public JWK of the key that signed it if err := json.Unmarshal([]byte(os.Getenv("ALLOWEDBY_TRUST_LIST_KEY")), &signer); err != nil { log.Fatal("ALLOWEDBY_TRUST_LIST_KEY: ", err) } tl, err := allowedby.ParseTrustList(string(jws), signer) if err != nil { log.Fatal(err) } aby, err := allowedby.New(allowedby.Options{ Origin: os.Getenv("ALLOWEDBY_ORIGIN"), Node: os.Getenv("ALLOWEDBY_NODE"), // still where the service asks for approvals TrustList: tl, // which nodes' passports and approvals are accepted Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1}, }, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, }) if err != nil { log.Fatal(err) } defer aby.Close() mux := http.NewServeMux() mux.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"notes": []}`)) }) srv := &http.Server{Addr: net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "8080")), Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second} log.Print(srv.ListenAndServe()) } ``` From `sdks/go/examples/trustlist/main.go`. - **Refresh**: node statements and status lists are fetched in the background every `RefreshInterval` (default 5 s, 1 s to 60 s), never on the request path. `New` returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, or one that scales to zero) trusts its node and holds its status lists before its first request. Status lists older than 60 s (write-hard, irreversible) or 3600 s (read, write) fail closed with `503 status_stale`. - **Logging**: `Options.Logger` (`*slog.Logger`, default `slog.Default()`) gets `[verifier] refresh failed` with the reason at each failed refresh, and one line per refusal with the route pattern and the code. Never tokens, keys, bodies or personal data. - **Limits**: `Allowed-By` and `AllowedBy-Proof` together at most 8 KiB and two JWS, a grant and one child (`431`; a child of a child is refused); request bodies on mapped routes at most `MaxBodyBytes` (1 MiB) and a JSON object (`400`) without member names that are equal or differ only in case (`encoding/json` would read the last one); the memory store holds 200 000 entries and refuses new ones when full of live entries. - **Behind a proxy**: set `Origin` to the public origin agents call. Forwarded headers are ignored: proofs are checked against `Origin` and the normalised path. ## Agents The Go SDK is a service SDK only; agent runtimes use the Python or TypeScript agent SDK (`docs/sdk/python.md`, `docs/sdk/js.md`). For tests, `allowedbytest.Agent` (section Testing) signs requests the way an agent runtime does: a passport or grant in `Allowed-By` and a fresh proof in `AllowedBy-Proof`. ## Errors Every refusal is an RFC 9457 problem document (`application/problem+json`, `type: https://allowedby.org/errors/`), with the same code and status in every SDK. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed `Allowed-By`, a mix of passport and grants, a body that is not a JSON object, a header sent twice. | 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, `human_sig` or chain link does not verify, or a proof is replayed or for another URL or body. | The agent signs a fresh proof for this exact request. | | `untrusted_node` | 401 | The document comes from a node this service does not trust (or no refresh has reached it yet: the first one at start failed or took over 5 s). | Use a trusted node; wait for the next refresh. | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses (trust list). | The node operator fixes its witnessing. | | `grant_required` | 401 | A passport on a route that needs a person's approval. | Follow the challenge: ask the person, retry with the grant. | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, single-use request, initiator). | 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 to the level, then approves. | | `qes_required` | 401 | The route needs a qualified electronic signature. | Not available in the Go SDK (refused at configuration). | | `authority_required` | 401 | The organisation's co-approvers are missing. | Not available in the Go SDK. | | `mandate_required` | 401 | A company mandate is missing or does not cover the request. | Ask for a personal approval: the Go SDK accepts no mandates and refuses every grant with `acting_for`. | | `expired` | 401 | The grant or passport has expired. | Ask again (or renew the passport). | | `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 is revoked. | Ask the person again. | | `actor_expired` | 401 | The agent key named in the grant has expired. | The agent rebinds the grant or gets a new passport. | | `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 the new request. | | `capability_denied` | 403 | No such route in the route map. | Call a route the service publishes. | | `tier_insufficient` | 403 | The agent's key custody or the passkey class is too weak for the route. | Use a stronger key custody or passkey. | | `human_not_linked` | 403 | The route needs a person linked to one of your accounts (`RequireLink`), to the one its path names. | Link the account first: `aby:link` with the code of the account page (see Account linking). | | `budget_exceeded` | 403 | A company budget is used up. | Not available in the Go SDK. | | `rate_limited` | 429 | Too many calls from this agent or its operator (`Options.Rate`). | Wait (`Retry-After: 60`). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain over two grants (a grant and one child). | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old, or the replay store is unavailable (fail closed). | Retry after `Retry-After` seconds. | Challenges (`401` with `WWW-Authenticate: AllowedBy realm=..., error=..., action=..., scope=..., class=..., level=..., tier=...`) come with `grant_required`, `grant_insufficient`, `level_insufficient`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed` and `actor_expired` on routes with a capability. For `write-hard` and `irreversible` routes they also carry `approve`, `poll`, `code`, `request` and `expires`: the approval the service created at its node (ABY-2 §6). ## Testing `go test ./...` in `sdks/go` runs the CONF-1 vectors (481 cases read from `vectors/`), the unit tests and the examples; `python sdks/interop/interop.py` runs the end-to-end interop test (26 scenarios) against the Go app. Linux and macOS: ```bash cd sdks/go go test -run TestVectors -v . # prints "481/481 cases passed" go test -race ./... go vet ./... go install honnef.co/go/tools/cmd/staticcheck@2026.2.2 && "$(go env GOPATH)/bin/staticcheck" ./... go build -o /tmp/aby-interop ./examples/frameworks/nethttp cd ../.. && pip install -r requirements.txt INTEROP_PORT_BASE=19300 python sdks/interop/interop.py --cmd /tmp/aby-interop ``` Windows (PowerShell): ```powershell cd sdks/go go test -run TestVectors -v . # prints "481/481 cases passed" go test ./... go build -o "$([IO.Path]::GetTempPath())aby-interop.exe" ./examples/frameworks/nethttp cd ../..; pip install -r requirements.txt $env:INTEROP_PORT_BASE = "19300"; python sdks/interop/interop.py --cmd "$([IO.Path]::GetTempPath())aby-interop.exe" ``` Every framework and Go version: `python sdks/go/examples/run_frameworks.py`. The command blocks of this page: `python sdks/go/examples/run_blocks.py`. Set `ALLOWEDBY_VECTORS` to the `vectors/` directory when the tests do not run from `sdks/go`. Fuzz the parsers with `go test -run '^$' -fuzz FuzzVerify .` (also `FuzzSigInput`, `FuzzNormPath`, and `FuzzParseJSON`, `FuzzParseJWS`, `FuzzCanon` in `./internal/jose`). Test your own app without a browser, a passkey or a node: `allowedbytest` is a fake node (passports, grants signed with a software passkey, status lists, approvals) and an agent that signs requests. ```go package notes import ( "context" "net/http" "net/http/httptest" "testing" allowedby "github.com/yannUpTo/allowedby/sdks/go" "github.com/yannUpTo/allowedby/sdks/go/allowedbytest" ) func TestNotesWithAnAgent(t *testing.T) { node := allowedbytest.NewNode(t) // a fake node on a local test server aby, err := allowedby.New(allowedby.Options{ Origin: "https://notes.example", Node: node.URL(), Org: allowedby.Org{LegalName: "Notes Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1}, }, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, }) if err != nil { t.Fatal(err) } defer aby.Close() if err := aby.Refresh(context.Background()); err != nil { // trust the node now t.Fatal(err) } app := aby.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) _, _ = w.Write([]byte(who.HumanID)) })) agent := node.NewAgent() // Without the person's approval: 401 and a challenge. rec := httptest.NewRecorder() app.ServeHTTP(rec, agent.Request("GET", "https://notes.example/notes", nil, agent.Passport)) if rec.Code != 401 || rec.Header().Get("WWW-Authenticate") == "" { t.Fatalf("without approval: %d", rec.Code) } // With it: the handler runs and knows who the person is (their pairwise id). grant := node.Grant(agent, allowedbytest.GrantSpec{Origin: "https://notes.example", Capability: "notes:read", Scope: "notes:*", Class: "read", Level: 1}) rec = httptest.NewRecorder() app.ServeHTTP(rec, agent.Request("GET", "https://notes.example/notes", nil, grant)) if rec.Code != 200 || rec.Body.String() != allowedbytest.HumanID { t.Fatalf("with approval: %d %s", rec.Code, rec.Body) } } ``` From `sdks/go/examples/testing/notes_test.go`. `node.Revoke(idx)` revokes, `node.SetStale(true)` makes the status list old, `node.Approvals()` lists the approvals your service asked for, and `GrantSpec.SingleUse` with `allowedbytest.RequestDigest` builds the one-time grant of a write-hard route. ## Reference The public API is `New`, `Options`, `Service` (`Handler`, `Check`, `Refresh`, `Close`), `Route`, `Template`, `ContextFrom` and `Context`, `Store`, and `ParseTrustList`. | Name | What | |---|---| | `func New(opts Options) (*Service, error)` | Validates the configuration, loads or creates the keys, starts the background refresh and waits for its first run (at most 5 s). | | `type Options struct` | `Origin`, `Node`, `Org`, `Routes`, `Templates` (required); `KeyFile`, `Store`, `TrustList`, `RefreshInterval`, `NodeMaxLevel`, `Clock`, `Title`, `Version`, `Description`, `RFC9421`, `Unprotected`, `HTTPClient`, `Logger`, `MaxBodyBytes`, `Nonce`, `Rate`, `LinkAuthorize`. | | `func (*Service) Handler(next http.Handler) http.Handler` | The `net/http` middleware. | | `func (*Service) Check(w, r) (*http.Request, bool)` | The middleware as a function, for adapters: `false` when it wrote the response. | | `func (*Service) CheckRouted(w, r, router, chosen) (*http.Request, bool)`, `type Router`, `type HostRouter`, `type EndpointLister`, `type Endpoint`, `type Dispatch`, `Unknown` | `Check` for an adapter that sees the route and the handler its router chose. | | `type OwnPath struct` | An entry of `Options.Unprotected`. | | `func (*Service) Refresh(ctx) error` | Fetches node statements and status lists now. | | `func (*Service) LinkStart(account string, ttl time.Duration) (string, error)` | A linking code for one of your accounts (account linking). | | `func (*Service) Close() error` | Stops the background refresh. | | `type Route struct`, `type Class`, `Read`, `Write`, `WriteHard`, `Irreversible`, `type Threshold` | The route map (section Routes and templates). | | `type Template struct`, `func Text(en string) Template` | The sentences people sign. | | `type Org struct`, `type Logo struct` | The organisation profile (ORG-1 §2). | | `func ContextFrom(ctx) (Context, bool)`, `type Context`, `Display`, `ChainLink`, `ActingFor` | What a handler learns. | | `type Store interface`, `type Charge`, `type MemoryStore`, `func NewMemoryStore()` | Replay set, single use and counters. | | `type TrustList`, `func ParseTrustList(jws string, signer map[string]any) (*TrustList, error)` | OAID-5 trust lists. | | `const Version`, `const SpecVersion` | `0.1.0` and `0.2.14`. | | `allowedbygin.Middleware(aby, engine)`, `allowedbygin.Context` | Gin. | | `allowedbyecho.Middleware`, `allowedbyecho.Context` | Echo. | | `allowedbychi.Middleware` | chi. | | `allowedbyredis.New(client, prefix) *Store` | The Redis store. | | `allowedbytest.NewNode`, `Node.NewAgent`, `Node.Grant`, `Agent.Request`, `GrantSpec` | Testing. | What is implemented (sdks/CONTRACT.md §2): | Item | Status | |---|---| | Configuration, route map, discovery (`/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`) | core: done | | Verification, ABY-2 §5 steps 1-10: proof JWT and RFC 9421, passports, grant chains, `human_sig` (WebAuthn: ES256, EdDSA, RS256 passkeys), `human.reg`, `initiator`, status lists, class and lifetime, scope, amount (per call, grant, day, week, month), count, fields, window, request digest and single use, replay set, TOFU and OAID-5 trust lists, EdDSA and ES256 only | core: done | | Challenges and service-initiated approvals (ABY-2 §6) | core: done | | Background refresh, context, store (memory, Redis), key file, `net/http`, Gin, Echo, chi | core: done | | Account linking (`aby:link` at `/allowedby/link`, `RequireLink`, `AccountParam`, `LinkStart`, ABY-3 §6) | extended: done (CONTRACT 1.8) | | AllowedBy-Nonce (`Options.Nonce`, `Route.Nonce`, ABY-2 §3.2), level profiles (`LevelProfile`, OAID-7 §5.3), rate limits (`Options.Rate`) | extended: done (CONTRACT 1.12) | | Tenants and tenant budgets (`Options.Tenants`, `RefundBudget`, ORG-1 §3.3, §5.3) | extended: done (CONTRACT 1.16), mandates enforced fail closed | | Disclosure callback and JWE (`/allowedby/callback`), authority policies, company mandates, QES, audit sink, admin console | extended: not yet; the matching route options are refused by `New` | ### AllowedBy-Nonce A nonce proves that a request was made just now, for this service (ABY-2 §3.2). With `Options.Nonce` on, a route with `Nonce: true`, and every `Irreversible` route, refuses a proof without a current nonce: `401 invalid_signature`, with a fresh nonce in the `AllowedBy-Nonce` header. The agent retries once with it, in the proof (`nonce`) or, with RFC 9421, in its `AllowedBy-Nonce` header, which counts only when the signature covers it (a covered value that is not base64url is refused with `401`). A route with `Nonce` while `Options.Nonce` is off fails in `New`. A nonce is stateless: its issue time and a MAC, base64url(`t` ‖ HMAC-SHA256(nonce key, `t`)[0:16]), `t` the time in seconds as 8 bytes big-endian. It is current for 300 s, on every instance that shares the key file (`KeyFile`), and across a restart. The nonce key is HKDF-SHA256 of the signing key's raw private key (no salt, info `allowedby/nonce/v1`), so every SDK on one key file takes the others' nonces. Without a key file, each instance has its own keys, and so its own nonces. ### Level profiles A level-3 route can require the profile of the person's level-3 identity check (OAID-7 §5.3): `LevelProfile: "eu"` (eIDAS high) or `"na"` (the North-American profile). A grant whose registration has another profile, or none, is refused with `401 level_insufficient`, and the approval the service asks for names the profile, so the person's node offers only sources of it. Without `LevelProfile`, a level-3 route takes either. `New` refuses it below level 3. ### Rate limits `Options.Rate` limits the calls per agent (`"actor"`, the passport's `sub`) and per operator (`"operator"`, its `operator.id`): `map[string]allowedby.RateLimit{"actor": {Calls: 20, Per: time.Minute}}`. The defaults are 600 and 6000 calls a minute; a key you leave out keeps its default, and any other key, or a limit that is not a positive number of calls in whole seconds, fails in `New` (a misspelt limit would leave the default in place). The window slides on `Clock`: a call at `t` sees those at `x` with `t - x` under the window. 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 over either limit gets `429 rate_limited` with `Retry-After: 60`, and counts for neither. The counts are kept in the process, like `MemoryStore`: behind several instances, each counts its own calls. Each limit keeps at most 10 000 agents (or operators), as the reference: a new one past that pushes out the one used least recently, in constant time, so a flood of new passports can neither grow it nor slow it down. ### Tenants and tenant budgets `Options.Tenants` lists the accounts the service hosts, by id, each named by the path parameter `{tenant}` (ORG-1 §3.3): `map[string]allowedby.Tenant{"acme": {Name: "Acme", Routes: map[string]allowedby.TenantRoute{"invoices:pay": {Level: 2, AmountMax: "1000.00"}}}}`. An override only tightens the route of that capability for that tenant: the higher `Level`, the stronger `Authn` (`synced`, `hardware`), `RequireLink` (and then level 1 at least), the shorter `MaxLifetime`, a lower ceiling `AmountMax` (above it, or without an amount, `403 capability_denied`, whatever the person approved), and `Operators`, an allowlist of `operator.id` (any other operator gets `403 capability_denied`). An override that would loosen the route changes nothing. `New` refuses a tenant id outside `[A-Za-z0-9_-]{1,64}`, a `Name` over 200 characters, an `Org` that is not an https origin with no path, `MembersOnly` without `Org`, a capability the route map does not have, a value out of range, and an override or a budget on a capability that has a route without `{tenant}` (where it would never apply; the error names the route). It copies the option: changing your map afterwards changes nothing. Until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with `mandate_required`: a `Mandate: true` override, and every route of a `MembersOnly` tenant, its identity routes too (an agent alone acts for no organisation). Such a route never challenges: any refusal an approval would fix there (`grant_required`, `expired`, ...) is the same plain `401 mandate_required`, with no `WWW-Authenticate`. `QES` and `Authority` overrides are refused by `New`, as the route options are. A tenant budget caps the amounts the service accepts on a capability (ORG-1 §5.3): `Budgets: map[string]allowedby.Budget{"invoices:pay": {Max: "5000.00", Currency: "EUR", Per: "day", TZ: "Europe/Paris"}}`, per `day`, `week` or `month` in `TZ` (default UTC). Every route of that capability needs an `AmountField`, or `New` refuses the budget. The count is kept in the verifier's store, per tenant, capability, currency, time zone and period, so every instance that shares the store (`allowedbyredis`) shares it; only an accepted request counts, in one store call that checks and adds. A request without an amount in the budget's currency, or over what is left, is refused with `403 budget_exceeded`, before any challenge, so no approval is asked for. When the store does not answer, the request gets `503 status_stale` with `Retry-After`, and what the check spent is given back. A refund on the SDK's own refusal gives the amount back too, and so does `aby.RefundBudget(r)`, when your handler refuses an accepted request (a wrong total, an unknown invoice), once. ### Account linking Account linking (ABY-3 §6) ties a person's AllowedBy identity to one of your accounts, so that a route can require the person who owns the account, not just any approved person. 1. Your signed-in account page calls `aby.LinkStart(account, 0)` and shows the code: 96 random bits, single use, valid 600 s (`ttl`, 1 s to a day). A new code for an account leaves its older ones pending. 2. The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves this route itself (`New` refuses an app route at that path), on that exact path only: a variant of it (an encoded letter such as `/allowedby/%6Cink`, a trailing or doubled slash, a dot segment) goes to your app as a path outside the map, asks for no approval and links nothing (CONTRACT 1.13). It checks the code first, before any approval is asked for: an unknown, used, revoked or expired code gets `400 invalid_request`. 3. The request is then verified on the SDK's own route: `aby:link`, `write`, level 1, scope `aby:link`, single-use approvals only. Without one, the service asks the node for the approval itself, bound to this request (`401` with the `approve` link). The person approves "Link your approvals to your account at " (`Templates["aby:link"]` overrides it). 4. Once accepted, the code is spent, the account's other pending codes are revoked, and the person (their home node and their pairwise id here) is linked to the account, replacing whoever was linked to it: `200 {"linked": true}`. A route with `RequireLink` answers `403 human_not_linked` unless the person of the approval is linked, and, when its path has the `AccountParam` parameter (`account` by default), linked to that account (compared as `Context.Params` has it: decoded once). The same pairwise id from another home node is another person. The approvals the service asks for on a linked account name its person (`human_home`, `human_hint`), so their node offers them first. On a `RequireLink` route, `Context.LinkedAccount` is the account the person is linked to: act for that one, which matters on a route whose path names no account (`GET /me/notes`). `Options.LinkAuthorize`, your own rule, is then asked `(account, route, params)` for a linked person (never for one who is not): only `true` lets them through; `false`, or a panic in it (recovered), answers `403 human_not_linked`, as Python's `link_authorize` does. It gets its own copy of `params`. Codes and links live in the process, in memory, like `MemoryStore`: at most 10 000 pending codes (`LinkStart` fails beyond that, it never drops one) and 100 000 links (the oldest goes). Behind several instances, a code links on the instance that issued it, and a link holds on the instance that made it: keep the links with your accounts, or route an account to one instance. `/.well-known/allowedby` has `link` and the `aby:link` capability, and `/openapi.json` describes the route. The extended interop app runs these features against a real node, agent and people (`sdks/interop/ext/interop_ext.py --features linking,nonce,level_profiles,rate,tenants,tenant_budgets`): ```go // Command interop_ext is the extended interop app (sdks/interop/ext/reference_app.py, in Go): account linking // (ABY-3 §6), AllowedBy-Nonce (ABY-2 §3.2), level profiles (OAID-7 §5.3), rate limits, tenants and tenant budgets // (ORG-1 §3.3, §5.3), for sdks/interop/ext/interop_ext.py. CI runs it against a real node, agent and people: `python // sdks/interop/ext/interop_ext.py --features linking,nonce,level_profiles,rate,tenants,tenant_budgets --cmd `. // // GET /me the agent's passport is enough (level 0) // GET /accounts/{account}/notes read, level 1: a person linked to that account only // POST /allowedby/link the SDK's own (aby:link, single use) // POST /drafts write, level 1, with an AllowedBy-Nonce: {"saved": true} // GET /vault/eu/{id} read, level 3 of the EU profile: {"vault": id} // GET /vault/na/{id} read, level 3 of the North-America profile: {"vault": id} // POST /t/{tenant}/orders write, level 1, an amount at /total: {"ordered": total, "account": tenant}; // tenants umbrella (as the map says), hooli (a ceiling of 50.00), budget (100.00 // EUR a day) // POST /interop/link-code outside the route map (TEST ONLY: it stands for the signed-in account page, // which shows the code): body {"account": string} -> {"code": string} // // Nonces are on; rate limits: 20 calls a minute per agent, 1000 per operator. package main import ( "cmp" "encoding/json" "log" "net" "net/http" "os" "time" allowedby "github.com/yannUpTo/allowedby/sdks/go" ) func main() { refresh, err := time.ParseDuration(cmp.Or(os.Getenv("ALLOWEDBY_REFRESH_SECONDS"), "5") + "s") if err != nil { log.Fatal(err) } aby, err := allowedby.New(allowedby.Options{ Origin: os.Getenv("ALLOWEDBY_ORIGIN"), Node: os.Getenv("ALLOWEDBY_NODE"), Org: allowedby.Org{LegalName: "Notes Interop Ltd", Country: "FR"}, Routes: []allowedby.Route{ {Method: "GET", Path: "/me", Summary: "Who is calling"}, {Method: "GET", Path: "/accounts/{account}/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "account:{account}", RequireLink: true, Summary: "List the notes of an account"}, {Method: "POST", Path: "/drafts", Capability: "drafts:write", Class: allowedby.Write, Level: 1, Resource: "draft:new", Nonce: true, Summary: "Save a draft", Body: map[string]string{"text": "the draft"}}, {Method: "GET", Path: "/vault/eu/{id}", Capability: "vault:read", Class: allowedby.Read, Level: 3, Resource: "vault:{id}", Authn: "hardware", LevelProfile: "eu", Summary: "Open a vault (EU level 3)"}, {Method: "GET", Path: "/vault/na/{id}", Capability: "vault:read", Class: allowedby.Read, Level: 3, Resource: "vault:{id}", Authn: "hardware", LevelProfile: "na", Summary: "Open a vault (North-America level 3)"}, {Method: "POST", Path: "/t/{tenant}/orders", Capability: "orders:place", Class: allowedby.Write, Level: 1, Resource: "tenant:{tenant}:order:new", AmountField: "/total", Summary: "Place an order"}, }, Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes"), "drafts:write": allowedby.Text("Save your drafts"), "vault:read": allowedby.Text("Open {scope}"), "orders:place": allowedby.Text("Place orders on {scope}")}, Rate: map[string]allowedby.RateLimit{"actor": {Calls: 20, Per: time.Minute}, "operator": {Calls: 1000, Per: time.Minute}}, Title: "Notes Interop API", RefreshInterval: refresh, Nonce: true, Tenants: tenants(), }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.HandleFunc("POST /interop/link-code", func(w http.ResponseWriter, r *http.Request) { // TEST ONLY var in struct { Account string `json:"account"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Account == "" { reply(w, http.StatusBadRequest, map[string]string{"error": "account"}) return } code, err := aby.LinkStart(in.Account, 0) // the account page of the signed-in account in.Account if err != nil { reply(w, http.StatusServiceUnavailable, map[string]string{"error": "no code"}) return } reply(w, http.StatusOK, map[string]string{"code": code}) }) mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) reply(w, http.StatusOK, map[string]any{"agent": who.Agent, "operator": who.Operator, "level": who.Level}) }) mux.HandleFunc("GET /accounts/{account}/notes", func(w http.ResponseWriter, r *http.Request) { who, ok := allowedby.ContextFrom(r.Context()) if !ok { reply(w, http.StatusNotFound, map[string]string{"error": "not found"}) return } // the SDK checked that the person is linked to this account reply(w, http.StatusOK, map[string]any{"account": who.Params["account"], "notes": []string{}}) }) mux.HandleFunc("POST /drafts", func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusOK, map[string]bool{"saved": true}) // the SDK checked the nonce }) vault := func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) reply(w, http.StatusOK, map[string]string{"vault": who.Params["id"]}) } mux.HandleFunc("GET /vault/eu/{id}", vault) mux.HandleFunc("GET /vault/na/{id}", func(w http.ResponseWriter, r *http.Request) { vault(w, r) }) mux.HandleFunc("POST /t/{tenant}/orders", func(w http.ResponseWriter, r *http.Request) { who, _ := allowedby.ContextFrom(r.Context()) var in struct { Total string `json:"total"` } _ = json.NewDecoder(r.Body).Decode(&in) // the SDK checked the amount against the approval and the tenant reply(w, http.StatusOK, map[string]string{"ordered": in.Total, "account": who.Tenant}) }) mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { reply(w, http.StatusNotFound, map[string]string{"error": "not found"}) }) addr := net.JoinHostPort(cmp.Or(os.Getenv("ALLOWEDBY_BIND"), "127.0.0.1"), cmp.Or(os.Getenv("PORT"), "18790")) srv := &http.Server{Addr: addr, Handler: aby.Handler(mux), ReadHeaderTimeout: 10 * time.Second} log.Fatal(srv.ListenAndServe()) } // tenants are the accounts of the orders route: umbrella as the map says, hooli with a ceiling of 50.00 a call, // budget with 100.00 EUR a day in all (ORG-1 §3.3, §5.3). func tenants() map[string]allowedby.Tenant { t := map[string]allowedby.Tenant{} t["umbrella"] = allowedby.Tenant{Name: "Umbrella"} t["hooli"] = allowedby.Tenant{Name: "Hooli", Routes: map[string]allowedby.TenantRoute{"orders:place": {AmountMax: "50.00"}}} t["budget"] = allowedby.Tenant{Name: "Budget Co", Budgets: map[string]allowedby.Budget{"orders:place": {Max: "100.00", Currency: "EUR", Per: "day"}}} return t } func reply(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } ``` --- Source: https://docs.allowedby.com/sdk/java # AllowedBy for Java and Kotlin The service SDK for the JVM: your API accepts AI agents that act for a person, and the person approves with a passkey tap. The SDK publishes your discovery documents, verifies every agent request offline (ABY-2 §5), answers challenges, and creates the approval itself for serious actions. It follows `sdks/CONTRACT.md`; the concepts (routes, classes, levels, the approval flow) are explained in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents). ## Install Build the SDK from `sdks/java` with the Maven wrapper, then depend on `org.allowedby:allowedby-core` and the module of your framework; Java 17 or later, and no runtime dependency in the core. The SDK is not published to Maven Central yet (publishing is a separate step), so install it in your local Maven repository first. Maven itself comes from the wrapper (a script; no binary in git). Linux and macOS: ```bash cd sdks/java ./mvnw -B install -DskipTests ``` Windows (PowerShell): ```powershell cd sdks\java .\mvnw.cmd -B install -DskipTests ``` With Docker only (no local JDK), from the repository root: ```bash docker run --rm -v "$PWD:/repo" -w /repo/sdks/java maven:3.9.11-eclipse-temurin-21@sha256:6fdc855a6ed81d288ca7ca37ac6ff5e9308b612485c0801d70b25a858c83d237 mvn -B verify ``` Then add the dependency (Maven): ```xml org.allowedby allowedby-spring-boot-starter 0.1.0 ``` Or with Gradle (Kotlin DSL), after `mavenLocal()` in `repositories`: ```kotlin dependencies { implementation("org.allowedby:allowedby-core:0.1.0") } ``` | Module | For | Dependencies | |---|---|---| | `allowedby-core` | Configuration, route map, verifier, challenges, context, in-memory store, a filter for the JDK HTTP server | none (JDK only) | | `allowedby-servlet` | A Jakarta Servlet 6 filter (Tomcat 10.1 and 11, Jetty 12, Undertow 2.3) | `jakarta.servlet-api` (provided by your server) | | `allowedby-spring-boot-starter` | Auto-configuration from `allowedby.*`, the filter, `@AllowedByContext` | Spring Boot 4.1 (yours) | | `allowedby-redis` | A store shared by every instance | Jedis 7.5.3 (with commons-pool2) | Why these choices: - **JDK crypto only.** Ed25519 (`EdDSA`, JDK 15+), P-256 (ES256, signatures as raw r‖s), ECDH, SHA-256 and zlib come from the JDK. No Bouncy Castle. - **A small strict JSON parser of our own, not Jackson**, in the core. The verifier must read JSON exactly as the reference does for RFC 8785 (JCS): `4200` stays an integer and `4200.00` a decimal. It also refuses a duplicate member name (so the verifier and your application never read two different values from one body), `NaN`, invalid UTF-8, lone surrogates and nesting deeper than 64. It is fuzzed in the tests. Your application keeps its own JSON library. - **Maven** (not Gradle): a declarative multi-module build, Spring Boot's dependency management imported as a BOM, and a script-only wrapper. Gradle users consume the jars as shown above. - **Jedis** for Redis: synchronous, small, no reactive runtime. ## Quick start Twenty lines on the JDK's own HTTP server accept agents on `GET /notes`; run them next to the local node and call them with the reference agent. From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/QuickStart.java`: ```java package org.allowedby.examples.quickstart; import com.sun.net.httpserver.HttpServer; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import org.allowedby.AllowedBy; import org.allowedby.Context; import org.allowedby.Route; import org.allowedby.httpserver.AllowedByHttpFilter; public final class QuickStart { public static void main(String[] args) throws Exception { AllowedBy aby = AllowedBy.builder() .origin("http://localhost:8000") // your public origin (https in production) .node("http://localhost:8700") // the node you trust: python demo/run.py --port 8700 .org("Notes Ltd", "FR") .route(Route.get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes") .build(); String bind = System.getenv().getOrDefault("ALLOWEDBY_BIND", "").strip(); // unset or blank: loopback only HttpServer server = HttpServer.create(new InetSocketAddress(bind.isEmpty() ? "127.0.0.1" : bind, 8000), 0); server.createContext("/", exchange -> { Context ctx = (Context) exchange.getAttribute(Context.ATTRIBUTE); // null outside the route map String json = ctx == null ? "{\"error\": \"not found\"}" : "{\"person\": \"" + ctx.getHumanId() + "\", \"notes\": []}"; byte[] out = json.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(ctx == null ? 404 : 200, out.length); exchange.getResponseBody().write(out); exchange.close(); }).getFilters().add(new AllowedByHttpFilter(aby)); server.start(); } } ``` See it work against the local node (`python demo/run.py --port 8700`). Linux and macOS, from the repository root: ```bash pip install -r requirements.txt (cd sdks/java && ./mvnw -B -q package -DskipTests -pl examples/quickstart -am) python demo/run.py --reset --port 8700 & curl -s -o /dev/null --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8700/.well-known/oaid java -jar sdks/java/examples/quickstart/target/allowedby-quickstart.jar & curl -is --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8000/notes # 401 passport_required ``` Windows (PowerShell): ```powershell pip install -r requirements.txt Push-Location sdks\java; .\mvnw.cmd -B -q package -DskipTests -pl examples/quickstart -am; Pop-Location Start-Process python -ArgumentList "demo/run.py", "--reset", "--port", "8700" curl.exe -s -o NUL --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8700/.well-known/oaid Start-Process java -ArgumentList "-jar", "sdks/java/examples/quickstart/target/allowedby-quickstart.jar" curl.exe -is --retry 60 --retry-delay 1 --retry-connrefused http://localhost:8000/notes ``` Then an agent calls it: it gets a passport from the node, meets the `401` challenge, asks you (the link is printed), and retries once you tap Allow: ```python import sys sys.path.insert(0, "sdks/python/src") from allowedby.agent import Agent agent = Agent("http://localhost:8700", tell=print) print(agent.call("GET", "http://localhost:8000/notes", action="notes:read")) ``` Against the hosted node, use `node("https://demo.allowedby.com")` once your origin is in its `ALLOWEDBY_AUDIENCES` ([`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents) §15). ## Routes and templates Each route says which capability a method and path need, how serious the action is (its class) and the identity level the person must have; each capability has a template, the sentence the person reads and signs. A route is immutable: every method returns a new one. `AllowedBy.Builder.build()` validates every route and fails with a `ConfigurationException` that names the route and what to fix. | Java | Reference name | Meaning | Default | |---|---|---|---| | `Route.get(path)`, `post`, `put`, `patch`, `delete`, `route(method, path)` | `method`, `path` | `{param}` matches one path segment | | | `.capability("notes:read")` | `capability` | `namespace:action`; required above level 0, refused at level 0 | none | | `.actionClass(ActionClass.WRITE)` | `class` | `read` (30 days), `write` (7 days), `write-hard` and `irreversible` (one approval per request, created by the service) | `read` | | `.classByAmount(Threshold.upTo("1000.00", WRITE_HARD), Threshold.otherwise(IRREVERSIBLE))` | `class` as a list | The class comes from the amount in the request | | | `.level(2)` | `level` | 0 passport only, 1 passkey, 2 verified identity, 3 eIDAS high | 1 | | `.resource("note:{id}")` | `resource` | The resource the grant's `scope` must name; `{param}` from the path | `:*` | | `.amountField("/total")`, `.currencyField("/currency")` | `amount_field`, `currency_field` | JSON Pointers into the body; the grant caps the amount | none, `/currency` | | `.authn("hardware")` | `authn` | The weakest passkey: `software`, `synced`, `hardware` | any | | `.tier(1)` | `tier` | The lowest custody tier of the agent's key (OAID-3) | 0 | | `.maxLifetime(Duration.ofMinutes(15))` | `max_lifetime` | The longest approval on this route, 60 s to 30 days | the class's | | `.levelProfile("eu")` | `level_profile` | A level-3 route for one profile of level 3 (`eu`, `na`) | none | | `.qes(true)` | `qes` | A qualified signature; this SDK has no EU trusted list, so such a route always answers `qes_required` | false | | `.requireLink(true)` | `require_link` | The person must have linked their account ([Account linking](#account-linking)); level 1 or more | false | | `.accountParam("acct")` | `account_param` | The path parameter that names one of your accounts, for `requireLink`: a `{name}` of the path | `account` | | `.nonce(true)` | `nonce` | An AllowedBy-Nonce on this route ([AllowedBy-Nonce](#allowedby-nonce)); needs `Builder.nonce(true)`, or construction fails | false | | `.summary(...)`, `.body(Map)` | `summary`, `body` | Descriptions for agents (OpenAPI) | none | The reference's other options (`mandate`, `disclose`, `disclose_optional`, `authority`) are not enforced by this SDK yet. Setting one (with `Route.option(name, value)` or in Spring properties) makes construction fail with a message naming it: an option is never accepted and then ignored. Templates: `template("notes:read", "Read your notes")` is shorthand for one English sentence. A full template gives a `summary` and the `lines` per language, with placeholders `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}` and `{fields}`. The display uses one language for every line, and each line is at most 280 characters (AMH-1 §4). Every capability of the route map needs a template. From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/Routes.java`: ```java package org.allowedby.examples.quickstart; import java.time.Duration; import java.util.List; import java.util.Map; import org.allowedby.ActionClass; import org.allowedby.AllowedBy; import org.allowedby.Route; import org.allowedby.Route.Threshold; /** A route map that uses every route option, and the templates the person reads. */ public final class Routes { private Routes() { } public static List routes() { return List.of( // level 0: the agent's passport is enough, no person Route.get("/me").level(0).summary("Who is calling"), // read, approved once (up to 30 days), on every note Route.get("/notes").capability("notes:read").level(1).resource("note:*") .summary("List your notes"), // write, the body documented for agents (OpenAPI) Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1) .resource("note:new").summary("Add a note").body(Map.of("text", "the note")), // write-hard: the service asks the person for this exact request, every time; verified identity Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD).level(2) .resource("note:{id}").authn("synced"), // a payment: the class comes from the amount; the approval caps the amount Route.post("/invoices/{id}/pay").capability("invoices:pay").level(2).resource("invoice:{id}") .amountField("/total").currencyField("/currency") .classByAmount(Threshold.upTo("1000.00", ActionClass.WRITE_HARD), Threshold.otherwise(ActionClass.IRREVERSIBLE)) .maxLifetime(Duration.ofMinutes(15)), // eIDAS high, EU profile, hardware passkey, an agent key in a TPM or an enclave (tier 1) Route.post("/contracts/{id}/sign").capability("contracts:sign").actionClass(ActionClass.IRREVERSIBLE) .level(3).levelProfile("eu").authn("hardware").tier(1).resource("contract:{id}")); } public static AllowedBy service() { return AllowedBy.builder() .origin("https://notes.example") .node("https://node.example.org") .org(Map.of("legal_name", "Notes Ltd", "country", "FR", "website", "https://notes.example", "privacy_policy", "https://notes.example/privacy")) .routes(routes()) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .template("invoices:pay", Map.of( "summary", Map.of("en", "Pay {scope}, up to {amount.max} {amount.currency}", "fr", "Payer {scope}, jusqu'à {amount.max} {amount.currency}"), "lines", Map.of("en", "Pay {scope}, up to {amount.max} {amount.currency}", "fr", "Payer {scope}, jusqu'à {amount.max} {amount.currency}"))) .template("contracts:sign", "Sign contract {scope}") .title("Notes API") .version("2.1.0") .build(); } public static void main(String[] args) { try (AllowedBy aby = service()) { System.out.println(aby.openApi().get("paths")); } } } ``` ## Framework recipes Three thin adapters over the core: a Jakarta Servlet filter, a Spring Boot starter and a filter for the JDK HTTP server; Kotlin uses the same API. Every app below is complete and runs in CI: the interop test (26 scenarios against a real node, agent and person) and a probe of path and method variants, on each server and version of `sdks/java/examples/frameworks.json` ([Testing](#testing)). They read `PORT`, `ALLOWEDBY_ORIGIN` and `ALLOWEDBY_NODE` from the environment. They listen on 127.0.0.1 only, unless `ALLOWEDBY_BIND` names another address (`0.0.0.0` in a container); unset, empty or blank means 127.0.0.1. Spring would listen on every address for an empty `server.address`, so the Spring Boot example and the recipes do not use a `${ALLOWEDBY_BIND:127.0.0.1}` placeholder: `ListenAddress`, an `EnvironmentPostProcessor` registered in `META-INF/spring.factories`, sets it in code. Every adapter does the same, in this order: it serves the SDK's endpoints (`GET|HEAD /.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), then checks every request on the route map, then calls your application. A path outside the map reaches your application unchanged, body unread. On the map, the body (at most 1 MiB) is read once and given back to your application intact; the verified `Context` goes with the request. Servers decode and normalise the path before they dispatch it: when that path and the raw path the SDK verifies differ on a route of the map (`/notes;x`, `//notes`, `/notes%2F1`, or `/v1/notes%3Aarchive` for a route `/v1/notes:archive`), the request is refused with `400 invalid_request`, so a protected handler is never called for a path the SDK did not check. Variants of a route are refused the same way (CONTRACT §2.10), with `400 invalid_request`, before they can reach a protected handler: a trailing or doubled `/` (`/notes/`, `//notes`), a format suffix (`/notes.json`), a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, a `_method` query parameter) and, in the servlet filter, a form body (urlencoded or multipart, which can carry `_method`) on a path of the map. A request that is itself a route of the map is never a variant: `/notes/report.pdf` on `/notes/{id}` is that route. A handler that serves a route of the map never runs for a request the SDK did not check for that route: - **HEAD is read as GET** in every rule: servers answer it with the GET handler. - **A refusal never repeats the request**: its title names the rule and the option (`unprotected(path)`), never the path, the query or a header, which may hold personal data or tokens. The debug log names the route template only. The challenge's `scope` holds the route's resource with its values (`note:7`), built from the normalised path (`%61b` gives `ab`), as ABY-2 §6 asks. A request whose value, decoded, is not 1 to 64 of `A-Z a-z 0-9 . _ -`, or whose path holds an escaped control character or `/`, or whose scope would pass 256 bytes, is refused with 400 and never gets a challenge. - **A target that is not plain** is refused with 400 on every path: a backslash, a control character (also percent-encoded), a dot segment, a malformed `%` or an escape that is not UTF-8, or a raw character outside printable ASCII or among ``| ^ " < > ` { }`` (browsers send `|` and `^` as they are: link to such pages percent-encoded, `%7C`, `%5E`). Servers and routers read these differently. This is stricter than rule 1 of the contract on purpose: your own paths that are not plain get 400 too, because no list of the ways a router may read them is complete, and a missed one would reach a protected handler. - **Spring Boot** sees the handler Spring selected. It refuses with 400 a controller method or functional route that serves a route of the map when the request was not checked for it: `/notes/{*id}` on `/notes/7/x`, an optional parameter, a mapping for any method, a forward, a filter that changes the path later. Your own handlers run, and so does a `/**` catch-all where every route has a handler of its own. `@AllowedByContext(required = false)` only lets the context be null outside the map: it lifts no refusal. The default `path-pattern-parser` strategy is required: with the ant path matcher the start fails, and so does a `DispatcherServlet` without Spring MVC's configuration (`WebMvcAutoConfiguration` excluded, no `@EnableWebMvc`). A functional route counts for the routes of every method its pattern covers, as its methods are not known: another method of yours on the same path needs a pattern of its own or a controller. A CORS preflight is Spring's own answer and goes through. Another servlet in the same application (Jersey, a `ServletRegistrationBean`) gets the rules of the servlet filter below, and so does the `DispatcherServlet` itself when a handler mapping of your own (a `SimpleUrlHandlerMapping` bean) does not carry the check: a warning at start names it. A filter after ours that changes the method is refused too. - **The handler of any route of the map**, in Spring, runs only for a request checked for that route, whatever its method (one handler for `GET` and `DELETE` of `/notes/{id}` is the `DELETE` route's): `@DeleteMapping("/notes/{id}/**")` next to the route `DELETE /notes/{id}/archive` is refused on `/notes/7/archive/x`. A catch-all, site-wide (`/**`, a front controller, a fallback page) or under a prefix (`/notes/{id}/**`), is protected for a route only while that route has no handler of its own known: then every unchecked request it gets is refused, requests near the route, of any method, are refused, and a warning at start names the route. A checked request that would run it gets 400, unless it is the only handler found for the route and the route covers every other route it is protected for; it then runs, and is never learnt. Once the route's own handler is known (a mapping or a function of its shape, or a handler learnt), a site-wide fallback is not that route's, so your fallback pages answer, and one request with a bad value never locks them out. A catch-all under the route's prefix (`/notes/{id}/**` next to `/notes/{id:[0-9]+}/archive`) serves that route's paths for other values, so it stays protected. 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. A front controller shared by routes of one capability runs only for a request checked for a route at least as strict as the others it serves. A handler no route is known to own (registered while the application runs) is learnt from the first checked request that runs it when the pattern Spring matched has the route's own shape, or when it serves the route's template and that route is at least as strict as every other route, of any method, whose handler is not known; otherwise it is refused. A page that takes one value of a route (`/notes/export` beside `/notes/{id}`) is never learnt as that route's handler. One controller method for several routes, whatever their shapes and methods (`@DeleteMapping({"/notes/{id}", "/items/{id}"})`, or `GET` and `POST` of `/items/{id}`), runs only for a request checked for a route that covers all the others, and a warning, at start or on the first request, names each pair that does not cover each other (router functions too). Functions follow the same rules: a `route(path("/**"), dispatcher)` that alone serves a route is protected, and beside routes that all have a function or a controller method of their own it is a fallback; a function runs for a request checked for a route only if that route covers every other route it serves, of the methods it takes (a `/**` or `/notes/**` function shared by a weak and a strict route runs only for the strict one). A router function counts as a route's own handler only when it has the route's shape and method. One function instance registered for several routes is one code; two method references to one method (`h::delete` written twice) are two instances, which the JVM does not tie to their method, so each route runs it on its own check. A warning at start names routes whose functions capture the same object; give each protected route its own method. No `unprotected` entry lifts any of this (CONTRACT §2.10 rule 5). - **The servlet filter and the JDK filter** do not see your routing. They refuse with 400 a path that a route matches if a parameter takes several segments, for a method of that route (`DELETE /notes/7/x` with `DELETE /notes/{id}`, `/n/1/x/c` with `/n/{id}/c`), and any other path of a servlet or JDK context registered for the prefix of a route (`/notes/*`, `createContext("/notes")`) with the same method. The servlet filter also refuses a form on such a longer path, whatever its method, and a path whose part below a servlet's prefix is a route that no servlet with a mapping of its own serves (`/console/me` with the route `/me`): declare such a page with `unprotected`. `GET /notes/7` with only `GET /notes` on the map goes through a servlet on `/*`. - **Limit of the servlet and JDK filters.** A route that ends in a literal (`DELETE /notes/{id}/archive`) is protected on a longer path only where a servlet or JDK context is registered for exactly its prefix (`/notes/*`, `createContext("/notes")`). When a servlet or JDK context registered for a shorter prefix (`/*`, `/`, `/api/*` for the route `/api/notes/{id}/archive`) does its own routing (Jersey, a front controller) and gives `/notes/7/archive/x` to the handler of that route, the filter cannot see it: match the route's own path in that handler, or use the Spring Boot starter, which sees the handler. - **Changed after the check** (plan point 14). An accepted request records what it was checked as: its method (HEAD as GET) and its path, normalised as the check normalises it, in the request attribute `AllowedByFilter.TARGET`. Another spelling of the same path is the same request. In Spring, the starter compares it again when Spring has chosen the handler: a filter after ours that rewrites the path (UrlRewriteFilter, Tuckey) or overrides the method (`HiddenHttpMethodFilter`), a `HttpServletRequestWrapper` that changes `getRequestURI()` or `getMethod()`, and a forward or an async dispatch (`AsyncContext.dispatch`) that moves it onto the map, to another route or a longer path of one, get 400 `invalid_request`, never repeating the path, before the handler runs. A dispatch off the map (a view, a static page) still runs, as an unchecked request would. An include of another route gets the refusal as its body (an included response cannot set its status). An error page (`ERROR`) of an accepted request still answers; nothing else passes unchecked. The plain servlet filter checks forwards, includes and async dispatches when it is registered for them (`EnumSet.allOf(DispatcherType.class)`), and refuses an include of a route of the map from a request that was not checked; it cannot see where a wrapper or a rewrite after it leads, and neither can the JDK filter, which a later filter can hand another exchange: put nothing that changes the method or the path after them, and act on `ctx.getParams()`, the values that were checked. - **Refunds** (CONTRACT §2 item 10, ABY-2 §5 step 9). The check spends as before: the single-use mark and the grant's `count` and `amount` totals, atomically. When the Spring Boot starter's interceptor, which runs right before the handler, refuses that accepted request on its first dispatch (its handler guard of rule 5, or a method or path changed after acceptance), it gives back exactly what the request spent, once, from the check's receipt: the approval is usable again for a request its route serves. Only that guard refunds, and only a request the starter's filter held for it; there is no public refund. An accepted request is held, started or refunded, never both started and refunded (switched atomically); a refunded one never reaches a handler, even when a layer dispatches it again (400). Nothing is given back once anything of yours could have acted: after the handler started, for a refusal of your own (a handler, or a filter after the SDK that answers), for any refusal of a forward, include or async dispatch, by the servlet filter or the interceptor (code of yours after the SDK, a filter or a framework mounted as one, dispatched it), and never with the plain servlet filter, the JDK filter or the plain integration, which never hold a request for a guard. A refund the store does not take (the store down) leaves the approval spent, logged without request data. A `Store` applies a refund as a charge with negative increments and no maximum, exactly. - **Your own pages that look like these** are declared: `.unprotected("/notes.txt")`, `.unprotected("DELETE", "/notes/{id}/comments")`, or `allowedby.unprotected` in Spring. A template needs a literal segment, and names its method when it is a longer path of a route (`/notes/{id}/comments` next to `DELETE /notes/{id}`). An entry that overlaps a route of the map, as it is or but for its last `/`, fails at construction, and so does one a router may read as another path (an encoded character, `;`, a doubled `/`). In Spring an entry never lifts the refusal of a protected handler. An exact entry without a method lifts every method: `.unprotected("/notes/7/x")` next to `DELETE /notes/{id}` lets a `DELETE` of that path through too, so name the method (`.unprotected("GET", "/notes/7/x")`) unless every method of it is yours. **Context path.** Write the map without it: an application at `/api` with the route `/notes` serves `https://api.example.com/api/notes`, and `origin` is `https://api.example.com`. The filter takes the prefix from the server (`server.servlet.context-path`, a WAR's name) and verifies the URL the agent called. A map that names the prefix (`/api/notes` in an application at `/api`) would protect nothing: such requests are refused with 400 and a message. A proxy that strips a prefix must be declared to the server, so that it reports the context path. A servlet path is not a context path: with `spring.mvc.servlet.path=/v1`, write `/v1/notes`. A JDK context is not one either: with `createContext("/api")`, write `/api/notes`. A request whose path below the context is a route of the map is refused with 400, unless that path is declared with `unprotected`. ### Jakarta Servlet Register `AllowedByFilter` on `/*`. The context is the request attribute `Context.ATTRIBUTE`. The service and the servlet are the same on every server; the three programs after them start Tomcat (10.1 and 11), Jetty 12 and Undertow 2.3. From `sdks/java/examples/frameworks/servlet-notes/src/main/java/org/allowedby/examples/servlet/NotesService.java`: ```java package org.allowedby.examples.servlet; import java.util.Map; import org.allowedby.ActionClass; import org.allowedby.AllowedBy; import org.allowedby.Route; /** The notes service: its route map and the sentences a person approves. */ public final class NotesService { private NotesService() { } /** Built from ALLOWEDBY_ORIGIN, ALLOWEDBY_NODE and ALLOWEDBY_REFRESH_SECONDS. */ public static AllowedBy fromEnvironment() { return AllowedBy.builder() .origin(System.getenv("ALLOWEDBY_ORIGIN")) .node(System.getenv("ALLOWEDBY_NODE")) .refreshSeconds(Integer.parseInt(System.getenv().getOrDefault("ALLOWEDBY_REFRESH_SECONDS", "5"))) .org("Notes Interop Ltd", "FR") .title("Notes Interop API") .route(Route.get("/me").level(0).summary("Who is calling")) .route(Route.get("/notes").capability("notes:read").level(1).resource("note:*") .summary("List your notes")) .route(Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1) .resource("note:new").summary("Add a note").body(Map.of("text", "the note"))) .route(Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD) .level(2).resource("note:{id}").summary("Delete a note")) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .build(); } } ``` From `sdks/java/examples/frameworks/servlet-notes/src/main/java/org/allowedby/examples/servlet/NotesServlet.java`: ```java package org.allowedby.examples.servlet; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.MissingNode; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.allowedby.Context; /** The application behind the AllowedBy filter: each person's own notes. */ public final class NotesServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final ObjectMapper JSON = new ObjectMapper(); private final transient Map>> notes = new ConcurrentHashMap<>(); private final AtomicInteger ids = new AtomicInteger(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE); // null outside the route map switch (req.getRequestURI()) { case "/health" -> send(res, 200, Map.of("ok", true)); case "/me" -> send(res, 200, Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator(), "level", ctx.getLevel())); case "/notes" -> { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key send(res, 403, Map.of("error", "no person at level 0")); return; } send(res, 200, Map.of("notes", mine(person))); } default -> notFound(res); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { if (!req.getRequestURI().equals("/notes")) { notFound(res); return; } Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE); String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key send(res, 403, Map.of("error", "no person at level 0")); return; } JsonNode text; try { text = JSON.readTree(req.getInputStream()).path("text"); } catch (JsonProcessingException e) { // not JSON: the same answer as a missing text text = MissingNode.getInstance(); } String t = text.asText(); // its length in characters, as the reference counts it if (!text.isTextual() || t.isEmpty() || t.codePointCount(0, t.length()) > 2000) { send(res, 400, Map.of("error", "text: a string of 1 to 2000 characters")); return; } String id = Integer.toString(ids.incrementAndGet()); mine(person).add(Map.of("id", id, "text", text.asText())); send(res, 201, Map.of("id", id)); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException { if (!req.getRequestURI().matches("/notes/[^/]+")) { // exactly the protected route notFound(res); return; } Context ctx = (Context) req.getAttribute(Context.ATTRIBUTE); String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key send(res, 403, Map.of("error", "no person at level 0")); return; } String id = ctx.getParams().get("id"); mine(person).removeIf(note -> note.get("id").equals(id)); send(res, 200, Map.of("deleted", id)); } private List> mine(String person) { return notes.computeIfAbsent(person, p -> new CopyOnWriteArrayList<>()); } private static void notFound(HttpServletResponse res) throws IOException { send(res, 404, Map.of("error", "not found")); } private static void send(HttpServletResponse res, int status, Object body) throws IOException { res.setStatus(status); res.setContentType("application/json"); JSON.writeValue(res.getOutputStream(), body); } } ``` From `sdks/java/examples/frameworks/tomcat-11/src/main/java/org/allowedby/examples/tomcat/TomcatApp.java`: ```java package org.allowedby.examples.tomcat; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import org.allowedby.examples.servlet.NotesServlet; import org.allowedby.examples.servlet.NotesService; import org.allowedby.servlet.AllowedByFilter; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; import org.apache.tomcat.util.descriptor.web.FilterDef; import org.apache.tomcat.util.descriptor.web.FilterMap; /** The servlet filter on embedded Tomcat (10.1 and 11). */ public final class TomcatApp { private TomcatApp() { } public static void main(String[] args) throws Exception { Tomcat tomcat = new Tomcat(); tomcat.setBaseDir(Files.createTempDirectory("tomcat").toString()); tomcat.setPort(Integer.parseInt(System.getenv("PORT"))); tomcat.getConnector().setProperty("address", address(System.getenv("ALLOWEDBY_BIND"))); Context app = tomcat.addContext("", null); FilterDef filter = new FilterDef(); filter.setFilterName("allowedby"); filter.setFilter(new AllowedByFilter(NotesService.fromEnvironment())); app.addFilterDef(filter); FilterMap everything = new FilterMap(); everything.setFilterName("allowedby"); everything.addURLPattern("/*"); app.addFilterMap(everything); Tomcat.addServlet(app, "notes", new NotesServlet()).addMapping("/*"); tomcat.start(); tomcat.getServer().await(); } /** * The address to listen on: ALLOWEDBY_BIND (0.0.0.0 in a container), 127.0.0.1 when unset or blank. Resolved here, * because Tomcat would listen on every address for an address it cannot resolve: the start fails instead. */ static String address(String bind) throws UnknownHostException { return InetAddress.getByName(bind == null || bind.isBlank() ? "127.0.0.1" : bind.strip()).getHostAddress(); } } ``` From `sdks/java/examples/frameworks/jetty-12/src/main/java/org/allowedby/examples/jetty/JettyApp.java`: ```java package org.allowedby.examples.jetty; import jakarta.servlet.DispatcherType; import java.util.EnumSet; import org.allowedby.examples.servlet.NotesServlet; import org.allowedby.examples.servlet.NotesService; import org.allowedby.servlet.AllowedByFilter; import org.eclipse.jetty.ee10.servlet.FilterHolder; import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; /** The servlet filter on embedded Jetty 12. */ public final class JettyApp { private JettyApp() { } public static void main(String[] args) throws Exception { ServletContextHandler app = new ServletContextHandler("/"); app.addFilter(new FilterHolder(new AllowedByFilter(NotesService.fromEnvironment())), "/*", EnumSet.of(DispatcherType.REQUEST)); app.addServlet(new ServletHolder(new NotesServlet()), "/*"); String bind = System.getenv().getOrDefault("ALLOWEDBY_BIND", "").strip(); // unset or blank: loopback only Server server = new Server(); ServerConnector http = new ServerConnector(server); http.setHost(bind.isEmpty() ? "127.0.0.1" : bind); http.setPort(Integer.parseInt(System.getenv("PORT"))); server.addConnector(http); server.setHandler(app); server.start(); server.join(); } } ``` From `sdks/java/examples/frameworks/undertow-2/src/main/java/org/allowedby/examples/undertow/UndertowApp.java`: ```java package org.allowedby.examples.undertow; import io.undertow.Undertow; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.util.ImmediateInstanceFactory; import jakarta.servlet.DispatcherType; import org.allowedby.examples.servlet.NotesServlet; import org.allowedby.examples.servlet.NotesService; import org.allowedby.servlet.AllowedByFilter; /** The servlet filter on embedded Undertow 2.3. */ public final class UndertowApp { private UndertowApp() { } public static void main(String[] args) throws Exception { AllowedByFilter filter = new AllowedByFilter(NotesService.fromEnvironment()); DeploymentInfo app = Servlets.deployment() .setClassLoader(UndertowApp.class.getClassLoader()) .setContextPath("/") .setDeploymentName("notes") .addFilter(Servlets.filter("allowedby", AllowedByFilter.class, new ImmediateInstanceFactory<>(filter))) .addFilterUrlMapping("allowedby", "/*", DispatcherType.REQUEST) .addServlet(Servlets.servlet("notes", NotesServlet.class).addMapping("/*")); DeploymentManager manager = Servlets.defaultContainer().addDeployment(app); String bind = System.getenv().getOrDefault("ALLOWEDBY_BIND", "").strip(); // unset or blank: loopback only manager.deploy(); Undertow.builder() .addHttpListener(Integer.parseInt(System.getenv("PORT")), bind.isEmpty() ? "127.0.0.1" : bind) .setHandler(manager.start()) .build() .start(); } } ``` ### Spring Boot Add `allowedby-spring-boot-starter`: it builds the `AllowedBy` bean from `allowedby.*`, registers the filter (order `allowedby.filter-order`, default -200, before Spring Security) and resolves `@AllowedByContext Context` parameters in controllers. A handler with a required context never runs without one (401). From `sdks/java/examples/frameworks/spring-boot-4/src/main/java/org/allowedby/examples/spring/NotesApplication.java`: ```java package org.allowedby.examples.spring; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.allowedby.Context; import org.allowedby.spring.AllowedByContext; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; /** Notes for AI agents, with the Spring Boot starter: the route map is in application.yml. */ @SpringBootApplication @RestController public class NotesApplication { record Note(String id, String text) { } private final Map> notes = new ConcurrentHashMap<>(); private final AtomicInteger ids = new AtomicInteger(); @GetMapping("/health") Map health() { // not on the route map: no AllowedBy check return Map.of("ok", true); } @GetMapping("/me") Map me(@AllowedByContext Context ctx) { return Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator(), "level", ctx.getLevel()); } @GetMapping("/notes") Map> list(@AllowedByContext Context ctx) { return Map.of("notes", mine(ctx)); } @PostMapping("/notes") ResponseEntity> add(@AllowedByContext Context ctx, @RequestBody Map body) { List mine = mine(ctx); // the person first: 403 at level 0, whatever the body // a JSON string only: never a number or a boolean turned into text if (!(body.get("text") instanceof String text) || text.isEmpty() || text.codePointCount(0, text.length()) > 2000) { // characters, as the reference return badText(); } Note note = new Note(Integer.toString(ids.incrementAndGet()), text); mine.add(note); return ResponseEntity.status(201).body(Map.of("id", note.id())); } @DeleteMapping("/notes/{id}") Map delete(@AllowedByContext Context ctx, @PathVariable String id) { mine(ctx).removeIf(note -> note.id().equals(id)); // approved for this exact request, once return Map.of("deleted", id); } @ExceptionHandler(HttpMessageNotReadableException.class) // a body that is not a JSON object ResponseEntity> notJson() { return badText(); } private static ResponseEntity> badText() { return ResponseEntity.badRequest().body(Map.of("error", "text: a string of 1 to 2000 characters")); } private List mine(Context ctx) { String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0"); } return notes.computeIfAbsent(person, p -> new CopyOnWriteArrayList<>()); } public static void main(String[] args) { SpringApplication.run(NotesApplication.class, args); } } ``` From `sdks/java/examples/frameworks/spring-boot-4/src/main/resources/application.yml`: ```yaml # AllowedBy for this app (allowedby-spring-boot-starter). Unknown keys fail the start. server: port: ${PORT:8080} allowedby: origin: ${ALLOWEDBY_ORIGIN:http://localhost:8080} # your public origin (https in production) node: ${ALLOWEDBY_NODE:http://localhost} # the node you trust refresh-seconds: ${ALLOWEDBY_REFRESH_SECONDS:5} title: Notes Interop API org: legal-name: Notes Interop Ltd country: FR # key-file: /var/lib/notes/allowedby-keys.json # keep keys across restarts, shared by every instance routes: - { method: GET, path: /me, level: 0, summary: Who is calling } - { method: GET, path: /notes, capability: "notes:read", level: 1, resource: "note:*", summary: List your notes } - { method: POST, path: /notes, capability: "notes:write", action-class: write, level: 1, resource: "note:new" } - { method: DELETE, path: "/notes/{id}", capability: "notes:delete", action-class: write-hard, level: 2, resource: "note:{id}" } templates: "[notes:read]": Read your notes "[notes:write]": Write new notes "[notes:delete]": Delete note {scope} ``` In YAML, capability keys are written `"[notes:read]"` so Spring keeps the colon; in `.properties`, escape it: `allowedby.templates[notes\:read]=Read your notes`. Unknown keys fail the start. Properties: `origin`, `node`, `org.legal-name`, `org.country`, `org.website`, `org.support`, `org.privacy-policy`, `routes[n].method`, `path`, `capability`, `action-class`, `level`, `resource`, `amount-field`, `currency-field`, `authn`, `tier`, `max-lifetime`, `level-profile`, `qes`, `summary`, `templates`, `key-file`, `refresh-seconds`, `node-max-level`, `title`, `version`, `description`, `rfc9421`, `nonce`, `rate.actor.calls`, `rate.actor.per`, `rate.operator.calls`, `rate.operator.per`, `filter-order`, `unprotected`, `enabled`; per route also `nonce`, `require-link`, `account-param`. To add routes in code, declare an `AllowedByCustomizer` bean (`b -> b.route(...).template(...)`); to share the store between instances, declare a `Store` bean (for example a `RedisStore`); to replace everything, declare your own `AllowedBy` bean. ### JDK HTTP server `AllowedByHttpFilter` (in the core, no dependency) on a `com.sun.net.httpserver` context; the quick start above uses it. The handler reads `exchange.getAttribute(Context.ATTRIBUTE)`. From `sdks/java/examples/frameworks/jdk-http-server/src/main/java/org/allowedby/examples/jdk/JdkApp.java`: ```java package org.allowedby.examples.jdk; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.MissingNode; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.allowedby.ActionClass; import org.allowedby.AllowedBy; import org.allowedby.Context; import org.allowedby.Route; import org.allowedby.httpserver.AllowedByHttpFilter; /** The notes service on the JDK's own HTTP server. */ public final class JdkApp { private static final ObjectMapper JSON = new ObjectMapper(); private static final Map>> NOTES = new ConcurrentHashMap<>(); private static final AtomicInteger IDS = new AtomicInteger(); private JdkApp() { } public static void main(String[] args) throws IOException { AllowedBy aby = AllowedBy.builder() .origin(System.getenv("ALLOWEDBY_ORIGIN")) .node(System.getenv("ALLOWEDBY_NODE")) .refreshSeconds(Integer.parseInt(System.getenv().getOrDefault("ALLOWEDBY_REFRESH_SECONDS", "5"))) .org("Notes Interop Ltd", "FR") .title("Notes Interop API") .route(Route.get("/me").level(0).summary("Who is calling")) .route(Route.get("/notes").capability("notes:read").level(1).resource("note:*")) .route(Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1) .resource("note:new").body(Map.of("text", "the note"))) .route(Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD) .level(2).resource("note:{id}")) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .build(); String bind = System.getenv().getOrDefault("ALLOWEDBY_BIND", "").strip(); // unset or blank: loopback only HttpServer server = HttpServer.create( new InetSocketAddress(bind.isEmpty() ? "127.0.0.1" : bind, Integer.parseInt(System.getenv("PORT"))), 0); server.createContext("/", JdkApp::handle).getFilters().add(new AllowedByHttpFilter(aby)); server.setExecutor(Executors.newCachedThreadPool()); server.start(); } private static void handle(HttpExchange exchange) throws IOException { Context ctx = (Context) exchange.getAttribute(Context.ATTRIBUTE); // null outside the route map if (ctx == null) { // the application's own pages; a route of the map always has a context boolean health = ("GET".equals(exchange.getRequestMethod()) || "HEAD".equals(exchange.getRequestMethod())) && "/health".equals(exchange.getRequestURI().getPath()); send(exchange, health ? 200 : 404, health ? Map.of("ok", true) : Map.of("error", "not found")); return; } String route = ctx.getRoute().method() + " " + ctx.getRoute().path(); // the route that was checked if ("GET /me".equals(route)) { // level 0: the agent, no person send(exchange, 200, Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator(), "level", ctx.getLevel())); return; } String person = ctx.getHumanId(); if (person == null) { // level 0: no person, and never a key send(exchange, 403, Map.of("error", "no person at level 0")); return; } switch (route) { case "GET /notes" -> send(exchange, 200, Map.of("notes", mine(person))); case "POST /notes" -> add(exchange, person); case "DELETE /notes/{id}" -> { String id = ctx.getParams().get("id"); // the value checked: normalised, decoded once mine(person).removeIf(note -> note.get("id").equals(id)); send(exchange, 200, Map.of("deleted", id)); } default -> send(exchange, 404, Map.of("error", "not found")); } } private static void add(HttpExchange exchange, String person) throws IOException { JsonNode text; try { text = JSON.readTree(exchange.getRequestBody()).path("text"); } catch (JsonProcessingException e) { // not JSON: the same answer as a missing text text = MissingNode.getInstance(); } String t = text.asText(); // its length in characters, as the reference counts it if (!text.isTextual() || t.isEmpty() || t.codePointCount(0, t.length()) > 2000) { send(exchange, 400, Map.of("error", "text: a string of 1 to 2000 characters")); return; } String id = Integer.toString(IDS.incrementAndGet()); mine(person).add(Map.of("id", id, "text", text.asText())); send(exchange, 201, Map.of("id", id)); } private static List> mine(String person) { return NOTES.computeIfAbsent(person, p -> new CopyOnWriteArrayList<>()); } private static void send(HttpExchange exchange, int status, Object body) throws IOException { byte[] out = JSON.writeValueAsBytes(body); exchange.getResponseHeaders().set("Content-Type", "application/json"); if ("HEAD".equals(exchange.getRequestMethod())) { // the GET route's answer, headers only exchange.sendResponseHeaders(status, -1); } else { exchange.sendResponseHeaders(status, out.length); exchange.getResponseBody().write(out); } exchange.close(); } } ``` ### Kotlin The same builder; the context's getters read as properties (`ctx.humanId`, `ctx.level`). From `sdks/java/examples/frameworks/kotlin/src/main/kotlin/org/allowedby/examples/kotlin/Notes.kt`: ```kotlin package org.allowedby.examples.kotlin import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.ObjectMapper import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpServer import java.net.InetSocketAddress import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger import org.allowedby.ActionClass import org.allowedby.AllowedBy import org.allowedby.Context import org.allowedby.Route import org.allowedby.httpserver.AllowedByHttpFilter data class Note(val id: String, val text: String) private val json = ObjectMapper() private val notes = ConcurrentHashMap>() private val ids = AtomicInteger() /** The SDK from Kotlin: the same builder, and the context's getters read as properties. */ fun main() { val aby = AllowedBy.builder() .origin(System.getenv("ALLOWEDBY_ORIGIN")) .node(System.getenv("ALLOWEDBY_NODE")) .refreshSeconds(System.getenv("ALLOWEDBY_REFRESH_SECONDS")?.toInt() ?: 5) .org("Notes Interop Ltd", "FR") .title("Notes Interop API") .route(Route.get("/me").level(0).summary("Who is calling")) .route(Route.get("/notes").capability("notes:read").level(1).resource("note:*")) .route( Route.post("/notes").capability("notes:write").actionClass(ActionClass.WRITE).level(1) .resource("note:new").body(mapOf("text" to "the note")) ) .route( Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD).level(2) .resource("note:{id}") ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .build() val bind = System.getenv("ALLOWEDBY_BIND").orEmpty().trim().ifEmpty { "127.0.0.1" } // unset or blank: loopback only val server = HttpServer.create(InetSocketAddress(bind, System.getenv("PORT").toInt()), 0) server.createContext("/", ::handle).filters.add(AllowedByHttpFilter(aby)) server.executor = Executors.newCachedThreadPool() server.start() } private fun handle(exchange: HttpExchange) { val ctx = exchange.getAttribute(Context.ATTRIBUTE) as Context? // null outside the route map val get = exchange.requestMethod == "GET" || exchange.requestMethod == "HEAD" val (status, body) = when { ctx == null -> if (get && exchange.requestURI.path == "/health") 200 to mapOf("ok" to true) else 404 to mapOf("error" to "not found") else -> { val route = ctx.route.method() + " " + ctx.route.path() // the route that was checked (HEAD as GET) val person = ctx.humanId when { route == "GET /me" -> 200 to mapOf("agent" to ctx.agent, "operator" to ctx.operator, "level" to ctx.level) person == null -> 403 to mapOf("error" to "no person at level 0") // level 0: never a key route == "GET /notes" -> 200 to mapOf("notes" to mine(person)) route == "POST /notes" -> add(person, textOf(exchange)) route == "DELETE /notes/{id}" -> { val id = ctx.params.getValue("id") mine(person).removeIf { it.id == id } 200 to mapOf("deleted" to id) } else -> 404 to mapOf("error" to "not found") // never a handler by elimination } } } val out = json.writeValueAsBytes(body) exchange.responseHeaders["Content-Type"] = "application/json" if (exchange.requestMethod == "HEAD") { // headers only exchange.sendResponseHeaders(status, -1) exchange.close() return } exchange.sendResponseHeaders(status, out.size.toLong()) exchange.responseBody.use { it.write(out) } } private fun textOf(exchange: HttpExchange): String? = try { json.readTree(exchange.requestBody).path("text").textValue() } catch (e: JsonProcessingException) { // not JSON: the same answer as a missing text null } private fun add(person: String, text: String?): Pair> { if (text.isNullOrEmpty() || text.codePointCount(0, text.length) > 2000) { return 400 to mapOf("error" to "text: a string of 1 to 2000 characters") } val note = Note(ids.incrementAndGet().toString(), text) mine(person).add(note) return 201 to mapOf("id" to note.id) } private fun mine(person: String): MutableList = notes.computeIfAbsent(person) { CopyOnWriteArrayList() } ``` ## The context An accepted request gives your handler a read-only `Context`: who the agent is, which person approved (a pairwise id), at which level, and for which capabilities. | Getter | Kotlin | What | |---|---|---| | `getHumanId()` | `humanId` | The person, as a pairwise id for this service (stable for one person and one service, different at every service). Null at level 0. Key your data on it. | | `getLevel()` | `level` | The level reached: 0 agent only, 1 passkey, 2 verified identity, 3 eIDAS high | | `getAgent()` | `agent` | The agent: its passport subject (`did:oaid:...`) | | `getOperator()` | `operator` | Who runs the agent (a verified domain, or the node's own operator id) | | `getCapabilities()` | `capabilities` | The capabilities the approval grants | | `getDisplay()` | `display` | The text the person approved: `{summary, lines, lang}` | | `getGid()`, `getRev()`, `getJti()` | `gid`, `rev`, `jti` | The grant id (stable across revisions), its revision and the document's jti | | `getChain()` | `chain` | The grant chain, leaf first: `(gid, rev)` for your audit log (ABY-2 §5 step 10) | | `getRoute()`, `getActionClass()` | `route`, `actionClass` | The route that matched, and the class of this request (a payment's class comes from its amount) | | `getParams()` | `params` | The route's path values as the SDK checked them (CONTRACT §2 item 7): each `{name}` of the route, from the normalised path, decoded once (`/t/acme%20co` gives `acme co`, `%2520` gives `%20`, an encoded `/` stays inside its value). An unmodifiable map, empty for a route without parameters. Act on these values, never on your own reading of the raw path (`DELETE /notes/7/.` is checked as `/notes/7`). | | `getHumanIss()` | `humanIss` | The person's home node | | `getProofJti()`, `getRun()`, `getCall()` | `proofJti`, `run`, `call` | The proof's jti, and the agent's run id and call number when it sent them (audit) | | `getTenant()` | `tenant` | The route's `{tenant}` value, the same as `getParams().get("tenant")` (decoded once), or null: the tenant whose rules held ([Tenants](#tenants)) | | `getActingFor()` | `actingFor` | Always null: company mandates are not in this SDK yet | | `getLinkedAccount()` | `linkedAccount` | On a `requireLink` route: your account the person's pair is linked to (and `linkAuthorize` allowed). Null elsewhere | ## Production Keep the keys in a key file shared by every instance, share one store between instances, trust your node (or a signed trust list), and watch the logs for `[verifier] refresh failed`. - **Keys (`keyFile`).** The signing key (approval requests, the signed organisation profile) and the disclosure key. The file is created on first use with mode 0600 (owner-only ACL on Windows), atomically: when several instances start together, the first writer wins and the others read its keys. Its format is the reference's (`{"signing": {"pem"}, "disclosure": {"pem"}}`, PKCS#8 PEM), so one file works in every SDK; CI checks this with the Python reference, both ways. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `keyFile` at it, or write it from your secret manager. An existing file works anywhere. Without a key file both keys are new at each start. - **Store.** `MemoryStore` (the default) is for one process only: with several instances, a proof could be replayed on another one. Use `RedisStore` (one Redis primary or Sentinel; Redis Cluster is not supported). The store uses the SDK's clock for expiry, never its own. A store that cannot answer refuses the request (`503`, `Retry-After`). - **Trust.** By default the SDK trusts `node` on first use and pins its `node` key: a statement signed by another key is refused and logged. `trustList(TrustList.load(path, serviceKey))` replaces this with a signed OAID-5 trust list (anchors, programs pinned by key, vouching, witnesses). - **Refresh.** One daemon thread fetches the node statement and status lists every `refreshSeconds` (default 5, at most 60), never on the request path. `build()` returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, or one that scales to zero) trusts its node and holds its status lists before its first request (the Spring Boot starter builds its bean this way, as the context starts). A list older than 60 s refuses `write-hard` and `irreversible` requests (`503 status_stale`), older than 3600 s refuses everything. `refresh()` runs one refresh now; `isReady()` says whether the node is trusted yet. `close()` stops the thread. - **Logging.** `System.Logger` named `org.allowedby` (routed to java.util.logging, or to SLF4J/Log4j with their JDK bridges). Refresh failures are `WARNING [verifier] refresh failed: ...`; each request is one `DEBUG` line with the route pattern and the code. No token, key, body or person id is ever logged. - **Behind a proxy.** The SDK rebuilds the URL from `origin` and the path the server sees, and ignores forwarded headers. Do not let the proxy rewrite the path. From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/Production.java`: ```java package org.allowedby.examples.quickstart; import java.nio.file.Path; import java.util.Map; import org.allowedby.AllowedBy; import org.allowedby.Route; import org.allowedby.TrustList; import org.allowedby.redis.RedisStore; /** * Production settings: keys kept across restarts and shared by instances, a store shared by instances, a signed trust * list (optional), the refresh interval. Every value comes from the environment. */ public final class Production { private Production() { } public static AllowedBy service(Map env) throws Exception { // System.getenv() AllowedBy.Builder b = AllowedBy.builder() .origin(env.get("ALLOWEDBY_ORIGIN")) // https://api.example.com .node(env.get("ALLOWEDBY_NODE")) // https://node.example.org .org("Notes Ltd", "FR") .route(Route.get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes") .keyFile(Path.of(env.get("ALLOWEDBY_KEY_FILE"))) // a private volume or a secret .store(new RedisStore(env.get("REDIS_URL"))) // shared by every instance .refreshSeconds(5); String trustList = env.get("ALLOWEDBY_TRUST_LIST"); // optional: OAID-5 instead of TOFU if (trustList != null) { Map serviceKey = Map.of("kty", "OKP", "crv", "Ed25519", "kid", env.get("ALLOWEDBY_TRUST_KID"), "x", env.get("ALLOWEDBY_TRUST_X")); b.trustList(TrustList.load(Path.of(trustList), serviceKey)); } AllowedBy aby = b.build(); Runtime.getRuntime().addShutdownHook(new Thread(aby::close)); return aby; } } ``` ## Agents This SDK is for services only: to build an agent, use the Python SDK (`sdks/python/src/allowedby/agent.py`) or the TypeScript SDK, whose agent runtimes call any service built with this one. ## Errors Every refusal is `application/problem+json` with `type: https://allowedby.org/errors/`; a refusal that an approval can fix also carries `WWW-Authenticate: AllowedBy ...` (a challenge). | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request: the body is not a JSON object (or over 1 MiB), a malformed `Allowed-By`, a passport mixed with grants, or a path the server reads differently (`/notes;x`). | Send a JSON object body, well-formed headers and the plain path. | | `passport_required` | 401 | The agent sent no passport (`Allowed-By`). | The caller is not an AllowedBy agent, or calls a protected route without one. | | `invalid_signature` | 401 | A bad, expired or replayed proof; a tampered or forged grant; a bad WebAuthn signature. | Check the agent's clock (proofs within -120 s/+60 s) and that the URL your server sees matches `origin`. | | `untrusted_node` | 401 | The passport or grant comes from a node you do not trust, or no refresh has reached it yet (the first one at start failed or took over 5 s). | Check `node` or your trust list, and the refresh log. | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses (trust list `witnesses_min`). | Check the trust list's witnesses. | | `grant_required` | 401 | No approval for this action; the challenge says what is needed. | Normal first call: the agent asks the person. | | `grant_insufficient` | 401 | The approval does not cover this resource, amount or request, or a serious action was not requested by the service. | The agent asks for a wider approval. | | `level_insufficient` | 401 | The person's level (or level-3 profile) is below the route's. | The person verifies their identity on the approval page. | | `qes_required` | 401 | A qualified signature is needed; this SDK cannot verify one. | Serve the route with the Python reference, or remove `qes`. | | `authority_required` | 401 | The organisation's co-approvers are needed (not in this SDK). | See ABY-1 §5. | | `mandate_required` | 401 | The approval acts for a company; mandates are not accepted by this SDK yet. | The person approves for themselves. | | `expired` | 401 | The approval expired. | The agent asks again. | | `not_yet_valid` | 401 | The document is not valid yet. | Check the clocks. | | `revoked` | 401 | The person withdrew the approval or their registration. | The agent asks again. | | `actor_expired` | 401 | The agent's key in the grant expired (the problem says `rebind: true`). | The agent rebinds its grant or gets a new passport. | | `class_lifetime_exceeded` | 401 | The approval lasts longer than this class (or `maxLifetime`) allows. | Ask for a shorter approval. | | `single_use_consumed` | 401 | A one-time approval was already used. | Expected on retries of a serious action. | | `capability_denied` | 403 | No such route on the map. | Check the route map. | | `tier_insufficient` | 403 | The agent's key custody, or the passkey kind (`authn`), is too weak. | Use a stronger key or passkey. | | `human_not_linked` | 403 | The route needs a person linked to one of your accounts (`requireLink`), to the one its path names. | Link the account first ([Account linking](#account-linking)). | | `budget_exceeded` | 403 | A tenant budget is used up, or the request has no amount in its currency ([Tenant budgets](#tenant-budgets)); refused before any approval is asked. | Wait for the next period, or ask the tenant to raise it. | | `rate_limited` | 429 | Too many calls from this agent or its operator ([Rate limits](#rate-limits)). | Wait for `Retry-After` (60 s). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (a root and one child, depth 1). | A chain too deep: a sub-agent's grant is a child of a root, never of a child. | | `status_stale` | 503 | Your copy of the node's revocation list is too old for this action, or the replay store cannot answer; `Retry-After: 5`. | Check that the app reaches the node (look for `[verifier] refresh failed`) and the store. | ## Testing Run the conformance vectors and the interop test like CI does, and test your own app without a browser with the test node of `allowedby-core`'s test jar. The vectors (every `verifier` case of `vectors/profiles.json`, 453 today, read from `vectors/` at run time; the runner prints `N/N cases passed`) and every unit test, Linux and macOS: ```bash cd sdks/java ./mvnw -B verify # all modules, SpotBugs, warnings as errors ./mvnw -B test -pl allowedby-core -Dtest=VectorsTest REDIS_URL=redis://localhost:6379 ./mvnw -B test -pl allowedby-redis -am # the Redis store against a real Redis ``` Windows (PowerShell): ```powershell cd sdks\java .\mvnw.cmd -B verify .\mvnw.cmd -B test -pl allowedby-core -Dtest=VectorsTest ``` The interop test runs an app against a real node, the reference agent and a person with a software passkey (26 scenarios), from the repository root; here the Tomcat app: ```bash (cd sdks/java && ./mvnw -B -q package -DskipTests -pl examples/frameworks/tomcat-11 -am) python sdks/interop/interop.py --cmd "java -jar sdks/java/examples/frameworks/tomcat-11/target/app.jar" ``` Every framework of this page, each on the version CI installs, then the variant probe: ```bash (cd sdks/java && ./mvnw -B -q package -DskipTests -Dspotbugs.skip=true) python sdks/java/tools/run_frameworks.py ``` Every code block of this page is copied from a file CI executes or is run by CI as written, as `sdks/java/examples/blocks.json` lists (`python sdks/java/tools/blocks.py check`). The PowerShell blocks are parsed by PowerShell in CI, not run. Your own app: depend on the test jar (`org.allowedby:allowedby-core:0.1.0`, `test-jar`, test scope). `org.allowedby.testing.TestNode` is a test-only node on a free port: it serves a statement and a status list, issues passports and countersigned grants with a software passkey, and answers approval requests. From `sdks/java/examples/quickstart/src/test/java/org/allowedby/examples/quickstart/NotesTest.java`: ```java package org.allowedby.examples.quickstart; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; import org.allowedby.AllowedBy; import org.allowedby.Outcome; import org.allowedby.Request; import org.allowedby.Route; import org.allowedby.testing.TestNode; import org.junit.jupiter.api.Test; /** Testing an app without a browser: a test node issues the passport and the person's approval. */ class NotesTest { static final String ORIGIN = "http://localhost:8000"; @Test void anAgentReadsTheNotesOnceThePersonApproved() throws Exception { try (TestNode node = TestNode.start(); AllowedBy aby = AllowedBy.builder().origin(ORIGIN).node(node.origin).org("Notes Ltd", "FR") .route(Route.get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes").build()) { assertEquals(List.of(), aby.refresh()); // fetch the node statement and status list now TestNode.Agent agent = node.agent(); Outcome refused = aby.process(Request.of("GET", "/notes", null, agent.sign("GET", ORIGIN + "/notes", agent.passport, null), null)); assertEquals(401, refused.getResponse().getStatus()); // grant_required: the agent asks the person String grant = node.grant(agent, ORIGIN).cap("notes:read", Map.of("scope", "note:*")).build(); Outcome ok = aby.process(Request.of("GET", "/notes", null, agent.sign("GET", ORIGIN + "/notes", grant, null), null)); assertTrue(ok.isAllowed()); assertEquals(1, ok.getContext().getLevel()); assertEquals(List.of("notes:read"), ok.getContext().getCapabilities()); } } @Test void theRouteCatalogueBuilds() { try (AllowedBy aby = Routes.service()) { assertEquals(6, aby.getRoutes().size()); } } } ``` ## Reference Every public type, by module. Packages `org.allowedby.internal` and `org.allowedby.testing` are not API. `allowedby-core`, package `org.allowedby`: | Type | Members | |---|---| | `AllowedBy` | `builder()`; `process(Request) -> Outcome` (endpoints, then the check); `handle(Request) -> Response` or null; `check(Request) -> Outcome`; `concerns(...)`, `sameRoute(...)`, `isVariant(...)`, `pathOnMap(path)`, `extendsRoute(...)`, `sharesHandler(...)`, `namesMount(...)` and their refusals (for adapters); `wellKnown()`, `openApi()`, `apiCatalog()`; `getOrigin()`, `getNode()`, `getRoutes()`, `getSigningKey()`; `linkStart(account)`, `linkStart(account, ttl)`, `LINK_PATH`; `refundBudget(Context)`; `refresh() -> List` failures; `isReady()`; `close()`; `refusal(ErrorCode, title) -> Response` | | `AllowedBy.Builder` | `origin`, `node`, `org(legalName, country)`, `org(Map)`, `route`, `routes`, `template(cap, text)`, `template(cap, Map)`, `templates(Map)`, `unprotected(path)`, `unprotected(method, path)`, `keyFile(Path)`, `store(Store)`, `trustList(TrustList)`, `refreshSeconds(int)`, `nodeMaxLevel(int)`, `clock(Clock)`, `title`, `version`, `description`, `rfc9421(boolean)`, `nonce(boolean)`, `rate(limit, calls, per)`, `tenants(Map)`, `linkAuthorize(LinkAuthorizer)`, `build()` (waits for the first refresh, at most 5 s) | | `Route` | `route(method, path)`, `get`, `post`, `put`, `patch`, `delete`; `capability`, `actionClass`, `classByAmount`, `level`, `resource`, `amountField`, `currencyField`, `authn`, `tier`, `maxLifetime`, `levelProfile`, `qes`, `requireLink`, `accountParam`, `nonce`, `summary`, `body`, `option(name, value)`; getters of the same names | | `Route.Threshold` | `upTo(amount, ActionClass)`, `otherwise(ActionClass)` | | `ActionClass` | `READ`, `WRITE`, `WRITE_HARD`, `IRREVERSIBLE`; `wire()`, `maxLifetime()`, `serious()`, `of(String)` | | `Context` | `ATTRIBUTE`; the getters of [The context](#the-context); `Context.ChainLink` (`getGid()`, `getRev()`) | | `Request` | `of(method, path, query, headers, body)`; `method()`, `path()`, `query()`, `header(name)`, `headers()`, `body()`, `mountedAt(prefix)`, `prefix()` | | `Response` | `getStatus()`, `getHeaders()`, `getBody()`, `getBodyText()` | | `Outcome` | `isAllowed()`, `getResponse()`, `getContext()` | | `Store` | `add(key, until, now)`, `get(key, now)`, `charge(List, now)`; `Store.Charge(key, increment, max, until)` | | `MemoryStore` | `MemoryStore()`, `MemoryStore(maxKeys)`: one process only | | `TrustList` | `parse(jws, serviceKey)`, `load(path, serviceKey)`; `exp()`, `anchors()`, `denied()`, `vouching()`, `programs()`, `witnessesMin()` | | `ErrorCode` | every code of [Errors](#errors); `code()`, `status()`, `challenge()`, `type()` | | `ConfigurationException` | thrown by `build()`; the message says what to fix | | `org.allowedby.httpserver.AllowedByHttpFilter` | the JDK HTTP server filter | `allowedby-servlet`: `org.allowedby.servlet.AllowedByFilter(AllowedBy)`, `AllowedByFilter(AllowedBy, seesHandler)`, `MAX_BODY`. `allowedby-spring-boot-starter`, package `org.allowedby.spring`: `AllowedByAutoConfiguration`, `AllowedByProperties`, `@AllowedByContext(required)`, `AllowedByContextResolver`, `AllowedByCustomizer`. `allowedby-redis`: `org.allowedby.redis.RedisStore(url)`, `RedisStore(UnifiedJedis)`, `RedisStore(UnifiedJedis, prefix)`. What is implemented (`sdks/CONTRACT.md` §2): | Item | Status | |---|---| | Core 1-10: configuration, route map, discovery, verification (ABY-2 §5 steps 1-10, proof JWT and RFC 9421, EdDSA and ES256 only), challenges and service-initiated approvals, background refresh, context, store (memory and Redis), keys and key file, framework adapters | Implemented | | Trust on first use, OAID-5 signed trust lists (anchors, programs, vouching, witnesses) | Implemented | | `qes` | Refused fail-closed (`qes_required`): no EU trusted list in this SDK | | Account linking (`linkStart`, `/allowedby/link`, `requireLink`, `accountParam`, ABY-3 §6) | Extended: implemented (CONTRACT 1.8) | | AllowedBy-Nonce (`Builder.nonce`, `Route.nonce`, ABY-2 §3.2), level profiles (`levelProfile`, OAID-7 §5.3), rate limits (`Builder.rate`) | Extended: implemented (CONTRACT 1.12) | | Tenants (`Builder.tenants`, ORG-1 §3.3) and tenant budgets (`tenants[t].budgets`, §5.3) | Extended: implemented (CONTRACT 1.16); a tenant's `mandate` or `members_only` refuses with `401 mandate_required`, as this SDK verifies no mandate | | Disclosure callback and JWE decryption, authority policies, company mandates, audit sink, admin console | Not in this SDK (extended); route options that need them fail construction, and a grant acting for a company is refused (`mandate_required`) | Where this SDK is stricter than the Python reference, on purpose: a JSON document with a duplicate member name is refused (the reference keeps the last value); the route map matches the normalised path (the reference matches the raw path, then normalises in the verifier); a route above level 0 needs a capability, a level-0 route has none (a route map with `capability` and `level` 0 fails `build()`; the reference follows in CONTRACT 1.18), and every capability a template; `node` and `origin` must be https except on localhost; values from the node's approval answer that go into a header are checked. A grant that is itself expired, not yet valid or revoked is reported as such before an expired actor key (ABY-2 §5, step 3 before step 4). Approval requests carry no `callback` (the disclosure callback is not served). Version: SDK 0.1.0, specification set 0.2.14. ### Account linking An extended feature (CONTRACT 1.8, ABY-3 §6): a person links their AllowedBy identity to one of your own accounts, so that a route can take only that person for that account. From `sdks/java/examples/quickstart/src/main/java/org/allowedby/examples/quickstart/InteropExt.java`, the extended interop app (`sdks/interop/ext/interop_ext.py --features linking,nonce,level_profiles,rate` passes against it in CI); the builder goes on in the sections below: ```java AllowedBy aby = AllowedBy.builder() .origin(System.getenv("ALLOWEDBY_ORIGIN")) .node(System.getenv("ALLOWEDBY_NODE")) .org("Notes Interop Ltd", "FR") .route(Route.get("/me").level(0)) .route(Route.get("/accounts/{account}/notes").capability("notes:read").level(1) .resource("account:{account}").requireLink(true)) // only the person linked to {account} .template("notes:read", "Read your notes") ``` 1. **A code.** Your signed-in account page calls `aby.linkStart(account)` (or `linkStart(account, ttl)`, 1 s to 86 400 s, default 600 s) and shows the code: 96 random bits, single use. Take the account from your own session, never from the request. A new code does not revoke older ones; at 10 000 pending codes `linkStart` refuses (`IllegalStateException`), with no limit per account. 2. **The link.** The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves it, on every adapter and in `process()`, on that exact path only: another spelling of it (`/allowedby/%6Cink`, a dot segment) gets `400 invalid_request` and asks for no approval, even with a valid code, and a trailing or doubled `/` is not it. The code is checked first: an unknown, spent, revoked or expired one gets `400 invalid_request` before any approval is asked for. Then the request is checked as the SDK's own route `aby:link` (`write`, level 1), with single-use approvals only; without one the service creates that approval itself. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (home node, pairwise id) is linked to the account, replacing any other pair: `200 {"linked": true}`. A grant with no person id for your origin gets `401 grant_insufficient` and links nothing. 3. **The routes.** A `requireLink` route 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 `getParams()` decodes it. Both members of the pair count: the same pairwise id from another home node is another person. `getLinkedAccount()` is the account. `Builder.linkAuthorize((account, route, params) -> ...)` adds your own authorisation: only `Boolean.TRUE` lets the request on; `false`, null or an exception refuses with 403. Approvals the service creates for an account that is linked carry `human_home` and `human_hint` (AMH-1 §7). `/.well-known/allowedby` has `link`, and `/openapi.json` describes the route and marks each `requireLink` route (`x-allowedby.require_link`, as the reference does); `template("aby:link", ...)` replaces the default sentence. An app route at `/allowedby/link`, or with the capability `aby:link`, fails construction, and so does `requireLink` on a level-0 route. The codes and links live in memory, in each instance: behind several instances, send the code and the link request to the same one, and keep your own record of who is linked to what. Proved in CI by the extended vectors (`VectorsExtTest` reads the files of `vectors/ext/profiles.json`'s `linking` feature), the extended interop above, and mutation testing with PIT (`./mvnw -P mutation -pl allowedby-core test-compile org.pitest:pitest-maven:mutationCoverage`) of the linking state (`Linking`, with `linkAuthorize`'s decision), the link endpoint (`LinkEndpoint`: the exact path, the code first, the refund) and the verifier's rules (`LinkRules`: no person id, `requireLink`, `aby:link`'s single use): every mutant is killed, none is excused as equivalent. ### AllowedBy-Nonce A nonce proves that a request was made just now, for this service (ABY-2 §3.2; CONTRACT 1.12). With `Builder.nonce(true)`, a route with `nonce(true)`, and every `irreversible` route, refuses a proof without a current nonce with `401 invalid_signature` and a fresh nonce in the `AllowedBy-Nonce` header. The agent retries once with it: in the proof (`nonce`), or with RFC 9421 in its `AllowedBy-Nonce` header, which counts only when the signature covers it (a covered value that is not base64url gets `401` before any check of it). A route with `nonce(true)` while the service has nonces off fails construction. `/openapi.json` marks the route (`x-allowedby.nonce`), so an agent can send a nonce from its first call. ```java .nonce(true) // AllowedBy-Nonce on: routes with nonce(true), and every irreversible route .route(Route.post("/drafts").capability("drafts:write").actionClass(ActionClass.WRITE).level(1) .resource("draft:new").nonce(true).body(Map.of("text", "the draft"))) .template("drafts:write", "Save your drafts") ``` A nonce is stateless: base64url(`t` ‖ HMAC-SHA256(nonce key, `t`)[0:16]), `t` its issue time in seconds as 8 bytes big-endian. It is current for 300 s, on every instance that shares the key file (`keyFile`), and across a restart. The nonce key is HKDF-SHA256 of the signing key's raw private key (no salt, info `allowedby/nonce/v1`), so every SDK on one key file takes the others' nonces. Without a key file, each instance has its own keys, and so its own nonces. ### Level profiles A level-3 route can require the profile of the person's level-3 identity check (OAID-7 §5.3): `levelProfile("eu")` (eIDAS high) or `levelProfile("na")` (the North-American profile). A grant whose registration has another profile, or none, is refused with `401 level_insufficient`, and the approval the service asks for names the profile, so the person's node offers only sources of it. Without it, a level-3 route takes either; below level 3 it fails construction. ```java .route(Route.get("/vault/eu/{id}").capability("vault:read").level(3).resource("vault:{id}") .authn("hardware").levelProfile("eu")) // only a level 3 of the EU profile .route(Route.get("/vault/na/{id}").capability("vault:read").level(3).resource("vault:{id}") .authn("hardware").levelProfile("na")) .template("vault:read", "Open {scope}") ``` ### Rate limits `Builder.rate("actor", calls, per)` limits the calls per agent (its passport's `sub`), and `rate("operator", calls, per)` per operator (`operator.id`). The defaults are 600 and 6000 calls a minute; a limit you leave out keeps its default, and another name, or a limit that is not a positive number of calls in a positive whole number of seconds, fails construction (a misspelt limit would leave the default in place). In Spring: `allowedby.rate.actor.calls` and `allowedby.rate.actor.per` (default one minute), the same for `operator`. ```java .rate("actor", 20, Duration.ofMinutes(1)) // per agent (default 600 a minute) .rate("operator", 1000, Duration.ofMinutes(1)) // per operator (default 6000 a minute) ``` The window slides on the builder's `clock`: a call at `t` sees those at `x` with `t - x` under the window. A call counts once its proof is verified and is no replay, whatever is decided after it (one refused as `grant_required` counts); a call over either limit gets `429 rate_limited` with `Retry-After: 60`, and counts for neither. The counts are kept in the process, like `MemoryStore`: behind several instances, each counts its own calls. Each limit keeps at most 10 000 agents (or operators), as the reference; past that, the one used least recently is dropped. Proved in CI, as account linking is: the extended vectors (`VectorsExtTest` runs the files of the `nonce`, `level_profiles` and `rate` features of `vectors/ext/profiles.json`, and checks the nonce key and the nonce of `nonce.json`), the extended interop above, and mutation testing with PIT of `Nonces` (the key, the nonce and its 300 s, which routes ask, the header's grammar) and `RateLimits` (the window, what counts, the bound, the configuration): every mutant is killed, none is excused as equivalent. ### Tenants A tenant is one of your customers, named by the path parameter `{tenant}` (ORG-1 §3.3; CONTRACT 1.16). Its rules tighten the routes that name it, never loosen them: `level` (the higher counts), `authn` (the stronger), `mandate` and `require_link` (true wins), `max_lifetime` (the shorter), `amount_max` (the lower; above it, or with no amount, `403 capability_denied`), `operators` (an allowlist of `operator.id`; any other operator gets `403 capability_denied`). From the extended interop app: ```java .route(Route.post("/t/{tenant}/orders").capability("orders:place").actionClass(ActionClass.WRITE) .level(1).resource("tenant:{tenant}:order:new").amountField("/total")) .template("orders:place", "Place orders on {scope}, up to {amount.max} {amount.currency} per " + "{amount.per}") .tenants(Map.of( "umbrella", Map.of("name", "Umbrella"), // the route as the map says "hooli", Map.of("name", "Hooli", "routes", Map.of("orders:place", Map.of("amount_max", "50.00"))), "budget", Map.of("name", "Budget Co", "budgets", Map.of("orders:place", Map.of("max", "100.00", "currency", "EUR", "per", "day"))))) ``` `tenants(Map)` takes JSON values (maps, lists, strings, numbers, booleans) and copies them: later changes to your maps change nothing. Construction fails on a tenant id outside `[A-Za-z0-9_-]{1,64}`, a key other than `name`, `routes`, `budgets`, `org` and `members_only`, a `name` that is not 1-200 characters, an `org` that is not an https origin with no path, a capability the route map does not have, a value of another shape, and an override or budget on a capability with a route without `{tenant}` (there it would never apply; the message names the route). A `resource` with `{tenant}` keeps one tenant's approvals off another's routes. `Context.getTenant()` is the tenant. This SDK verifies no company mandate (ORG-1 §6), so a tenant's `mandate: true`, and a `members_only` tenant with an `org`, refuse every request with `401 mandate_required`, and ask for no approval that could not be accepted. The tenant keys `authority` and `authority_policy_revision` (authority policies) fail construction: they are not in this SDK yet; so does the override `qes`, as this SDK has no EU trusted list to check a qualified signature. A level-0 route has no capability (construction refuses one), so no override applies to it; `members_only` holds for the whole tenant, so its level-0 routes refuse with `401 mandate_required` too (no grant, so no mandate), with no challenge. In Spring, set tenants with an `AllowedByCustomizer` (`b -> b.tenants(...)`): Spring's properties would turn the numbers into strings. ### Tenant budgets A tenant budget (ORG-1 §5.3) is `tenants[t].budgets[capability]`, `{max, currency, per: day | week | month, tz?}`, on a capability whose every route has `amountField`. The service counts the amounts it accepts per tenant, capability, currency, zone and calendar period in `tz` (default UTC), in the builder's `store`: every instance that shares the store (a `RedisStore`) shares the count. A request over what is left, or without an amount in the budget's currency (never converted), gets `403 budget_exceeded`, before any approval is asked: no approval can fix a budget. A request refused for another reason is not counted, and the charge is the only count: the store is read only to say, in a refusal, how much is used. When the store does not answer, the request gets `503 status_stale` with `Retry-After: 5`; when that happens after the check accepted it, what the check charged (a single use, an approval's totals) is given back first. A request the SDK itself refuses before its handler (CONTRACT §2 item 10) gives the amount back with the rest. When your handler refuses an accepted request itself (a wrong total, an unknown order), call `aby.refundBudget(ctx)`: the amount it did not spend counts no more. It gives the amount back once (a second call, or one after the SDK's own refund, does nothing), does nothing for a request whose route has no budget, and gives back only the budget: the approval stays spent. Proved in CI: the extended vectors (`VectorsExtTest` runs `tenants.json` and `tenant-budgets.json`, the `tenants` and `tenant_budgets` features of `vectors/ext/profiles.json`), the extended interop above (`--features ...,tenants,tenant_budgets`), and mutation testing with PIT of `Tenants` (the option's checks, each override, the operator allowlist and the ceiling, the mandate refusal, the budget's amount and key, its refund once): every mutant is killed, none is excused as equivalent. --- Source: https://docs.allowedby.com/sdk/dotnet # AllowedBy SDK for C# and .NET This guide shows how a service written in C# accepts AI agents that act for a person. The concepts (routes, classes, levels, the approval flow, the context) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents); this guide shows them in C#. The SDK is in `sdks/dotnet`. It follows `sdks/CONTRACT.md` and implements spec set 0.2.14. Terms used below: a **node** issues agent passports and serves the approval page; a **grant** is a person's signed approval; a **proof** is a JWT (JSON Web Token) the agent signs for each request; **ABY-2** is the specification of how a service verifies requests. ## Install Answer: reference `AllowedBy.AspNetCore` (it brings `AllowedBy`); add `AllowedBy.Redis` for several instances. The packages are not published on NuGet yet. Until they are, reference the projects from a clone next to your project (the same commands on Windows): ```bash dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.AspNetCore/AllowedBy.AspNetCore.csproj dotnet add reference ../allowedby/sdks/dotnet/src/AllowedBy.Redis/AllowedBy.Redis.csproj ``` Once published: `dotnet add package AllowedBy.AspNetCore` and `dotnet add package AllowedBy.Redis`. | Package | What | Depends on | |---|---|---| | `AllowedBy` | The core: configuration, route map, discovery documents, verification (ABY-2 §5), challenges, stores. No web framework. | `BouncyCastle.Cryptography` 2.5.1 | | `AllowedBy.AspNetCore` | `AddAllowedBy`, `UseAllowedBy`, `HttpContext.GetAllowedBy()`, `[FromAllowedBy]`, the background refresh. | ASP.NET Core shared framework | | `AllowedBy.Redis` | `RedisStore`: the store shared by every instance. | `StackExchange.Redis` 2.8.16 | Why each dependency: - **BouncyCastle.Cryptography** (pinned 2.5.1): Ed25519 (EdDSA) signatures, which the .NET base class library does not have. It is pure managed code (no native library to ship or patch), so it runs the same in any container. NSec would need libsodium binaries. Everything else comes from the base class library: ECDSA P-256 (ES256), ECDH, SHA-256, zlib, `System.Text.Json`. - **StackExchange.Redis** (pinned 2.8.16, only in `AllowedBy.Redis`): the standard Redis client for .NET. Runtimes: the packages target `net8.0` and run on .NET 8 and every later runtime; CI tests .NET 8 and .NET 10 on Linux and .NET 10 on Windows. .NET 8 left Microsoft support on 2026-11-10: use .NET 10 (LTS) for new services. ## Quick start Answer: `AddAllowedBy(o => ...)`, `app.UseAllowedBy()`, and take `AllowedByContext` in your handler. ```csharp using AllowedBy; using AllowedBy.AspNetCore; using static AllowedBy.Routes; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAllowedBy(o => { o.Origin = builder.Configuration["ALLOWEDBY_ORIGIN"]!; // your app's public URL o.Node = builder.Configuration["ALLOWEDBY_NODE"]!; // the node you trust: people approve there o.Org = new AllowedByOrg { LegalName = "Notes Ltd", Country = "FR" }; o.Routes = [Route("GET", "/notes", "notes:read", level: 1, resource: "note:*")]; o.Templates["notes:read"] = "Read your notes"; // what the person approves }); var app = builder.Build(); app.UseAllowedBy(); app.MapGet("/notes", (AllowedByContext ctx) => new { notes = Array.Empty(), person = ctx.HumanId }); app.Run(); ``` This is `sdks/dotnet/examples/Recipes/Quickstart/Program.cs`; CI runs it against a real node, agent and person. See it work against the local node. In one terminal, start the demo (node on port 8700): ```bash pip install -r requirements.txt python demo/run.py --port 8700 ``` In another, run the app: ```bash export ALLOWEDBY_ORIGIN=http://localhost:5000 ALLOWEDBY_NODE=http://localhost:8700 dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000 ``` The same on Windows (PowerShell): ```powershell $env:ALLOWEDBY_ORIGIN = "http://localhost:5000"; $env:ALLOWEDBY_NODE = "http://localhost:8700" dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000 ``` Call it without a passport: ```bash curl -i http://localhost:5000/.well-known/allowedby curl -i http://localhost:5000/notes ``` The second call answers `401 passport_required` with `WWW-Authenticate: AllowedBy realm="localhost:5000", ...`: the route is protected. An agent (the Python or TypeScript agent SDK) gets a passport from the node, is challenged, asks the person, and retries with the grant. The app in Docker instead: ```bash docker run --rm --network host -v "$PWD":/src -w /src \ -e ALLOWEDBY_ORIGIN=http://localhost:5000 -e ALLOWEDBY_NODE=http://localhost:8700 \ mcr.microsoft.com/dotnet/sdk:10.0 \ dotnet run --project sdks/dotnet/examples/Recipes/Quickstart --urls http://localhost:5000 ``` With the hosted node instead of a local one, set `ALLOWEDBY_NODE=https://demo.allowedby.com` and `ALLOWEDBY_ORIGIN` to your public origin (the node must reach your `/.well-known/allowedby`). ## Routes and templates Answer: each route names a method, a path, a capability, a class and a level; each capability has the sentence the person signs. `Routes.Route(method, path, capability, cls, level, resource, ...)` takes the same arguments as Python's `route()` and validates them at once (an `ArgumentException` says what to fix). Requests whose method and path are not in the map reach your app unchanged, without a context. | Argument | Meaning | |---|---| | `method`, `path` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`; `{name}` is one path segment. `HEAD` is checked as `GET`. Literal segments match without case and empty segments (a trailing or doubled slash) are ignored, as ASP.NET Core routing does, so no spelling of a protected path reaches your handler unchecked. | | `capability` | `namespace:action`, e.g. `notes:read`. `null` for a level-0 route (the agent's passport is enough). | | `cls` | `read`, `write`, `write-hard`, `irreversible` (ABY-3 §4). For `write-hard` and `irreversible` the SDK creates the approval itself, bound to this exact request (single use). | | `level` | 0 (agent only), 1 (passkey), 2 (verified identity), 3 (eIDAS high, hardware passkey). | | `resource` | What the call acts on, e.g. `note:{id}`; default `:*`. The grant's `scope` must cover it. | | `amountField`, `currencyField` | JSON pointers into the body (`/total`, default `/currency`): the grant must cap the amount. | | `classByAmount` | Thresholds instead of `cls`: `[new() { UpTo = "1000.00", Class = "write-hard" }, new() { Class = "irreversible" }]`. | | `authn` | Minimum passkey class: `synced` or `hardware`. | | `tier` | Minimum custody tier of the agent's key (OAID-3). | | `maxLifetime` | Longest grant lifetime in seconds (60 s to 30 days; default the class's: 30 days, 7 days, 24 h, 1 h). | | `levelProfile` | On a level-3 route: `eu` or `na` (OAID-7 §5.3). See [Level profiles](#level-profiles). | | `nonce` | An AllowedBy-Nonce on this route, whatever its class (ABY-2 §3.2). Needs the service option `Nonce`: construction fails without it. See [AllowedBy-Nonce](#allowedby-nonce). | | `qes` | A qualified electronic signature. Not supported yet (it needs an EU trusted list): `true` fails construction. | | `requireLink`, `accountParam` | The person must have linked their identity to one of your accounts (ABY-3 §6), and, on a path with the `accountParam` parameter (default `account`), to that account: `403 human_not_linked` otherwise. Level 1 or more: on a level-0 route it fails construction. An `accountParam` you set must be a parameter of the path, as written (one that differs only by case fails construction). See [Account linking](#account-linking). | | `summary`, `body` | What the operation does and its body members, published in `/openapi.json`. | Templates are the only source of the text the person signs (AMH-1 §4). A string is English for both the summary and the line; for several languages give `Summary` and `Lines` per language code. Placeholders: `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{fields}`. Inside `AddAllowedBy` (from `sdks/dotnet/examples/Production/Program.cs`): ```csharp o.Templates["notes:read"] = "Read your notes"; // English, for the summary and the line o.Templates["invoices:pay"] = new AllowedByTemplate { Summary = new Dictionary { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, Lines = new Dictionary { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, }; ``` Options the Python reference accepts and this SDK does not enforce yet (`Mandate`, `Disclose`, `DiscloseOptional`, `Authority`, `Qes`) make construction fail with a message naming the option: accepting an option and not enforcing it would fail open. ### Account linking Answer: your signed-in account page calls `aby.LinkStart(account)` and shows the code; the person gives it to their agent, which sends it to `POST /allowedby/link`; their approval then links their identity to that account, and routes with `requireLink: true` accept only a linked person (ABY-3 §6; an extended feature of `sdks/CONTRACT.md`). 1. **The code.** `LinkStart(account, ttl = 600)` returns a code for one of your accounts (its id, 1 to 256 characters): 96 random bits, single use, valid `ttl` seconds (1 to 86400). A new code revokes no older one. Show it only to the signed-in owner of the account. 2. **The request.** The agent sends `POST /allowedby/link` with `{"code": ""}`. The SDK serves this route itself (`UseAllowedBy()` answers it before routing; your app never sees it) and publishes it in its route map (`aby:link`, class write, level 1). An unknown, spent, revoked or expired code is refused with `400 invalid_request` before any approval is asked for. Then the request is checked as any route, with a single-use approval only: the SDK creates it at the node (as for write-hard routes) and the person approves it with a passkey tap. 3. **The link.** Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home node, their pairwise id for your origin) is linked to the code's account, in place of any person linked to it before (one person per account, one account per person). The answer is `200 {"linked": true}`. 4. **The routes.** On a route with `requireLink: true`, a person who has not linked is refused with `403 human_not_linked`. When the path has the `accountParam` parameter (default `account`), only the person linked to that account is accepted. Both members of the pair count: the same pairwise id from another home node is another person. An approval that names no person for your origin (no `human.id` for it) is refused with `401 grant_insufficient`, here and on `POST /allowedby/link`: an empty id would match every such approval. Under rule 5, a route covers a `requireLink` route whose path names the account only with the same parameter in the same segment. The context names the account (`LinkedAccount`). The approvals the SDK creates for such a route name the linked person (`human_hint`). 5. **Your authorisation.** A route whose path names no account accepts any linked person. To decide yourself, set `o.LinkAuthorize = (account, route, values) => ...` (Python's `link_authorize`): only `true` passes; `false`, or an exception it throws, refuses with `403 human_not_linked`. It is called only for a linked person (and only for the account the path names, when it names one), with the route and its path values, decoded once. 6. **Removing a link.** When you delete an account, or the person asks to be forgotten, call `aby.Unlink(account)` (ABY-3 §6, Removing a link): the stored pair and the account's pending codes go, so a code issued before cannot re-link it. A `requireLink` route then refuses the person (`403 human_not_linked`) until they link again with a new code. It returns whether the account was linked (an unknown account is a no-op, `false`), and throws `ArgumentException` for an account `LinkStart` refuses. From `sdks/dotnet/examples/interop_ext/Program.cs`, which `sdks/interop/ext/interop_ext.py` runs against a real node: ```csharp Route("GET", "/accounts/{account}/notes", "notes:read", level: 1, resource: "account:{account}", requireLink: true, summary: "List the notes of an account"), ``` Limits: codes and links are kept in the process's memory, bounded (10,000 pending codes, 100,000 links, the oldest link dropped first). With several instances each keeps its own: link on the instance that serves the account page, or run one. When 10,000 codes are pending, `LinkStart` throws `InvalidOperationException`: catch it, and show one code per visit of the account page (not one per reload). Without ASP.NET Core (`HttpListener`), answer `POST /allowedby/link` yourself: when `aby.IsLinkRequest(method, path)`, send what `await aby.LinkAsync(request)` returns, before `CheckAsync`. Only the exact path as sent, `/allowedby/link`, is the endpoint: any other spelling (a trailing or doubled slash, a dot segment, an encoded letter, another letter case) asks for no approval and links nothing, even with a valid code, and `CheckAsync` refuses it (`400 invalid_request`, no challenge). ### AllowedBy-Nonce Answer: `o.Nonce = true` makes every irreversible route, and each route with `nonce: true`, refuse a proof without a current service nonce, so a proof captured earlier cannot be sent again later (ABY-2 §3.2). - **The refusal.** Without a current nonce the request gets `401 invalid_signature` and a fresh nonce in the `AllowedBy-Nonce` response header. The agent signs again with it (the proof's `nonce` claim) and retries once, whatever the route's class. With the RFC 9421 profile (`o.Rfc9421`), the nonce is the request's `AllowedBy-Nonce` header, and counts only when the signature covers it; a covered value that is no base64url nonce is `401`. - **The nonces.** A nonce is current for 300 s from its issue. Nothing is stored: a nonce is its issue time and a MAC of it, under a key derived from the signing key (HKDF-SHA256, `sdks/CONTRACT.md`, Extended: AllowedBy-Nonce). With a `KeyFile`, every instance takes the others' nonces, a restart keeps them current, and so does an SDK of any other language on the same key file. Without one, the key is new at each start. - **Configuration.** A route with `nonce: true` while `o.Nonce` is off fails construction, naming the route. ### Level profiles Answer: on a level-3 route, `levelProfile: "eu"` or `"na"` accepts only a person whose level 3 comes from that profile (OAID-7 §5.3); another profile, or none, is `401 level_insufficient`. Without it, a level-3 route accepts either profile. ### Rate limits Answer: every agent (the passport's `sub`) and every operator (`operator.id`) may make at most a given number of calls in a sliding window; one more is refused with `429 rate_limited` and `Retry-After: 60`. - **Defaults.** 600 calls per 60 s per agent, 6000 per operator. Set them with `o.Rate`, for example `new Dictionary { ["actor"] = [20, 60], ["operator"] = [1000, 60] }`. Any other key, or a value that is not two positive integers (calls, seconds), fails construction: a misspelt limit would leave the default in place. - **What counts.** 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 a limit counts for neither. The window slides on `o.Clock`: a call at t sees those at x with t - x < seconds. - **Limits.** The counts are kept in the process's memory (10,000 agents and operators at most, the least recent dropped first): with several instances, each counts its own calls. From `sdks/dotnet/examples/interop_ext/Program.cs`, which `sdks/interop/ext/interop_ext.py` runs against a real node: ```csharp Route("POST", "/drafts", "drafts:write", cls: "write", level: 1, resource: "draft:new", nonce: true, summary: "Save a draft", body: new Dictionary { ["text"] = "the draft" }), Route("GET", "/vault/eu/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware", levelProfile: "eu", summary: "Open a vault (EU level 3)"), Route("GET", "/vault/na/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware", levelProfile: "na", summary: "Open a vault (North-America level 3)"), ]; o.Nonce = true; // AllowedBy-Nonce on /drafts and on every irreversible route o.Rate = new Dictionary { ["actor"] = [20, 60], ["operator"] = [1000, 60] }; ``` ## Framework recipes Answer: minimal APIs take `AllowedByContext` as a parameter; controllers use `[FromAllowedBy]`; both come from `UseAllowedBy()`. The middleware runs, in order: the SDK's own endpoints (`GET|HEAD /.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog`), then the check on every route of the map, then your app. On a route of the map it reads the body once (at most `MaxBodyBytes`: 1 KiB to 64 MiB, 1 MiB by default), checks it is a JSON object, and gives the same bytes back to your app. Place `app.UseAllowedBy()` before your endpoints. The route map uses the paths your endpoints see: with `app.UsePathBase("/api")` (before `UseAllowedBy()`), declare `/notes`, while agents call and sign `/api/notes`. Path rewriting onto a route of the map is refused (`400`): the SDK never checks one path and lets the app serve another. Method-override headers (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`) naming a protected route are refused (`400`), and after `UseAllowedBy()` any middleware that changes the method or path to a protected route that was not checked (`UseHttpMethodOverride`, `UseRewriter`, `UsePathBase`) is stopped (`400`); so put `UsePathBase` before `UseAllowedBy()`; and route paths are literal segments and `{name}` only (catch-all, optional, default and constrained parameters are refused at construction, since the router would match them differently). The handler of a route of the map runs only for requests checked for that route: see [What is refused and why](#what-is-refused-and-why). A control character in a protected path, and a map written with the path base in it, are refused (`400`). Endpoint routing is required (the default). Each app below is in `sdks/dotnet/examples/frameworks`; CI runs it on .NET 8 and .NET 10 against a real node, agent and person (`sdks/dotnet/examples/frameworks.json`). **Minimal APIs** (`minimal-api/Program.cs`, then `minimal-api/NoteEndpoints.cs`): ```csharp using AllowedBy; using AllowedBy.AspNetCore; using static AllowedBy.Routes; var builder = WebApplication.CreateBuilder(args); var config = builder.Configuration; // environment variables and appsettings.json builder.WebHost.UseUrls("http://localhost:" + (config["PORT"] ?? "5000")); builder.Services.AddAllowedBy(o => { o.Origin = config["ALLOWEDBY_ORIGIN"] ?? "http://localhost:5000"; o.Node = config["ALLOWEDBY_NODE"] ?? "http://localhost:8700"; o.RefreshSeconds = config.GetValue("ALLOWEDBY_REFRESH_SECONDS", 5); o.Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR" }; o.Title = "Notes Interop API"; o.Routes = [ Route("GET", "/me", level: 0, summary: "Who is calling"), Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:new", summary: "Add a note", body: new Dictionary { ["text"] = "the note" }), Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note"), ]; o.Templates = new Dictionary { ["notes:read"] = "Read your notes", ["notes:write"] = "Write new notes", ["notes:delete"] = "Delete note {scope}", }; }); var app = builder.Build(); app.UseAllowedBy(); app.MapNotes(); app.Run(); ``` ```csharp using System.Globalization; using AllowedBy; using AllowedBy.AspNetCore; /// The endpoints: ordinary minimal APIs that take the verified context as a parameter. internal static class NoteEndpoints { private static readonly Dictionary> People = []; private static readonly object Gate = new(); private static int _lastId; public static void MapNotes(this WebApplication app) { // outside the route map: it reaches the app unchecked, with no context app.MapGet("/health", () => new { ok = true }); app.MapGet("/me", (AllowedByContext ctx) => new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level }); app.MapGet("/notes", ([FromAllowedBy] AllowedByContext ctx) => { lock (Gate) { return new { notes = Mine(ctx).ToList() }; } }); app.MapPost("/notes", (NewNote input, [FromAllowedBy] AllowedByContext ctx) => { if (string.IsNullOrEmpty(input.Text) || input.Text.Length > 2000) { return Results.Json(new { error = "text: a string of 1 to 2000 characters" }, statusCode: 400); } lock (Gate) { var id = (++_lastId).ToString(CultureInfo.InvariantCulture); Mine(ctx).Add(new Note(id, input.Text)); return Results.Json(new { id }, statusCode: 201); } }); app.MapDelete("/notes/{id}", (string id, [FromAllowedBy] AllowedByContext ctx) => { lock (Gate) { Mine(ctx).RemoveAll(n => n.Id == id); } return new { deleted = id }; }); app.MapFallback(() => Results.Json(new { error = "not found" }, statusCode: 404)); } /// This person's notes: HumanId is their id at this app. A level-0 route has no person (HumanId is /// null): stop here rather than key anyone's notes by a missing id. private static List Mine(AllowedByContext ctx) { var person = ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); if (!People.TryGetValue(person, out var notes)) { People[person] = notes = []; } return notes; } } internal sealed record Note(string Id, string Text); internal sealed record NewNote(string? Text); ``` `AllowedByContext` is registered per request, so a minimal-API parameter of that type is filled without an attribute (`/me` above); `[FromAllowedBy]` says it explicitly. Asking for it on a request the SDK did not accept throws: a handler never receives an unverified request. On an endpoint that also serves paths outside the map, call `HttpContext.GetAllowedBy()`, which returns `null` there. **MVC controllers**, with the routes in `appsettings.json` (`mvc/`; `NoteStore.cs` there keeps the notes): ```csharp using AllowedBy.AspNetCore; var builder = WebApplication.CreateBuilder(args); var config = builder.Configuration; builder.WebHost.UseUrls("http://localhost:" + (config["PORT"] ?? "5000")); builder.Services.AddSingleton(); builder.Services.AddControllers(); builder.Services.AddAllowedBy(config.GetSection("AllowedBy"), o => // appsettings.json, then what each deployment sets { o.Origin = config["ALLOWEDBY_ORIGIN"] ?? o.Origin; o.Node = config["ALLOWEDBY_NODE"] ?? o.Node; o.RefreshSeconds = config.GetValue("ALLOWEDBY_REFRESH_SECONDS", o.RefreshSeconds); }); var app = builder.Build(); app.UseAllowedBy(); app.MapControllers(); app.MapFallback(() => Results.Json(new { error = "not found" }, statusCode: 404)); app.Run(); ``` ```csharp using AllowedBy.AspNetCore; using Microsoft.AspNetCore.Mvc; namespace AllowedBy.Examples.Mvc; /// The person's notes. The routes, their levels and their sentences are in appsettings.json. [ApiController] [Route("notes")] public sealed class NotesController(NoteStore store) : ControllerBase { /// GET /notes (notes:read, level 1). [HttpGet] public IActionResult List([FromAllowedBy] AllowedByContext ctx) => Ok(new { notes = store.List(Person(ctx)) }); /// POST /notes (notes:write, level 1), body {"text": "..."}. [HttpPost] public IActionResult Add([FromAllowedBy] AllowedByContext ctx, [FromBody] NewNote note) => string.IsNullOrEmpty(note?.Text) || note.Text.Length > 2000 ? BadRequest(new { error = "text: a string of 1 to 2000 characters" }) : StatusCode(201, new { id = store.Add(Person(ctx), note.Text) }); /// DELETE /notes/{id} (notes:delete, write-hard, level 2): the person approved this exact request. [HttpDelete("{id}")] public IActionResult Delete(string id, [FromAllowedBy] AllowedByContext ctx) { store.Delete(Person(ctx), id); return Ok(new { deleted = id }); } /// The person the notes belong to. A level-0 route has no person (HumanId is null): stop here rather than /// key anyone's notes by a missing id. private static string Person(AllowedByContext ctx) => ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); } /// The body of POST /notes. /// The note. public sealed record NewNote(string? Text); ``` ```csharp using AllowedBy.AspNetCore; using Microsoft.AspNetCore.Mvc; namespace AllowedBy.Examples.Mvc; /// GET /me (level 0: the agent's passport only) and GET /health (outside the route map: unchecked). [ApiController] public sealed class AgentController : ControllerBase { /// Which agent is calling. [HttpGet("/me")] public IActionResult Me([FromAllowedBy] AllowedByContext ctx) => Ok(new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level }); /// The app's own path. [HttpGet("/health")] public IActionResult Health() => Ok(new { ok = true }); } ``` ```json { "AllowedBy": { "Origin": "http://localhost:5000", "Node": "http://localhost:8700", "Org": { "LegalName": "Notes Interop Ltd", "Country": "FR" }, "Title": "Notes Interop API", "RefreshSeconds": 5, "Routes": [ { "Method": "GET", "Path": "/me", "Level": 0, "Summary": "Who is calling" }, { "Method": "GET", "Path": "/notes", "Capability": "notes:read", "Resource": "note:*", "Summary": "List your notes", "Template": "Read your notes" }, { "Method": "POST", "Path": "/notes", "Capability": "notes:write", "Class": "write", "Resource": "note:new", "Summary": "Add a note", "Body": { "text": "the note" }, "Template": "Write new notes" }, { "Method": "DELETE", "Path": "/notes/{id}", "Capability": "notes:delete", "Class": "write-hard", "Level": 2, "Resource": "note:{id}", "Summary": "Delete a note", "Template": "Delete note {scope}" } ] }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } } } ``` In configuration a capability cannot be a dictionary key (`:` separates configuration sections), so give each route's sentence as its `Template` (a string, or `{"Summary": {"en": ...}, "Lines": {"en": ...}}`). **Without ASP.NET Core** (another server, a gateway): build an `AllowedByService` and call it yourself. `Handle(method, path)` returns the discovery documents or `null`; `MustCheck` says whether to read the body; `CheckAsync(new AllowedByRequest(method, rawPath, rawQuery, headers, body))` returns the `Context`, or the `Refusal` to send back as is. Dispatch on `Context.Route`, the route that was checked, and take its values from `Context.Params` (each decoded once: `a%20b` is `a b`, never decode it again), never from a second reading of the path. Call `RunAsync(stoppingToken)` once to keep the node's keys and revocation lists fresh; the first checks wait for its first refresh (at most 5 s). The whole server, on `HttpListener` (`httplistener/Program.cs`): ```csharp using System.Globalization; using System.Net; using System.Text.Json; using AllowedBy; using static AllowedBy.Routes; static string Env(string name, string otherwise) => Environment.GetEnvironmentVariable(name) ?? otherwise; using var aby = new AllowedByService(new AllowedByOptions { Origin = Env("ALLOWEDBY_ORIGIN", "http://localhost:5000"), Node = Env("ALLOWEDBY_NODE", "http://localhost:8700"), RefreshSeconds = int.Parse(Env("ALLOWEDBY_REFRESH_SECONDS", "5"), CultureInfo.InvariantCulture), Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR" }, Routes = [ Route("GET", "/me", level: 0, summary: "Who is calling"), Route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), Route("POST", "/notes", "notes:write", cls: "write", level: 1, resource: "note:new", summary: "Add a note", body: new Dictionary { ["text"] = "the note" }), Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note"), ], Templates = new Dictionary { ["notes:read"] = "Read your notes", ["notes:write"] = "Write new notes", ["notes:delete"] = "Delete note {scope}", }, }); _ = aby.RunAsync(CancellationToken.None); // keeps the node's keys and revocation lists fresh, in the background var people = new Dictionary>(); var lastId = 0; var web = new JsonSerializerOptions(JsonSerializerDefaults.Web); // camelCase using var server = new HttpListener(); // http.sys on Windows: no firewall prompt, localhost needs no admin; elsewhere localhost would bind ::1 only server.Prefixes.Add("http://" + (OperatingSystem.IsWindows() ? "localhost" : "*") + ":" + Env("PORT", "5000") + "/"); server.Start(); while (true) { var http = await server.GetContextAsync(); _ = Task.Run(async () => { try { await Serve(http); } catch (Exception e) when (e is HttpListenerException or IOException or ObjectDisposedException) { http.Response.Abort(); // the client went away } catch (Exception e) { Console.Error.WriteLine("request failed: " + e.GetType().Name); // never the path, query or headers try { http.Response.StatusCode = 500; http.Response.Close(); } catch (Exception) { http.Response.Abort(); } } }); } async Task Serve(HttpListenerContext http) { var raw = http.Request.RawUrl ?? "/"; // as sent, still percent-encoded: what the agent signed var q = raw.IndexOf('?', StringComparison.Ordinal); var (path, query) = q < 0 ? (raw, null) : (raw[..q], raw[(q + 1)..]); var method = http.Request.HttpMethod; if (aby.Handle(method, path) is { } document) // /.well-known/allowedby, /openapi.json, ... { await Send(http, document.Status, document.Headers, document.Body); return; } var headers = http.Request.Headers.AllKeys.Where(k => k is not null) .Select(k => new KeyValuePair(k!, http.Request.Headers[k] ?? "")).ToList(); if (!aby.MustCheck(new AllowedByRequest(method, path, query, headers, ReadOnlyMemory.Empty))) { await Json(http, path == "/health" ? 200 : 404, path == "/health" ? new { ok = true } : new { error = "not found" }); return; } var body = await ReadBody(http.Request.InputStream, aby.MaxBodyBytes + 1); var result = await aby.CheckAsync(new AllowedByRequest(method, path, query, headers, body)); if (result.Refusal is { } refusal) { await Send(http, refusal.Status, refusal.Headers, refusal.Body); // as is: it carries the challenge return; } if (result.Context is not { Route: { } route } ctx) { await Json(http, 404, new { error = "not found" }); return; } var (status, answer) = Dispatch(route.Method + " " + route.Path, ctx, body); // the route that was checked await Json(http, status, answer); } (int Status, object Answer) Dispatch(string route, AllowedByContext ctx, byte[] body) { if (route == "GET /me") { return (200, new { agent = ctx.Agent, @operator = ctx.Operator, level = ctx.Level }); } // A level-0 route has no person (HumanId is null): stop here rather than key anyone's notes by a missing id. var person = ctx.HumanId ?? throw new InvalidOperationException("HumanId is null: level-0 routes have no person; use level 1+"); lock (people) { if (!people.TryGetValue(person, out var mine)) { people[person] = mine = []; } switch (route) { case "GET /notes": return (200, new { notes = mine.ToList() }); case "POST /notes": using (var doc = JsonDocument.Parse(body.Length == 0 ? "{}"u8.ToArray() : body)) { var text = doc.RootElement.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null; if (text is null || text.Length is 0 or > 2000) { return (400, new { error = "text: a string of 1 to 2000 characters" }); } var note = new Note((++lastId).ToString(CultureInfo.InvariantCulture), text); mine.Add(note); return (201, new { id = note.Id }); } case "DELETE /notes/{id}": var id = ctx.Params["id"]; // the value that was checked, decoded once: never the path read again mine.RemoveAll(n => n.Id == id); return (200, new { deleted = id }); default: return (404, new { error = "not found" }); } } } static async Task ReadBody(Stream input, int limit) { using var body = new MemoryStream(); var buffer = new byte[16384]; int n; while (body.Length < limit && (n = await input.ReadAsync(buffer)) > 0) { body.Write(buffer, 0, Math.Min(n, limit - (int)body.Length)); } return body.ToArray(); // one byte over the limit at most: CheckAsync then refuses it } Task Json(HttpListenerContext http, int status, object answer) => Send(http, status, new Dictionary { ["Content-Type"] = "application/json" }, JsonSerializer.SerializeToUtf8Bytes(answer, web)); static async Task Send(HttpListenerContext http, int status, IReadOnlyDictionary headers, ReadOnlyMemory body) { http.Response.StatusCode = status; foreach (var (name, value) in headers) { http.Response.AddHeader(name, value); } if (http.Request.HttpMethod != "HEAD") { http.Response.ContentLength64 = body.Length; await http.Response.OutputStream.WriteAsync(body); } http.Response.Close(); } internal sealed record Note(string Id, string Text); ``` The service cannot see which handler your router chooses, so it refuses (`400`) every request that is not on the map but that a mapped template would match if a parameter took several segments (`DELETE /notes/7/x` for `DELETE /notes/{id}`, for the method or one a method-override header names); `GET /notes/7` with only `GET /notes` mapped goes through. Declare a page of your own in `Unprotected`. The ASP.NET Core adapter applies the same rule to a request for which the router selected no endpoint made for its path (none: a handler in `app.Run` or other terminal middleware, or routing placed after `UseAllowedBy()`; or a fallback or a catch-all, after which middleware may still dispatch the path by hand); where the router did select one, it judges that endpoint's handler instead. So with `UseRouting()` after `UseAllowedBy()`, your own longer routes are refused too: `DELETE /notes/7/comments`, served by `MapDelete("/notes/{id}/comments", DeleteComment)` next to `DELETE /notes/{id}` in the map, is a `400` until you either call `app.UseRouting()` before `app.UseAllowedBy()` (the default `WebApplication` routes first) or declare `("DELETE", "/notes/{id}/comments")` in `Unprotected`. ### What is refused and why The handler of a route of the map never runs for a request the SDK did not check for that route (sdks/CONTRACT.md §2.10). ASP.NET Core tells the middleware which endpoint the router selected, before or after `UseAllowedBy()`, so the SDK decides by the handler, not by the path: a handler reached by a wider template acts on the values that template gives it, so no path of it is safe to run unchecked. These requests are refused (`400 invalid_request`): | Request without a check | Example (map: `DELETE /notes/{id}`) | Why | |---|---|---| | An endpoint of the route whose template accepts more | `MapDelete("/notes/{**id}")`, `{id?}`, `{id=1}`, `{id:int}/{more?}`: `DELETE /notes/7/x` | the protected handler runs with `id = "7/x"` | | A catch-all that is the only endpoint of a route ending in a literal | map `DELETE /notes/{id}/archive`, `MapDelete("/notes/{id}/{**rest}")`: `DELETE /notes/7/archive/x`, `DELETE /notes/7/other` | the catch-all takes the literal with the rest; its handler is the route's | | A root catch-all that is the handler of a route | `MapDelete("/{**path}")` as the only endpoint of the route: `DELETE /x/notes/7` | any path reaches the same handler | | A generic endpoint that serves a route | `Map("/{a}/{**rest}")`: `POST /notes/7`, `GET /other/x/y` | the handler serves every method and every path of the template | | Another endpoint of the same handler, of any method | `MapDelete("/alias/{id}", Handler)`, `MapGet("/notes/{id}", Handler)` beside the protected `MapDelete("/notes/{id}", Handler)`, `MapGroup`, a second `[HttpDelete]` template, a conventional MVC route, an inherited action, a dynamic MVC route, a `RequestDelegate` with or without endpoint filters | the same code runs, and may read its input from the query; `Unprotected` never lifts it. The refusal names the fix: map that method too, or give it a handler of its own | | A path declared in `Unprotected` that a protected handler serves | `Unprotected = [("DELETE", "/notes/{id}/comments")]` with `MapDelete("/notes/{**id}")`: `DELETE /notes/7/comments` | `Unprotected` never lifts this refusal | | A reverse proxy pipeline with one route in the map (YARP) | `MapReverseProxy()`: the proxy's other routes | one pipeline is one handler | | A `HEAD` request a GET handler would answer | `MapMethods("/notes/{**id}", ["GET", "HEAD"])`, `[HttpHead]` on another template, a middleware that turns `HEAD` into `GET`: `HEAD /notes/7/x` with `GET /notes/{id}` mapped | `HEAD` is read as `GET` everywhere | | A short-circuited endpoint of a protected handler | `MapDelete("/notes/{id}", Delete).ShortCircuit()` | the router runs it before any middleware: the app does not start | | A control character in a protected path | `DELETE /notes/7%0A` | a router may match before it | | A parameter no approval can carry (ABY-2 §6) | a value of the `scope` (the route's `resource` with the values of the normalised path: `%61b` is `ab`) that is not 1 to 64 of `A-Z a-z 0-9 . _ -` (`a%20b`, `x%C3%A9`, `~`, `:`, `*`), a malformed escape, an escaped control character or `/`, or a `scope` over 256 bytes | an approval of that scope could never satisfy the route; the scope goes back as it is, never re-encoded | | A map written with the path base in it, a rewritten path, a method override naming a protected route | `UsePathBase("/api")` and `/api/notes/{id}` in the map | the path checked would not be the path routed | The safe pattern: give each page of your own an endpoint and a handler of its own, beside the protected ones (`MapDelete("/notes/{id}/comments", DeleteComment)` next to `MapDelete("/notes/{id}", DeleteNote)`). Your endpoints, longer routes, fallbacks and static catch-alls that serve no route of the map run unchanged. Prefer handlers with typed parameters on protected routes: they are compared by their method in every case. `o.Unprotected` (a path, or a method and a path, as your app routes it) declares a page of your own where no handler is judged (below): it lifts the refusal of a longer path for its method only. It never lifts a method override onto a mapped route, nor the refusal of a protected handler. An entry that reaches a route of the map, has no literal segment, is a template for a longer path of a route without naming its method, or (exact) may be read as another path (`//`, `.`, `..`, `;`, `%`) fails construction. **Catch-alls** (sdks/CONTRACT.md §2.10 rule 5). An endpoint that also takes a route's path with one of its words replaced (`/{**path}`, `/{a}/{**rest}`, `/notes/{id}/{**rest}` for `DELETE /notes/{id}/archive`), and any fallback, is a catch-all of that route. The route's own handler is known when one of its endpoints is no catch-all of it and takes a value for each of its parameters (`MapDelete("/notes/{id:int}")` for `DELETE /notes/{id}`). Then a request checked for the route that the router gives to a catch-all (a value the route's own endpoint turns down) is refused (`400`); a site-wide catch-all (`/{**path}`, `MapFallback`) is not the route's handler, so an SPA's pages run; a catch-all under the route's prefix stays protected for that route, and so do its other endpoints. While the route's own handler is not known and a catch-all is its only handler (a front controller, a router mounted at `/`), a request checked for the route runs it, and unchecked requests that would run it are refused; for a site-wide one the SDK logs once at startup `DELETE /notes/{id} is served only by a site-wide catch-all: give it a handler of its own`. A handler that serves several routes of the map runs for a request checked for one of them, even through that route's own endpoint, only if that route covers each other route the handler is known or protected for, whatever its shape: one delegate on `MapDelete("/notes/{id}")` (level 3) and `MapDelete("/items/{id}")` (level 1) never runs for a request checked for `/items/7`; one whose own handler is not known; one it serves as a catch-all; and the same template with another method (one handler for both, which does not dispatch per method: `MapMethods("/items/{id}", ["GET", "POST"], Handler)`, an action with two `Http*` attributes, one delegate on `MapGet` and `MapPost`). The SDK logs once at startup each pair of routes whose own endpoints run one handler where one does not cover the other, whatever their templates (`DELETE /items/{id} and DELETE /notes/{id} run one handler, and one does not cover the other: map both at the same capability and level, or give each its own handler`). Through a catch-all, another route's own handler is never run for it. Covering means the same capability, resource, amount field and currency field; a level and tier at least as high; its lowest class at least the other's highest; its longest grant at most the other's shortest; an `authn` at least as strong (`hardware`, then `synced`, then none); and the `levelProfile` the other sets. Two routes that share a catch-all without covering each other refuse each other: give each a handler of its own. Two limits follow (sdks/CONTRACT.md §2.10 rule 5): a site-wide catch-all that dispatches protected actions on paths no route maps (`Map("/{**path}", Legacy)` that deletes at `/legacy/delete?id=7`) is not something the SDK can see, as those paths are no route of the map; and a front controller shared by routes of different capabilities or resources runs for none of them. Give each protected route its own handler. An endpoint found for a route only under a path base the SDK guesses (`UsePathBase`, `Map`) never makes the route's own handler known, so a site-wide catch-all stays protected there. Nothing is learnt from requests: the endpoints decide, the same way for every request. An `OPTIONS` that the framework answers (`405`, a CORS preflight answered from the endpoint's metadata) runs no code of yours and is not refused; an endpoint of yours that takes `OPTIONS` (`Map(...)`) is refused like any other method. A refusal (its title, detail and headers) and a log line never repeat the path, the query, a header, or a value read from the passport or the grant (issuer, organisation, capability, key, subject, level), which may hold personal data or tokens; the challenge's `scope` alone carries the path's values, back to the caller: the log names the route template (`DELETE /notes/{id} -> passport_required`, `DELETE a longer path of /notes/{id} -> invalid_request`). A handler that no endpoint stands for (`app.Run`, `Map` branches that dispatch by hand) is not seen either, so for a request with no endpoint the SDK refuses longer paths of mapped routes, as without ASP.NET Core (below). Not seen by the SDK, so protect them yourself: code two handlers share (a lambda that calls another handler), and middleware that answers a request in place of the endpoint the router selected for it (the SDK judges that endpoint). A fallback (`MapFallback`, `MapFallbackToFile`) that reaches a mapped route only by its template (the route's own endpoint has a constraint, `{id:int}`, or there is none) serves your other pages, and is refused (400) for an unchecked path that continues a mapped route of the request's method (`DELETE /notes/7/archive/x`); a fallback that runs a protected handler is refused for every unchecked request. A CORS preflight that the router gives to a protected endpoint with CORS metadata reaches the CORS middleware with that metadata; the endpoint itself refuses it (400) should anything pass it on (no CORS middleware, a policy that does not resolve): its handler never runs for it. In a Startup-style or generic-host pipeline (`UseAllowedBy()` on a builder that is not a `WebApplication`), the SDK cannot tell which data sources share one matcher, so no endpoint of one data source hides a wider one of another: a catch-all of the app under a route's prefix (`Map("/notes/{**path}")` next to a protected action for `DELETE /notes/{id}/archive`) counts as that action's handler and its unchecked requests get a `400`. Give such pages endpoints of their own, or host on `WebApplication`. A short-circuited endpoint is known by the full name of ASP.NET Core's internal metadata (`Microsoft.AspNetCore.Routing.ShortCircuit.ShortCircuitMetadata`, .NET 8 and 10): the SDK's tests fail if a version of ASP.NET Core adds another. One added at runtime (a data source that changes its endpoints) makes every request a `400` while it is there. With a matcher policy that is not ASP.NET Core's own (API versioning, your own), no endpoint is taken to always win a route: wider endpoints of a mapped route count as its handlers. Endpoint routing is required (the default): with `MvcOptions.EnableEndpointRouting = false` the app does not start. ## The context Answer: `AllowedByContext` says who the agent is, for which person, at which level, under which grant. | Property | What | |---|---| | `HumanId` | The person's pairwise identifier for your service: stable for one person here, different at every other service. `null` on level-0 routes. Use it as the account key. | | `Level` | The level reached for this request: 0 to 3. | | `Agent` | The agent's identifier (its passport `sub`). | | `Operator` | Who runs the agent (the operator id from its passport). | | `Capabilities` | The capabilities of the grant used. | | `Display` | The words the person approved: `Summary`, `Lines`, `Lang`. | | `Gid`, `Rev`, `Jti` | The grant id, its revision (0, then +1 at each rebind) and the grant document's id. | | `ActingFor` | The organisation under a company mandate. Always `null` here: mandates are not supported yet. | | `Tenant` | The `{tenant}` path parameter, when the route has one. | | `Route` | The route that matched: method, path pattern, capability, class of this request, level. | | `Chain` | The delegation chain, leaf first: each grant's `Gid` and `Rev`. | | `HumanIssuer` | The person's home node. | | `LinkedAccount` | On a `requireLink` route: the account of yours the person linked ([Account linking](#account-linking)). Null elsewhere. | | `ProofJti`, `Run`, `Call` | The proof's id, and the agent's run id and call counter when it sent them (audit only). | ## Production Answer: set `KeyFile`, use `RedisStore` with several instances, keep the background refresh running, and read the `AllowedBy` log category. The `AllowedBy` log category names route templates, never a request's path, query or headers. ASP.NET Core's own request lines (`Microsoft.AspNetCore.Hosting.Diagnostics`, at `Information`) do log the full URL, which may hold personal data or tokens: the examples set `"Microsoft.AspNetCore": "Warning"` in their `appsettings.json`, and CI fails a run whose log repeats a request path. CI runs this app (`sdks/dotnet/examples/Production`) with Redis against a real node, agent and person: ```csharp using AllowedBy; using AllowedBy.AspNetCore; using AllowedBy.Redis; using StackExchange.Redis; using static AllowedBy.Routes; var builder = WebApplication.CreateBuilder(args); var config = builder.Configuration; if (string.IsNullOrEmpty(config["urls"])) // --urls or ASPNETCORE_URLS win { // loopback unless ALLOWEDBY_BIND says otherwise (the Dockerfile sets 0.0.0.0); an empty value counts as unset var bind = config["ALLOWEDBY_BIND"]; var port = config["PORT"]; builder.WebHost.UseUrls("http://" + (string.IsNullOrEmpty(bind) ? "127.0.0.1" : bind) + ":" + (string.IsNullOrEmpty(port) ? "8080" : port)); } // One Redis connection per process; every instance shares the replay set, single-use set and counters. builder.Services.AddSingleton(ConnectionMultiplexer.Connect(config["REDIS"] ?? "localhost:6379")); builder.Services.AddSingleton(sp => new RedisStore(sp.GetRequiredService())); builder.Services.AddAllowedBy(o => { o.Origin = config["ALLOWEDBY_ORIGIN"]!; // your public URL: construction fails, and says so, when it is missing o.Node = config["ALLOWEDBY_NODE"]!; o.Org = new AllowedByOrg { LegalName = "Notes Interop Ltd", Country = "FR", PrivacyPolicy = "https://notes.example/privacy" }; // The same keys on every instance and across restarts (created on first start, mode 0600). o.KeyFile = config["ALLOWEDBY_KEY_FILE"] ?? "/var/lib/notes/allowedby-keys.json"; o.Routes = [ Route("GET", "/me", level: 0), Route("GET", "/notes", "notes:read", resource: "note:*"), Route("POST", "/notes", "notes:write", cls: "write", resource: "note:new"), Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}"), Route("POST", "/invoices/{id}/pay", "invoices:pay", resource: "invoice:{id}", amountField: "/total", classByAmount: [new() { UpTo = "1000.00", Class = "write-hard" }, new() { Class = "irreversible" }], level: 2, authn: "hardware"), ]; o.Templates["notes:read"] = "Read your notes"; // English, for the summary and the line o.Templates["invoices:pay"] = new AllowedByTemplate { Summary = new Dictionary { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, Lines = new Dictionary { ["en"] = "Pay {scope}, up to {amount.max} {amount.currency}", ["fr"] = "Payer {scope}, jusqu'à {amount.max} {amount.currency}", }, }; o.Templates["notes:write"] = "Write new notes"; o.Templates["notes:delete"] = "Delete note {scope}"; }); var app = builder.Build(); app.UseAllowedBy(); app.MapPost("/invoices/{id}/pay", (string id, AllowedByContext ctx) => new { paid = id, by = ctx.HumanId, gid = ctx.Gid }); app.MapNotes(); // frameworks/minimal-api/NoteEndpoints.cs app.Run(); ``` - **Keys (`KeyFile`)**: a JSON file `{"signing": {"pem": ...}, "disclosure": {"pem": ...}}` (PKCS#8 PEM), the same format as the Python SDK's `key_file`: one file works in every SDK. Created on first start with mode 0600, atomically; when several instances start together, the first writer wins and the others read its keys (one atomic `link`, so the file system needs hard links; on one without, the first start fails and says so: create the file once elsewhere). Keep it on a volume or in your secret store; never in the image. Without it the keys are new at each start, and agents re-fetch `/.well-known/allowedby`. - **Store**: `MemoryStore` (the default) is for one process only: with several instances a replayed proof or a single-use grant could be accepted once per instance. `RedisStore` uses compare-and-set transactions; its keys share one hash tag (`{allowedby}:`), so it also works on Redis Cluster. Register any `IAllowedByStore` in DI, or set `o.Store`. A store error refuses the request (`503`, `Retry-After: 5`). - **Refunds** (sdks/CONTRACT.md, Refund on the SDK's own refusal): the check consumes a single-use approval and adds to the grant's `count` and `amount` totals. When the SDK then refuses that request itself before its endpoint starts (rule 5, a method or path changed after the check), it gives back exactly what the check spent, so the approval stays usable for its own route. A refund the store does not take leaves the approval spent (logged). Nothing is refunded once the endpoint started, nor when your own middleware or handler answers. - **Trust**: by default the node's key is trusted on first use and pinned (a changed key is refused and logged). For an OAID-5 signed trust list, set `o.TrustList` (the compact JWS) and `o.TrustListKey` (the public JWK of your key that signed it): anchors, pinned program lists, vouching and witnesses are then evaluated by the background refresh. - **Refresh**: `AddAllowedBy` runs the refresh as a hosted service every `RefreshSeconds` (1 to 60, default 5): node statement, status lists, trust list. Never on the request path. The host serves once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, one that scales to zero) answers its first request from a filled cache, not with `untrusted_node` or `503 status_stale` (sdks/CONTRACT.md §2 item 4); without ASP.NET Core, the first `CheckAsync` calls wait for the first refresh of `RunAsync` the same way, and never fetch anything themselves. Until a refresh succeeds, every agent request is refused (`untrusted_node`); a status list older than 60 s pauses write-hard and irreversible routes (`503 status_stale`), older than 3600 s pauses every route. - **Logging**: log category `AllowedBy`. Each checked request logs its outcome code (never tokens, keys or bodies); failures of the refresh log `[verifier] refresh failed: ...` at Warning. Alert on those. - **Origin and proxies**: `Origin` is your public origin. The SDK rebuilds each request's URL from `Origin` and the path as received (the raw request target), and ignores `Host` and `X-Forwarded-*`. A proxy must not rewrite the path. - **Clock**: `o.Clock` is a `TimeProvider`; every time check uses it (proofs from -120 s to +60 s, expiry, store deadlines). - **Listening**: the example listens on `ALLOWEDBY_BIND` (default `127.0.0.1`, loopback only) and `PORT` (default `8080`), unless `--urls` or `ASPNETCORE_URLS` names the addresses; an empty value counts as unset. The container sets `ALLOWEDBY_BIND=0.0.0.0`. Run it in a container (`sdks/dotnet/examples/Production/Dockerfile`): ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src COPY . . RUN dotnet publish sdks/dotnet/examples/Production -c Release -o /app FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app . ENV ALLOWEDBY_BIND=0.0.0.0 PORT=8080 ENTRYPOINT ["dotnet", "AllowedBy.Examples.Production.dll"] ``` ```bash docker build -f sdks/dotnet/examples/Production/Dockerfile -t notes . ``` ```bash docker run --rm --network host -e ALLOWEDBY_ORIGIN=http://localhost:8080 -e ALLOWEDBY_NODE=http://localhost:8700 notes ``` ## Agents Answer: there is no agent SDK for .NET; agents use the Python or TypeScript agent SDK, and any of them can call a .NET service. What your service needs from agents is in the protocol, not in a language: an agent passport, a grant and a proof on each request (see [`docs/sdk/python.md`](https://docs.allowedby.com/sdk/python) and [`docs/sdk/js.md`](https://docs.allowedby.com/sdk/js), section Agents). The interop test below drives the .NET example app with the Python reference agent. ## Errors Answer: every refusal is `application/problem+json` with `type: https://allowedby.org/errors/`; challenges also carry `WWW-Authenticate: AllowedBy ...`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request, or the body is not one JSON object, repeats a member name (even with another case), or is larger than `MaxBodyBytes`. | Send a JSON object body, each member once. | | `passport_required` | 401 | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. | | `invalid_signature` | 401 | Bad, expired or replayed proof; tampered grant or passport. | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match `Origin`). | | `untrusted_node` | 401 | The passport or grant comes from a node you do not trust, or the first refresh has not succeeded yet. | Check `Node` or your trust list, and the refresh log. | | `insufficient_witnesses` | 401 | The node's log is not witnessed by enough trusted nodes (trust list `witnesses_min`). | Check the trust list. | | `grant_required` | 401 | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. | | `grant_insufficient` | 401 | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. | | `level_insufficient` | 401 | The person's level is below the route's. | The person verifies their identity on the approval page. | | `qes_required` | 401 | A qualified signature is needed. | Not produced by this SDK (`Qes` routes are refused at construction). | | `mandate_required` | 401 | The approval was given for an organisation; this SDK checks no mandates. | The person approves for themselves. | | `authority_required` | 401 | The organisation's co-approvers are needed. | Not produced by this SDK (that route option is refused at construction). | | `expired`, `actor_expired` | 401 | The approval, or the agent's passport key, expired. | The agent rebinds or asks again. | | `not_yet_valid` | 401 | The approval starts later. | The agent retries later. | | `revoked` | 401 | The person withdrew the approval (or a parent grant in its chain). | The agent asks again. | | `single_use_consumed` | 401 | A one-time approval was already used. | Expected on retries of a serious action. | | `class_lifetime_exceeded` | 401 | The approval lasts longer than this class allows. | Lower the requested period. | | `capability_denied` | 403 | No such route. | Check the route map. | | `tier_insufficient` | 403 | The passkey or the agent's key custody is not of the required kind (`authn`, `tier`). | The person uses a hardware passkey, or the agent a stronger key custody. | | `human_not_linked` | 403 | The route needs a linked account (`requireLink`), and the person has not linked theirs, or linked another one. No challenge: no approval fixes it. | The person links their account: [Account linking](#account-linking). | | `budget_exceeded` | 403 | A tenant budget. | Not produced by this SDK. | | `rate_limited` | 429 | Too many requests from this agent or operator. `Retry-After: 60`. | The agent waits, then retries: [Rate limits](#rate-limits). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain over two grants (depth 1: a root and one child). | Usually a delegation chain too deep. | | `status_stale` | 503 | Your copy of the node's revocation list is too old, or the store failed; the action is paused. `Retry-After: 5`. | Check that your app reaches the node and the store; look for `[verifier] refresh failed` in your logs. | ## Testing Answer: `dotnet run --project sdks/dotnet/tests/AllowedBy.Vectors`, `dotnet test sdks/dotnet/tests/AllowedBy.Tests`, and `python sdks/interop/interop.py --cmd "..."` for the end-to-end test. The CONF-1 vectors (every case of the `verifier` profile, read from `vectors/` at run time): ```bash dotnet run --project sdks/dotnet/tests/AllowedBy.Vectors -c Release -f net10.0 -- vectors ``` It prints each failure and `N/N cases passed` (453/453), and exits 1 on any failure or any case it cannot run. Unit tests, real requests through the middleware (WebApplicationFactory) and the Redis store: ```bash docker run -d --name allowedby-redis -p 6379:6379 redis:7.4-alpine REDIS_URL=localhost:6379 dotnet test sdks/dotnet/tests/AllowedBy.Tests -c Release ``` On Windows (PowerShell): ```powershell docker run -d --name allowedby-redis -p 6379:6379 redis:7.4-alpine $env:REDIS_URL = "localhost:6379"; dotnet test sdks/dotnet/tests/AllowedBy.Tests -c Release ``` The interop test runs the example app against a real node, the reference agent and a person with a software passkey (26 scenarios: discovery, approval, standing grants, replay, tampering, forged grants, serious actions at level 2, single use, revocation, paths outside the map, concurrency): ```bash pip install -r requirements.txt dotnet build sdks/dotnet/examples/frameworks/minimal-api -c Release INTEROP_PORT_BASE=19500 python sdks/interop/interop.py --cmd "dotnet sdks/dotnet/examples/frameworks/minimal-api/bin/Release/net10.0/AllowedBy.Examples.MinimalApi.dll" ``` On Windows (PowerShell): ```powershell pip install -r requirements.txt dotnet build sdks/dotnet/examples/frameworks/minimal-api -c Release $env:INTEROP_PORT_BASE = "19500"; python sdks/interop/interop.py --cmd "dotnet sdks/dotnet/examples/frameworks/minimal-api/bin/Release/net10.0/AllowedBy.Examples.MinimalApi.dll" ``` To test your own app without a browser: refusals (discovery, `401` challenges, `400` bodies) need no node, so test them with `WebApplicationFactory` (see `sdks/dotnet/tests/AllowedBy.Tests/AspNetCoreTests.cs`). For accepted requests, use `sdks/interop/interop.py` as the model: it starts a node and plays the person with a software passkey (`demo/e2e.py`, `Human`), and the reference agent (`sdks/python/src/allowedby/agent.py`) calls your routes. ## Reference Answer: three public types do the work: `AllowedByOptions`, `AllowedByService` and `AllowedByContext`; the rest are their parts. Namespace `AllowedBy` (package `AllowedBy`): | Type | Members | |---|---| | `AllowedByOptions` | `Origin`, `Node`, `Org`, `Routes`, `Templates`, `KeyFile`, `Store`, `Unprotected`, `TrustList`, `TrustListKey`, `RefreshSeconds`, `NodeMaxLevel`, `Clock`, `Title`, `Version`, `Description`, `Rfc9421` (accept the RFC 9421 Web Bot Auth profile), `MaxBodyBytes`, `HttpClient`, `Log`, `LinkAuthorize`, `Nonce`, `Rate`. | | `AllowedByOrg` | `LegalName`, `Country`, `Website`, `Support`, `PrivacyPolicy`. | | `AllowedByRoute` | `Method`, `Path`, `Capability`, `Class`, `ClassByAmount`, `Level`, `Resource`, `AmountField`, `CurrencyField`, `Authn`, `Tier`, `MaxLifetime`, `LevelProfile`, `RequireLink`, `AccountParam`, `Nonce`, `Template`, `Summary`, `Body`; refused when set: `Mandate`, `Disclose`, `DiscloseOptional`, `Authority`, `Qes`. | | `AllowedByUnprotected` | `Method`, `Path`; a string converts to it. | | `AllowedByAmountClass` | `UpTo`, `Class`. | | `AllowedByTemplate` | `Text`, `Summary`, `Lines`; a string converts to it. | | `Routes` | `Route(method, path, capability, cls, level, resource, amountField, currencyField, authn, tier, maxLifetime, summary, body, classByAmount, levelProfile, qes, requireLink, accountParam, nonce)`. | | `AllowedByService` | `new AllowedByService(options)`, `Handle(method, path)`, `CheckAsync(request, ct)`, `LinkStart(account, ttl)`, `Unlink(account)`, `IsLinkRequest(method, path)` (the path as sent, still percent-encoded), `LinkAsync(request, ct)`, `InRouteMap(method, path)`, `IsUnprotected(method, path)`, `RouteMap`, `MustCheck(request)`, `RefreshAsync(ct)`, `RunAsync(stoppingToken)`, `Origin`, `SigningKeyId`, `Store`, `RefreshInterval`, `MaxBodyBytes`, `Dispose()`. | | `AllowedByRequest` | `new AllowedByRequest(method, path, query, headers, body, routePath, pathBase)`, `Header(name)`, `RoutePath`, `PathBase`. | | `AllowedByResult` | `Allowed`, `Context`, `Refusal`, `InRouteMap`. | | `AllowedByResponse` | `Status`, `Headers`, `Body`, `Code`. | | `AllowedByContext` | See "The context". | | `AllowedByDisplay`, `AllowedByRouteInfo`, `AllowedByChainLink` | Parts of the context. | | `IAllowedByStore` | `AddAsync(key, until, now)`, `GetAsync(key, now)`, `ChargeAsync(charges, now)`. | | `MemoryStore`, `AllowedByCharge` | The one-process store; one counter increment. | Namespace `AllowedBy.AspNetCore` (package `AllowedBy.AspNetCore`): `AddAllowedBy(Action)`, `AddAllowedBy(IConfiguration section, Action?)`, `UseAllowedBy()`, `HttpContext.GetAllowedBy()`, `[FromAllowedBy]`, `IAllowedByFeature`. Namespace `AllowedBy.Redis` (package `AllowedBy.Redis`): `new RedisStore(IConnectionMultiplexer, prefix = "{allowedby}:", database = -1)`. What is implemented, against `sdks/CONTRACT.md`: - **Core, all of it**: configuration with validation; the route map (classes, class by amount, levels, resources, amounts, authn, tier, lifetime); discovery (`/.well-known/allowedby` with the signed organisation profile and `Link` header, `/openapi.json`, `/.well-known/api-catalog`, byte-compatible with Python's `json.dumps` output); ABY-2 §5 steps 1-10 (proof JWT or RFC 9421, passports, grants and delegation chains, WebAuthn `human_sig` and batch approvals, `human.reg`, `initiator`, status lists with per-class freshness, lifetimes, ABY-3 constraints, request digest and single use, replay set, TOFU or OAID-5 trust lists with programs, vouching and witnesses, EdDSA and ES256 only); challenges with the service-initiated approval for write-hard and irreversible routes; background refresh; the context; `MemoryStore` and `RedisStore`; the key file; the ASP.NET Core middleware. - **Extended, implemented**: account linking (`LinkStart`, `/allowedby/link`, `requireLink` and `accountParam`; ABY-3 §6), AllowedBy-Nonce (`Nonce`; ABY-2 §3.2), level profiles (`levelProfile`; OAID-7 §5.3) and rate limits (`Rate`). Each passes its files of `vectors/ext/` (`profiles.json`, `features`) and its scenarios of `sdks/interop/ext/interop_ext.py`, and is mutation tested (`sdks/dotnet/tools/mutate.py`). - **Extended, not implemented** (the route options are refused at construction): the disclosure callback and JWE decryption (`/allowedby/callback`), tenants and tenant budgets, authority policies, company mandates, the audit sink and the admin console. The disclosure key is kept in the key file but not published. --- Source: https://docs.allowedby.com/sdk/php # AllowedBy PHP SDK guide The PHP service SDK lets AI agents call your API for a person, with that person's approval, and checks every request offline. The concepts (routes, classes, levels, the approval flow, the context) are explained once in [docs/deploy-saas.md](https://docs.allowedby.com/guides/accept-agents); this guide shows them in PHP. Every runnable example here is a file under `sdks/php/examples/` that CI runs or analyses, named above each snippet. Terms used below: a **node** issues agent passports and runs the approval page; a **grant** is the person's signed approval; a **proof** is the agent's signature over one request; **JWS** is a signed JSON token (RFC 7515); **TOFU** is trust on first use. ## Install The package needs PHP 8.2 or later and a shared store (APCu or Redis). It is not published yet: point Composer at a clone of this repository (`@dev` because there is no released version yet). ```bash composer config repositories.allowedby path ../allowedby/sdks/php composer require "allowedby/allowedby:@dev" ``` Or in `composer.json`: ```json { "repositories": [{"type": "path", "url": "../allowedby/sdks/php"}], "require": {"allowedby/allowedby": "@dev"} } ``` | Requirement | Why | |---|---| | PHP 8.2, 8.3 or 8.4 | readonly properties, named arguments; CI tests all three | | `ext-sodium` | Ed25519 signatures (bundled with PHP since 7.2) | | `ext-openssl` | ES256 (P-256) signatures, RSA passkeys, the disclosure key | | `ext-zlib` | status lists are zlib-compressed | | `ext-curl` (recommended) | outgoing calls bounded as a whole (`CurlHttpClient`, the default when loaded); without it, PHP's stream wrapper bounds each step of a call, not the call | | `ext-apcu`, or Redis through `ext-redis` (phpredis) or `predis/predis` | the shared store: PHP keeps nothing between requests, so the replay set and the node cache live there | Runtime dependencies are PSR interfaces only: `psr/http-message`, `psr/http-factory`, `psr/http-server-handler`, `psr/http-server-middleware` (the middleware) and `psr/log` (logging). Laravel and Symfony are not required; their adapters load only when you use them. Linux and macOS: ```bash sudo apt-get install -y php-apcu # Debian/Ubuntu; macOS: pecl install apcu php -m | grep -E 'sodium|openssl|zlib|apcu' ``` Windows (PowerShell): ```powershell php -m | Select-String -Pattern 'sodium|openssl|zlib|apcu' # APCu: download php_apcu.dll for your PHP build from PECL, then add "extension=apcu" to php.ini ``` Docker: ```dockerfile FROM php:8.4.14-cli RUN pecl install apcu-5.1.27 && docker-php-ext-enable apcu RUN echo "apc.enable_cli=1" >> /usr/local/etc/php/conf.d/docker-php-ext-apcu.ini COPY --from=composer:2 /usr/bin/composer /usr/bin/composer ``` ## Quick start `new AllowedBy(...)` with your origin, node, organisation, routes and templates, then `processGlobals()` on each request. From `examples/quickstart/app.php` (CI runs it as written): ```php 'Notes Ltd', 'country' => 'FR'], routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')], templates: ['notes:read' => 'Read your notes'], keyFile: __DIR__.'/allowedby-keys.json', // in production: outside the web root ); $decision = $aby->processGlobals(); if (null !== $decision->response) { $decision->response->send(); // discovery documents, refusals and challenges exit; } if (null === $decision->context) { // not a route of the map: nothing was checked, so nothing is served http_response_code(404); exit; } header('Content-Type: application/json'); echo json_encode(['notes' => [], 'person' => $decision->context->humanId]); ``` Run it (Linux, macOS and Windows alike): ```bash php -d apc.enable_cli=1 -S 127.0.0.1:8000 app.php curl -i http://localhost:8000/.well-known/allowedby curl -i http://localhost:8000/notes ``` The second call answers `401` with `WWW-Authenticate: AllowedBy realm="localhost:8000", error="passport_required"`. To see agents get through end to end, run the framework examples ([Testing](#testing)): each starts a real node, the app and the reference agent, and plays the person with a software passkey (approvals, a write-hard deletion at level 2, replay, revocation). To try a local node by hand, see the repository's [README](https://docs.allowedby.com/). The hosted demo node is `https://demo.allowedby.com`; use it as `node` when your app is reachable over https. ## Routes and templates `route(method, path, capability, class:, level:, resource:, ...)` describes one route; a template is the sentence the person signs. Arguments (the same as Python's `route()`, in PHP's naming): | Argument | Meaning | Default | |---|---|---| | `capability` | What the person allows, `namespace:action`. Leave it out (with `level: 0`) where the agent's passport is enough. | none | | `class` | `read`, `write`, `write-hard`, `irreversible`; or amount thresholds `[['up_to' => '1000.00', 'class' => 'write-hard'], ['class' => 'irreversible']]` read at `amountField`. For `write-hard` and `irreversible` the SDK creates the approval itself, bound to the exact request, used once. | `read` | | `level` | 0 agent only, 1 passkey, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. | `1` | | `resource` | The resource id, `{param}` from the path: `note:{id}`. | `:*` | | `amountField`, `currencyField` | JSON Pointers to the amount and currency in the body. Approvals then carry a limit per call, per day, week or month, or in total. | none, `/currency` | | `authn` | `hardware` refuses synced passkeys; `synced` refuses software ones. | any | | `tier` | Minimum custody tier of the agent's key (0-2). | `0` | | `maxLifetime` | Seconds an approval for this route may last, 60 s to 30 days. | the class's maximum | | `levelProfile` | `eu` or `na`, on level-3 routes (OAID-7 §5.3). | none | | `qes` | A qualified signature: this SDK has no EU trusted list, so such routes always answer `qes_required` (as the reference without one). | `false` | | `requireLink` | The person must have linked their AllowedBy identity to one of your accounts ([Account linking](#account-linking)); otherwise 403 `human_not_linked`. | `false` | | `accountParam` | The path parameter that names one of your accounts on a `requireLink` route: a person linked to another account is refused. | the service's, `account` | | `nonce` | The proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2); needs `nonce: true` on the service. | `false` | | `summary`, `body` | What the route does, and each JSON body member: they go into `/openapi.json`. | none | `mandate`, `disclose`, `discloseOptional` and `authority` belong to features this SDK does not have yet: passing one throws at construction (never accepted and ignored). From `examples/routes/routes.php` (CI runs it): ```php '1000.00', 'class' => 'write-hard'], ['class' => 'irreversible']], level: 2, amountField: '/total'), ]; $templates = ['notes:read' => 'Read your notes', 'notes:delete' => 'Delete note {scope}', 'pay:send' => 'Pay up to {amount.max} {amount.currency}']; $aby = new AllowedBy(origin: 'https://notes.example', node: 'https://node.example.org', org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'], routes: $routes, templates: $templates, store: new MemoryStore(), deferRefresh: true); // a check of the map: nothing fetched from the node echo count($routes), " routes, valid\n"; // $aby->routes also holds the SDK's own POST /allowedby/link ``` **The sentence the person signs** comes only from your templates (AMH-1 §4): the node fills `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}` and `{fields}` from the approval and shows it on the approval page; the grant carries it in `display`. A string is shorthand for English; give several languages as `['summary' => ['en' => ..., 'fr' => ...], 'lines' => ['en' => ..., 'fr' => ...]]`. Every capability of the route map needs a template: a missing one fails at construction. In a framework config file, a route is an array of the same arguments: `['method' => 'GET', 'path' => '/notes', 'capability' => 'notes:read', 'level' => 1]` or `['GET', '/notes', 'notes:read', 'level' => 1]`. ## Framework recipes One middleware or adapter per framework: the SDK's endpoints first, then the check on every route of the map, then your handler. Paths outside the map reach your app unchanged, without a context. Every example below is a complete app, the same notes API each time; CI runs each against a real node, agent and person, 26 of 26 interop scenarios (`examples/frameworks.json` lists them with their versions and servers). ### PSR-15 (Slim, Mezzio, any PSR-15 stack) Slim 4, from `examples/frameworks/slim/app.php` (run with PHP's server, under PHP-FPM and nginx, and under RoadRunner with the Redis store): ```php getBody()->write((string) json_encode($data)); return $response->withStatus($status)->withHeader('Content-Type', 'application/json'); }; $app = AppFactory::create(); $checked = new RequireContext(new ResponseFactory(), new StreamFactory()); // on every protected route $app->get('/health', fn (Request $request, Response $response) => $json($response, ['ok' => true])); $app->get('/me', function (Request $request, Response $response) use ($json) { $context = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE); return $json($response, ['agent' => $context->agent, 'operator' => $context->operator, 'level' => $context->level]); })->add($checked); $app->get('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0'); return $json($response, ['notes' => $notes->list($person)]); })->add($checked); $app->post('/notes', function (Request $request, Response $response) use ($json, $notes) { $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0'); $text = json_decode((string) $request->getBody(), true)['text'] ?? null; if (!is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) { return $json($response, ['error' => 'text: a string of 1 to 2000 characters'], 400); } return $json($response, ['id' => $notes->add($person, $text)['id']], 201); })->add($checked); $app->delete('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) { $person = $request->getAttribute(AllowedByMiddleware::ATTRIBUTE)->humanId ?? throw new LogicException('no person at level 0'); $notes->delete($person, $args['id']); return $json($response, ['deleted' => $args['id']]); })->add($checked); $aby = new AllowedBy( origin: (string) getenv('ALLOWEDBY_ORIGIN'), node: (string) getenv('ALLOWEDBY_NODE'), org: ['legal_name' => 'Notes Interop Ltd', 'country' => 'FR'], routes: [ route('GET', '/me', level: 0, summary: 'Who is calling'), route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*', summary: 'List your notes'), route('POST', '/notes', 'notes:write', class: 'write', level: 1, 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}'], keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'), // private store: null === $redis ? new ApcuStore() : new RedisStore($redis), title: 'Notes Interop API', refreshSeconds: (int) (getenv('ALLOWEDBY_REFRESH_SECONDS') ?: 5), ); $app->addErrorMiddleware(false, false, false); // 404 and 405 as responses $app->add(new AllowedByMiddleware($aby, new ResponseFactory(), new StreamFactory())); // added last: runs first return $app; ``` Mezzio 3: pipe the middleware before routing, as `examples/frameworks/mezzio/` does. ### Laravel 12 The package is auto-discovered. Publish the config, fill it, and the middleware runs on every request (`global`): ```bash php artisan vendor:publish --tag=allowedby-config ``` From `examples/frameworks/laravel/config/allowedby.php`: ```php env('ALLOWEDBY_ORIGIN'), 'node' => env('ALLOWEDBY_NODE'), 'org' => ['legal_name' => 'Notes Interop Ltd', 'country' => 'FR'], 'routes' => [ ['GET', '/me', 'level' => 0, 'summary' => 'Who is calling'], ['GET', '/notes', 'notes:read', 'level' => 1, 'resource' => 'note:*', 'summary' => 'List your notes'], ['POST', '/notes', 'notes:write', 'class' => 'write', 'level' => 1, 'resource' => 'note:new', 'summary' => 'Add a note', 'body' => ['text' => 'the note']], ['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}', ], 'key_file' => env('ALLOWEDBY_KEY_FILE', storage_path('app/allowedby-keys.json')), 'store' => env('ALLOWEDBY_STORE', 'apcu'), // "redis" on several servers 'redis_connection' => 'default', 'refresh_seconds' => (int) env('ALLOWEDBY_REFRESH_SECONDS', 5), 'title' => 'Notes Interop API', 'global' => true, ]; ``` The example serves `routes/api.php` without Laravel's `/api` prefix (`apiPrefix: ''` in `bootstrap/app.php`). With the default prefix, write `/api/notes` in the map: the map holds the paths the router matches. From `examples/frameworks/laravel/routes/api.php`: ```php allowedby() is the accepted context, null * outside the map. A protected handler refuses without one, so a route left off the map fails closed. */ use AllowedBy\AllowedBy; use AllowedBy\Context; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; // the SDK's own refusal (400 invalid_request), as everywhere else: not a challenge an agent would answer $refuse = static function (): never { $r = AllowedBy::notOnTheMap(); abort(response($r->body, $r->status, $r->headers)); }; $context = static fn (Request $request): Context => $request->allowedby() ?? $refuse(); Route::get('/health', static fn (): array => ['ok' => true]); Route::get('/me', static function (Request $request) use ($context): array { $context = $context($request); return ['agent' => $context->agent, 'operator' => $context->operator, 'level' => $context->level]; }); Route::get('/notes', static fn (Request $request, Notes $notes): array => [ 'notes' => $notes->list($context($request)->humanId ?? throw new LogicException('no person at level 0')), ]); Route::post('/notes', static function (Request $request, Notes $notes) use ($context): JsonResponse { $text = $request->json('text'); if (!is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) { return response()->json(['error' => 'text: a string of 1 to 2000 characters'], 400); } return response()->json(['id' => $notes->add($context($request)->humanId ?? throw new LogicException('no person at level 0'), $text)['id']], 201); }); Route::delete('/notes/{id}', static function (Request $request, Notes $notes, string $id) use ($context): array { $notes->delete($context($request)->humanId ?? throw new LogicException('no person at level 0'), $id); return ['deleted' => $id]; }); ``` With `'global' => false`, add the middleware alias yourself: `Route::middleware('allowedby')->group(...)`. The routes of the map must then all be inside that group; the discovery documents are served only on the paths the middleware covers. ### Symfony 7 and 8 Register `AllowedBy\Symfony\AllowedByBundle` in `config/bundles.php`, then configure it. `ALLOWEDBY_REFRESH_SECONDS` has a default in the example's `framework.yaml` (`env(ALLOWEDBY_REFRESH_SECONDS): '5'`); without it, set the variable or write a number. From `examples/frameworks/symfony/config/packages/allowedby.yaml`: ```yaml # config/packages/allowedby.yaml of the notes API (bundle: AllowedBy\Symfony\AllowedByBundle) allowedby: origin: '%env(ALLOWEDBY_ORIGIN)%' node: '%env(ALLOWEDBY_NODE)%' org: { legal_name: Notes Interop Ltd, country: FR } routes: - { method: GET, path: /me, level: 0, summary: Who is calling } - { method: GET, path: /notes, capability: 'notes:read', level: 1, resource: 'note:*', summary: List your notes } - { method: POST, path: /notes, capability: 'notes:write', class: write, level: 1, resource: 'note:new', summary: Add a note, body: { text: the note } } - { method: DELETE, path: '/notes/{id}', capability: '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} key_file: '%env(ALLOWEDBY_KEY_FILE)%' # private, outside public/ store: apcu # or the id of a service implementing AllowedBy\Store\Store (a RedisStore) refresh_seconds: '%env(int:ALLOWEDBY_REFRESH_SECONDS)%' title: Notes Interop API ``` From `examples/frameworks/symfony/src/Controller/NotesController.php`: ```php true]); } #[Route('/me', methods: ['GET'])] public function me(#[AllowedByContext] Context $ctx): JsonResponse { return new JsonResponse(['agent' => $ctx->agent, 'operator' => $ctx->operator, 'level' => $ctx->level]); } #[Route('/notes', methods: ['GET'])] public function list(#[AllowedByContext] Context $ctx): JsonResponse { return new JsonResponse(['notes' => $this->notes->list($ctx->humanId ?? throw new \LogicException('no person at level 0'))]); } #[Route('/notes', methods: ['POST'])] public function add(#[AllowedByContext] Context $ctx, Request $request): JsonResponse { $text = json_decode($request->getContent(), true)['text'] ?? null; if (!\is_string($text) || 1 !== preg_match('/\A.{1,2000}\z/su', $text)) { return new JsonResponse(['error' => 'text: a string of 1 to 2000 characters'], 400); } return new JsonResponse(['id' => $this->notes->add($ctx->humanId ?? throw new \LogicException('no person at level 0'), $text)['id']], 201); } #[Route('/notes/{id}', methods: ['DELETE'])] public function delete(#[AllowedByContext] Context $ctx, string $id): JsonResponse { $this->notes->delete($ctx->humanId ?? throw new \LogicException('no person at level 0'), $id); return new JsonResponse(['deleted' => $id]); } } ``` The bundle's subscriber runs on `kernel.request` before the router (priority 256). A controller argument typed `Context` or marked `#[AllowedByContext]` receives the context; a non-nullable one on a request without a context is refused with 403, so a handler never runs unchecked. ### Plain PHP `$aby->processGlobals()` reads `$_SERVER` and `php://input`; `$decision->response->send()` answers. `context` is null outside the route map: nothing was checked there, so serve only your own public paths. There is no router: dispatch on `$context->route`, and take the path's values from `$context->params`, never from `$_SERVER['REQUEST_URI']`: the example's `case 'DELETE /notes/{id}':` deletes `$context->params['id']`, the id the SDK checked. See [Quick start](#quick-start) and `examples/frameworks/plain/`. ## The context An accepted request on the route map carries an `AllowedBy\Context`, read-only: | Field | Type | Meaning | |---|---|---| | `agent` | string | The agent: its passport's `sub` (`did:oaid:...`). | | `operator` | string | Who runs the agent: its verified domain, or a node-scoped id. | | `humanId` | ?string | The person's pairwise id for your origin: stable, different at every service. Null at level 0. | | `level` | int | 0 agent only, 1 passkey, 2 verified identity, 3 eIDAS high: the lowest of the grant, the registration and the node's cap. | | `capabilities` | list | The grant's capabilities. | | `display` | ?array | What the person approved: `summary`, `lines`, `lang`. | | `gid`, `rev`, `jti` | ?string, ?int, ?string | The grant's id, revision and document id. | | `chain` | list | `[{gid, rev}]`, leaf first, for delegated (sub-agent) grants. | | `route` | string | The route of the map that matched, `"DELETE /notes/{id}"`. | | `params` | array | The route's path values as the SDK checked them: each `{name}` of the template, from the normalised path, percent-decoded once (`/t/acme%20co` gives `['tenant' => 'acme co']`; `%2520` gives `%20`). Bytes that are not UTF-8 (`%FF`) give U+FFFD. Empty for a route without parameters. Act on these, never on your own reading of the raw path, which can differ (`/t/%61cme%2a` is checked as `/t/acme%2A`, and gives `acme*`; dot segments are refused). | | `proofJti`, `run`, `call` | ?string, ?string, ?int | The proof's id and the agent's own run and call ids, for your audit log. | | `humanIss` | ?string | The person's home node. | | `linkedAccount` | ?string | On a `requireLink` route, the account the person is linked to (the one the path names, when it names one); null on other routes. Act for this account only. | | `actingFor`, `tenant` | null | Company mandates and tenants are not supported by this SDK yet. | Where to read it: `$decision->context` (plain PHP), the request attribute `allowedby.context` (PSR-15), `$request->allowedby()` (Laravel), a `Context` controller argument (Symfony). ## Production Use a key file, a shared store, https, and refresh the node cache on a timer if your traffic has quiet periods. **Keys (`keyFile`).** The signing key signs your organisation profile and the approvals your service asks for; the grant then records its `kid` as `initiator`, so it must stay the same across requests and servers. `keyFile` is created on first use with mode 0600, atomically (the first writer wins), in the same JSON format as Python's `load_keys`: one file serves every SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `keyFile` at it, or write it from your secret manager. An existing file works anywhere. Keep it outside the web root, back it up, share it between servers (a secret manager mounted as a file). `keyFile` is required, except with a `MemoryStore` (tests, one process), where a key is created for the process's lifetime. **Shared store.** PHP shares nothing between requests, so the replay set, single-use consumption, counters and the node cache must be shared: | Store | When | Notes | |---|---|---| | `new ApcuStore()` | one machine (PHP-FPM, `php -S` with workers: both run in CI) | the default when APCu is enabled; size `apc.shm_size` (about 300 bytes per request kept 300 s); it refuses writes when nearly full rather than let APCu wipe the replay set | | `new RedisStore($redis)` | several machines | phpredis `\Redis` or `Predis\Client`; set `maxmemory-policy noeviction` | | `new MemoryStore()` | tests, single-process long-running servers | only when you pass it: several workers would each keep their own replay set, so it is never a default | Without `store`, the SDK uses `ApcuStore` when APCu is enabled and otherwise fails at construction. A store error refuses the request with `503 status_stale` and `Retry-After` (fail closed). **Refunds** (CONTRACT §2 item 10, ABY-2 §5 step 9). The check spends the approval: a single-use grant's mark and its `count` and `amount` totals. When the SDK itself then refuses that accepted request before its handler starts, it gives back exactly what the request spent, once, from a receipt the check kept, so the approval serves the request on its own route afterwards. That covers the route guard of Laravel (`RouteMatched`, and the `allowedby` route middleware), Symfony's listener after the router, and PSR-15's `RequireContext`: the handler guard of rule 5 and a method or path changed after the check. It also covers the account-linking endpoint's refusals after the approval (a code already used, links full or busy, no person). Nothing is refunded once the handler was reached, for a refusal of your own (a handler, a middleware or a listener that answers), or when the endpoint may have linked (a store failure while the link was written). A refunded request never reaches a handler, even dispatched again. A refund the store does not take leaves the approval spent, and is logged without request data. A store refunds with `Charge`s of negative increments and no `max`, applied exactly, so a counter may read below 0 (`Store::charge`). Adapters call `$aby->release($context)` and `$aby->started($context)`; an app does not need to. **Refresh.** Node statements and status lists are fetched in the background, never on the request path (ARCH-1). PHP has no background thread, so the SDK refreshes lazily: a request that finds the cache older than `refreshSeconds` (default 5, at most 60) schedules a refresh after its response (a shutdown function; Symfony and Laravel flush the response first with `fastcgi_finish_request()`). One process at a time refreshes, under a lock in the store; all others keep serving from the cached copy. Only an empty cache is filled inline, once. The trade-off against a background thread (CONTRACT §2.6): after a quiet period the first request sees an old status list. That stays safe, since lists carry their own time and a list older than its class allows is refused (`status_stale`, 60 s for write-hard and irreversible, 3600 s otherwise), but serious routes then answer 503 once. To avoid it, call `$aby->refresh()` on a timer: a console command run by cron every minute (or every few seconds from a loop) that builds your `AllowedBy` the way your app does and calls `refresh()`; it writes to the same shared store. In long-running workers (Octane, RoadRunner, Swoole, FrankenPHP), where shutdown functions do not run per request, the refresh is inline under the lock; that is automatic on the `cli` and `frankenphp` SAPIs, and `deferRefresh` (`defer_refresh` in Laravel and Symfony) forces either mode. CI runs PHP's server with workers, PHP-FPM with nginx, and RoadRunner; Octane, Swoole and FrankenPHP are not run. **Startup (a cold cache, CONTRACT §2 item 4).** A service that starts cold (a new instance, one that scales to zero, an emptied store) must hold node statements and status lists before its first request, without fetching at request time (ARCH-1 §4). What that means depends on how PHP runs: | Mode | What the SDK does at start | What you do | |---|---|---| | Long-running worker (the `cli` SAPI: RoadRunner, Octane, Swoole; or a FrankenPHP worker script, `FRANKENPHP_WORKER`) | `new AllowedBy(...)` runs the first refresh before it returns: over, done or failed, within `AllowedBy::STARTUP_WAIT` (5 s: with ext-curl each fetch, from connecting to its last byte, gets what is left of it; without it, PHP's stream wrapper bounds connecting and each read of the headers separately, so a node that drips its headers can hold the start longer). A cache another process refreshed less than `refreshSeconds` ago is used as it is; while another worker holds the refresh lock, it serves a stale copy at once, and waits for that worker's copy only when the cache is empty, so workers that start cold together fetch once. A node that does not answer delays the start by at most 5 s, and the worker then serves from what it has (fail closed); a refresh cut short there never replaces a complete cached copy, and a first fill cut short stays stale, so the next refresh completes it. | Build the SDK when the worker starts, before its request loop, as `slim/worker.php` does through `app.php`. Laravel Octane: list `AllowedBy\AllowedBy::class` in `config/octane.php` `warm`. A framework that builds its services on the first request (Symfony's runtime in worker mode) builds the SDK then, and that request waits. | | PHP-FPM, Apache `mod_php`, PHP's server, FrankenPHP's classic mode | Nothing: every request builds the SDK, so there is no start to wait at, and no request waits for another one's refresh. | Fill the cache before traffic: run your refresh command (the cron job above) once in the deploy, after the store is up and before the instance takes requests. With `RedisStore` it fills the cache every instance reads. (That command runs on the `cli` SAPI, where building the SDK refreshes a stale cache: build it there with `deferRefresh: true`, since `refresh()` fetches anyway.) | What is left of a cold start. With `ApcuStore` under PHP-FPM no step before traffic can fill the cache: APCu memory belongs to the FPM master, and a CLI process (`php refresh.php`) has its own. The first request after an FPM restart then fills the empty cache inline, under the lock, and requests that arrive while it does are refused (`untrusted_node`, fail closed). That fill, and the inline refresh of a long-running worker whose request finds the cache stale (above), are the fetches at request time this SDK keeps, since PHP has no thread to move them to; use Redis when cold starts are frequent (a service that scales to zero). In tests, pass `deferRefresh: true` (`defer_refresh: true` in Laravel and Symfony), so that building the SDK on the `cli` SAPI does not fetch from the node. **Trust.** By default the SDK trusts the one `node` you configure, pinning its key on first use (TOFU); a changed key is refused and logged. For several nodes, programs and vouching, pass a signed OAID-5 trust list: `trustList: TrustList::load('/etc/allowedby/trust.jwt', $yourPublicJwk)`. **Logging.** Pass a PSR-3 `logger:`. It gets one `info` line per checked request (`[host] GET /notes -> accepted`) and a `warning` on each failed refresh (`[verifier] refresh failed: ...`). Without one, warnings go to `error_log()`. No token, key or body is ever logged. **Several instances** need the same `keyFile`, the same Redis store, and the same `origin` (what agents sign). Behind a proxy the SDK ignores `Forwarded` and `X-Forwarded-*`: the URL is always built from `origin`. **Path and method variants (CONTRACT §2.10).** Routers decode the path before matching, and some apply method overrides, so a variant could reach a protected handler around the route map. The SDK refuses with 400 a request that could: dot segments (percent-encoded or not), an encoded `/` or `\` (`%2F`, `%5C`), a doubled `/`, or an encoded spelling whose decoded path is a route of the map; and, on a path of the map, `X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, a `_method` query parameter, or (PSR-15) a `_method` form field. Other requests pass unchanged. Under Laravel and Symfony the method checked is the one the router dispatches (`getMethod()`). A trailing `/` is the same route (checked). Neither adds format suffixes (`/notes.json`) unless your routes declare `{_format}`: list such paths in the route map. **Base paths and wide patterns.** The proof is checked against the full path the agent signed; routes are matched on the path your router sees, so the map never holds the prefix the app is served under: such a map is refused with 400. Laravel and Symfony give the prefix; plain PHP uses `PATH_INFO` when the server sets it; with PSR-15, give the prefix your router strips (Slim's `setBasePath`) as the middleware's `basePath`. A router can send a path that is not on the map to a protected handler (`{id:.*}` takes `/notes/7/x`). Laravel and Symfony see the route the router chose: when it is a route of the map (same template and method, whatever the patterns) and the request was not checked for it, the answer is 400. A handler for several methods counts for each of them, and the handler of a mapped route is refused under any other route (`/notes/{id}/archive/{rest}` with `where('rest', '.*')` next to a mapped `/notes/{id}/archive`). PSR-15 and plain PHP do not see it, so in the mapped method they refuse a path that matches a template when a parameter takes several segments, or a format suffix (`/notes.json`). `/notes/7` is served when only `/notes` is mapped. List your own such pages, which the log also names: `unprotected: ['/notes.json', ['GET', '/notes/{id}/comments']]` (in the configuration of Laravel and Symfony too). An entry is exact, or a template of whole-segment parameters with a literal segment, which names its method when a mapped route could reach it; one that overlaps the map, or that a router may read as another path, fails at construction. Laravel and Symfony never let an entry run the handler of a mapped route. Under PSR-15, also put `RequireContext` on protected routes: it covers a pattern that leaves a segment out (`/notes[/{id}]`). Under PSR-15 and plain PHP, a wide route after a protected route that ends in a literal (`/notes/{id}/archive/{rest:.*}` running the handler of `/notes/{id}/archive`) is not refused: the SDK cannot see the handler, so do not give such a route the handler of a protected one, or put `RequireContext` on it. Control characters in a protected path are refused everywhere. Catch-alls (CONTRACT §2.10 rule 5). Laravel and Symfony also ask the router which rule it picks for sample paths of each mapped route (`/notes/1`, `/notes/a`, `/notes/`), and refuse a handler of a mapped route in any method, OPTIONS included (an OPTIONS request Laravel answers itself, with no rule of yours, runs no code of yours and is served). A handler that also serves the sample path with one of its words replaced is a catch-all: site-wide when the router picks it for the path with its first word replaced through a rule that takes the whole path (`Route::fallback()`, `/{any}` with `where('any', '.*')`, `/{path<.+>}`), under the route's prefix otherwise (`/notes/{id}/{rest}`). A route's own handler is known from a rule of its shape, or from a handler a sample reaches that is no catch-all. Once it is known, a site-wide catch-all keeps serving your other pages and one under the prefix stays protected; a request checked for the route that the router sends through either is refused. While it is not known, every request near the route is refused unless checked, and a catch-all found for it is protected; when one catch-all is its only handler (a front controller), a request checked for the route runs it only if the route covers every other route that catch-all is protected for (same capability, resource and amount fields, a level, tier and class at least theirs, a grant no longer, every option they require), and the log says `route X is served only by a site-wide catch-all` when the map is built. One handler (a closure, or a controller method) for two mapped routes, the same path in two methods (`Route::match(['GET', 'POST'], ...)`, `methods: ['GET', 'POST']`) or two paths (`DELETE /notes/{id}` and `DELETE /items/{id}`), runs only for a request checked for a route that covers the other; otherwise the answer is 400, "map both at the same capability and level, or give each its own handler", and the log names the pair when the map is built. Separate closures or controller methods are not affected. Nothing is learnt from requests (PHP keeps nothing between them): give each mapped route its own rule. A site-wide catch-all that dispatches actions itself, on paths no route maps (`/{any}` reading `?action=delete`), is not seen: map those actions, or give them rules of their own. Under PSR-15, `RequireContext` reads the route Slim (`__route__`) or Mezzio (`RouteResult`) chose, and refuses a request checked for a route of another shape, so on a catch-all it runs for no checked request; a router it cannot read is the limit above. After acceptance. The SDK records the method and the normalised path an accepted request was checked for. A rewrite rule or a method override placed after it that moves the request (`GET /me` to `GET /health`, or to `HEAD /me`) would run a handler on values the person never approved, so the request is refused with 400 before any handler runs. The path is never repeated in the refusal. Laravel checks it when the router picks the route, Symfony once its router has run, and PSR-15 in `RequireContext`. Another spelling of the same path (`/%6De` for `/me`) is the same request, and so is a Mezzio pipeline that only took its prefix off the path (`pipe('/api', ...)`: `/me` for `/api/me`), when you declare that prefix (`AllowedByMiddleware`'s base path counts; another one: `new RequireContext($responses, $streams, ['/api'])`). Nothing on the request shows which middleware took a prefix off, so an undeclared one is refused as a move. The limits: under PSR-15 without `RequireContext` nothing sees the request after the SDK. Plain PHP has no router after the SDK, and your code dispatches on `$context->route` and `$context->params`, so do not rewrite the request there. A Symfony listener that runs after the router (priority below 16) is not seen either. ## Agents The PHP SDK is a service SDK only. To build an agent, use the Python or TypeScript agent SDK ([docs/sdk/python.md](https://docs.allowedby.com/sdk/python), [docs/sdk/js.md](https://docs.allowedby.com/sdk/js)); they work against any service, PHP included. ## Errors Every refusal is `application/problem+json` (RFC 9457) with `type` `https://allowedby.org/errors/`. Codes and statuses are the same in every SDK (ABY-2 §6): | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed headers, a body that is not a JSON object on a route of the map, or a typ mix. | Fix the request. | | `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and retries. | | `invalid_signature` | 401 | A signature, proof, chain link or WebAuthn check failed, or the proof was replayed. | Never retried as is; the agent signs a new proof. | | `untrusted_node` | 401 | Signed by a node this service does not trust (or the node cache is empty). | Check `node` / the trust list; wait for the first refresh. | | `insufficient_witnesses` | 401 | The node's log is not cosigned by enough trusted witnesses. | The node operator fixes its witnesses. | | `grant_required` | 401 | A person's approval is needed: the challenge says what to ask for. | The agent asks the person (service-initiated: the `approve` link). | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, single-use digest, initiator). | Ask for a wider approval. | | `level_insufficient` | 401 | The person's identity level is too low. | The person verifies their identity on the node. | | `qes_required` | 401 | The route needs a qualified signature. | Not available with this SDK. | | `authority_required` | 401 | Co-approvers are needed. | Not used by this SDK. | | `mandate_required` | 401 | A company mandate is needed, or the grant acts for a company. | Not supported by this SDK. | | `expired` | 401 | The grant has expired. | Ask again. | | `not_yet_valid` | 401 | The grant's `nbf` is in the future. | Check clocks. | | `revoked` | 401 | The person withdrew the approval (status list). | Ask again. | | `actor_expired` | 401 | The agent's key expired; the problem says `rebind: true`. | The agent rebinds its grant (ABY-2 §9). | | `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. | | `capability_denied` | 403 | Not allowed here (no such route for credentials). | Nothing to retry. | | `tier_insufficient` | 403 | The agent's key custody or the passkey class is too weak. | Use a stronger key or passkey. | | `human_not_linked` | 403 | The person is not linked to the account the route names (`requireLink`). | Link the account ([Account linking](#account-linking)). | | `budget_exceeded` | 403 | A budget is used up. | Not used by this SDK. | | `rate_limited` | 429 | Too many calls from this agent or its operator (see Rate limits); `Retry-After` is set. | Retry after a minute. | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (depth 1: a root and one child, ABY-2 §2). | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old; `Retry-After` is set. | Retry after a few seconds. | A shared store that cannot answer is also `status_stale` (503, `Retry-After: 5`): the request is refused, never let through. A body over 1 MiB on a route of the map is `invalid_request` with 413. ## Testing `php tests/run-vectors.php` runs the 453 CONF-1 vectors; `vendor/bin/phpunit` the unit and framework tests; the framework examples run against a real node. ```bash cd sdks/php composer install php tests/run-vectors.php # 453/453 cases passed vendor/bin/phpunit vendor/bin/phpstan analyse && vendor/bin/php-cs-fixer check ``` The framework examples against a real node (Linux and macOS: PHP's built-in server has no workers on Windows, use WSL there), from the repository root. `frameworks.py` without a name runs all of them; that also needs nginx, PHP-FPM, RoadRunner and Redis: ```bash pip install -r requirements.txt python sdks/php/examples/frameworks.py plain ``` **Testing your own app without a browser.** In unit tests, give the SDK a fixed clock and a `MemoryStore`, and send it requests signed like the vectors do: `tests/Support/Fixture.php` builds a service from `vectors/service.json` and replays signed requests from the vector files (a passport on `GET /me`, a grant on a comment route). Your handlers then receive a real `Context`. For an end-to-end test, run your app against the local node and the reference agent as the interop test does: the harness plays the person with a software passkey. ## Reference Namespace `AllowedBy`. Classes marked internal are not part of the public API. | Name | What | |---|---| | `route(string $method, string $path, ?string $capability = null, string\|array $class = 'read', int $level = 1, ?string $resource = null, ?string $amountField = null, string $currencyField = '/currency', ?string $authn = null, int $tier = 0, ?int $maxLifetime = null, ?string $summary = null, ?array $body = null, ?string $levelProfile = null, bool $qes = false): Route` | One line of the route map. | | `Route::fromArray(array $a): Route` | The same from a config array (positional `method, path, capability` allowed). | | `new AllowedBy(origin, node, org, routes, templates, keyFile?, store?, trustList?, refreshSeconds = 5, nodeMaxLevel = 3, clock?, title?, version = '1.0.0', description?, rfc9421 = false, http?, logger?, deferRefresh?, signingKey?)` | The SDK. Throws `InvalidArgumentException` on bad configuration. | | `AllowedBy::process(method, path, headers, body = '', query = ''): Decision` | Discovery, then the check: what adapters call. | | `AllowedBy::processGlobals(): Decision` | `process()` from `$_SERVER` and `php://input`. | | `AllowedBy::check(...)`, `AllowedBy::handle(method, path): ?Response` | The check alone; the discovery endpoints alone. | | `AllowedBy::refresh(): void` | Fetch node statements and status lists now. | | `AllowedBy::wellKnown()`, `openapi()`, `apiCatalog()`, `orgProfile()`, `publicKey()` | The published documents. | | `Decision` | `?Context $context`, `?Response $response`, `allowed(): bool`. | | `Response` | `int $status`, `array $headers`, `string $body`, `send()`, `code()`, `data()`. | | `Context` | [The context](#the-context). | | `Reject` | A refusal inside the verifier: `error` (the code), `status`, `why`. `Reject::STATUS` maps codes to statuses. | | `Config::build(array $config): AllowedBy` | The SDK from a snake_case config array (Laravel, Symfony). | | `KeyFile::load(string $path)` | Read or create the key file. | | `SigningKey` | `generate()`, `fromSeed()`, `fromPem()`, `toPem()`, `kid()`, `jwk()`. | | `Store\Store` | `add`, `get`, `charge` (with `Store\Charge`), `fetch`, `save`, `lock`, `unlock`. | | `Store\MemoryStore`, `Store\ApcuStore`, `Store\RedisStore` | The stores ([Production](#production)). `Store\StoreException` on failure. | | `Trust\TrustList` | `new TrustList($jws, $serviceJwk)`, `TrustList::load($path, $serviceJwk)` (OAID-5). | | `Http\HttpClient`, `Http\CurlHttpClient`, `Http\StreamHttpClient` | Outgoing calls (refresh, approvals): curl when it is loaded, the stream wrapper otherwise; replace for a proxy. | | `Psr15\AllowedByMiddleware` | PSR-15 middleware; attribute `allowedby.context`. | | `Laravel\AllowedByServiceProvider`, `Laravel\Middleware` | Laravel package; alias `allowedby`; `$request->allowedby()`. | | `Symfony\AllowedByBundle`, `Symfony\AllowedByContext`, `Symfony\RequestSubscriber`, `Symfony\ContextValueResolver` | Symfony bundle. | | `Verifier`, `Trust\*` (except `TrustList`), `Internal\*` | Internal. | ## Account linking ABY-3 §6: a person links their AllowedBy identity (their home node and their pairwise id for your origin) to one of your own accounts, and a `requireLink` route then accepts them for that account only. 1. Your signed-in account page asks for a code and shows it: `$code = $aby->linkStart($accountId)` (valid 600 s, or `linkStart($accountId, $ttl)`, up to 30 days; single use; a 192-bit random nonce, sealed). 2. The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves this route itself (capability `aby:link`, write, level 1): don't map it. An unknown, used, revoked or expired code is refused with 400 `invalid_request` before anything is asked of the person. Otherwise the SDK asks for a single-use approval of `aby:link` (it creates the approval, as for write-hard), and once it is given it links the person to the code's account and answers `{"linked": true}`. 3. Using a code revokes the account's other pending codes, and linking an account again moves it to the new person. A link names both the home node and the pairwise id: the same id from another node is another person. Routes: `route('GET', '/accounts/{account}/notes', 'notes:read', resource: 'account:{account}', requireLink: true)` refuses a person who is not linked, or who is linked to another account than `{account}` (403 `human_not_linked`). Name the parameter with `accountParam` on the route, or once for the service (`new AllowedBy(..., accountParam: 'acct')`, `account_param` in the Laravel and Symfony configuration). Approvals the SDK creates for a linked account name the person (`human_hint`, `human_home`). A route whose path names no account (`/documents/{id}`) checks only that the person is linked. The context's `linkedAccount` says to which account: act for that account only, for instance by loading the document only when that account owns it. Alternatively, decide in the SDK with `new AllowedBy(..., linkAuthorize: fn (string $account, Route $route, array $params): bool => $documents->ownedBy($params['id'], $account))`, which receives the decoded path values. When it returns anything other than `true`, or throws, the request is refused with 403 `human_not_linked` before your handler runs. In the Laravel configuration, `link_authorize` is an invokable class (resolved from the container); in Symfony's, the id of such a service. `max_links` sets `maxLinks` in both. A code is sealed (XSalsa20-Poly1305 with a 192-bit random nonce) with a key of its own, derived from your signing key by HKDF-SHA256 (RFC 5869, info `allowedby/link/v1`; the key file every server shares), so nothing is kept per code. Links and each account's epoch (a random token that using a code replaces, under the store's lock) live in the store, shared by your servers as the replay set is: APCu on one machine, Redis across several. A store that loses them (a restart, a flush, an eviction) never revives a code: the account's next epoch is new and random, so codes issued before are unknown, and links must be made again. Pending codes are bounded: past 10 000 issued in the last ten to twenty minutes, `linkStart` throws (a `RuntimeException`) rather than revoke a code someone holds. Links are bounded too: at `maxLinks` linked accounts (`new AllowedBy(..., maxLinks: 100000)`, the default), linking another account is refused with 400 `invalid_request` before any approval is asked for. No one's link is evicted, and the code stays pending. Each account has one person and each person one account: linking an account again removes the previous person's entry, and a person who links another account unlinks the old one. `$aby->unlink($accountId)` removes an account's link when you delete the account or the person asks to be forgotten: the stored pair, its place under `maxLinks` and the account's pending codes (false when it was not linked; an empty account throws, as for `linkStart`). Every change of the links is journaled, so a store failure partway is completed by the next one and never leaves a wrong count. Under Laravel the global middleware (the default) serves `POST /allowedby/link`; under Symfony and PSR-15 the SDK answers it before the router runs. A tested app: `examples/interop_ext/`. ## AllowedBy-Nonce ABY-2 §3.2: with `new AllowedBy(..., nonce: true)` (`nonce` in the Laravel and Symfony configuration), every `irreversible` route, and every route with `nonce: true`, refuses a proof without a current nonce of the service with `401 invalid_signature` and a fresh nonce in its `AllowedBy-Nonce` header; the agent retries once with it. A route with `nonce: true` while the service has nonces off throws at construction. With the RFC 9421 proof, the nonce is the request's `AllowedBy-Nonce` header, covered by the signature; a covered value that is not base64url is refused (401). A nonce is stateless: base64url(`t` ‖ HMAC-SHA256(key, `t`)[0:16]), `t` its issue time in seconds (8 bytes, big endian), current for 300 s from its issue. The key is HKDF-SHA256 of your signing key (RFC 5869: the 32-byte Ed25519 seed, no salt, info `allowedby/nonce/v1`), used for nothing else, so every server that shares the key file takes the others' nonces, and a restart keeps them current. Nothing is stored per nonce: a nonce is single use through the proof's own replay set (its `jti`), as every proof is. ## Level profiles OAID-7 §5.3: a level-3 route with `levelProfile: 'eu'` or `'na'` accepts only a person whose registration's `level_source.profile` is that profile, and refuses any other, or none, with `401 level_insufficient`. A level-3 route without `levelProfile` accepts any level-3 registration. `levelProfile` on a route below level 3 throws at construction. ## Rate limits Every call is counted, per agent (the passport's `sub`) and per operator (`operator.id`), in a sliding window on the SDK's clock: a call at `t` sees those at `x` with `t - x < seconds`. The defaults are 600 calls a minute per agent and 6000 per operator; set them with `new AllowedBy(..., rate: ['actor' => [20, 60], 'operator' => [1000, 60]])` (`rate` in the Laravel and Symfony configuration), either or both. Any other key, or a value that is not two positive integers, throws at construction: a misspelt limit would leave the default in place. A call over either limit is refused with `429 rate_limited` and `Retry-After: 60`. A call counts once its proof is verified and is no replay, whatever is decided after it (a call later refused as `grant_required` counts); a call refused by the limit counts for neither limit. The counts live in the store, shared by your servers as the replay set is: one small document per agent and per operator (its calls per second over the last window), changed under the store's locks, so both limits are checked and counted as one step. The store drops it a window after its last call (`ExpiringStore`, which `ApcuStore`, `RedisStore` and `MemoryStore` implement; a store of your own that does not keeps it until it is replaced). A store failure refuses the call (`503 status_stale`). --- Source: https://docs.allowedby.com/sdk/ruby # AllowedBy Ruby SDK The `allowedby` gem lets AI agents call your Ruby app on behalf of a person who approved them with a passkey tap. It publishes your discovery documents, verifies every agent request offline (ABY-2: the AllowedBy HTTP verification), answers with a challenge when an approval is missing, and creates the approval itself for serious actions. It is the Ruby port of the Python reference (`sdks/python/src/allowedby/sdk.py`) and follows `sdks/CONTRACT.md`. The concepts (routes, classes, levels, the approval flow) are explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents). Terms used below: a **node** issues agent passports and records the person's approvals; a **grant** is a person's signed approval; a **proof** is the agent's signature over one request; **JWS** is a signed JSON document (RFC 7515); **JCS** is canonical JSON (RFC 8785). ## Install Add the gem with Bundler; it needs Ruby 3.2 or later and one gem, `tzinfo` (time zones), which a Rails app has already. The gem is not on RubyGems yet, so Bundler takes it from the repository (the repository is private: Bundler needs your GitHub credentials, `bundle config set --global github.com :`). ```bash bundle add allowedby --git https://github.com/yannUpTo/allowedby --glob "sdks/ruby/*.gemspec" ``` The same command works in PowerShell on Windows. Or write the line in your Gemfile, as in `examples/Gemfile.app`: ```ruby # frozen_string_literal: true # Your application's Gemfile (docs/sdk/ruby.md, "Install"). The gem is not on RubyGems yet: Bundler takes it from # the repository. source "https://rubygems.org" gem "allowedby", git: "https://github.com/yannUpTo/allowedby", glob: "sdks/ruby/*.gemspec" gem "puma" # any Rack server gem "rackup" # the rackup command for config.ru gem "tzinfo-data", platforms: %i[windows jruby] # time zones where the system has none (tzinfo, a dependency) ``` | | | |---|---| | Ruby | CRuby 3.2 and 3.3 (tested in CI); the gem uses no gem that later Rubies unbundle (`base64`, `bigdecimal`, `logger`). | | Runtime dependencies | `tzinfo` 2 (the IANA time zones of tenant budgets: a budget per day in `Europe/Paris`, across its clock changes; the standard library has no zone database), which nearly every Ruby app has through Rails. It reads the system's zoneinfo; on Windows, which has none, add `tzinfo-data` (as `examples/Gemfile.app` does). `openssl` (Ed25519, P-256, ECDH, AES-GCM), `json`, `net/http`, `zlib`, `securerandom` come with Ruby. OpenSSL 1.1.1 or later is needed for Ed25519. | | Optional | `redis` (redis-rb 5) for `AllowedBy::RedisStore`; `rails` for the Railtie. You bring them; the gem does not depend on them. | | Development | Exact versions in `sdks/ruby/Gemfile` (minitest, rack, rack-test, rubocop, puma, webrick, rackup, railties, actionpack, sinatra, redis). | ## Quick start A Rack app that accepts agents is one `AllowedBy.new` call and one `use AllowedBy::Middleware` line. ```ruby # frozen_string_literal: true require "allowedby" require "json" aby = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN", "http://localhost:9292"), # the URL agents call node: ENV.fetch("ALLOWEDBY_NODE", "http://localhost"), # the AllowedBy node you trust org: { legal_name: "Notes Ltd", country: "FR" }, routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*"), AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new")], templates: { "notes:read" => "Read your notes", "notes:write" => "Write new notes" } ) notes = Hash.new { |h, k| h[k] = [] } use AllowedBy::Middleware, aby run(lambda do |env| ctx = env["allowedby.context"] # nil outside the route map, else: human_id, level, agent, operator... return [404, { "content-type" => "text/plain" }, ["not found\n"]] if ctx.nil? # no person (a level-0 route): refused, never a store keyed by nil person = ctx.human_id or return [403, { "content-type" => "text/plain" }, ["no person: this route needs one\n"]] notes[person] << JSON.parse(env["rack.input"].read)["text"] if env["REQUEST_METHOD"] == "POST" [200, { "content-type" => "application/json" }, [JSON.generate({ "notes" => notes[person] })]] end) ``` Run it against the local node from a clone of the repository. On Linux and macOS: ```bash python demo/run.py --reset # terminal 1: the local node, http://localhost (port 80) cd sdks/ruby && bundle install && bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru # terminal 2 python sdks/ruby/examples/agent_call.py # terminal 3, from the repository root ``` On Windows (PowerShell), the same commands, one per terminal: ```powershell python demo/run.py --reset cd sdks/ruby; bundle install; bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru python sdks/ruby/examples/agent_call.py ``` With Docker instead of a local Ruby: terminal 2 becomes this command (the container uses the host's network, so it reaches the node on `http://localhost`; Docker Desktop 4.34 or later has host networking as a setting): ```bash docker run --rm -it --network host -v "$PWD:/repo" -w /repo/sdks/ruby ruby:3.3 \ sh -c "bundle install && bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru" ``` The agent (the Python reference agent, `examples/agent_call.py`) prints an approval link and a code. Open the link, check the code, tap your passkey; the agent retries and gets `200`, then reads the notes after a second approval: ```python """Call the Ruby quick start (examples/quickstart.ru) as an AllowedBy agent, with the Python reference agent. Start the local node (python demo/run.py --reset), then the app (bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru), then, from the repository root: python sdks/ruby/examples/agent_call.py The agent prints the approval link and its code: open the link, check the code, tap your passkey. """ import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "python", "src")) from allowedby.agent import Agent # noqa: E402 APP = os.environ.get("APP_URL", "http://localhost:9292") agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=print) print(agent.call("POST", APP + "/notes", {"text": "Buy milk"}, action="notes:write")) print(agent.call("GET", APP + "/notes", action="notes:read")) ``` The hosted node (`https://demo.allowedby.com`) approves only for its own demo sites; use the local node for your app. ## Routes and templates Each protected route is one `AllowedBy.route(method, path, capability, **options)` line; anything not in the map reaches your app unchanged. `AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2, resource: "note:{id}")` reads: deleting a note needs the person's approval for this exact request, at identity level 2, on the resource `note:`. | Option | Values | Meaning | |---|---|---| | `capability` | `"resource:action"` | What the person approves (ABY-3). Required from level 1; a level-0 route has none (it needs no grant, ABY-3 §4.1), and `AllowedBy.route` refuses one there. | | `class:` (or `cls:`) | `read`, `write`, `write-hard`, `irreversible`; or amount thresholds `[{up_to: "1000.00", class: "write-hard"}, {class: "irreversible"}]` | How long an approval lasts (30 days, 7 days, 1 day, 1 hour). `write-hard` and `irreversible`: the service asks for every request itself, approved once for that exact request. | | `level:` | 0, 1, 2, 3 (default 1) | 0: the agent's passport is enough, no person. 1: a passkey tap. 2: verified identity (eIDAS substantial). 3: eIDAS high on a hardware passkey. | | `resource:` | `"note:{id}"` (default `":*"`) | The resource, with `{params}` from the path. A grant's `scope` must cover it. | | `amount_field:`, `currency_field:` | JSON Pointers, e.g. `"/total"`, `"/currency"` (default) | The amount the approval caps; a request above the cap is refused. | | `authn:` | `synced`, `hardware` | Only these passkeys count. | | `tier:` | 0-3 (default 0) | The agent key's custody tier (OAID-6). | | `max_lifetime:` | 60 s to 30 days | A shorter limit than the class's. | | `level_profile:` | `eu`, `na` (level 3 only) | The level-3 identity profile (OAID-7 §5.3). | | `summary:`, `body:` | text; `{member: "description"}` | How the route is described to agents in `/openapi.json`. | | `require_link:` | `true`, `false` (default) | The person must have linked their identity to one of your accounts (ABY-3 §6): see [Account linking](#account-linking). `403 human_not_linked` otherwise. | | `account_param:` | a path parameter (default `"account"`) | With `require_link`: the parameter that names one of your accounts; the person must be linked to that one. | | `nonce:` | `true`, `false` (default) | The proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2): see [AllowedBy-Nonce](#allowedby-nonce). Needs `nonce: true` on `AllowedBy.new`. | Options the Python SDK has and this SDK does not enforce yet (`mandate`, `disclose`, `disclose_optional`, `authority`, `qes`) raise `AllowedBy::ConfigError` naming the option: accepting them without enforcing them would let requests through that should be refused. **The sentence the person signs.** `templates:` gives one sentence per capability: `{"notes:delete" => "Delete note {scope}"}`, or every language: `{"notes:delete" => {"summary" => {"en" => "...", "fr" => "..."}, "lines" => {"en" => "...", "fr" => "..."}}}`. Placeholders are the grant's constraints: `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`, `{fields}`. The person's node renders the approval page from these templates only (AMH-1 §4), so the person reads your words, not the agent's. Every capability of the route map needs a template: the SDK refuses to start without one. ## Framework recipes Every Rack framework takes the same middleware; Rails also gets a Railtie, a controller helper and a generator. Each app below is the interop app in that framework, and CI runs all 26 interop scenarios against it on Puma and on WEBrick (`examples/frameworks.json` lists the runs and the exact versions). Other Rack 3 frameworks take the same `use` line, but CI does not run them. **Rack** (`config.ru`): `use AllowedBy::Middleware, service`. The middleware serves `/.well-known/allowedby`, `/openapi.json` and `/.well-known/api-catalog`, checks every route of the map, and puts the accepted context in `env["allowedby.context"]`. It reads the body of a mapped route once (at most 1 MiB, `max_body:`) and gives it back to the app intact; other paths are not touched. A mounted app checks `PATH_INFO` against the route map, which names the paths the app sees, without the prefix; proofs are over the public URL (`SCRIPT_NAME + PATH_INFO`). `use` the middleware inside the `map` block: there, a route map that names the prefix is refused (`400`). Around the block the SDK cannot see the mount: write the map with the prefix there. A request target whose path holds a byte that is not plain (a raw non-ASCII byte, a space, a quote, a control character, a backslash) is refused (`400 invalid_request`) before routing, on every path. Paths are matched after RFC 3986 normalisation (percent-encoding, dot segments), and the app then routes on that same path. A variant that a lenient router would send to a protected action is refused with `400 invalid_request`, never handed to the app unchecked: a trailing or doubled `/`, a suffix (`/notes.json`, `/notes.a-b`, `/notes;a`), dot segments (`/x/../notes`), encoded separators (`/notes%2F7`), control characters, another letter case of the method. For the same reason the last path parameter of a protected route cannot contain a dot followed by text (`/notes/7.json` is refused: Rails would run it as note 7 while the person approved "7.json"). A path that a mapped template would match if one or more of its parameters took several segments (`/notes/7/x` for `/notes/{id}`), for a method the map uses there, is refused (`400`) too: a glob or a splat would run the protected action. In Rails, and in a Sinatra app that registers the guard and is the next app after the middleware, the router's choice decides instead. `/notes/7` when only `/notes` is mapped is your app's. `unprotected:` names your own pages of those kinds, for every method or one: `unprotected: ["/notes.csv", ["GET", "/notes/{id}/photo"]]`. An exact path lifts every rule for that very path; a template of whole-segment parameters lifts the one for longer paths. An entry that overlaps a route of the map, differs from one by a last `/` only (`/notes/new/`: the router may drop it) or holds `;`, `%` or a dot segment fails at start; each one is logged at start, and a refusal names the option. A request on a path with another protected verb is refused the same way when `X-HTTP-Method-Override`, `X-HTTP-Method` or `X-Method-Override` names that verb, when its query contains `_method`, or when it is a `POST` whose form contains `_method` or is over `max_body:`. A plain Rack app does its own routing, which the SDK cannot see: match paths exactly and run nothing for a nil context, as the app below. **Changed after the check.** A step after the middleware (a rewrite of `PATH_INFO`, `Rack::MethodOverride`, a mount that rewrites the path) could move an accepted request to another path or method: its handler would then act on values the person never approved. The Rails and Sinatra guards compare the method and the whole path (`SCRIPT_NAME + PATH_INFO`, normalised as the check) that reach the handler with those that were checked, and refuse a request that changed (`400 invalid_request`, the path not repeated), whatever handler the router chose; Rails' own error page for a checked request (`exceptions_app`) still answers. In Sinatra this holds for a `before` filter of your own too, as Sinatra routes after its filters. Not covered: a plain Rack app (the SDK cannot see its routing) and a controller without the Railtie's guard (`ActionController::Metal`). Put nothing that changes the method or the path after the middleware there, and read the values from `context.params`. **Refunds** (CONTRACT 1.10, ABY-2 §5 step 9). The check spends what an accepted request costs, atomically: the mark of a single-use approval, the grant's `count` and `amount` totals. When the SDK itself then refuses that request before its handler starts (the Rails or Sinatra guard: rule 5 below, a method or path changed after the check; the link endpoint, when it cannot link an accepted request), it gives back exactly what the check charged for it, once, from a receipt the check kept: the approval can be used again for a request its route serves. A refund the store does not take (the store down) leaves the approval spent, and the log says so without request data. Nothing is given back once the handler started (an action or a block that refuses the request itself), for an answer of the app's own (a middleware in front of the router), or in a plain Rack app, where the SDK cannot see a handler start. An accepted request is started or given back, never both: one given back never reaches a handler, even when a layer dispatches it again. An adapter of your own does the same with `service.release(context)` and `service.started(context)`, and calls `service.forget(context)` once it has the app's answer (see Reference); the middleware forgets each request itself, and the Rails and Sinatra guards release and start it. The whole app (`examples/frameworks/rack/config.ru`): ```ruby # frozen_string_literal: true # A plain Rack app behind AllowedBy (docs/sdk/ruby.md, "Rack"). # # bundle exec puma -b tcp://127.0.0.1:9292 config.ru # or: bundle exec rackup -s webrick -o 127.0.0.1 config.ru require "allowedby" require "json" aby = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call node: ENV.fetch("ALLOWEDBY_NODE"), # the AllowedBy node you trust org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"), AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new", summary: "Add a note", body: { text: "the note" }), AllowedBy.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}" }, title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5")) ) notes = Hash.new { |people, person| people[person] = [] } lock = Mutex.new last_id = 0 use AllowedBy::Middleware, aby run(lambda do |env| request = Rack::Request.new(env) context = env["allowedby.context"] # nil on a path outside the route map if context&.level&.positive? # a route of a person: refused without one (403), never a store keyed by nil person = context.human_id or return [403, { "content-type" => "text/plain" }, ["no person: this route needs one\n"]] end status, body = lock.synchronize do case [request.request_method, request.path_info] in ["GET", "/health"] then [200, { ok: true }] in ["GET", "/me"] if context [200, { agent: context.agent, operator: context.operator, level: context.level }] in ["GET", "/notes"] if person then [200, { notes: notes[person] }] in ["POST", "/notes"] if person # a route of the map runs for a checked request only raw = request.body.read.to_s text = JSON.parse(raw.empty? ? "{}" : raw)["text"] if text.is_a?(String) && text.length.between?(1, 2000) id = (last_id += 1).to_s notes[person] << { id: id, text: text } [201, { id: id }] else [400, { error: "text: a string of 1 to 2000 characters" }] end in ["DELETE", %r{\A/notes/[^/]+\z}] if person id = context.params["id"] # the value checked, never a reading of the raw path notes[person].reject! { |note| note[:id] == id } [200, { deleted: id }] else [404, { error: "not found" }] end end [status, { "content-type" => "application/json" }, [JSON.generate(body)]] end) ``` **Rails.** `bin/rails generate allowedby:install` writes `config/initializers/allowedby.rb`. Setting `config.allowedby.service` adds the middleware; controllers call `allowedby_context`. Add `before_action :require_allowedby!` to the controllers of protected routes: an action reached without the middleware's check answers `400` instead of running. A nested route of your own (`/notes/{id}/comments`) needs nothing: the middleware asks the Rails router, and refuses a longer path only when it goes to a protected action or to what the Railtie does not cover (an engine, a Rack endpoint). The Railtie does the same for every action that the Rails router gives a mapped path to (another route to it, a mount); an action that also serves an unchecked path on purpose opts out with `skip_before_action :refuse_unchecked_allowedby_action` (which also lifts the handler checks below for that action), and declare protected routes with `format: false`. Both guards (Rails and Sinatra) follow CONTRACT §2.10 rule 5. A request checked for one route of the map never runs another route's handler (an alias on its path, a glob, a longer pattern), whatever the method: a `GET` that reaches the action of a protected `POST` is refused (`400`). An action that the app's router gives several routes of the map (a Rails action on two verbs or two paths, a Sinatra block given to both) runs for a request checked for one of them only when that route covers every other (needs at least as much): a level-1 `DELETE /items/{id}` never runs the action of a level-2 `DELETE /notes/{id}`. The service says so at start. Whatever makes an action a route's own, a checked request never runs one that is protected as a catch-all for another route it does not cover. A catch-all (an action that also serves a route's path with one of its words replaced) is never learnt. Next to the route's own action, a checked request that reaches it is refused (`400`), unless the rule Rails or Sinatra matched has the route's own shape; while it is the only action found for the route (a front controller), a checked request runs it when its route needs at least what every other route the front controller is protected for needs (a route whose own action is not known and that the front controller serves, or one it is a catch-all under the prefix of: a level-1 route never runs a level-3 route's front controller), and unchecked requests near the route are still refused. A catch-all under a route's prefix (`notes/:id/*rest`) is protected: it can only be another action of that route. A fallback the router chose through a site-wide wildcard (`*path`, a Sinatra `/*`) is protected only while a route it serves has no known action of its own (it may be that route's action; the service says so at start). Once the route's own action is known (a rule of its shape, a sample, a checked request), the fallback is not protected for it and keeps serving every other page. 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. An action that no sample reaches and no rule of the route's shape names serves only the value it was called with (`/notes/export` next to `/notes/{id}`): a checked request that reaches it is refused, and it is never learnt. An action is learnt from a checked request only when the rule that matched has the route's own shape, and only when that route needs at least what every other route, of any method, with an unknown action needs. When no action of the app serves a route of the map, an unchecked request near it (on its path or a longer one, of any method) is refused: the SDK cannot tell what runs there. `unprotected:` never lifts this. The startup warnings (a route served only by a site-wide catch-all, one handler for two methods) are logged when a guard builds its map of handlers: at start in Rails with eager loading (production), otherwise at the first request the guard sees (Sinatra, and Rails in development). A controller without the Railtie's guard (`ActionController::Metal`) and a plain Rack app are not covered: the middleware's own rules apply there. From the app in `examples/frameworks/rails`, the initializer: ```ruby # frozen_string_literal: true Rails.application.config.allowedby.service = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call node: ENV.fetch("ALLOWEDBY_NODE"), # the AllowedBy node you trust org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"), AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new", summary: "Add a note", body: { text: "the note" }), AllowedBy.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}" }, title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5")) ) ``` The routes: ```ruby # frozen_string_literal: true Rails.application.routes.draw do get "health", to: "health#show" # outside the AllowedBy route map: your app's own path get "me", to: "me#show" # format: false: /notes.json is not another way in (the middleware also refuses such variants) resources :notes, only: %i[index create destroy], format: false not_found = ->(_env) { [404, { "content-type" => "application/json" }, ['{"error":"not found"}']] } match "*path", via: :all, to: not_found end ``` The controller of the protected routes: ```ruby # frozen_string_literal: true class NotesController < ActionController::API # Second line of defence: an action of a protected route never runs without the middleware's check. before_action :require_allowedby! # No person (a level-0 route): refused, never a store keyed by nil. class NoPerson < StandardError; end rescue_from(NoPerson) { render json: { error: "no person: this route needs one" }, status: :forbidden } def index render json: { notes: Note.of(person) } end def create note = Note.add(person, params[:text]) if note render json: { id: note[:id] }, status: :created else render json: { error: "text: a string of 1 to 2000 characters" }, status: :bad_request end end def destroy Note.delete(person, params[:id]) render json: { deleted: params[:id] } end private # The person the request is for. def person allowedby_context.human_id or raise NoPerson end end ``` **Sinatra** (`examples/frameworks/sinatra/notes_app.rb`, run by its `config.ru`). `require "allowedby/sinatra"`, `set :allowedby, service` (or a class method, as here) and `register AllowedBy::SinatraGuard` add a second line: the handler of a mapped route never runs unchecked. Register the guard before any `before` filter of your own: a filter declared earlier runs without its check. ```ruby # frozen_string_literal: true # A modular Sinatra app behind AllowedBy (docs/sdk/ruby.md, "Sinatra"), served by config.ru. require "sinatra/base" require "allowedby/sinatra" require "json" class NotesApp < Sinatra::Base class << self attr_writer :allowedby # tests put their own here def allowedby @allowedby ||= AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call node: ENV.fetch("ALLOWEDBY_NODE"), # the AllowedBy node you trust org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"), AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new", summary: "Add a note", body: { text: "the note" }), AllowedBy.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}" }, title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5")) ) end end set :lock, true # the notes are in memory: one request at a time set(:notes, Hash.new { |people, person| people[person] = [] }) set :last_id, 0 use AllowedBy::Middleware, -> { NotesApp.allowedby } register AllowedBy::SinatraGuard # the handler of a mapped route never runs unchecked helpers do # The notes of the person the request is for; a route without one (level 0) is refused, never keyed by nil. def mine person = allowedby_context.human_id or halt 403, JSON.generate({ error: "no person: this route needs one" }) settings.notes[person] end end before { content_type :json } get "/health" do JSON.generate({ ok: true }) end get "/me" do JSON.generate({ agent: allowedby_context.agent, operator: allowedby_context.operator, level: allowedby_context.level }) end get "/notes" do JSON.generate({ notes: mine }) end post "/notes" do raw = request.body.read.to_s text = JSON.parse(raw.empty? ? "{}" : raw)["text"] unless text.is_a?(String) && text.length.between?(1, 2000) halt 400, JSON.generate({ error: "text: a string of 1 to 2000 characters" }) end id = (settings.last_id += 1).to_s mine << { id: id, text: text } status 201 JSON.generate({ id: id }) end delete "/notes/:id" do mine.reject! { |note| note[:id] == params["id"] } JSON.generate({ deleted: params["id"] }) end not_found { JSON.generate({ error: "not found" }) } end ``` **Puma and WEBrick.** The SDK is thread-safe: one service per process, shared by every thread. In Puma's cluster mode the refresh thread is started again in each worker on its first request, which does not wait for it: a service built before the fork (`preload_app!`) gives each worker its cache, one built in each worker waits for its first refresh there. Serve any of the apps above with `bundle exec puma -b tcp://127.0.0.1:9292 config.ru` or `bundle exec rackup -s webrick -o 127.0.0.1 config.ru`, from its folder. Name the address: Puma otherwise listens on every interface (`0.0.0.0`), as rackup does outside development, and `localhost` can be `::1` on Windows. In a container without host networking, bind `0.0.0.0`. ## The context The handler of an accepted request receives an `AllowedBy::Context`, a frozen value object. | Field | Type | What | |---|---|---| | `human_id` | String or nil | The person's pairwise id at your service (the same person, the same id, every time; another id at another service). nil on a level-0 route. | | `level` | Integer | The effective level: the lowest of the grant's, the person's registration's and the nodes' maximum. | | `agent` | String | The agent (its passport `sub`). | | `operator` | String | Who runs the agent (a verified domain, or a node-scoped id). | | `capabilities` | Array of String | The capabilities of the grant. | | `display` | Hash or nil | What the person read and signed: `{"summary", "lines", "lang"}`. | | `gid`, `rev`, `jti` | String, Integer, String | The grant (leaf of the chain), its revision, its document id. | | `chain` | Array | `[[gid, rev], ...]`, leaf first (a sub-agent's chain has two). | | `human_iss` | String | The person's home node. | | `proof_jti`, `run`, `call` | String, String or nil, Integer or nil | The request proof's id and the agent's own audit ids (ABY-2 §5 step 10). | | `route` | Hash | The route of the map that matched. | | `params` | Hash of String to String | The route's path values as checked (CONTRACT §2 item 7): each `{name}` of the route's template, from the normalised path, decoded once (`/t/acme%20co` gives `"acme co"`, `%2520` gives `"%20"`). Frozen; empty when the route has no parameter. Act on these values, never on your own reading of the raw path, which can differ (`DELETE /notes/7/.` is checked as `/notes/7`). | | `tenant` | String or nil | The route's `{tenant}` value, as in `params`; nil when the route has none. | | `acting_for` | nil | An extended feature (company mandates) this SDK does not implement. | | `linked_account` | String or nil | On a `require_link` route, the account the person is linked to (see Account linking), also when the path names none; nil on other routes. | ## Production Keep the keys in a file, share the replay state between instances, and check that your app reaches the node. ```ruby # frozen_string_literal: true # A production configuration (docs/sdk/ruby.md, "Production"): the keys kept across restarts and shared by every # instance, the replay and single-use state in Redis, your logger. Build it once per process (after the fork in # Puma cluster mode; the SDK restarts its refresh thread itself if you build it before). require "allowedby" require "logger" require "redis" module NotesProduction def self.allowedby(env = ENV) log = Logger.new($stderr) AllowedBy.new( origin: env.fetch("ALLOWEDBY_ORIGIN"), # https://notes.example.com, exactly as agents call it node: env.fetch("ALLOWEDBY_NODE"), # the node you trust, e.g. https://node.example.org org: { legal_name: "Notes Ltd", country: "FR", website: "https://notes.example.com", privacy_policy: "https://notes.example.com/privacy" }, routes: [ AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"), AllowedBy.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:delete" => "Delete note {scope}" }, key_file: env.fetch("ALLOWEDBY_KEY_FILE", "/var/lib/notes/allowedby-keys.json"), # a volume, mode 0600 store: AllowedBy::RedisStore.new(Redis.new(url: env.fetch("REDIS_URL"))), # shared by instances refresh_seconds: 5, logger: ->(message) { log.warn(message) } # "[verifier] refresh failed: ..." when the node is unreachable ) end end ``` - **Keys** (`key_file:`). The signing key (Ed25519) signs your organisation profile and your approval requests; the disclosure key (P-256) is kept for the SDKs that receive personal data, not published by this one. The file is created on first use, atomically, mode 0600, first writer wins, in the Python SDK's format (`{"signing": {"pem"}, "disclosure": {"pem"}}`), so one file works in every SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `key_file` at it, or write it from your secret manager. An existing file works anywhere. Without `key_file` the keys are new at every start: agents must fetch your discovery document again. Keep the file out of git and in a volume shared by your instances. - **Store** (`store:`). Replayed proofs, single-use approvals and counters live in a store. `MemoryStore` (the default) is for one process only: with several processes or machines, an instance that has not seen a proof accepts its replay. Use `AllowedBy::RedisStore.new(Redis.new(url: ...))`. A store that cannot answer refuses the request (`503 status_stale`, `Retry-After: 5`), never accepts it. - **Trust** (`node:` or `trust_list:`). By default the SDK trusts one node and pins its key on first fetch. For a signed list of nodes (OAID-5: anchors, programs, vouching, witnesses), pass `trust_list: AllowedBy::TrustList.load("trust.jws", your_public_jwk)`. - **Refresh** (`refresh_seconds:`, default 5, at most 60). A background thread fetches the node's statement and status lists; no request waits on the network, except the approval a serious route creates. `AllowedBy.new` returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, one that scales to zero) holds them before its first request. With no fresh list (older than 60 s for `write-hard` and `irreversible`, 3600 s otherwise) requests are refused with `503 status_stale` (fail closed). - **Logging** (`logger:`, any `#call(message)`, default standard error). `[verifier] refresh failed: ` on every failed refresh; one line per checked request with its outcome code. Tokens, keys and bodies are never logged. - **Origin.** `origin:` is the public URL agents call (scheme, host, port). Behind a proxy, it is the proxy's public URL: the SDK ignores `Host` and `X-Forwarded-*` headers. - **Several instances.** One `key_file` and one `RedisStore` for all; each instance refreshes on its own. ## Agents This is a service SDK: there is no agent SDK in Ruby yet; agents use the Python or TypeScript agent SDK (see `examples/agent_call.py` in the quick start). ## Errors Every refusal is `application/problem+json` (RFC 9457) with `type: https://allowedby.org/errors/`, the same codes and statuses in every AllowedBy SDK; a `401` that an approval can fix carries `WWW-Authenticate: AllowedBy`. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed request, or the body of a mapped route is not a JSON object. | Send a JSON object body. | | `passport_required` | 401 | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. | | `grant_required` | 401 | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. | | `grant_insufficient` | 401 | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. | | `level_insufficient` | 401 | The person's level is below the route's. | The person verifies their identity on the approval page. | | `mandate_required` | 401 | The route needs a company mandate, or the mandate does not cover this. This SDK accepts no mandate: a grant acting for a company is refused. | The person approves for themselves. | | `expired`, `actor_expired` | 401 | The approval, or the agent's key, expired. | The agent rebinds or asks again. | | `not_yet_valid` | 401 | The approval starts in the future. | Check the clocks. | | `revoked` | 401 | The person withdrew the approval. | The agent asks again. | | `single_use_consumed` | 401 | A one-time approval was already used. | Expected on retries of a serious action. | | `class_lifetime_exceeded` | 401 | The approval lasts longer than this class allows. | Lower the requested period. | | `invalid_signature` | 401 | Bad, expired or replayed proof; tampered grant; no current AllowedBy-Nonce where the route needs one (the answer's `AllowedBy-Nonce` header holds a fresh one). | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match `origin`). | | `untrusted_node` | 401 | The approval comes from a node you do not trust, or none is trusted yet. | Check `node:` or your trust list, and that the first refresh succeeded. | | `insufficient_witnesses` | 401 | The trust list asks for witnessed node logs and this node's is not. | Check `witnesses_min` in your trust list. | | `qes_required`, `authority_required` | 401 | A qualified signature, or the organisation's co-approvers, are needed. | Not available in this SDK. | | `budget_exceeded` | 403 | A tenant budget is used up, or the request has no amount in its currency. Refused before any approval is asked. | Wait for the next period, or raise the budget ([Tenants and tenant budgets](#tenants-and-tenant-budgets)). | | `capability_denied` | 403 | No such route, or the account refuses this operator or amount. | Check the route map. | | `tier_insufficient` | 403 | The passkey or the agent's key custody is not of the required kind (e.g. `authn: "hardware"`). | The person uses a hardware passkey, or the agent a stronger key custody. | | `human_not_linked` | 403 | The route needs a linked account (`require_link`), and the person has not linked theirs, or linked another one than the path names. | The person links their account: [Account linking](#account-linking). | | `rate_limited` | 429 | Too many requests from this agent or operator. `Retry-After: 60`. | The agent slows down; raise `rate:` if the limits are too low for your API ([Rate limits](#rate-limits)). | | `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (deeper than 1, ABY-2 §2). | A sub-agent delegates only from a root grant: one level. | | `status_stale` | 503 | Your copy of the node's revocation list is too old (or the shared store is unreachable); serious actions are paused. `Retry-After: 5`. | Check that your app reaches the node and Redis; look for `[verifier] refresh failed` in your logs. | A body over `max_body` (1 MiB) on a mapped route is refused with `413` and code `invalid_request`. A configuration the SDK cannot honour raises `AllowedBy::ConfigError` at start, with what to fix. ## Testing Run the CONF-1 vectors and the interop test, and test your own app with the in-memory node of `allowedby/testing`. From `sdks/ruby` (Linux, macOS and Windows PowerShell alike): ```bash bundle install bundle exec rake test # unit tests, every framework adapter, fuzzing, and the vectors bundle exec rake vectors # only the vectors: prints "481/481 cases passed" bundle exec rubocop # lint, every offence fails ``` The Redis tests need a server: `REDIS_URL=redis://localhost:6379/0 bundle exec rake test` (PowerShell: `$env:REDIS_URL = "redis://localhost:6379/0"; bundle exec rake test`), or `docker run --rm -p 6379:6379 redis:7.4-alpine` first. Without `REDIS_URL` they are skipped. The interop test runs an example app against a real node, the reference agent and a person with a software passkey (26 scenarios), from the repository root: ```bash pip install -r requirements.txt ruby sdks/ruby/test/frameworks.rb rack-puma # one run; no name: every run of examples/frameworks.json ``` Set `INTEROP_PORT_BASE` to move its ports. **Your own app, without a browser.** `AllowedBy::Testing::Node` issues an agent's passport and a person's approvals with real signatures, and answers the SDK's fetches through the `http:` option. A complete Minitest file (`examples/notes_app_test.rb`, run in CI): ```ruby # frozen_string_literal: true # Testing your own app without a browser or a network (docs/sdk/ruby.md, "Testing"): AllowedBy::Testing::Node is # an in-memory node that issues an agent's passport and a person's approvals, and answers the SDK's fetches. # # bundle exec ruby -Ilib examples/notes_app_test.rb require "minitest/autorun" require "rack/test" require "json" require "allowedby" require "allowedby/testing" class NotesAppTest < Minitest::Test include Rack::Test::Methods ORIGIN = "https://notes.example" def setup @node = AllowedBy::Testing::Node.new @aby = AllowedBy.new( origin: ORIGIN, node: @node.origin, org: { legal_name: "Notes Ltd", country: "FR" }, routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")], templates: { "notes:read" => "Read your notes" }, http: @node, start: false # the test node answers; no background thread ) @aby.verifier.refresh # fetch the node's statement and status list now @agent = @node.agent end def app notes_app = lambda do |env| # the person's id at this service; none on a level-0 route: refused, never used as a key who = env["allowedby.context"].human_id or return [403, {}, []] [200, { "content-type" => "application/json" }, [JSON.generate({ "who" => who })]] end AllowedBy::Middleware.new(notes_app, @aby) end def test_an_approved_agent_reads_the_notes grant = @node.grant(@agent, audience: ORIGIN, capabilities: [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }]) @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant).each { |name, value| header name, value } get "/notes" assert_equal 200, last_response.status assert_equal @node.human_id(ORIGIN), JSON.parse(last_response.body)["who"] end def test_without_the_persons_approval_the_agent_is_asked_to_get_one @agent.headers("GET", "#{ORIGIN}/notes").each { |name, value| header name, value } # the passport alone get "/notes" assert_equal 401, last_response.status assert_match(/error="grant_required"/, last_response.headers["www-authenticate"]) end def test_a_revoked_approval_is_refused_after_the_next_refresh grant = @node.grant(@agent, audience: ORIGIN, capabilities: [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }]) @node.revoke(grant) @aby.verifier.refresh @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant).each { |name, value| header name, value } get "/notes" assert_equal 401, last_response.status assert_equal "https://allowedby.org/errors/revoked", JSON.parse(last_response.body)["type"] end end ``` ## Reference Everything public, in `require "allowedby"` (and `require "allowedby/testing"` for the test helpers). **Building the service** - `AllowedBy.new(origin:, node:, org:, routes:, templates:, key_file: nil, store: nil, trust_list: nil, refresh_seconds: 5, node_max_level: 3, clock: nil, title: nil, version: "1.0.0", description: nil, rfc9421: false, logger: nil, http: nil, start: true, unprotected: [], link_authorize: nil, nonce: false, rate: nil, tenants: {})` -> `AllowedBy::Service`. `clock`: `-> Integer` seconds; `rfc9421`: accept the RFC 9421 Web Bot Auth signature instead of the proof JWT; `http`: the HTTP client, any `#call(method, url, body, headers) -> [status, body]`; `start`: run the background refresh; `nonce`: AllowedBy-Nonce on irreversible routes and routes with `nonce:` ([AllowedBy-Nonce](#allowedby-nonce)); `rate`: `{actor: [n, seconds], operator: [n, seconds]}` ([Rate limits](#rate-limits)); `tenants`: the accounts named by `{tenant}` ([Tenants and tenant budgets](#tenants-and-tenant-budgets)). - `AllowedBy.route(method, path, capability = nil, **options)` -> a frozen Hash (see Routes and templates). - `AllowedBy::ConfigError` (an `ArgumentError`): the configuration is refused. **`AllowedBy::Service`** - `check(method, path, headers, body = nil, query = nil)` -> `[Context, nil]` when allowed, `[nil, [status, headers, body_hash]]` to send back; `[nil, nil]` outside the route map. `POST /allowedby/link` is the SDK's own: its answer, accepted or not, is the second member. - `release(context)` -> true when what the check charged for this accepted request was given back (the SDK refused it itself before its handler started); `started(context)` -> false when it was given back already, or forgotten (it must not reach a handler); `forget(context)` once the request is answered (its refund state goes; without it, the state of at most 10 000 requests is kept): see Refunds, under Framework recipes. `refund(context)` -> true when the tenant budget this accepted request counted was given back (the handler refused it). - `link_start(account, ttl = 600)` -> a linking code for one of your accounts; `link(headers, body, query = nil, mount: "")` -> the answer to `POST /allowedby/link` (see [Account linking](#account-linking)). - `handle(method, path, mount = "")` -> the SDK's own endpoints as `[status, headers, body_hash]`, or nil. - `route_for(method, path)`, `variant_of(method, path)`, `protects?(method, path)`, `well_known(mount = "")`, `openapi(mount = "")`, `api_catalog(mount = "")`, `challenge(request, reject)`, `problem(code, status, detail = nil, headers = {}, **members)`. - `origin`, `node`, `host`, `routes`, `templates`, `key` (`AllowedBy::Key`), `verifier`, `title`, `version`. **Frameworks** - `AllowedBy::Middleware.new(app, service_or_callable, max_body: 1 << 20)`; `AllowedBy::Middleware::ENV_KEY` (`"allowedby.context"`). - `AllowedBy::Railtie` (`config.allowedby.service`, `config.allowedby.enabled`), `AllowedBy::ControllerHelpers#allowedby_context` and `#require_allowedby!` (a `before_action`), `bin/rails generate allowedby:install`. **Verification** - `AllowedBy::Verifier`: `verify(request)` -> `Context` or raises `AllowedBy::Reject`; `refresh`, `start_refresh`, `ensure_refresh` (restarts it after a fork), `stop_refresh`; `install_node(statement_jws, max_level, origin:)`, `install_status(uri, jws)` (statements and status lists obtained another way); `nodes`, `status`, `store`, `nonce` (an `AllowedBy::Nonce`, nil with nonces off), `rate` (an `AllowedBy::RateLimit`). - `AllowedBy::Request.new(http_method:, path:, query:, headers:, body:)`; `AllowedBy::Context` (see The context). - `AllowedBy::Reject` (`code`, `status`, `why`, `route`, `actor_sub`, `nonce`: the fresh nonce of the answer); `AllowedBy::STATUS` (code -> status); `AllowedBy::CHALLENGE_CODES`. - `AllowedBy::TrustList.new(jws, key)`, `.load(path, key)`, `.sign(key, payload)`; `AllowedBy::TrustResolver`. **State** - Store interface: `add(key, expires, now) -> bool`, `get(key, now)`, `charge([[key, inc, max, expires]], now) -> bool`, all with the SDK's clock. `AllowedBy::MemoryStore.new(max_keys: 200_000)`, `AllowedBy::RedisStore.new(redis, prefix: "allowedby:")`; `AllowedBy::StoreError`. - `AllowedBy::KeyFile.load(path)` -> `[Key, OpenSSL::PKey::EC]`; `AllowedBy::Key` (`generate`, `from_pem`, `sign`, `alg`, `kid`, `jwk`, `to_pem`, `derive(info)`: a 32-byte key derived from it, HKDF-SHA256). - `AllowedBy::Nonce.new(key)` (`.key_for(signing_key)`, `issue(now)`, `current?(value, now)`, `LIFETIME` 300); `AllowedBy::RateLimit.new(rate = nil)` (`.limits(rate)`, `take(actor, operator, now)` -> bool, `limits`, `DEFAULTS`, `MAX_KEYS`). **Building blocks** (what the verifier uses; stable, for tools and tests) - `AllowedBy::JCS.dump(value)`, `.bytes(value)` (RFC 8785); `AllowedBy::JWS.sign`, `.parse`, `.payload`; `AllowedBy::JWE.encrypt(jwk, plaintext)`, `.decrypt(pkey, token)` (ECDH-ES+A256KW, A256GCM); `AllowedBy::Crypto.verify_raw`, `.thumbprint`, `.public_key`; `AllowedBy::Grants.core`, `.core_hash`, `.request_digest`, `.make_proof`; `AllowedBy::WebAuthn.check`; `AllowedBy::Capabilities` (route matching, constraints, `render_display`); `AllowedBy::HTTP`. **Testing** (`require "allowedby/testing"`) - `AllowedBy::Testing::Node.new(name: "node.test", clock:, level: 2, authn: "hardware")`: `origin`, `agent`, `grant(agent, audience:, capabilities:, level:, initiator:, single_use:, ttl:)`, `sub_grant(parent, agent, capabilities:, ttl:)` (a sub-agent's grant, ABY-1 §4), `revoke(token)`, `human_id(audience)`, `approvals`, `call` (the `http:` client). - `AllowedBy::Testing::Agent`: `headers(method, url, allowed_by:, body:)`, `passport`, `sub`, `key`. **Version**: `AllowedBy::VERSION` (`0.1.0`), `AllowedBy::SPEC_VERSION` (`0.2.14`). ### Account linking An extended feature (CONTRACT 1.8), as ABY-3 §6 specifies it: the person links their AllowedBy identity to one of your accounts once, and routes with `require_link: true` accept them only for that account. 1. While the person is signed in, your account page calls `aby.link_start(account)` and shows the code it returns (96 random bits, valid `ttl` seconds, 600 by default, single use). 2. The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": ""}`. The middleware serves it (and `check` answers it in an app without the middleware). An unknown, spent, revoked or expired code is refused (`400 invalid_request`) before any approval is asked for. 3. The request is then checked as a route of the map (`aby:link`, `write`, level 1, resource `aby:link`), on a single-use grant only: without one, the service asks the node for the approval itself, bound to this request. 4. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home node, their pairwise id here) is linked to the account in place of any other: `200 {"linked": true}`. A request for a `require_link` route is then refused (`403 human_not_linked`) unless its pair is linked, and linked to the account the route's `account_param` names when the path has one (`/accounts/{account}/...`, compared decoded once, as `context.params`). The same pairwise id from another home node is another person. A grant that names no person for this service (no id for this origin in `human.id`, or an empty one) is refused on the link endpoint and on a `require_link` route (`401 grant_insufficient`): an empty id would link, or match, every grant that lacks it. Rule 5 (Framework recipes) counts such a route as covered by another only when that one names the same account parameter in the same segment of its path. The approvals the service creates for such an account name the linked person (`human_hint`, AMH-1 §7). The handler reads the account from `context.linked_account`, also on a route whose path names none. `link_authorize: ->(account, route, params) { ... }`, a service option, is your own authorisation of that account for the route (a shared resource, a suspended account): only a literal `true` passes, anything else (an exception included, logged without its message) is `403 human_not_linked`, and it is never called for a person who is not linked. Only `POST /allowedby/link` itself, read on its normalised path (`/allowedby/%6Cink` is the same), is the link endpoint: `/allowedby/link/` or `//allowedby/link` are paths of your app, outside the map, and no other caller is ever answered on its `aby:link` route. `/.well-known/allowedby` names the endpoint (`link`), `/openapi.json` describes it, and the person approves the sentence of `templates["aby:link"]` (a default is given). Codes and links are kept in the process's memory, bounded: 100 000 links, the oldest dropped first, and 10 000 pending codes. A new code never revokes an older one (ABY-3 §6), so when 10 000 codes are pending `link_start` raises `ArgumentError` until some expire or are used: catch it on the account page (and show the page's code once per visit rather than on every reload). Behind several instances, serve the account page and the link endpoint from one, or keep the link with your own accounts. The extended interop app (`examples/interop_ext/config.ru`): ```ruby # frozen_string_literal: true # The extended interop app (sdks/interop/ext/reference_app.py, in Ruby) for sdks/interop/ext/interop_ext.py: account # linking (ABY-3 §6), AllowedBy-Nonce (ABY-2 §3.2), level profiles (OAID-7 §5.3), rate limits, tenants and tenant # budgets (ORG-1 §3.3, §5.3). Routes: GET /me # (level 0), GET /accounts/{account}/notes (needs a linked person, for that account only), POST /drafts (with an # AllowedBy-Nonce), GET /vault/eu/{id} and GET /vault/na/{id} (level 3 for the EU or the North-America profile), # POST /t/{tenant}/orders (an amount at /total; tenants umbrella as the map says, hooli with a ceiling of 50.00, budget # with 100.00 EUR a day), # POST /allowedby/link (the SDK's own), and POST /interop/link-code, outside the route map (TEST ONLY: it stands for # the signed-in account page, which shows the code). Nonces on; rate limits: 20 calls a minute per agent, 1000 per # operator. # # PORT=18790 bundle exec puma -b tcp://127.0.0.1:18790 config.ru require "allowedby" require "json" aby = AllowedBy.new( origin: ENV.fetch("ALLOWEDBY_ORIGIN"), node: ENV.fetch("ALLOWEDBY_NODE"), org: { legal_name: "Notes Interop Ltd", country: "FR" }, routes: [ AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"), AllowedBy.route("GET", "/accounts/{account}/notes", "notes:read", level: 1, resource: "account:{account}", require_link: true, summary: "List the notes of an account"), AllowedBy.route("POST", "/drafts", "drafts:write", class: "write", resource: "draft:new", nonce: true, summary: "Save a draft", body: { text: "the draft" }), AllowedBy.route("GET", "/vault/eu/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware", level_profile: "eu", summary: "Open a vault (EU level 3)"), AllowedBy.route("GET", "/vault/na/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware", level_profile: "na", summary: "Open a vault (North-America level 3)"), AllowedBy.route("POST", "/t/{tenant}/orders", "orders:place", class: "write", resource: "tenant:{tenant}:order:new", amount_field: "/total", summary: "Place an order") ], templates: { "notes:read" => "Read your notes", "drafts:write" => "Save your drafts", "vault:read" => "Open {scope}", "orders:place" => "Place orders on {scope}, up to {amount.max} {amount.currency} per {amount.per}" }, title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5")), nonce: true, rate: { actor: [20, 60], operator: [1000, 60] }, tenants: { umbrella: { name: "Umbrella" }, hooli: { name: "Hooli", routes: { "orders:place" => { amount_max: "50.00" } } }, budget: { name: "Budget Co", budgets: { "orders:place" => { max: "100.00", currency: "EUR", per: "day" } } } } ) use AllowedBy::Middleware, aby run(lambda do |env| request = Rack::Request.new(env) context = env["allowedby.context"] # nil on a path outside the route map status, body = case [request.request_method, request.path_info] in ["POST", "/interop/link-code"] # TEST ONLY: the signed-in account page account = begin JSON.parse(request.body.read.to_s)["account"] rescue JSON::ParserError, NoMethodError, TypeError nil end if account.is_a?(String) && !account.empty? [200, { code: aby.link_start(account) }] else [400, { error: "account" }] end in ["GET", "/me"] if context [200, { agent: context.agent, operator: context.operator, level: context.level }] in ["GET", %r{\A/accounts/[^/]+/notes\z}] if context [200, { account: context.params["account"], notes: [] }] in ["POST", "/drafts"] if context [200, { saved: true }] in ["GET", %r{\A/vault/(?:eu|na)/[^/]+\z}] if context [200, { vault: context.params["id"] }] in ["POST", %r{\A/t/[^/]+/orders\z}] if context total = begin JSON.parse(request.body.read.to_s)["total"] rescue JSON::ParserError, NoMethodError, TypeError nil end [200, { ordered: total, account: context.tenant }] else [404, { error: "not found" }] end [status, { "content-type" => "application/json" }, [JSON.generate(body)]] end) ``` CI runs every vector file of the features this SDK implements (`features` of `vectors/ext/profiles.json`: linking's `linking.json`, `linking-person.json`, `linking-endpoint.json`, and `nonce.json`, `level-profiles.json`, `rate-limits.json`, `tenants.json`, `tenant-budgets.json`; `test/vectors_ext_test.rb`), `sdks/interop/ext/interop_ext.py --features linking,nonce,level_profiles,rate,tenants,tenant_budgets` against that app (with a real node, agent and passkey) and mutation testing of their code (`test/mutate.rb`, every change killed or listed as equivalent in `test/mutants_equivalent.txt`). ### AllowedBy-Nonce An extended feature, as ABY-2 §3.2 specifies it: a route can ask that each proof carries a nonce the service issued a moment before, so a proof made in advance is refused. `AllowedBy.new(..., nonce: true)` turns nonces on: every `irreversible` route then asks for one, and so does every route with `nonce: true` (on any class). A route with `nonce: true` while the service has nonces off raises `ConfigError` at start. A request without a current nonce is refused with `401 invalid_signature` and a fresh nonce in the answer's `AllowedBy-Nonce` header; the agent signs the request again with it (the `nonce` member of the proof JWT, or with RFC 9421 the request's `AllowedBy-Nonce` header, which counts only when the signature covers it; a covered value that is not base64url is refused). The AllowedBy agent runtimes retry once, on any route. A nonce is current for 300 s from its issue. Nonces are stateless (the issue time and a MAC), so every instance that shares the `key_file` takes the nonces of the others, and a restart keeps those it handed out current: the nonce key is HKDF-SHA256 of the signing key's raw private key (info `allowedby/nonce/v1`, used for nothing else), the same in every AllowedBy SDK. Without a `key_file` each process has its own key, and a nonce is good only on the process that issued it. A nonce is not single use: within its 300 s, the replay set (one use per proof) is what stops a proof from being sent twice. ### Level profiles Level 3 is eIDAS high in the EU and its North-American counterpart elsewhere (OAID-7 §5.3). `level_profile: "eu"` or `"na"`, on a level-3 route only, accepts only a person whose registration's level source is of that profile; another one, or none, is refused with `401 level_insufficient` (the approval the service creates for a serious route asks the node for that profile). A level-3 route without `level_profile` takes either. ### Rate limits Every service limits the calls of each agent (its passport's `sub`) and of each operator (`operator.id`), by default 600 and 6000 calls per 60 s. `AllowedBy.new(..., rate: { actor: [20, 60], operator: [1000, 60] })` sets them, each optional; another key, or a value that is not two positive integers, raises `ConfigError` (a misspelt limit would leave the default in place). A call over either limit is refused with `429 rate_limited` and `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 then refused as `grant_required` or `revoked` counts); a call refused by the limit itself, or before it (a bad proof, a missing nonce, an expired agent key), counts for neither limit. The counts are kept in the process's memory, for at most 10 000 agents and as many operators (the one seen least recently dropped first): behind several instances, each counts its own calls. ### Tenants and tenant budgets An extended feature, as ORG-1 §3.3 and §5.3 specify it: one route map serves many accounts of yours (your customers' companies), and each can tighten the rules on its own routes. The account is the route's `{tenant}` path parameter (`context.tenant`). The extended interop app above has three: `umbrella` as the route map says, `hooli` with an amount ceiling of 50.00 on `orders:place`, and `budget` with a budget of 100.00 EUR a day on it. A tenant's overrides only tighten its routes: `level` (the higher one counts), `authn` (the stronger), `require_link` (true wins), `max_lifetime` (the shorter), `amount_max` (above it, or with no amount, `403 capability_denied`), `operators` (an allowlist of `operator.id`; any other operator gets `403 capability_denied`). A level-0 route has no capability (it needs no grant; `AllowedBy.route` refuses one), so no override reaches it. `mandate`, and `members_only` with `org` (a mandate from that organisation on every route of the tenant), are accepted, but until this SDK verifies mandates (CONTRACT: company mandates), such a tenant route refuses every request with `401 mandate_required`, before any challenge: no one is asked to approve what cannot succeed. `members_only` is tenant-wide: it reaches the tenant's level-0 routes too, which a passport alone calls, so those refuse every request with `401 mandate_required`, asking no approval. `qes` is refused when the service is built: this SDK has no EU trusted list to check qualified signatures with. A resource that names the tenant (`tenant:{tenant}:...`) keeps one tenant's approvals off another's routes. A budget, `{max, currency, per: day | week | month, tz}`, caps the amounts the service accepts on a capability for one tenant, per calendar period in `tz`: any IANA zone this machine knows (`Europe/Paris`; UTC by default), a period running from local midnight to local midnight, so a day that changes the clocks lasts 23 or 25 hours. A zone the machine does not know is refused when the service is built. Every route of that capability needs `amount_field`. The count is kept in the verifier's store, so every instance that shares a `RedisStore` shares it. A request with no amount in the budget's currency, or over what is left, is refused with `403 budget_exceeded`, and the refusal comes before any challenge: no one is asked to approve what cannot succeed. A refused request is not counted; `release` gives the amount back with the rest, and `refund(context)` gives it back when your handler refuses the request (a wrong total, an unknown order). The store down: `503 status_stale` with `Retry-After: 5`, and what the check had charged is given back. The option is checked when the service is built: a tenant id outside `[A-Za-z0-9_-]{1,64}`, another key (`authority` and `authority_policy_revision` among them: authority policies are not implemented here), a `name` that is not 1-200 characters, an `org` that is not an https origin with no path, a capability the map does not have, a value of another shape, or an override or budget on a capability with a route that has no `{tenant}` (where it would never apply; the error names the route) raises `ConfigError`. The SDK keeps its own frozen copy, with string keys: your hash is never written. ### Implemented | CONTRACT §2 (core) | Ruby SDK | |---|---| | 1. Configuration, refused with a message | Yes (`AllowedBy.new`, `ConfigError`) | | 2. Route map, classes and amount thresholds, levels, params | Yes (`AllowedBy.route`) | | 3. Discovery: `/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog` | Yes | | 4. Verification, ABY-2 §5 steps 1-10, proof JWT and RFC 9421, EdDSA and ES256 only | Yes: 481/481 CONF-1 `verifier` vectors, `challenge-scope.json` included | | 5. Challenges, service-initiated approvals for serious routes | Yes | | 6. Background refresh, fail closed, `[verifier] refresh failed` | Yes | | 7. Read-only context | Yes (`AllowedBy::Context`, frozen) | | 8. Store: memory (thread-safe) and shared | Yes: `MemoryStore`, `RedisStore` | | 9. Keys and `keyFile` in the Python format | Yes (`key_file:`) | | 10. Framework middleware | Yes: Rack, Rails, Sinatra | Extended features (CONTRACT §2) implemented: account linking (`/allowedby/link`, `require_link`, `account_param`; see [Account linking](#account-linking)), [AllowedBy-Nonce](#allowedby-nonce) (`nonce`), [level profiles](#level-profiles) (`level_profile`), [rate limits](#rate-limits) (`rate`) and [tenants and tenant budgets](#tenants-and-tenant-budgets) (`tenants`). Not implemented: the disclosure callback and JWE decryption of personal data (the JWE primitives exist, `/allowedby/callback` is not served), authority policies, company mandates (refused), the audit sink, the admin console. Asking for one raises `ConfigError` naming it. Time zones: a grant's `amount.tz` and `window.tz` other than UTC never match (fail closed); tenant budgets take any IANA zone (tzinfo). --- Source: https://docs.allowedby.com/sdk/rust # AllowedBy for Rust This guide shows how a Rust API accepts AI agents that act for a person, with that person's approval. The concepts (routes, classes, levels, the approval flow, the context) are explained once in [docs/deploy-saas.md](https://docs.allowedby.com/guides/accept-agents); this guide shows them in Rust. Every code block below is a file under `sdks/rust/examples/` that CI builds, and a test checks that the blocks here are those files, byte for byte. Terms used once: an **agent** is software acting for a person; its **passport** (OAID-3) names the agent and its operator; a **grant** (ABY-1) is the person's signed approval; a **proof** (ABY-2 §3) is the agent's signature over one request; a **node** issues passports and runs the approval page; **JWS** is a signed JSON document (RFC 7515). ## Install Add the `allowedby` crate from the repository with the feature of your framework; it needs Rust 1.89 or newer. ```bash cargo add allowedby --git https://github.com/yannUpTo/allowedby --features axum ``` The command is the same on Linux, macOS and Windows (PowerShell). Features: | Feature | Gives | Default | |---|---|---| | `http` | The HTTP client for the background refresh and the service-initiated approval (`ureq`, rustls). | on | | `tower` | `AllowedByLayer`, a tower layer for any tower + `http` 1 stack (axum, hyper). | off | | `axum` | `allowedby::axum::protect` and the `AllowedByContext` extractor (includes `tower`). | off | | `actix` | `allowedby::actix::AllowedBy` middleware and the extractor. | off | | `redis` | `RedisStore`, a store shared by every instance. | off | Dependencies, each pinned (exact versions for the verification core, `Cargo.lock` for the integrations), and why: `serde` and `serde_json` (JSON; this SDK refuses duplicate member names and implements JCS, RFC 8785, itself), `sha2` (SHA-256), `ed25519-dalek` (EdDSA), `p256` (ES256 and the disclosure key), `getrandom` (keys and ids), `miniz_oxide` (zlib status lists), `ureq` (HTTP), `jiff` (feature `tz`, default: the IANA time-zone database, bundled, for tenant budgets in local calendar periods). The library forbids `unsafe` and denies `unwrap`, `expect` and `panic`. With Docker, without a local Rust toolchain (Linux and macOS): ```bash docker run --rm -v "$PWD":/src -w /src/sdks/rust rust:1.89 cargo test --all-features ``` Windows PowerShell: ```powershell docker run --rm -v "${PWD}:/src" -w /src/sdks/rust rust:1.89 cargo test --all-features ``` ## Quick start A complete axum app that serves `GET /notes` to agents once the person approved "Read your notes" (`sdks/rust/examples/quickstart.rs`): ```rust use allowedby::{AllowedByContext, Options, Org, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; async fn notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "for": ctx.human_id, "level": ctx.level})) } #[tokio::main] async fn main() -> Result<(), Box> { let aby = Service::new( Options::new("http://localhost:8790", "http://localhost:8000") .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes"), )?; let app = allowedby::axum::protect(Router::new().route("/notes", get(notes)), aby); let listener = tokio::net::TcpListener::bind("127.0.0.1:8790").await?; axum::serve(listener, app).await?; Ok(()) } ``` See it work against the local node. From the repository root, start the node (needs Python 3.10+ and `pip install -r requirements.txt`), then the app: ```bash python demo/run.py --port 8000 & cd sdks/rust && cargo run --features axum --example quickstart ``` ```powershell Start-Process python -ArgumentList "demo/run.py", "--port", "8000" cd sdks/rust; cargo run --features axum --example quickstart ``` Then ask as an agent without credentials would: ```bash curl -i http://localhost:8790/notes curl -s http://localhost:8790/.well-known/allowedby ``` ```powershell curl.exe -i http://localhost:8790/notes Invoke-RestMethod http://localhost:8790/.well-known/allowedby ``` The first answers `401` with `WWW-Authenticate: AllowedBy realm="localhost:8790", error="passport_required"`; the second lists the capability and the sentence the person signs. To see the whole flow (passport, approval with a passkey, retry, replay refused, revocation), run the interop test against this SDK (section Testing). Against the hosted node, use `https://demo.allowedby.com` as `node` and your public `https` origin as `origin`. ## Routes and templates Each route of your API that agents may call is one `Route`: the capability a grant must hold, its class, the identity level, and the resource it acts on; the template is the sentence the person reads and signs. | Builder | Meaning | Default | |---|---|---| | `Route::get(path)`, `post`, `put`, `patch`, `delete`, `Route::new(method, path)` | The operation. `{param}` segments are path parameters. | | | `.capability("notes:read")` | What the person allows, `namespace:action`. Without it the route is level 0: the agent's passport is enough. | none | | `.class(Class::Read)` | `Read`, `Write` (reversible), `WriteHard` (hard to undo), `Irreversible` (money, final steps). For `WriteHard` and `Irreversible` the SDK creates the approval, bound to the exact request, usable once. | `Read` | | `.class_by_amount(vec![Threshold::up_to("1000.00", Class::WriteHard), Threshold::rest(Class::Irreversible)])` | The class read from the request's amount (needs `amount_field`); no readable amount: the last class. | | | `.level(n)` | 0 agent only, 1 a passkey tap, 2 verified identity (eIDAS substantial), 3 eIDAS high on a hardware passkey. | 1 | | `.resource("note:{id}")` | The resource; `{param}` takes the path parameter. Grants must name it in their `scope`. | `:*` | | `.amount_field("/total")`, `.currency_field("/currency")` | JSON Pointers to the amount and currency in the body; grants must cap the amount. | none, `/currency` | | `.authn(Authn::Synced)` | The person's authenticator class at least `Synced` or `Hardware`. | any | | `.tier(n)` | The agent key's custody tier at least `n` (OAID-6). | 0 | | `.max_lifetime(seconds)` | A shorter grant lifetime than the class allows (60 s to 30 days). | the class's | | `.level_profile("eu")` | Level 3 from this OAID-7 §5.3 profile only (`eu` or `na`; see Level profiles). | none | | `.nonce(true)` | A current service nonce in every proof (see AllowedBy-Nonce); needs `Options::nonce(true)`. | off | | `.require_link(true)`, `.account_param("account")` | A person linked to your account (see Account linking). | off, `account` | | `.qes(true)` | A qualified electronic signature. No EU trusted list in this SDK yet: `Service::new` refuses it (a bare `Verifier` refuses every request with `qes_required`). | off | | `.summary(text)`, `.body_field(name, description)` | What the operation does and each body member, for agents (OpenAPI). | none | Templates: `.template("notes:read", "Read your notes")` is the English sentence; `Template::new().lang("en", summary, line).lang("fr", ...)` gives several languages. Placeholders: `{scope}`, `{fields}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`. `Service::new` refuses a capability without a template, a route the Python `route()` would refuse, and the route options this SDK does not enforce (`Route::from_json` names them). Every option, and the documents agents read (`sdks/rust/examples/routes.rs`): ```rust //! Every route option, and the documents agents read: prints /openapi.json and /.well-known/allowedby. //! Runs offline: `cargo run --example routes`. use allowedby::{Authn, Class, Options, Org, Request, Route, Service, Template, Threshold}; fn main() -> Result<(), Box> { let aby = Service::new( Options::new("https://api.example.com", "https://node.example.org") .org(Org::new("Invoices Ltd", "FR").website("https://example.com").support("https://example.com/help")) // level 0: the agent's passport is enough, no person approves .route(Route::get("/me").level(0).summary("Who is calling")) // read, level 1 (the defaults): a passkey tap, standing for up to 30 days .route(Route::get("/invoices").capability("invoices:read").resource("invoice:*").summary("List invoices")) // write: standing for up to 7 days; the body members are described for agents .route( Route::post("/invoices/{id}/comments") .capability("invoices:comment") .class(Class::Write) .resource("invoice:{id}") .body_field("text", "the comment"), ) // write-hard, level 2, synced passkey or better: approved for this exact request, used once .route( Route::post("/invoices/{id}/approve") .capability("invoices:approve") .class(Class::WriteHard) .level(2) .authn(Authn::Synced) .resource("invoice:{id}") .amount_field("/total") .currency_field("/currency"), ) // a payment: its class depends on the amount; level 3 for the EU profile, hardware key, custody tier 1 .route( Route::post("/invoices/{id}/pay") .capability("invoices:pay") .class_by_amount(vec![ Threshold::up_to("1000.00", Class::WriteHard), Threshold::rest(Class::Irreversible), ]) .amount_field("/total") .level(3) .level_profile("eu") .authn(Authn::Hardware) .tier(1) .max_lifetime(600) .resource("invoice:{id}"), ) .template("invoices:read", "Read your invoices") .template( "invoices:comment", Template::new().lang("en", "Comment on {scope}", "Comment on {scope}").lang( "fr", "Commenter {scope}", "Commenter {scope}", ), ) .template("invoices:approve", "Approve {scope}, up to {amount.max} {amount.currency}") .template("invoices:pay", "Pay {scope}, up to {amount.max} {amount.currency}") .background_refresh(false), )?; for path in ["/openapi.json", "/.well-known/allowedby"] { if let allowedby::Outcome::Respond(r) = aby.handle(&Request::new("GET", path)) { println!("{path}: {}", String::from_utf8_lossy(&r.body)); } } Ok(()) } ``` ### AllowedBy-Nonce (extended) AllowedBy-Nonce (ABY-2 §3.2, CONTRACT "Extended") makes a captured proof useless after 300 s, whatever its own time says. `Options::nonce(true)` turns it on (off by default). Every `irreversible` route, and every route with `.nonce(true)`, then takes only a proof that carries a current service nonce. A proof without one gets `401 invalid_signature` with a fresh nonce in `AllowedBy-Nonce`, and the agent retries once with it. With RFC 9421 the nonce is the request's `AllowedBy-Nonce` header, and it counts only when the signature covers it. A route with `.nonce(true)` while the service has nonces off is refused by `Service::new`. Nonces carry no state: a nonce is its issue time and a MAC of it under a key derived from your signing key (HKDF-SHA256, info `allowedby/nonce/v1`). So every instance that shares the key file, and a restart, takes the nonces of the others, and so do the SDKs of the other languages on the same key file. ### Level profiles (extended) `.level_profile("eu")` or `.level_profile("na")` on a level-3 route (OAID-7 §5.3) takes only a person verified to level 3 by a source of that profile: another profile, or none, gets `401 level_insufficient`. The approval the service asks for names the profile, so the person's home node offers only those sources. A level-3 route without a profile takes any. ### Tenants (extended) `Options::tenants(json!({id: {name, routes: {capability: override}, members_only, org, budgets}}))` (ORG-1 §3.3) gives each customer account of a multi-tenant API its own rules, on the routes whose path has the `tenant` parameter (`/t/{tenant}/invoices/{id}`). An override only tightens the route of its capability: `level` (the higher counts), `authn` (the stronger), `mandate` and `require_link` (true wins; a link raises level 0 to 1), `max_lifetime` (the shorter), `amount_max` (the lower; above it `403 capability_denied`) and `operators` (an allowlist of `operator.id`; any other operator gets `403 capability_denied`). Overrides are by capability, and a level-0 route has none (it needs no grant: `Service::new` refuses one), so they never reach a route the agent alone may call. A tenant the path names but the option does not has the route as the map has it. `Service::new` refuses an id outside `[A-Za-z0-9_-]{1,64}`, any other key (`policy` among them), a `name` that is not 1-200 characters, an `org` that is not an https origin with no path, a capability the map does not have, a value of another shape, and an override or a budget on a capability that has a route without `{tenant}` (the error names that route): a misspelt override would leave the route as loose as yours. The option is read, never changed. This SDK verifies no company mandates yet (CONTRACT: company mandates), so until it does, a tenant route with `mandate: true`, and every route of a `members_only` tenant with an `org`, refuses every request with `401 mandate_required`. `members_only` is the whole tenant's: it holds on the routes the agent alone may call too (level 0), refused with no challenge, since no approval can bring a mandate there. The overrides `qes` and `authority` are refused by `Service::new` (no EU trusted list, no authority policies yet). ### Tenant budgets (extended) `tenants[id].budgets[capability] = {max, currency, per: day | week | month, tz?}` (ORG-1 §5.3) caps what a tenant spends on a capability per calendar period. Every route of that capability needs `amount_field`, or `Service::new` refuses the budget. The service counts the amounts it accepts in the verifier's store, per tenant, capability, currency, zone and period, so every instance that shares the store shares the count. A request without an amount in the budget's currency, or over what is left, gets `403 budget_exceeded`, before any challenge: no approval is asked for one that cannot succeed. A refused request counts nothing, and a refund (CONTRACT §2 item 10) gives the amount back. When the store does not answer, the request gets `503 status_stale` with `Retry-After`, and what the check spent is given back. `tz` is any IANA zone (`Europe/Paris`; `UTC` by default): the default feature `tz` bundles the IANA database (`jiff`), and a period runs from a local midnight to the next one, so a day with a daylight-saving change lasts 23 or 25 hours. Without that feature, only `UTC` and the fixed offsets `Etc/GMT-N` / `Etc/GMT+N`; `Service::new` refuses any other zone. ### Rate limits (extended) Every service limits calls per agent (the passport's `sub`) and per operator (`operator.id`): 600 and 6000 calls per 60 s by default, `Options::rate((calls, seconds), (calls, seconds))` for others (each number 1 or more, checked by `Service::new`). A call over either limit gets `429 rate_limited` with `Retry-After`. The window slides on the SDK's clock (a call at t sees those of the last `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 the limit refuses counts for neither limit. A call with an expired agent key is refused (`actor_expired`) before it counts. The counts are per process, like `MemoryStore`. ### Account linking (extended) Account linking (ABY-3 §6, CONTRACT "Extended") ties a person's AllowedBy identity to one of your own accounts, so that a route reaches only the account the person owns. - **The code.** While the user is signed in, your account page calls `aby.link_start(&account)` (or `link_start_ttl(&account, ttl)`, 1 s to a day; 600 s by default) and shows the code. It is single use, 96 random bits. Using one revokes the account's other pending codes. It fails (`LinkError`) for an empty account, or when 10 000 codes are pending. The SDK always draws the code: the cargo feature `conformance-hooks`, which lets the conformance runner set one, is for this SDK's own tests only; never enable it in an app. - **The endpoint.** The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "..."}`. The SDK serves it itself, through `Service::handle` and every adapter; your router needs no route for it. An unknown or expired code is refused with `400 invalid_request` before any approval is asked for. Then the request needs a single-use grant of `aby:link`: without one, the SDK asks the node for an approval bound to this request (the agent gets a challenge). Accepted, the pair (home node, pairwise id) is linked to the account, replacing any other person linked to it: `200 {"linked": true}`. Only that exact path is the endpoint: a variant (`/allowedby/link/`, `/allowedby/%6Cink`, `//allowedby/link`) or a method override asks for no approval and links nothing. `/.well-known/allowedby` names the endpoint (`link`), and `/openapi.json` lists it. - **The routes.** `Route::require_link(true)` needs a linked person (`403 human_not_linked` otherwise), on a route of level 1 or more: `Service::new` refuses it on a level-0 route. When the path has the `account_param` parameter (`Route::account_param`, default `account`), the person must be linked to that very account. The context's `linked_account` is the account, also when the path names none. A grant that names no person for your service (`human.id`) is refused with `401 grant_insufficient` on the endpoint and on these routes. An approval the service asks for on a route that names a linked account names that person (`human_hint`, AMH-1 §7). - **Your own rule.** `Options::link_authorize(|account, route, params| ...)` is your authorisation of the linked account for the resource. Only `true` lets the request through; `false`, or a panic in it, is `403 human_not_linked`. It is asked only for a person linked to the account the path names. - **Rule 5.** A handler shared with a route that needs a link runs for another route only if that route needs one too, with the account in the same path segment, by the same parameter. - **Limits.** Codes and links live in memory, per process: behind several instances, a code is used on the instance that issued it, and a link holds on the instance that made it. At most 10 000 pending codes and 100 000 links (the oldest link goes first). ## Framework recipes Wrap your whole app so the SDK's endpoints come first, then the check on every route of the map, then your handlers; paths outside the map reach your app unchanged and the body is handed on intact. Variants of a protected route that a router could still dispatch to its handler are refused with `400 invalid_request` (CONTRACT §2.10): a trailing or doubled `/` (`/notes/`, `//notes`), a dot segment (`/notes/..`, `/x/../notes`), a control character (`/notes%0A`), `;parameters`, a format suffix (`/notes.json`), a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `?_method=`) on a path of the map. axum and actix-web read no method from a form body (`_method`); do not add a middleware that rewrites paths or methods between the SDK and your handlers. A wildcard serves more paths than the route map names: `/notes/{*id}` (axum) or `/notes/{id:.*}` (actix-web) also runs for `/notes/7/x`, which no approval was checked for, and `/notes/{id}/{*rest}` runs for `/notes/7/archive/x` next to `DELETE /notes/{id}/archive`. No adapter here can tell which handler its router chose (actix-web's resource map ignores method guards), so, for the methods the map uses there, every request below a route of the map that has a parameter, or that a parameter taking several segments would make one, is refused with `400` (stricter than CONTRACT §2.10 asks). A route without a parameter keeps its sub-resources: `GET /notes/7` runs when only `GET /notes` is mapped. Under axum's `nest`, wrap the outer router with `protect`, and write the map with the paths it sees. A map that names the mount point of a nested `protect` would protect nothing: its requests are refused with `400`. Under actix-web's `web::scope("/api").wrap(AllowedBy::new(..))` it is the other way round: the middleware sees the whole path, so the map holds `/api/notes/{id}`; a map written with the scope's own paths (`/notes/{id}`) would protect nothing, and its requests are refused with `400`. Each framework below has a complete app, the notes API of `sdks/interop/reference_app.py`, that CI runs against a real node, agent and person: the whole interop test (26 scenarios: levels 0, 1 and 2, every refusal), on Rust stable and on Rust 1.89, for each version in `sdks/rust/examples/frameworks.json`. **axum**: `allowedby::axum::protect(router, service)` wraps a `Router`; handlers take `AllowedByContext` (or `Option` on paths outside the map). Feature `axum` (`sdks/rust/examples/frameworks/axum/main.rs`): ```rust //! axum: the notes API of sdks/interop/reference_app.py (sdks/CONTRACT.md §6), the interop test's app. //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features axum --example interop //! //! GET /me (level 0), GET /health (outside the route map), GET /notes (notes:read, L1), POST /notes //! (notes:write, write, L1), DELETE /notes/{id} (notes:delete, write-hard, L2); anything else 404. use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use axum::body::Bytes; use axum::extract::{Path, State}; use axum::http::StatusCode; use axum::routing::get; use axum::{Json, Router}; use serde_json::{json, Value}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; type Reply = (StatusCode, Json); fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } async fn health() -> Json { Json(json!({"ok": true})) } async fn me(ctx: AllowedByContext) -> Json { Json(json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } async fn get_notes(State(db): State, ctx: AllowedByContext) -> Reply { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx .human_id .as_ref() .and_then(|h| db.by_person.get(h)) .map(|n| list(n.as_slice())) .unwrap_or_else(|| json!([])); (StatusCode::OK, Json(json!({"notes": mine}))) } async fn add_note(State(db): State, ctx: AllowedByContext, body: Bytes) -> Reply { let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return (StatusCode::BAD_REQUEST, Json(json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } (StatusCode::CREATED, Json(json!({"id": id}))) } async fn delete_note(State(db): State, ctx: AllowedByContext, Path(id): Path) -> Reply { let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| *i != id); } (StatusCode::OK, Json(json!({"deleted": id}))) } async fn not_found() -> Reply { (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; // the handlers of the routes of the map, registered with the service: CONTRACT §2.10 rule 5 holds for them (an // alias of one on another path, another method or a catch-all is refused); /health is the app's own page use allowedby::axum as aby_routing; let router = Router::new() .route("/health", get(health)) .route("/me", aby_routing::get(&aby, "/me", me)) .route("/notes", aby_routing::get(&aby, "/notes", get_notes)) .route("/notes", aby_routing::post(&aby, "/notes", add_note)) .route("/notes/{id}", aby_routing::delete(&aby, "/notes/{id}", delete_note)) .fallback(not_found) .with_state(Db::default()); let app = allowedby::axum::protect(router, aby); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); axum::serve(listener, app).await?; Ok(()) } ``` **tower**: `AllowedByLayer::new(service).layer(inner)` (feature `tower`) gives a `tower::Service>`; the inner service receives `http::Request>>` (`allowedby::tower::AbyReqBody`): the original body outside the route map, the verified bytes on it, with an `AllowedByContext` in its extensions. Verification runs on Tokio's blocking pool, since a serious route's challenge calls the node. Here the service behind the layer routes by hand, and axum only serves the connection (`sdks/rust/examples/frameworks/tower/main.rs`): ```rust //! The bare tower layer: the notes API of sdks/interop/reference_app.py as a service that routes by hand behind //! `AllowedByLayer` (no axum router behind the layer), so that the interop test runs against the layer alone //! (sdks/CONTRACT.md §6). axum only serves the connection. //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features axum --example interop_tower use allowedby::tower::{AbyReqBody, AllowedByLayer}; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use bytes::Bytes; use http::{Method, Request, Response, StatusCode}; use http_body_util::{BodyExt, Full, Limited}; use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::Infallible; use std::sync::{Arc, Mutex}; use tower::Layer; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; fn reply(status: StatusCode, v: Value) -> Response> { let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); *r.status_mut() = status; r.headers_mut().insert(http::header::CONTENT_TYPE, http::HeaderValue::from_static("application/json")); r } fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } /// The app's own routing: by method and path segments, as a hand-written hyper service does. async fn app(db: Db, req: Request>) -> Result>, Infallible> { let ctx = req.extensions().get::().cloned(); let method = req.method().clone(); let path = req.uri().path().to_owned(); let segments: Vec<&str> = path.split('/').skip(1).collect(); let read = method == Method::GET || method == Method::HEAD; // a protected handler without the context the layer gives: the layer let the request through unchecked let unchecked = || reply(StatusCode::INTERNAL_SERVER_ERROR, json!({"error": "no AllowedBy context"})); Ok(match (segments.as_slice(), ctx) { (["health"], _) if read => reply(StatusCode::OK, json!({"ok": true})), (["me"], Some(ctx)) if read => { reply(StatusCode::OK, json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } (["notes"], Some(ctx)) if read => { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx.human_id.as_ref().and_then(|h| db.by_person.get(h)).map(|n| list(n.as_slice())); reply(StatusCode::OK, json!({"notes": mine.unwrap_or_else(|| json!([]))})) } (["notes"], Some(ctx)) if method == Method::POST => { let body = Limited::new(req.into_body(), 1 << 20).collect().await.map(|b| b.to_bytes()).unwrap_or_default(); let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return Ok(reply(StatusCode::BAD_REQUEST, json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } reply(StatusCode::CREATED, json!({"id": id})) } (["notes", _], Some(ctx)) if method == Method::DELETE => { // the id as the SDK checked it, never this app's own reading of the raw path let Some(id) = ctx.params.get("id") else { return Ok(reply(StatusCode::NOT_FOUND, json!({}))) }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| i != id); } reply(StatusCode::OK, json!({"deleted": id})) } (["me"] | ["notes"], None) if read || method == Method::POST => unchecked(), (["notes", id], None) if method == Method::DELETE && !id.is_empty() => unchecked(), _ => reply(StatusCode::NOT_FOUND, json!({"error": "not found"})), }) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; let db = Db::default(); let inner = tower::service_fn(move |req| app(db.clone(), req)); let layered = AllowedByLayer::new(aby).layer(inner); // axum only serves the connection: nothing is routed before the layer let server = axum::Router::new().fallback_service(layered); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); axum::serve(listener, server).await?; Ok(()) } ``` **hyper**: the same tower service, served by hyper's own HTTP/1 connection through hyper-util's `TowerToHyperService`, without a framework (`sdks/rust/examples/frameworks/hyper/main.rs`): ```rust //! hyper 1 without a framework: the notes API of sdks/interop/reference_app.py as a hand-written service behind //! `AllowedByLayer`, served by hyper's own HTTP/1 connection (hyper-util's `TowerToHyperService` turns the tower //! service into a hyper one). The interop test runs against it (sdks/CONTRACT.md §6). //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features tower --example interop_hyper use allowedby::tower::{AbyReqBody, AllowedByLayer}; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use bytes::Bytes; use http::{Method, Request, Response, StatusCode}; use http_body_util::{BodyExt, Full, Limited}; use hyper::body::Incoming; use hyper::server::conn::http1; use hyper_util::rt::TokioIo; use hyper_util::service::TowerToHyperService; use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::Infallible; use std::sync::{Arc, Mutex}; use tower::Layer; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = Arc>; fn reply(status: StatusCode, v: Value) -> Response> { let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); *r.status_mut() = status; r.headers_mut().insert(http::header::CONTENT_TYPE, http::HeaderValue::from_static("application/json")); r } fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } /// The app's own routing: by method and path segments. async fn app(db: Db, req: Request>) -> Result>, Infallible> { let ctx = req.extensions().get::().cloned(); let method = req.method().clone(); let path = req.uri().path().to_owned(); let segments: Vec<&str> = path.split('/').skip(1).collect(); let read = method == Method::GET || method == Method::HEAD; // a protected handler without the context the layer gives: the layer let the request through unchecked let unchecked = || reply(StatusCode::INTERNAL_SERVER_ERROR, json!({"error": "no AllowedBy context"})); Ok(match (segments.as_slice(), ctx) { (["health"], _) if read => reply(StatusCode::OK, json!({"ok": true})), (["me"], Some(ctx)) if read => { reply(StatusCode::OK, json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } (["notes"], Some(ctx)) if read => { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx.human_id.as_ref().and_then(|h| db.by_person.get(h)).map(|n| list(n.as_slice())); reply(StatusCode::OK, json!({"notes": mine.unwrap_or_else(|| json!([]))})) } (["notes"], Some(ctx)) if method == Method::POST => { let body = Limited::new(req.into_body(), 1 << 20).collect().await.map(|b| b.to_bytes()).unwrap_or_default(); let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return Ok(reply(StatusCode::BAD_REQUEST, json!({"error": "text: a string of 1 to 2000 characters"}))); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } reply(StatusCode::CREATED, json!({"id": id})) } (["notes", _], Some(ctx)) if method == Method::DELETE => { // the id as the SDK checked it, never this app's own reading of the raw path let Some(id) = ctx.params.get("id") else { return Ok(reply(StatusCode::NOT_FOUND, json!({}))) }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| i != id); } reply(StatusCode::OK, json!({"deleted": id})) } (["me"] | ["notes"], None) if read || method == Method::POST => unchecked(), (["notes", id], None) if method == Method::DELETE && !id.is_empty() => unchecked(), _ => reply(StatusCode::NOT_FOUND, json!({"error": "not found"})), }) } fn env(k: &str) -> Result { std::env::var(k).map_err(|_| format!("{k} is not set")) } #[tokio::main] async fn main() -> Result<(), Box> { let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "18790".into()).parse()?; let refresh: u64 = std::env::var("ALLOWEDBY_REFRESH_SECONDS").unwrap_or_else(|_| "5".into()).parse()?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), )?; let db = Db::default(); let service = AllowedByLayer::new(aby).layer(tower::service_fn(move |req| app(db.clone(), req))); let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?; println!("interop app listening on {port}"); loop { let (stream, _) = listener.accept().await?; let service = TowerToHyperService::new(service.clone()); tokio::spawn(async move { if let Err(e) = http1::Builder::new().serve_connection(TokioIo::new(stream), service).await { eprintln!("connection: {e}"); } }); } } ``` **actix-web**: `App::new().wrap(allowedby::actix::AllowedBy::new(service))`; handlers take `AllowedByContext`. Feature `actix` (`sdks/rust/examples/frameworks/actix-web/main.rs`): ```rust //! actix-web: the notes API of sdks/interop/reference_app.py behind the actix-web middleware; the interop test runs //! against it (sdks/CONTRACT.md §6). //! //! ALLOWEDBY_ORIGIN=http://localhost:18790 ALLOWEDBY_NODE=http://localhost:18780 PORT=18790 \ //! cargo run --release --features actix --example interop_actix use actix_web::{web, App, HttpResponse, HttpServer}; use allowedby::actix::AllowedBy; use allowedby::{AllowedByContext, Class, Options, Org, Route, Service}; use serde_json::{json, Value}; use std::collections::HashMap; use std::sync::Mutex; #[derive(Default)] struct Notes { by_person: HashMap>, last_id: u64, } type Db = web::Data>; fn list(notes: &[(String, String)]) -> Value { Value::Array(notes.iter().map(|(id, text)| json!({"id": id, "text": text})).collect()) } async fn health() -> HttpResponse { HttpResponse::Ok().json(json!({"ok": true})) } async fn me(ctx: AllowedByContext) -> HttpResponse { HttpResponse::Ok().json(json!({"agent": ctx.agent, "operator": ctx.operator, "level": ctx.level})) } async fn get_notes(db: Db, ctx: AllowedByContext) -> HttpResponse { let db = db.lock().unwrap_or_else(|e| e.into_inner()); let mine = ctx .human_id .as_ref() .and_then(|h| db.by_person.get(h)) .map(|n| list(n.as_slice())) .unwrap_or_else(|| json!([])); HttpResponse::Ok().json(json!({"notes": mine})) } async fn add_note(db: Db, ctx: AllowedByContext, body: web::Bytes) -> HttpResponse { let text = serde_json::from_slice::(&body) .ok() .and_then(|v| v.get("text").and_then(Value::as_str).map(str::to_owned)); let Some(text) = text.filter(|t| !t.is_empty() && t.chars().count() <= 2000) else { return HttpResponse::BadRequest().json(json!({"error": "text: a string of 1 to 2000 characters"})); }; let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); db.last_id += 1; let id = db.last_id.to_string(); if let Some(h) = &ctx.human_id { db.by_person.entry(h.clone()).or_default().push((id.clone(), text)); } HttpResponse::Created().json(json!({"id": id})) } async fn delete_note(db: Db, ctx: AllowedByContext, id: web::Path) -> HttpResponse { let id = id.into_inner(); let mut db = db.lock().unwrap_or_else(|e| e.into_inner()); if let Some(mine) = ctx.human_id.as_ref().and_then(|h| db.by_person.get_mut(h)) { mine.retain(|(i, _)| *i != id); } HttpResponse::Ok().json(json!({"deleted": id})) } async fn not_found() -> HttpResponse { HttpResponse::NotFound().json(json!({"error": "not found"})) } fn env(k: &str) -> std::io::Result { std::env::var(k).map_err(|_| std::io::Error::other(format!("{k} is not set"))) } fn number(k: &str, default: &str) -> std::io::Result { std::env::var(k) .unwrap_or_else(|_| default.into()) .parse() .map_err(|_| std::io::Error::other(format!("{k}: a number"))) } #[actix_web::main] async fn main() -> std::io::Result<()> { let port: u16 = number("PORT", "18790")?; let refresh: u64 = number("ALLOWEDBY_REFRESH_SECONDS", "5")?; let aby = Service::new( Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Interop Ltd", "FR")) .route(Route::get("/me").level(0).summary("Who is calling")) .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*").summary("List your notes")) .route( Route::post("/notes") .capability("notes:write") .class(Class::Write) .level(1) .resource("note:new") .summary("Add a note") .body_field("text", "the note"), ) .route( Route::delete("/notes/{id}") .capability("notes:delete") .class(Class::WriteHard) .level(2) .resource("note:{id}") .summary("Delete a note"), ) .template("notes:read", "Read your notes") .template("notes:write", "Write new notes") .template("notes:delete", "Delete note {scope}") .title("Notes Interop API") .refresh_seconds(refresh), ) .map_err(std::io::Error::other)?; let db: Db = web::Data::new(Mutex::new(Notes::default())); let server = HttpServer::new(move || { // the handlers of the routes of the map, registered with the service: CONTRACT §2.10 rule 5 holds for them (an // alias of one on another path, another method or a catch-all is refused); /health is the app's own page App::new() .app_data(db.clone()) .wrap(AllowedBy::new(aby.clone())) .route("/health", web::get().to(health)) .service(allowedby::actix::get(&aby, "/me", me)) .service(allowedby::actix::get(&aby, "/notes", get_notes).post(add_note)) .service(allowedby::actix::delete(&aby, "/notes/{id}", delete_note)) .default_service(web::to(not_found)) }) .bind(("127.0.0.1", port))?; println!("interop app listening on {port}"); server.run().await } ``` **Any other framework**: build an `allowedby::Request` (method, path as sent, query, headers, body bytes) and call `service.handle(&request)`: `Outcome::Respond(response)` is what to send, `Outcome::Forward(context)` means call your handler with that context (`None` outside the route map). `sdks/rust/examples/testing.rs` shows it. ### Your own sub-resources With `GET /notes/{id}` on the map, your own `GET /notes/{id}/comments` is refused with `400` until you declare it. The refusal names the route it is below and the line to add, and the service lists the routes concerned once in its log at startup. Declare the template with the method your handler serves, and a word of its own (a template that a route of any method reaches must name its method). A page the rules above take for a variant is declared by its exact path, `Options::unprotected_for("GET", "/notes.json")`. An entry a router may read as another path (`;`, `%`, `\`, dot segments), or that is a route of the map but for its last `/`, fails at construction (`sdks/rust/examples/sub_resources.rs`): ```rust //! Your own sub-resources: below a route of the map that has a parameter, a path is refused (400) until the app //! declares that a handler of its own serves it. The refusal names the line to add. Runs offline: //! `cargo run --example sub_resources`. use allowedby::{Options, Org, Outcome, Request, Route, Service}; fn main() -> Result<(), Box> { let notes = || { Options::new("https://notes.example", "https://node.example.org") .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes/{id}").capability("notes:read").resource("note:{id}")) .template("notes:read", "Read note {scope}") .background_refresh(false) }; let comments = Request::new("GET", "/notes/7/comments"); // not declared: refused, and the answer says what to add let Outcome::Respond(r) = Service::new(notes())?.handle(&comments) else { return Err("not refused".into()) }; let detail = String::from_utf8(r.body)?; assert_eq!(r.status, 400); assert!(detail.contains(r#"Options::unprotected_for(\"GET\", \"/notes/{id}/\")"#), "{detail}"); assert!(!detail.contains("comments"), "the answer never repeats the path: {detail}"); // declared: it reaches your app, without a context (your own authentication applies) let aby = Service::new(notes().unprotected_for("GET", "/notes/{id}/comments"))?; assert_eq!(aby.handle(&comments), Outcome::Forward(None)); println!("ok: /notes/7/comments is refused until declared, then reaches the app"); Ok(()) } ``` ### Handler identity (CONTRACT §2.10 rule 5): register your handlers Rule 5 asks an adapter to refuse any request not checked for a route that would run that route's handler: an alias on another path, another method, a catch-all, one function on two routes that do not cover each other. No Rust adapter sees on its own which handler its router chose: - **axum** (`protect`, and any tower stack): the layer runs in front of the whole `Router`, before it routes. axum names the rule it matched only to the matched route's own services (`MatchedPath`, after routing), and nothing in axum tells which function a route runs: a `Router` cannot be listed, and two `.route(..)` calls with one handler are two unrelated services. - **actix-web** (`AllowedBy` on the `App` or a `web::scope`): the middleware runs before the resource is chosen. `ServiceRequest::match_pattern()` compares patterns only (it ignores method guards), and actix-web does not expose which function a resource's route runs. So register the handlers of your routes with the SDK. With axum: `allowedby::axum::{get, post, put, patch, delete, any}(&service, path, handler)` in place of `axum::routing`'s, with the path the route map writes for them (the axum app above does). Under `nest`, with `protect` around the outer router, that is the full path, mount prefix included: `.nest("/api", Router::new().route("/notes/{id}", delete(&aby, "/api/notes/{id}", remove)))`; a handler registered with the path inside the mount answers `400` on its route, with a refusal that says so. Each registration records the handler's type (every function item and closure expression has its own; the closures one generic function returns share one, so they count as one handler) and its method and path, and runs after routing, where axum names the rule that matched. Rule 5 then holds for registered handlers, so the Known gaps line says `rules 1-4, 6` and this guide says rule 5 with registered handlers: - a registered handler of a route of the map runs only for a request checked for that route (HEAD is read as GET); registered on another path, under another method or behind a catch-all (`any(&service, "/{*rest}", handler)`), it answers `400` there, with a refusal that names the fix and never the path; - registered on two routes of the map, it runs only for a request checked for a route that covers the other (the same capability, resource and amount fields; a level, tier, class and passkey at least as strong; a grant lifetime no longer); otherwise for neither, and the service logs both routes once, at registration; - a registered handler that serves no route of the map runs as before for a request checked for no route; for a request checked for a route, it is refused like any handler of another route: a literal page `/notes/export` registered next to `GET /notes/{id}` on the map gets that route's check and then `400` (CONTRACT §2.10 rule 5: a handler that serves only the request's value is refused). Give such a page a path no route of the map matches, or register it with `axum::routing`; - every handler registered with `axum::routing` behaves as before: the extractor below is what protects it. A function registered once with the SDK and again with `axum::routing` is seen only where it is registered with the SDK: register every use of a protected handler. With actix-web, register them the same way: `allowedby::actix::{get, post, put, patch, delete, any}(&service, path, handler)` build a resource whose handlers are registered, which you give to `.service(..)`; add the other methods of the same path on it (`get(&aby, "/notes", list).post(add)`), as one actix-web resource serves one path. The check runs after the resource is chosen, with the pattern actix-web matched (the actix-web app above does). Inside `web::scope("/api")`, the route map writes the whole path and the resource its own pattern: `allowedby::actix::delete(&aby, "/api/notes/{id}", remove).at("/notes/{id}")`. The same refusals apply, and the same pair line is logged. A request is checked against the route actix-web runs for it: the first of the resource's routes whose method takes it. For HEAD, every GET and `any` route of the resource is checked, and each must allow it, so a registered handler never runs unchecked whichever of them actix-web picks. What protects an unregistered handler is that it takes `AllowedByContext`. The extractor fails (`500`) when no route of the map was checked for the request, so a protected handler's body never runs for an unchecked request, whatever path reached it; it cannot tell which route was checked. So give each protected route its own handler, taking `AllowedByContext` (not `Option`), register it, and do not give it to another path or a catch-all (`/{*rest}`, `{tail:.*}`) through the framework's own API. A site-wide catch-all that dispatches protected actions on paths no route maps (a legacy front controller that deletes at `/legacy/delete?id=7`) is not something any adapter can see, and a front controller shared by routes of different capabilities or resources runs for none of them: give each protected route its own handler. ### A request changed after the check A layer between the SDK and your handler can rewrite an accepted request: a tower layer or axum's `map_request` on the router inside `protect`, an actix-web middleware wrapped before `AllowedBy`, a rewrite of the URI or a method override. The handler would then act on values the person never approved. So the SDK keeps, with an accepted request, the method it checked (HEAD as GET) and its normalised path, and refuses it with `400 invalid_request` (never repeating the path) where it can see the handler run: in the `AllowedByContext` extractor (axum's `Option` too; with actix-web, `allowedby::actix::OptionalContext`, since actix-web turns an error of an extractor inside `Option` into `None`), and in the handlers registered with `allowedby::axum::{get, ...}` or `allowedby::actix::{get, ...}`. Another spelling of the same path (`/notes/%37` for `/notes/7`) and a mount axum's `nest` took off the path are not changes. Limit: a handler that takes no `AllowedByContext` and is not registered runs whatever a layer did to the request. Put no layer that rewrites the method or the URI after the SDK, and take path values from the context's `params`. ## The context A handler of an accepted request receives `AllowedByContext`, a read-only `Context` (it derefs to it) with who is calling, for whom, and with which approval. | Field | Type | What | |---|---|---| | `agent` | `String` | The agent: its passport `sub`. | | `operator` | `String` | The agent's operator (vendor), `operator.id`. | | `human_id` | `Option` | The person's pairwise id at your service (different at every service); `None` on level-0 routes. Key their data on it. | | `level` | `u8` | The identity level of this request (0 to 3). | | `capabilities` | `Vec` | The grant's capabilities. | | `display` | `Option` | What the person approved: `{summary, lines, lang}`. | | `gid`, `rev`, `jti` | `Option`, `Option`, `Option` | The leaf grant's id, revision and `jti`. | | `acting_for` | `Option` | Company mandates: always `None` (not supported yet). | | `tenant` | `Option` | The `{tenant}` path parameter, when the route has one, decoded once as in `params`. | | `route` | `RouteInfo` | The route matched: method, path pattern, capability, class used, level. | | `chain` | `Vec<(String, Option)>` | The grant chain, leaf first: (gid, rev). | | `human_iss` | `Option` | The person's home node. | | `linked_account` | `Option` | On a `require_link` route, your account the person is linked to (Account linking); `None` elsewhere. | | `proof_jti` | `String` | The proof's `jti` (or RFC 9421 nonce), for your audit log. | | `run`, `call` | `Option`, `Option` | The agent's run id and call number, audit only. | | `params` | `BTreeMap` | The route's path values as the SDK checked them: each `{name}` of the route, from the normalised path, decoded once. | Act on `params`, never on your own reading of the raw path: the two can differ (`/notes/%37` is checked as note `7`; `/notes/%2561` gives `%61`, decoded once, not `a`). A framework router already hands your handler the values it matched (axum's `Path`, actix-web's `web::Path`), and the SDK refuses a path that it would read another way; a service without a router, behind the tower layer or on hyper, takes them from `params` (`sdks/rust/examples/frameworks/tower/main.rs`, `sdks/rust/examples/frameworks/hyper/main.rs`). ## Production In production, keep the keys in a private file or a secret manager, share one store between instances, choose your trust (one node, or a signed trust list), and leave the refresh running. - **Keys** (`key_file(path)` or `keys(Keys)`): the signing key (Ed25519) signs your organisation profile and your approval requests; the disclosure key (P-256) receives personal data. Without either, both are new at each start and agents re-fetch `/.well-known/allowedby`. The file uses the Python SDK's format, is created with mode 0600, and concurrent starts agree on one file (first writer wins, every start uses the keys on disk). The folder needs hard links: on a file system without them the first start fails and says so; create the file elsewhere and point `key_file` at it, or write it from your secret manager. An existing file works anywhere. - **Store** (`store(Arc)`): the replay set, single-use consumption and counters. `MemoryStore` (the default) is for one process only: behind a load balancer use `RedisStore` (feature `redis`) or your own `Store`. A store error refuses the request (`503 status_stale`, the agent retries). - **Refunds** (CONTRACT §2 item 10): the check spends the approval (a single-use grant's mark, its `count` and `amount` totals). When the SDK itself then refuses that accepted request before its handler started, it gives back exactly what the request spent, once, so the approval serves the request on its own route afterwards. That covers the guard of a registered handler (axum's `allowedby::axum::{get, post, ..}`, actix-web's `allowedby::actix::{resource, get, ..}`): a refusal of rule 5, or of a request changed after the check. Nothing is refunded once a guard handed the request to its handler, for a refusal of your own (a handler, a layer or a middleware that answers), or for the `AllowedByContext` and `OptionalContext` extractors, which run inside the handler. A request for a route that no registered handler serves is spent for good as the layer or middleware hands it on (a handler the SDK does not know may act on it), and every request is once the app has answered it. A refunded request never reaches a handler, even dispatched again (`400`). A refund the store does not take leaves the approval spent, and is logged without request data. A store refunds with a `charge` of negative increments and no maximum, which it applies exactly (`Store::charge`). - **Trust**: by default the node's key is pinned on first fetch (trust on first use). `trust_list(jws)` takes a signed OAID-5 list (anchors, programs, vouching, witnesses) instead; it must be signed by your own key. - **Refresh**: node statements and status lists are fetched every `refresh_seconds` (default 5, at least 1, at most 60) on a background thread, never on the request path. `Service::new` returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new instance, or one that scales to zero) holds the node's keys and status lists before its first request; it blocks the calling thread that long, so build the service at startup, before serving. A failed refresh logs `[verifier] refresh failed: ...` on stderr and the cache keeps serving; an old status list then fails closed. - **Logging**: nothing per request by default; `log_requests(true)` prints the method, route pattern and outcome code (no ids, no tokens, no bodies). - **Several instances**: share the key file (or `Keys`) and the store; each instance refreshes on its own. - **Listening**: the example listens on loopback (`127.0.0.1`) unless `ALLOWEDBY_BIND` says otherwise (the name the Python SDK reads); in a container set `ALLOWEDBY_BIND=0.0.0.0`, as the repository's Dockerfile does. (`sdks/rust/examples/production.rs`): ```rust //! Production settings: keys kept in a private file, a store shared by every instance (Redis), an optional signed //! trust list, the refresh interval and request logs. Environment: ALLOWEDBY_ORIGIN, ALLOWEDBY_NODE, //! ALLOWEDBY_KEY_FILE, REDIS_URL, ALLOWEDBY_TRUST_LIST (a file, optional), PORT, ALLOWEDBY_BIND (the address to //! listen on: loopback only by default, `0.0.0.0` in a container). use allowedby::{AllowedByContext, Options, Org, RedisStore, Route, Service}; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; use std::sync::Arc; async fn notes(ctx: AllowedByContext) -> Json { Json(json!({"notes": [], "for": ctx.human_id})) } #[tokio::main] async fn main() -> Result<(), Box> { let env = |k: &str| std::env::var(k).map_err(|_| format!("{k} is not set")); let mut opts = Options::new(&env("ALLOWEDBY_ORIGIN")?, &env("ALLOWEDBY_NODE")?) .org(Org::new("Notes Ltd", "FR").privacy_policy("https://notes.example/privacy")) .route(Route::get("/notes").capability("notes:read").resource("note:*")) .template("notes:read", "Read your notes") // the signing key and the disclosure key: created once (mode 0600), the same on every instance .key_file(env("ALLOWEDBY_KEY_FILE")?) // replay set, single use and counters shared by every instance .store(Arc::new(RedisStore::open(&env("REDIS_URL")?, "notes")?)) // node statements and status lists every 5 s (status lists at least every 60 s whatever you set) .refresh_seconds(5) .log_requests(true); if let Ok(path) = std::env::var("ALLOWEDBY_TRUST_LIST") { // an OAID-5 trust list signed by this service's own key, instead of trust on first use of the node opts = opts.trust_list(std::fs::read_to_string(path)?.trim()); } let aby = Service::new(opts)?; let app = allowedby::axum::protect(Router::new().route("/notes", get(notes)), aby); let port: u16 = std::env::var("PORT").unwrap_or_else(|_| "8080".into()).parse()?; // unset or empty: loopback only let bind = std::env::var("ALLOWEDBY_BIND").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "127.0.0.1".into()); axum::serve(tokio::net::TcpListener::bind((bind.as_str(), port)).await?, app).await?; Ok(()) } ``` ## Agents The Rust SDK is a service SDK only: agents call your API with the Python or TypeScript agent SDKs (see [python.md](https://docs.allowedby.com/sdk/python) and [js.md](https://docs.allowedby.com/sdk/js)), which handle passports, proofs, challenges and approvals. ## Errors Every refusal is an RFC 9457 problem (`application/problem+json`, `type: https://allowedby.org/errors/`); the codes and statuses are the same in every AllowedBy SDK. | Code | Status | Meaning | What to do | |---|---|---|---| | `invalid_request` | 400 | Malformed envelope, a body that is not a JSON object, a passport and grants mixed, a header sent twice, a variant of a protected path or a method override. | Fix the request. | | `passport_required` | 401 | No `Allowed-By` header. | The agent gets a passport from its node and retries. | | `invalid_signature` | 401 | A signature, proof, replay, request binding or chain failed. | Sign a fresh proof for this exact request; never replay. | | `untrusted_node` | 401 | The document comes from a node this service does not trust (or not fetched yet). | Use a trusted node; the service checks its trust. | | `insufficient_witnesses` | 401 | The node's log has too few trusted witnesses (trust list `witnesses_min`). | The node operator fixes its witnessing. | | `grant_required` | 401 | The route needs the person's approval (challenge). | Ask the person through the node (or follow `approve`), then retry. | | `grant_insufficient` | 401 | The grant does not cover this request (capability, scope, amount, audience, initiator, digest). | Ask for an approval that covers it. | | `level_insufficient` | 401 | A higher identity level is needed. | The person verifies their identity at the level named, then approves. | | `qes_required` | 401 | A qualified electronic signature is needed. | Approve with a qualified signature (not available with this SDK yet). | | `authority_required` | 401 | The organisation's co-approvers must approve (extended; never sent by this SDK). | Collect the approvals the policy names. | | `mandate_required` | 401 | The person must act under a company mandate (this SDK refuses every grant acting for an organisation: mandates are not supported yet). | Approve for the company with its mandate, or as yourself. | | `expired` | 401 | The grant expired. | Ask for a new approval. | | `not_yet_valid` | 401 | The grant is not valid yet. | Retry later or check clocks. | | `revoked` | 401 | The grant, an ancestor or the person's registration was withdrawn. | Ask again; the person may refuse. | | `actor_expired` | 401 | The agent's key in the grant expired (`rebind: true`). | Rebind the grant to the new key (ABY-1 §6) or ask again. | | `class_lifetime_exceeded` | 401 | The grant lasts longer than the route's class allows. | Ask for a shorter approval. | | `single_use_consumed` | 401 | The single-use grant was already used. | Ask for a new approval for this request. | | `capability_denied` | 403 | No such route or capability. | Do not retry. | | `tier_insufficient` | 403 | The agent's key custody or the person's authenticator is too weak. | Use a stronger key custody or authenticator. | | `human_not_linked` | 403 | The person is not linked to the account this route serves (Account linking), or `link_authorize` said no. | Link the account (`aby:link`). | | `budget_exceeded` | 403 | The tenant's budget for this action cannot take this amount, or the request has none in its currency (Tenant budgets). | Wait for the next period or raise the budget. | | `rate_limited` | 429 | Too many calls of this agent or of its operator (Rate limits). | Retry after `Retry-After`. | | `envelope_too_large` | 431 | `Allowed-By` plus `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (a grant and one child). | Send a shorter chain. | | `status_stale` | 503 | The revocation list is too old, or the replay store is unreachable (fail closed). | Retry after `Retry-After`. | The challenge codes (`grant_required`, `grant_insufficient`, `level_insufficient`, `qes_required`, `mandate_required`, `expired`, `revoked`, `class_lifetime_exceeded`, `single_use_consumed`, `actor_expired`) come with `WWW-Authenticate: AllowedBy realm=..., error=..., action=..., scope=..., class=..., level=..., tier=...`; on `write-hard` and `irreversible` routes also `code`, `approve`, `poll`, `request` and `expires` of the approval the service created. ## Testing Run the CONF-1 vectors, the unit and adapter tests, and the interop test against a real node; test your own app with plain values, without a browser. ```bash cd sdks/rust cargo test --all-features --test vectors -- --nocapture # prints "481/481 cases passed" cargo test --all-features # REDIS_URL=redis://127.0.0.1:6379/ runs the Redis tests too cargo build --release --features axum --example interop cd ../.. && pip install -r requirements.txt python sdks/interop/interop.py --cmd "sdks/rust/target/release/examples/interop" --cwd . ``` ```powershell cd sdks/rust cargo test --all-features --test vectors -- --nocapture cargo test --all-features cargo build --release --features axum --example interop cd ../..; pip install -r requirements.txt $env:INTEROP_PORT_BASE = "19800" python sdks/interop/interop.py --cmd "sdks/rust/target/release/examples/interop" --cwd . ``` The vectors are read from `vectors/` at run time (`vectors/profiles.json`, profile `verifier`); the runner fails on any failure or any case it cannot run. The interop test prints `26/26 interop scenarios passed`. Your own app, offline (`sdks/rust/examples/testing.rs`): ```rust //! Test your own app without a browser or a node: the SDK's answers are plain values. //! Runs offline: `cargo run --example testing`. use allowedby::{Class, Code, Options, Org, Outcome, Request, Route, Service}; fn main() -> Result<(), Box> { let aby = Service::new( Options::new("https://notes.example", "https://node.example.org") .org(Org::new("Notes Ltd", "FR")) .route(Route::get("/notes").capability("notes:read").resource("note:*")) .route(Route::delete("/notes/{id}").capability("notes:delete").class(Class::WriteHard).level(2)) .template("notes:read", "Read your notes") .template("notes:delete", "Delete note {scope}") .clock(|| 1_761_480_000) // a fixed time: tests are repeatable .background_refresh(false), // no network: install documents yourself if you need them )?; // a call without a passport gets the challenge every agent understands let Outcome::Respond(r) = aby.handle(&Request::new("GET", "/notes")) else { return Err("not refused".into()) }; assert_eq!(r.status, Code::PassportRequired.status()); assert_eq!(r.header("WWW-Authenticate"), Some("AllowedBy realm=\"notes.example\", error=\"passport_required\"")); // a path outside the route map reaches your app unchanged, without a context assert_eq!(aby.handle(&Request::new("GET", "/health")), Outcome::Forward(None)); // the discovery document names every capability and the sentence the person signs let wk = aby.well_known(); assert_eq!(wk["templates"]["notes:read"]["summary"]["en"], "Read your notes"); assert_eq!(wk["capabilities"][1]["class"], "write-hard"); println!("ok: refusals, paths outside the map and discovery behave as expected"); Ok(()) } ``` To accept requests in tests, install a test node's statement and status list with `service.verifier().install_node(..)` and `install_status_list(..)`, and sign passports and proofs with `SigningKey` and `proto::make_proof` (the crate's `tests/common/mod.rs` does exactly this). ## Reference The public API: one service, its options, the route map, the context, the store, and the building blocks the conformance runner uses. | Item | What | |---|---| | `Service::new(Options) -> Result` | The SDK. `Clone` (an `Arc`). Starts the background refresh and returns once its first run is over (at most 5 s). | | `Service::handle(&Request) -> Outcome` | The middleware in one call: endpoints, then the check. | | `Service::check(&Request) -> Result, Response>` | The check alone (`Ok(None)` outside the map). | | `Service::endpoint(&Request) -> Option` | The SDK's own endpoints alone: discovery, and `POST /allowedby/link`. | | `Service::link_start(&account) -> Result`, `link_start_ttl(&account, ttl)` | A linking code for one of your accounts (Account linking). | | `Service::challenge(&Request, &Reject) -> Response` | The answer to a refusal. | | `Service::well_known()`, `openapi()`, `api_catalog()` | The discovery documents as JSON. | | `Service::verifier()`, `refresh_now()`, `origin()`, `kid()`, `sign(typ, payload)` | The verifier, a refresh now, the origin, the signing kid, a JWS signed by this service. | | `Options::new(origin, node)` | `.org`, `.route`, `.routes`, `.template`, `.key_file`, `.keys`, `.store`, `.trust_list`, `.unprotected`, `.unprotected_for`, `.refresh_seconds`, `.node_max_level`, `.clock`, `.title`, `.version`, `.description`, `.rfc9421`, `.http_client`, `.background_refresh`, `.log_requests`, `.link_authorize`, `.nonce`, `.rate`, `.tenants`. | | `Org::new(legal_name, country)` | `.website`, `.support`, `.privacy_policy`. | | `Template::new().lang(lang, summary, line)`, `Template::from(&str)` | A capability's sentences. | | `Route`, `Class`, `Authn`, `Threshold`, `MAX_LIFETIME` | The route map (section Routes and templates); `Route::validate`, `Route::from_json`. | | `Outcome::{Respond(Response), Forward(Option)}` | What to do with a request. | | `Request { method, path, query, headers, body }`, `Response { status, headers, body }` | Framework-neutral HTTP. | | `Context`, `RouteInfo`, `AllowedByContext` | The verified context (section The context); `AllowedByContext` is the extractor. | | `LinkError`, `LinkAuthorize` | Why no linking code was given; the type of `Options::link_authorize`'s rule. | | `Code`, `Reject`, `ConfigError` | Refusal codes (`as_str`, `status`, `is_challenge`), a refusal, a configuration error. | | `Store`, `MemoryStore`, `RedisStore`, `Charge`, `StoreError` | The store interface and its implementations. | | `Keys`, `SigningKey` | The service's keys (`load_or_create`, `generate`, `from_seed`). | | `AllowedByLayer` (feature `tower`), `allowedby::axum::protect` (feature `axum`), `allowedby::actix::AllowedBy` (feature `actix`) | The framework integrations. | | `verifier::Verifier` | `verify`, `node_doc`, `status_bit`, `human`, `registration`, `install_node`, `install_status_list`, `set_nodes`, `nodes`. | | `trust::{Statement, TrustList, Checkpoint}`, `refresh::{Refresher, Trust}` | Node statements, OAID-5 trust lists, signed notes and witnesses, the refresh. | | `jose`, `json`, `proto`, `b64`, `util`, `caps`, `http` | Building blocks: JWS and thumbprints, strict JSON and JCS, grant cores and digests, base64, paths and amounts, constraints and display, the HTTP client trait. | | `SPEC_VERSION` | `"0.2.14"`. | --- Source: https://docs.allowedby.com/status # Test results The newest passing run of each SDK, up to the version served here, on the commit shown. A version is published only when every check on its own commit passed. ## Run one now A live run against the demo, with a test passkey, in your browser. ## What the numbers mean - **Conformance cases** are exact inputs with the outcome every SDK must reach: signatures, levels, limits, replay, withdrawal. See [test vectors](https://docs.allowedby.com/vectors). - **End-to-end scenarios** run the SDK's app against a real node, a real agent and a person with a test passkey. - **Recipes** are the examples of this site, run one by one, refusals included. What each guarantee rests on, and what is not covered, is in [how it is tested](https://docs.allowedby.com/assurance). --- Source: https://docs.allowedby.com/assurance # How it is tested Every guarantee below has a test that runs in CI. A failure in any workflow of a commit stops its deploy. ## The guarantees, and what proves them | Guarantee | Proved by | Where | |---|---|---| | Signed documents, levels, limits, replay and revocation are checked exactly as the specifications say | Conformance vectors: 453 verifier cases and 122 runtime cases, in all eight SDKs; `vectors/verify.py`, a second verifier that shares no code with the first | `vectors/`; each `sdk-*` workflow; `test` | | A test notices when the verifier is broken | Mutation testing: every small breaking change to the verifier must fail a test | `tools/mutate.py`; workflow `assurance` | | An SDK works with a real node, a real agent and a person with a passkey | End-to-end test: 26 scenarios for services, 7 for agents | `sdks/interop/`; each `sdk-*` workflow | | A request cannot go around the route map | 31 variants of protected requests (paths, methods, overrides) sent to every SDK, none served | `sdks/interop/`, scenario "NO WAY AROUND"; each adapter's own tests | | The whole product works: node, wallet, approvals, organisations, identity, logs | 225 end-to-end scenarios | `demo/e2e.py`; job `test` | | Identity sources and their cryptography (eID, passports, wallets, MDS3, signatures) | Unit tests against simulators that sign for real | `demo/tests/`; job `test` | | The security code stays covered | A floor per module, lines and branches | `tools/coverage_floors.json`; job `test` | | Two instances starting together share one key | Threads and processes racing to create the key file, in every SDK | each `sdk-*` workflow | | No known vulnerability, no secret in the repository | Dependency audit, static analysis, secret scan of the history | job `security` | | The documentation is true | Links, anchors, code blocks, error tables against the verifier, counts, installs; examples compared with files that CI runs | `tools/docs.py`, job `quality`; `test_docs` of each SDK | | The reference matches the code | Generated, and compared in CI | `tools/build_reference.py`, job `reference` | | Specifications are versioned | Change log and version of every changed document | `tools/check_versions.py`, job `test` | | Every change is read critically | AI review of each pull request; a blocking finding fails it | workflow `ai review` | ## Mutation testing `tools/mutate.py` makes one small change at a time to `verifier.py` (and to `agent.py`, the runtime): a comparison reversed, a condition dropped, a refusal removed. A test must fail. When it was first run, 1103 of 1614 changes were noticed. The missing tests were written, most of them as vectors so that every SDK is held to them, and redundant code was deleted. Now every change is noticed except the ones in `tools/mutants_equivalent.txt`, each with the reason it changes no behaviour. Writing them found two defects, both fixed: a document dated in the future was accepted, and a vouch signed with a revoked key still counted. The complete run takes place every week; a pull request that changes the verifier runs one eighth of it. ## Stability The end-to-end demo runs 20 times in a row every week. A test that fails once is a defect to find, not to retry. ## What is not covered - **No independent security audit** has been made. The reviews are automated. - **Hardware attestation** (TPM, Secure Enclave, cloud KMS) and **qualified signatures** are tested with simulated certificate chains; the real ones need vendor hardware and EU trusted lists. - **Identity providers** are tested against their sandboxes or simulators, not in production. - **Mutation testing covers the verifier and the agent** of the Python reference. The other SDKs are held to the same vectors, but their own code is not mutated. - **`node.py`, the node, is at 81% coverage**, and it is tested by the end-to-end scenarios rather than by vectors. - **Load**: the tests check that 20 parallel agents work, not a production load. - **Windows and macOS**: the SDKs run mainly on Linux in CI; .NET also runs on Windows. ## Run it yourself ```bash pip install -r requirements.txt python demo/e2e.py # the whole product python vectors/verify.py # every vector, with the second verifier python sdks/python/tests/conformance.py # every vector, with the Python SDK python sdks/interop/interop.py --cmd "python sdks/interop/reference_app.py" python tools/docs.py check # the documentation python tools/mutate.py sdks/python/src/allowedby/verifier.py --no-e2e # about an hour on 8 cores python tools/mutate.py sdks/python/src/allowedby/agent.py --no-e2e # about 10 minutes ``` --- Source: https://docs.allowedby.com/vectors # AllowedBy test vectors (v0.2.14-draft) **TEST ONLY.** Every key in these files comes from a public seed. Never use them outside conformance testing. These are the CONF-1 §4 vectors. They follow `specs/` v0.2.14-draft (CHANGES-0.2 §1–§28). ## What they are for A spec in prose is read differently by every implementer. These files turn it into exact bytes and verdicts: fixed keys, signed documents, HTTP requests, each with the outcome every implementation MUST reach ("accept" plus the identity tuple, or a precise error code and status). - **Implementers** (SDKs, nodes, verifiers in any language) run their code over every case. A disagreement means either the code or the spec is wrong, and it shows up before production. - **Interop**: two independent implementations that both pass are byte-compatible (JCS, signatures, hashes, WebAuthn challenges, Merkle roots). - **Conformance claims** (CONF-1 §2): "passes the v0.2 vectors" is the testable claim. - **Spec review**: writing them forces every vague sentence to become a decision; the list below is what they surfaced. - **Regression**: any spec change regenerates the files; the diff shows exactly what changed on the wire. `verify.py` + `verify_ext.py` is a small reference verifier that shares no code with the generator (`generate.py` + `generate_ext.py`), so the two cross-check each other. ## Regenerate and check ```bash python generate.py # writes every *.json here; needs only `cryptography` (>= 44) python verify.py # reference verifier; asserts every case; exit 0 = all pass (601/601) ``` The output is deterministic: - Ed25519 seeds are `SHA-256("allowedby/test-vectors/0.2/ed25519/" || name)`. - P-256 scalars are derived the same way. - ES256 uses RFC 6979 deterministic nonces, so ES256 signatures are reproducible too. - Time is fixed at `now = 1761480000`. - ULIDs and jtis are hash-derived. Running the generator twice gives byte-identical files. The one caveat is the zlib build used for the status list. Do not hand-edit the files: regenerate them and diff. ## Files Each file has `cases: [{name, kind, input, expected, http_status?, output?, accept_tuple?}]`. `expected` is `"accept"` or a spec error code. | File | Contents | |---|---| | `keys.json` | All keys (public JWK, kid, private seed or scalar), the WebAuthn assertion builder recipe, the pairwise secret | | `jcs.json` | RFC 8785 cases: key order (UTF-16), `4200.00`→`4200`, number edge cases, unicode and escapes | | `node-statement.json` | Statements for `node.example.org` (role keys, `revoked_keys`) and `home.example.org` | | `service.json` | Verifier config: `public_origin`, trust anchors, route map, status max ages, service `initiator` key | | `human-reg.json` | `oaid-human+jwt` (with `rp_id`) and pairwise ids for two audiences | | `passport.json` | Passports A1 (tier 1), A2 (renewal, `prev`), A3 (new key), S1 (tier 0, ES256) and a wrong-role passport | | `grant-core.json` | Grant cores, core JCS, SHA-256, WebAuthn challenge, batch challenge | | `human-sig.json` | WebAuthn assertion with debug bytes, plus negative vectors: type, challenge, origin, rpIdHash, UP, UV, wrong key, altered display | | `grant.json` | Countersigned grant, levels chosen by the route (L3 accept, L2 on an L3 route, level 3 on a synced passkey, `qes_required`), wrong role, tampered payload, expired, class lifetime, `*` or other audience, level, `initiator`, amount and currency; then every rule a grant must satisfy, one case each side of its limit: time, status reference, revoked keys, audiences, the registration and its level, `human_sig` members, batches, the ABY-3 constraints, custody tier | | `proof.json` | Proof valid and invalid: htm, htu, query, normalisation, proxies, bdh, dth, iat ±119/120/121 and +59/60/61, `actor_expired`, kid, `alg none`, RS256, typ confusion, replay, the exact size budget, `jti` length, member types, `actor.exp` boundaries | | `chain.json` | Depth-1 attenuated child (ES256 leaf) and broken chains: one case per rule of ABY-1 §4 and ABY-3 §3, and which grant of a chain fails first | | `chain-depth.json` | ABY-2 §2 0.2.14: a chain is at most two JWS, counted before any JWS is parsed (`431 envelope_too_large`). Opt-in of the `verifier` profile: SDKs that still allow four JWS are on its `opt_out` list (CONTRACT Known gaps) | | `request-digest.json` | `request_digest` computations, single-use accept, reuse, query and body mismatch, bodiless DELETE | | `rebind.json` | Revisions 0/1/2 of one `gid` (same core and `human_sig`, distinct `jti`), node-side rebind via `prev` and via `operator_sig`, refusals | | `status.json` | Status-list sets (clean, revoked, stale, age 3599/3601), bit decoding, revoked grant and `human.reg`, fail-closed | | `revoked-ancestor.json` | Child valid, parent bit revoked → `revoked` | | `envelope-9421.json` | RFC 9421 / Web Bot Auth profile instead of the proof JWT: Ed25519 and ES256, passport and chain, signature base shown; refusals for uncovered components, `Content-Digest`, `tag`, `created` ±, `expires`, nonce replay, wrong `keyid`, internal `@target-uri` | | `passport-issuance.json` | `POST {passports}` with node nonce and `dth` over the key: tier 0 `none` (TTL capped), tier 0 `orchestrator` evidence (`valid_until`), node-scoped operator; refusals for nonce used or expired, wrong key, `dth`, tier 0 key reuse, P-384, unbound operator, tier 1 with `none`, stale, foreign or unregistered orchestrator evidence. Renewal: tier 1 accepted (`prev`), tier 0 refused, wrong key, attestation older than 7 days | | `challenge.json` | Service-initiated `grant_required` (with the service's signed `POST {approvals}`, the node's answer, `WWW-Authenticate`, problem JSON and `request_digest`), runtime-initiated (no `approve`/`poll`/`code`/`summary`), `passport_required` (realm and error only), `403` with no challenge, `503` with `Retry-After`; the challenge `scope` (escaped-path characters, at most 256 bytes, else `400`) | | `approval-states.json` | All 25 state pairs (4 allowed), poll status per state, who may poll, creation rules (`expires_in` 60–3600, audience, `initiator`, level, callback host, fair-use cap), re-request after `not_me`, `aid` and `code` alphabet | | `display.json` | `display` built from the service templates (en, fr, `{fields}`); refusals for a missing language, constraint or template, over 280 characters, non-decimal amount, non-ISO currency | | `log.json` | 8 entries (2 vouches, 6 passports) with salts and commitments, roots at sizes 1/3/4/7/8, checkpoints at 4 and 8 (C2SP signed notes), 2 witness cosignatures, inclusion and consistency proofs (good and bad), witness accept and conflict, log promise kept and broken | | `trust-list.json` | Signed trust list: anchors, a pinned and an unpinned program, `denied`, vouching at depth 1 and 2 with `min_vouchers` 2; refusals (depth 3, one voucher, expired vouch, old kid, vouching off, impostor statement); `witnesses_min` counting only trusted witnesses within 24 h | Not covered: positive QES (needs qualified certificate chains and EU trusted lists), and tier 1 and 2 hardware attestation evidence (TPM, Apple, Android, FIDO, cloud KMS, confidential computing). Those formats are vendor-defined and need real certificate chains; the vectors cover `none` and `orchestrator` only. ## Ambiguities found (and the reading used) All of these are now decided in the specs: see `specs/CHANGES-0.2.md` §16. 1. **File names.** Cases are split by topic; CONF-1 §4 now lists these files. 2. **`jti` in the core.** ABY-1 §3.1 puts `jti` in the core, but a revision is a new document. Per §15, `jti` is outside the core and each revision has its own. `iat`/`nbf`/`exp` stay in the core, so every revision keeps rev 0's `iat`. 3. **Revision numbering.** CONF-1 says "revisions 1 and 2", while ABY-1 says `rev` is 0 at issuance. The vectors use 0, 1 and 2. 4. **Status-list `typ`.** OAID-1 and OAID-2 say `oaid-status+jwt`; OAID-3 says `statuslist+jwt`. Per §15, `statuslist+jwt` is used. List age is measured from the list's `iat`. The read/write ceiling of 3600 s is inclusive. 5. **Error codes the specs don't name.** The vectors use: - `invalid_signature` for `human_sig` and chain-link failures (ABY-2 §5 step 3 only says "the failure code"); - `grant_insufficient` for an audience mismatch or `"*"`, an unmet constraint, a `request_digest` mismatch, and a failed `initiator` check; - `invalid_request` for node-side rebind refusals. 6. **`rpId`.** ABY-1 §3.2 says rpId = "approval origin", but an rpId is a host. The vectors follow §15: `human.reg.rp_id`, with origin `https://`. 7. **`htu` normalisation.** The comparison is strict. The proof's `htu` must already be normalised; `HTTPS://API.EXAMPLE.COM:443/…` is rejected. The verifier normalises the request path (percent-encoding, dot segments) and ignores forwarded headers. 8. **Pairwise id.** `‖` is taken as plain UTF-8 concatenation with no separator: `HMAC(home_secret, utf8(internal_id) || utf8(origin))`. 9. **Signature encodings differ.** `human_sig.signature` is ASN.1 DER (WebAuthn), while JWS ES256 is raw `r||s`. clientDataJSON uses the browser member order, not JCS. 10. **Rebind `operator_sig`.** No `typ` was given before §15. The vectors use `aby-operator+jwt` over `{gid, sub, aud, iat, exp ≤ iat+300}`, carried in the body as `{"operator_sig": …}`. The rebind proof is signed by the new passport key. 11. **`initiator` on chains.** Only the root has a core, so `initiator` is checked on the root. A child must carry `human` byte-identical to its parent's, and has no `display`, `human_sig` or `initiator`. 12. **Clock skew on `exp`.** The 60 s skew (OAID-1 §4.4) is applied to a grant's `exp`, so the expired vector uses `exp + 61`. Proof `iat` bounds are inclusive (−120 and +60 accept). 13. **Batch challenge encoding.** The `batch` entries' encoding is unspecified; base64url core hashes are used. 14. **`human.reg` status freshness.** The home node's status list follows the same per-class freshness as the route. 15. **RS256 vector.** It carries a junk 256-byte signature with no RSA key. It must be refused on `alg` alone. 16. **Constraints without state.** The reference verifier keeps no shared counters, so `count`, `amount per: grant` and `window` are treated as unsatisfiable (ABY-3 §3 permits this for services that cannot count). 17. **Vouch signer.** OAID-5 §4 does not say which key signs `oaid-vouch+jwt`. The vectors use the voucher's `issue` role key. 18. **Vouching depth with `min_vouchers`.** A node is at depth *d* when at least `min_vouchers` distinct trusted nodes at depth < *d* vouch for it. Anchors and program nodes are depth 0. 19. **Program level cap.** A program node's `max_level` is the lower of the program's anchor entry and the trust list's `programs[].max_level`. 20. **Program keys.** The trust list pins program keys by thumbprint (`kids`) only. The program list carries its JWK in the JWS header (`jwk`), checked against the pin. 21. **Checkpoint key name.** The signed-note key name is the log origin; cosignature key names are the witness node names. 22. **Witness refusals.** A second checkpoint of the same size with another root, and a failed consistency proof, are both labelled `conflict` here; on the wire the witness uses the C2SP `tlog-witness` statuses. 23. **Log promise.** `promise_broken` and `invalid_proof` are monitor findings, not registered error codes. 24. **RFC 9421 `alg`.** Optional; when present, the vectors use the RFC 9421 registry names `ed25519` and `ecdsa-p256-sha256`. `@target-uri` includes the query (unlike `htu`) and is built from `public_origin`. `Signature-Agent` is the quoted node origin. 25. **Display rendering.** One language for the whole display: the human's if every capability has it, else the first common one; no per-line fallback. `scope`, `fields` and `amount` values must match the ABY-3 §2 grammar before rendering, because they are copied into the text the human signs. `{fields}` is joined with ", ". 26. **Approval creation.** A caller that sends `initiator` gets `invalid_request` (it is not silently dropped). `level` must be 1 or 2. `callback` must be `https` on an audience host. 27. **Re-request after denial.** A repeat within 10 minutes of `not_me` or `unknown_agent` is `rate_limited`. 28. **Runtime-initiated challenge.** It also omits `expires`, since no approval exists yet. The problem JSON carries `status` and `single_use: false`. 29. **Issuance codes.** Nonce failures are `invalid_signature`; an unsupported key, an unverified domain operator and tier 0 key reuse are `invalid_request`. The orchestrator evidence format is defined here (`typ: oaid-orchestrator+jwt`, `{iss, runtime, sandbox, key, iat, exp}` in `custody.evidence.orchestrator`); OAID-6 only describes it. 30. **Renewal without evidence** keeps the old `custody` unchanged, including `valid_until`. --- Source: https://docs.allowedby.com/specs # AllowedBy — Specification Set Version 0.2.14-draft · 28 November 2026 · Status: working draft, not for implementation claims **AllowedBy** is the one brand: company, product, SDKs and badge. It has three layers: | Layer | Prefix | What it names | |---|---|---| | Identity and network | `oaid` (wire prefix only: `/.well-known/oaid`, `oaid-node`) | The passport, the nodes, the transparency log, trust lists, custody tiers, assurance levels, human registration. | | Consent | ABY | The grant, the capability model, the HTTP envelope and the challenge a service returns. | | Approval | AMH — the **AskMyHuman** page and link domain | The approval request, the link and binding code a human receives, the approval page on the human's home node and how the grant comes back. | ## Document map | Id | Title | Defines | |---|---|---| | CHANGES-0.2 | Changes in 0.2.x-draft | What changed and why. Normative for this revision; §15 (second review fixes) overrides earlier sections. | | [ARCH-1](https://docs.allowedby.com/specs/ARCH-1-architecture) | Product and technical architecture (informative) | The five surfaces, the hot path budget, node/runtime/service internals, threat model, the simplicity contract, targets, build order, product and governance. Read first. | | [OAID-1](https://docs.allowedby.com/specs/OAID-1-core) | Core: terminology, identifiers, cryptography, encodings | Vocabulary, identifier syntax, signature suites, JWS profile, errors, standards alignment, IANA, privacy. | | [OAID-2](https://docs.allowedby.com/specs/OAID-2-node) | Node: statement, discovery, endpoints | The `/.well-known/oaid` statement, node and role keys, DNS binding, the node HTTP API. | | [OAID-3](https://docs.allowedby.com/specs/OAID-3-passport) | Passport: format, issuance, renewal, revocation | The identity document of an agent runtime and its lifecycle. | | [OAID-4](https://docs.allowedby.com/specs/OAID-4-log) | Transparency log and witnessing | Commitment log, C2SP checkpoints, proofs, witness cosignatures, monitors. | | [OAID-5](https://docs.allowedby.com/specs/OAID-5-trust) | Trust lists, vouching, trust programs | How a service decides which nodes it accepts. | | [OAID-6](https://docs.allowedby.com/specs/OAID-6-custody) | Key custody tiers and attestation | Where private keys live, what evidence a runtime presents, how a node grades it. | | [OAID-7](https://docs.allowedby.com/specs/OAID-7-levels) | Assurance levels and human registration | L0 to L3, qualified signatures, human registration (`human.reg`), pairwise ids, organisational authority, privacy. | | [ABY-1](https://docs.allowedby.com/specs/ABY-1-grant) | Grant: format, human signature, delegation, lifecycle | The consent document, `display`, how a human signs it, revisions, attenuation, expiry. | | [ABY-2](https://docs.allowedby.com/specs/ABY-2-http) | HTTP envelope, proof, challenge | Two headers (`Allowed-By` + `AllowedBy-Proof`), the proof JWT, the `AllowedBy` challenge, verification algorithm, replay, rebind, errors. RFC 9421 via the Web Bot Auth profile, optional. | | [ABY-3](https://docs.allowedby.com/specs/ABY-3-capabilities) | Capability model | Capability strings, JSON constraints, attenuation rules, classes and their defaults. | | [AMH-1](https://docs.allowedby.com/specs/AMH-1-approval) | Approval flow and page | Creating an approval request, the link and binding code, states and polling, the page, step-up, denial. | | [ORG-1](https://docs.allowedby.com/specs/ORG-1-organisations) | Organisations | Organisation profile, SaaS and API provider configuration and tenants, personal data shared, budgets (grant, human, organisation), mandates to act for a company, fleet management of humans and agents. | | [CONF-1](https://docs.allowedby.com/specs/CONF-1-conformance) | Conformance profiles and test vectors | What a runtime, a node, a verifier and an approval page must implement; test vectors in `vectors/` (generated by `vectors/generate.py`). | ## Levels Assurance and authority are two axes. **L0**: an agent with a passport and no human (identification without consent). **L1**: a human with a passkey. **L2**: a human whose legal identity was verified (eIDAS substantial; EU Digital Identity Wallet by default). **L3**: verified at eIDAS high, on a hardware passkey. A route may also require a **qualified electronic signature**. The service chooses the level per route. Organisational authority is a separate `authority` countersign, not a level. Every grant carries a human passkey signature. ## Reading order Everyone: ARCH-1 first, for the shape of the system and why it is fast, secure and simple. CHANGES-0.2 if you read 0.1. Implementers of a **service** that wants to accept agents: OAID-1, ABY-2, ABY-1, OAID-7 §4 (just the human registration a grant embeds), OAID-5, ABY-3. Nothing else is required; a service never contacts a node at request time. **SaaS and API providers** setting up: ORG-1 §2–§3 first (profile, configuration file, setup steps, tenants), then the service list above. **Enterprises** managing staff and agents: ORG-1 §5–§8. Implementers of an **agent runtime**: OAID-1, OAID-3, OAID-6, ABY-2, AMH-1. Operators of a **node**: everything. ## Conventions The key words MUST, MUST NOT, REQUIRED, SHALL, SHOULD, SHOULD NOT, RECOMMENDED, MAY and OPTIONAL are to be interpreted as described in RFC 2119 and RFC 8174 when, and only when, they appear in all capitals. JSON examples are illustrative; where an example and normative text disagree, the text wins. All examples use `node.example.org` as a node, `acme.example` as an operator and `api.example.com` as a service. ## Versioning The **set version** is the highest document version, today 0.2.14-draft. Each document carries its own version and a **Change log** section at its end. Every change to a document, however small: 1. adds a row to that document's Change log (version, date, one-line change, the CHANGES section that holds the reasoning); 2. increments the document's version: the patch number for changes within a release (0.2.1 → 0.2.2), the minor number for a new release (0.2.x → 0.3.0); 3. raises the set version here if it is now the highest; 4. adds the reasoning to the current CHANGES file when it is normative. `tools/check_versions.py` checks rules 1–3 and runs in the pre-commit hook. Wire formats carry a `v` field; implementations MUST reject documents whose major version they do not implement. ## Change log Every change to this document adds a row here and increments its version (README, Versioning). | Version | Date | Change | |---|---|---| | 0.2.14-draft | 2026-11-28 | Set version 0.2.14-draft (CHANGES §28). | | 0.2.13-draft | 2026-11-26 | Set version 0.2.13-draft (CHANGES §27). | | 0.2.12-draft | 2026-11-26 | Set version 0.2.12-draft (CHANGES §26). | | 0.2.11-draft | 2026-11-19 | Set version 0.2.11-draft (CHANGES §25). | | 0.2.10-draft | 2026-11-18 | Set version 0.2.10-draft (CHANGES §24). | | 0.2.9-draft | 2026-11-08 | Set version 0.2.9-draft (CHANGES §23). | | 0.2.8-draft | 2026-10-29 | Set version 0.2.8-draft (CHANGES §22). | | 0.2.7-draft | 2026-10-29 | Set version 0.2.7-draft (CHANGES §21). | | 0.2.6-draft | 2026-10-29 | Set version 0.2.6-draft (CHANGES §20). | | 0.2.5-draft | 2026-10-29 | Set version 0.2.5-draft (CHANGES §19). | | 0.2.4-draft | 2026-10-29 | ORG-1 added to the map and reading order; set version 0.2.4-draft (CHANGES §18). | | 0.2.3-draft | 2026-10-28 | Levels L0–L3 and QES; set version 0.2.3-draft (CHANGES §17). | | 0.2.2-draft | 2026-10-27 | Set version 0.2.2-draft; versioning rule: every change adds a change-log entry and increments the version. | | 0.2.1-draft | 2026-10-27 | Set index updated for the second review fixes (CHANGES §15). | | 0.2.0-draft | 2026-10-27 | Single brand AllowedBy; document map and reading order rewritten for 0.2 (CHANGES §1). |