# 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
<dependency>
  <groupId>org.allowedby</groupId>
  <artifactId>allowedby-spring-boot-starter</artifactId>   <version>0.1.0</version>
</dependency>
```

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 | `<namespace>:*` |
| `.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<Route> 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<String, List<Map<String, String>>> 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<Map<String, String>> 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<String, List<Note>> notes = new ConcurrentHashMap<>();
    private final AtomicInteger ids = new AtomicInteger();

    @GetMapping("/health")
    Map<String, Boolean> health() { // not on the route map: no AllowedBy check
        return Map.of("ok", true);
    }

    @GetMapping("/me")
    Map<String, Object> me(@AllowedByContext Context ctx) {
        return Map.of("agent", ctx.getAgent(), "operator", ctx.getOperator(), "level", ctx.getLevel());
    }

    @GetMapping("/notes")
    Map<String, List<Note>> list(@AllowedByContext Context ctx) {
        return Map.of("notes", mine(ctx));
    }

    @PostMapping("/notes")
    ResponseEntity<Map<String, String>> add(@AllowedByContext Context ctx, @RequestBody Map<String, Object> body) {
        List<Note> 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<String, String> 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<Map<String, String>> notJson() {
        return badText();
    }

    private static ResponseEntity<Map<String, String>> badText() {
        return ResponseEntity.badRequest().body(Map.of("error", "text: a string of 1 to 2000 characters"));
    }

    private List<Note> 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<String, List<Map<String, String>>> 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<Map<String, String>> 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<String, MutableList<Note>>()
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<Int, Map<String, String>> {
    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<Note> = 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<String, String> 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<String, Object> 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/<code>`; 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`, `<type>test-jar</type>`, 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<String>` 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<Charge>, 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.
