# AllowedBy Ruby SDK

The `allowedby` gem lets AI agents call your Ruby app on behalf of a person who approved them with a passkey tap.
It publishes your discovery documents, verifies every agent request offline (ABY-2: the AllowedBy HTTP
verification), answers with a challenge when an approval is missing, and creates the approval itself for serious
actions. It is the Ruby port of the Python reference (`sdks/python/src/allowedby/sdk.py`) and follows
`sdks/CONTRACT.md`. The concepts (routes, classes, levels, the approval flow) are
explained once in [`docs/deploy-saas.md`](https://docs.allowedby.com/guides/accept-agents).

Terms used below: a **node** issues agent passports and records the person's approvals; a **grant** is a person's
signed approval; a **proof** is the agent's signature over one request; **JWS** is a signed JSON document (RFC
7515); **JCS** is canonical JSON (RFC 8785).

## Install

Add the gem with Bundler; it needs Ruby 3.2 or later and one gem, `tzinfo` (time zones), which a Rails app has
already.

The gem is not on RubyGems yet, so Bundler takes it from the repository (the repository is private: Bundler needs
your GitHub credentials, `bundle config set --global github.com <user>:<token>`).

```bash
bundle add allowedby --git https://github.com/yannUpTo/allowedby --glob "sdks/ruby/*.gemspec"
```

The same command works in PowerShell on Windows. Or write the line in your Gemfile, as in
`examples/Gemfile.app`:

```ruby
# frozen_string_literal: true

# Your application's Gemfile (docs/sdk/ruby.md, "Install"). The gem is not on RubyGems yet: Bundler takes it from
# the repository.
source "https://rubygems.org"

gem "allowedby", git: "https://github.com/yannUpTo/allowedby", glob: "sdks/ruby/*.gemspec"
gem "puma" # any Rack server
gem "rackup" # the rackup command for config.ru
gem "tzinfo-data", platforms: %i[windows jruby] # time zones where the system has none (tzinfo, a dependency)
```

| | |
|---|---|
| Ruby | CRuby 3.2 and 3.3 (tested in CI); the gem uses no gem that later Rubies unbundle (`base64`, `bigdecimal`, `logger`). |
| Runtime dependencies | `tzinfo` 2 (the IANA time zones of tenant budgets: a budget per day in `Europe/Paris`, across its clock changes; the standard library has no zone database), which nearly every Ruby app has through Rails. It reads the system's zoneinfo; on Windows, which has none, add `tzinfo-data` (as `examples/Gemfile.app` does). `openssl` (Ed25519, P-256, ECDH, AES-GCM), `json`, `net/http`, `zlib`, `securerandom` come with Ruby. OpenSSL 1.1.1 or later is needed for Ed25519. |
| Optional | `redis` (redis-rb 5) for `AllowedBy::RedisStore`; `rails` for the Railtie. You bring them; the gem does not depend on them. |
| Development | Exact versions in `sdks/ruby/Gemfile` (minitest, rack, rack-test, rubocop, puma, webrick, rackup, railties, actionpack, sinatra, redis). |

## Quick start

A Rack app that accepts agents is one `AllowedBy.new` call and one `use AllowedBy::Middleware` line.

```ruby
# frozen_string_literal: true

require "allowedby"
require "json"

aby = AllowedBy.new(
  origin: ENV.fetch("ALLOWEDBY_ORIGIN", "http://localhost:9292"), # the URL agents call
  node: ENV.fetch("ALLOWEDBY_NODE", "http://localhost"),          # the AllowedBy node you trust
  org: { legal_name: "Notes Ltd", country: "FR" },
  routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*"),
           AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new")],
  templates: { "notes:read" => "Read your notes", "notes:write" => "Write new notes" }
)
notes = Hash.new { |h, k| h[k] = [] }

use AllowedBy::Middleware, aby
run(lambda do |env|
  ctx = env["allowedby.context"] # nil outside the route map, else: human_id, level, agent, operator...
  return [404, { "content-type" => "text/plain" }, ["not found\n"]] if ctx.nil?

  # no person (a level-0 route): refused, never a store keyed by nil
  person = ctx.human_id or return [403, { "content-type" => "text/plain" }, ["no person: this route needs one\n"]]
  notes[person] << JSON.parse(env["rack.input"].read)["text"] if env["REQUEST_METHOD"] == "POST"
  [200, { "content-type" => "application/json" }, [JSON.generate({ "notes" => notes[person] })]]
end)
```

Run it against the local node from a clone of the repository. On Linux and macOS:

```bash
python demo/run.py --reset                     # terminal 1: the local node, http://localhost (port 80)
cd sdks/ruby && bundle install && bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru   # terminal 2
python sdks/ruby/examples/agent_call.py        # terminal 3, from the repository root
```

On Windows (PowerShell), the same commands, one per terminal:

```powershell
python demo/run.py --reset
cd sdks/ruby; bundle install; bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru
python sdks/ruby/examples/agent_call.py
```

With Docker instead of a local Ruby: terminal 2 becomes this command (the container uses the host's network, so it
reaches the node on `http://localhost`; Docker Desktop 4.34 or later has host networking as a setting):

```bash
docker run --rm -it --network host -v "$PWD:/repo" -w /repo/sdks/ruby ruby:3.3 \
  sh -c "bundle install && bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru"
```

The agent (the Python reference agent, `examples/agent_call.py`) prints an approval link and a code. Open the link,
check the code, tap your passkey; the agent retries and gets `200`, then reads the notes after a second approval:

```python
"""Call the Ruby quick start (examples/quickstart.ru) as an AllowedBy agent, with the Python reference agent.

Start the local node (python demo/run.py --reset), then the app (bundle exec rackup -o 127.0.0.1 -p 9292 examples/quickstart.ru),
then, from the repository root:

    python sdks/ruby/examples/agent_call.py

The agent prints the approval link and its code: open the link, check the code, tap your passkey.
"""
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "python", "src"))
from allowedby.agent import Agent  # noqa: E402

APP = os.environ.get("APP_URL", "http://localhost:9292")
agent = Agent(os.environ.get("ALLOWEDBY_NODE", "http://localhost"), tell=print)
print(agent.call("POST", APP + "/notes", {"text": "Buy milk"}, action="notes:write"))
print(agent.call("GET", APP + "/notes", action="notes:read"))
```

The hosted node (`https://demo.allowedby.com`) approves only for its own demo sites; use the local node for your app.

## Routes and templates

Each protected route is one `AllowedBy.route(method, path, capability, **options)` line; anything not in the map
reaches your app unchanged.

`AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2, resource: "note:{id}")`
reads: deleting a note needs the person's approval for this exact request, at identity level 2, on the resource
`note:<id>`.

| Option | Values | Meaning |
|---|---|---|
| `capability` | `"resource:action"` | What the person approves (ABY-3). Required from level 1; a level-0 route has none (it needs no grant, ABY-3 §4.1), and `AllowedBy.route` refuses one there. |
| `class:` (or `cls:`) | `read`, `write`, `write-hard`, `irreversible`; or amount thresholds `[{up_to: "1000.00", class: "write-hard"}, {class: "irreversible"}]` | How long an approval lasts (30 days, 7 days, 1 day, 1 hour). `write-hard` and `irreversible`: the service asks for every request itself, approved once for that exact request. |
| `level:` | 0, 1, 2, 3 (default 1) | 0: the agent's passport is enough, no person. 1: a passkey tap. 2: verified identity (eIDAS substantial). 3: eIDAS high on a hardware passkey. |
| `resource:` | `"note:{id}"` (default `"<namespace>:*"`) | The resource, with `{params}` from the path. A grant's `scope` must cover it. |
| `amount_field:`, `currency_field:` | JSON Pointers, e.g. `"/total"`, `"/currency"` (default) | The amount the approval caps; a request above the cap is refused. |
| `authn:` | `synced`, `hardware` | Only these passkeys count. |
| `tier:` | 0-3 (default 0) | The agent key's custody tier (OAID-6). |
| `max_lifetime:` | 60 s to 30 days | A shorter limit than the class's. |
| `level_profile:` | `eu`, `na` (level 3 only) | The level-3 identity profile (OAID-7 §5.3). |
| `summary:`, `body:` | text; `{member: "description"}` | How the route is described to agents in `/openapi.json`. |
| `require_link:` | `true`, `false` (default) | The person must have linked their identity to one of your accounts (ABY-3 §6): see [Account linking](#account-linking). `403 human_not_linked` otherwise. |
| `account_param:` | a path parameter (default `"account"`) | With `require_link`: the parameter that names one of your accounts; the person must be linked to that one. |
| `nonce:` | `true`, `false` (default) | The proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2): see [AllowedBy-Nonce](#allowedby-nonce). Needs `nonce: true` on `AllowedBy.new`. |

Options the Python SDK has and this SDK does not enforce yet (`mandate`, `disclose`,
`disclose_optional`, `authority`, `qes`) raise `AllowedBy::ConfigError` naming the option:
accepting them without enforcing them would let requests through that should be refused.

**The sentence the person signs.** `templates:` gives one sentence per capability:
`{"notes:delete" => "Delete note {scope}"}`, or every language:
`{"notes:delete" => {"summary" => {"en" => "...", "fr" => "..."}, "lines" => {"en" => "...", "fr" => "..."}}}`.
Placeholders are the grant's constraints: `{scope}`, `{amount.max}`, `{amount.currency}`, `{amount.per}`,
`{fields}`. The person's node renders the approval page from these templates only (AMH-1 §4), so the person reads
your words, not the agent's. Every capability of the route map needs a template: the SDK refuses to start without
one.

## Framework recipes

Every Rack framework takes the same middleware; Rails also gets a Railtie, a controller helper and a generator.

Each app below is the interop app in that framework, and CI runs all 26 interop scenarios against it on Puma and on
WEBrick (`examples/frameworks.json` lists the runs and the exact versions). Other Rack 3 frameworks take the same
`use` line, but CI does not run them.

**Rack** (`config.ru`): `use AllowedBy::Middleware, service`. The
middleware serves `/.well-known/allowedby`, `/openapi.json` and `/.well-known/api-catalog`, checks every route of
the map, and puts the accepted context in `env["allowedby.context"]`. It reads the body of a mapped route once (at
most 1 MiB, `max_body:`) and gives it back to the app intact; other paths are not touched. A mounted app checks
`PATH_INFO` against the route map, which names the paths the app sees, without the prefix; proofs are over the public
URL (`SCRIPT_NAME + PATH_INFO`). `use` the middleware inside the `map` block: there, a route map that names the prefix
is refused (`400`). Around the block the SDK cannot see the mount: write the map with the prefix there.

A request target whose path holds a byte that is not plain (a raw non-ASCII byte, a space, a quote, a control
character, a backslash) is refused (`400 invalid_request`) before routing, on every path. Paths are matched after RFC 3986 normalisation (percent-encoding, dot segments), and the app then routes on that same
path. A variant that a lenient router would send to a protected action is refused with `400 invalid_request`, never
handed to the app unchecked: a trailing or doubled `/`, a suffix (`/notes.json`, `/notes.a-b`, `/notes;a`), dot
segments (`/x/../notes`), encoded separators (`/notes%2F7`), control characters, another letter case of the method. For
the same reason the last path parameter of a protected route cannot contain a dot followed by text (`/notes/7.json` is
refused: Rails would run it as note 7 while the person approved "7.json"). A path that a mapped template would
match if one or more of its parameters took several segments (`/notes/7/x` for `/notes/{id}`), for a method the map uses
there, is refused (`400`) too: a glob or a splat would run the protected action. In Rails, and in a Sinatra app that
registers the guard and is the next app after the middleware, the router's choice decides instead. `/notes/7` when only `/notes` is mapped
is your app's. `unprotected:` names your own pages of those kinds, for every method or one:
`unprotected: ["/notes.csv", ["GET", "/notes/{id}/photo"]]`. An exact path lifts every rule for that very path; a
template of whole-segment parameters lifts the one for longer paths. An entry that overlaps a route of the map, differs from
one by a last `/` only (`/notes/new/`: the router may drop it) or holds `;`, `%` or a dot segment fails at start; each one is logged at start, and a refusal names the option.
A request on a path with another protected verb is refused the same way when
`X-HTTP-Method-Override`, `X-HTTP-Method` or `X-Method-Override` names that verb, when its query contains `_method`, or
when it is a `POST` whose form contains `_method` or is over `max_body:`.
A plain Rack app does its own routing, which the SDK cannot see: match paths exactly and run
nothing for a nil context, as the app below.

**Changed after the check.** A step after the middleware (a rewrite of `PATH_INFO`, `Rack::MethodOverride`, a
mount that rewrites the path) could move an accepted request to another path or method: its handler would then act on
values the person never approved. The Rails and Sinatra guards compare the method and the whole path (`SCRIPT_NAME +
PATH_INFO`, normalised as the check) that reach the handler with those that were checked, and refuse a request that
changed (`400 invalid_request`, the path not repeated), whatever handler the router chose; Rails' own error page for a
checked request (`exceptions_app`) still answers. In Sinatra this holds for a `before` filter of your own too, as
Sinatra routes after its filters. Not covered: a plain Rack app (the SDK cannot see its routing) and a controller
without the Railtie's guard (`ActionController::Metal`). Put nothing that changes the method or the path after the
middleware there, and read the values from `context.params`.

**Refunds** (CONTRACT 1.10, ABY-2 §5 step 9). The check spends what an accepted request costs, atomically: the mark
of a single-use approval, the grant's `count` and `amount` totals. When the SDK itself then refuses that request
before its handler starts (the Rails or Sinatra guard: rule 5 below, a method or path changed after the check; the
link endpoint, when it cannot link an accepted request), it gives back exactly what the check charged for it, once,
from a receipt the check kept: the approval can be used again for a request its route serves. A refund the store
does not take (the store down) leaves the approval spent, and the log says so without request data. Nothing is given
back once the handler started (an action or a block that refuses the request itself), for an answer of the app's own
(a middleware in front of the router), or in a plain Rack app, where the SDK cannot see a handler start. An accepted
request is started or given back, never both: one given back never reaches a handler, even when a layer dispatches it
again. An adapter of your own does the same with `service.release(context)` and `service.started(context)`, and calls
`service.forget(context)` once it has the app's answer (see Reference); the middleware forgets each request itself,
and the Rails and Sinatra guards release and start it.

The whole app (`examples/frameworks/rack/config.ru`):

```ruby
# frozen_string_literal: true

# A plain Rack app behind AllowedBy (docs/sdk/ruby.md, "Rack").
#
#   bundle exec puma -b tcp://127.0.0.1:9292 config.ru   # or: bundle exec rackup -s webrick -o 127.0.0.1 config.ru

require "allowedby"
require "json"

aby = AllowedBy.new(
  origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call
  node: ENV.fetch("ALLOWEDBY_NODE"),     # the AllowedBy node you trust
  org: { legal_name: "Notes Interop Ltd", country: "FR" },
  routes: [
    AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"),
    AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
    AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new",
                                                     summary: "Add a note", body: { text: "the note" }),
    AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2,
                                                             resource: "note:{id}", summary: "Delete a note")
  ],
  templates: { "notes:read" => "Read your notes", "notes:write" => "Write new notes",
               "notes:delete" => "Delete note {scope}" },
  title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5"))
)
notes = Hash.new { |people, person| people[person] = [] }
lock = Mutex.new
last_id = 0

use AllowedBy::Middleware, aby

run(lambda do |env|
  request = Rack::Request.new(env)
  context = env["allowedby.context"] # nil on a path outside the route map
  if context&.level&.positive? # a route of a person: refused without one (403), never a store keyed by nil
    person = context.human_id or return [403, { "content-type" => "text/plain" }, ["no person: this route needs one\n"]]
  end

  status, body = lock.synchronize do
    case [request.request_method, request.path_info]
    in ["GET", "/health"] then [200, { ok: true }]
    in ["GET", "/me"] if context
      [200, { agent: context.agent, operator: context.operator, level: context.level }]
    in ["GET", "/notes"] if person then [200, { notes: notes[person] }]
    in ["POST", "/notes"] if person # a route of the map runs for a checked request only
      raw = request.body.read.to_s
      text = JSON.parse(raw.empty? ? "{}" : raw)["text"]
      if text.is_a?(String) && text.length.between?(1, 2000)
        id = (last_id += 1).to_s
        notes[person] << { id: id, text: text }
        [201, { id: id }]
      else
        [400, { error: "text: a string of 1 to 2000 characters" }]
      end
    in ["DELETE", %r{\A/notes/[^/]+\z}] if person
      id = context.params["id"] # the value checked, never a reading of the raw path
      notes[person].reject! { |note| note[:id] == id }
      [200, { deleted: id }]
    else [404, { error: "not found" }]
    end
  end
  [status, { "content-type" => "application/json" }, [JSON.generate(body)]]
end)
```

**Rails.** `bin/rails generate allowedby:install` writes `config/initializers/allowedby.rb`. Setting
`config.allowedby.service` adds the middleware; controllers call `allowedby_context`. Add
`before_action :require_allowedby!` to the controllers of protected routes: an action reached without the
middleware's check answers `400` instead of running. A nested route of your own (`/notes/{id}/comments`)
needs nothing: the middleware asks the Rails router, and refuses a longer path only when it goes to a protected action
or to what the Railtie does not cover (an engine, a Rack endpoint). The Railtie does the same for every action that the Rails
router gives a mapped path to (another route to it, a mount); an action that also serves an unchecked path on purpose
opts out with `skip_before_action :refuse_unchecked_allowedby_action` (which also lifts the handler checks below
for that action), and declare protected routes
with `format: false`.

Both guards (Rails and Sinatra) follow CONTRACT §2.10 rule 5. A request checked for one route of the map never runs
another route's handler (an alias on its path, a glob, a longer pattern), whatever the method: a `GET` that reaches
the action of a protected `POST` is refused (`400`). An action that the app's router gives several routes of the map
(a Rails action on two verbs or two paths, a Sinatra block given to both) runs for a request checked for one of them
only when that route covers every other (needs at least as much): a level-1 `DELETE /items/{id}` never runs the action
of a level-2 `DELETE /notes/{id}`. The service says so at start. Whatever makes an action a route's own, a checked request never runs one that
is protected as a catch-all for another route it does not cover. A catch-all (an action that also serves a route's path with one of its words replaced) is never
learnt. Next to the route's own action, a checked request that reaches it is refused (`400`), unless the rule Rails or
Sinatra matched has the route's own shape; while it is the only action found for the route (a front controller), a
checked request runs it when its route needs at least what every other route the front controller is protected for
needs (a route whose own action is not known and that the front controller serves, or one it is a catch-all under the
prefix of: a level-1 route never runs a level-3 route's front controller), and unchecked requests near the route are
still refused. A catch-all under a route's prefix (`notes/:id/*rest`) is
protected: it can only be another action of that route. A fallback the router chose through a site-wide wildcard
(`*path`, a Sinatra `/*`) is protected only while a route it serves has no known action of its own (it may be that
route's action; the service says so at start). Once the route's own action is known (a rule of its shape, a sample, a
checked request), the fallback is not protected for it and keeps serving every other page. A handler that dispatches protected actions itself (one handler for every path that deletes or pays,
or a legacy controller on a path no route maps) is not something the SDK can see. A front controller shared by
protected routes of different capabilities or resources runs for none of them. Give each protected route its own
handler. An action that no sample reaches and no rule of the route's shape names serves only the value
it was called with (`/notes/export` next to `/notes/{id}`): a checked request that reaches it is refused, and it is
never learnt. An action is learnt from a checked request only when the rule that matched has the route's own shape,
and only when that route needs at least what every other route, of any method, with an unknown action needs. When no action of the app serves a route of the map, an unchecked request near it (on its path or a longer one, of any method) is refused: the SDK cannot tell what runs there. `unprotected:` never lifts this. The startup warnings (a route served only by a site-wide catch-all, one handler for two methods) are logged when a
guard builds its map of handlers: at start in Rails with eager loading (production), otherwise at the first request
the guard sees (Sinatra, and Rails in development). A controller without
the Railtie's guard (`ActionController::Metal`) and a plain Rack app are not covered: the middleware's own rules apply there. From the app
in `examples/frameworks/rails`, the initializer:

```ruby
# frozen_string_literal: true

Rails.application.config.allowedby.service = AllowedBy.new(
  origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call
  node: ENV.fetch("ALLOWEDBY_NODE"),     # the AllowedBy node you trust
  org: { legal_name: "Notes Interop Ltd", country: "FR" },
  routes: [
    AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"),
    AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
    AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new",
                                                     summary: "Add a note", body: { text: "the note" }),
    AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2,
                                                             resource: "note:{id}", summary: "Delete a note")
  ],
  templates: { "notes:read" => "Read your notes", "notes:write" => "Write new notes",
               "notes:delete" => "Delete note {scope}" },
  title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5"))
)
```

The routes:

```ruby
# frozen_string_literal: true

Rails.application.routes.draw do
  get "health", to: "health#show" # outside the AllowedBy route map: your app's own path
  get "me", to: "me#show"
  # format: false: /notes.json is not another way in (the middleware also refuses such variants)
  resources :notes, only: %i[index create destroy], format: false
  not_found = ->(_env) { [404, { "content-type" => "application/json" }, ['{"error":"not found"}']] }
  match "*path", via: :all, to: not_found
end
```

The controller of the protected routes:

```ruby
# frozen_string_literal: true

class NotesController < ActionController::API
  # Second line of defence: an action of a protected route never runs without the middleware's check.
  before_action :require_allowedby!

  # No person (a level-0 route): refused, never a store keyed by nil.
  class NoPerson < StandardError; end
  rescue_from(NoPerson) { render json: { error: "no person: this route needs one" }, status: :forbidden }

  def index
    render json: { notes: Note.of(person) }
  end

  def create
    note = Note.add(person, params[:text])
    if note
      render json: { id: note[:id] }, status: :created
    else
      render json: { error: "text: a string of 1 to 2000 characters" }, status: :bad_request
    end
  end

  def destroy
    Note.delete(person, params[:id])
    render json: { deleted: params[:id] }
  end

  private

  # The person the request is for.
  def person
    allowedby_context.human_id or raise NoPerson
  end
end
```

**Sinatra** (`examples/frameworks/sinatra/notes_app.rb`, run by its `config.ru`). `require "allowedby/sinatra"`,
`set :allowedby, service` (or a class method, as here) and `register AllowedBy::SinatraGuard` add a second line: the
handler of a mapped route never runs unchecked. Register the guard before any `before` filter of your own: a filter
declared earlier runs without its check.

```ruby
# frozen_string_literal: true

# A modular Sinatra app behind AllowedBy (docs/sdk/ruby.md, "Sinatra"), served by config.ru.

require "sinatra/base"
require "allowedby/sinatra"
require "json"

class NotesApp < Sinatra::Base
  class << self
    attr_writer :allowedby # tests put their own here

    def allowedby
      @allowedby ||= AllowedBy.new(
        origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # the URL agents call
        node: ENV.fetch("ALLOWEDBY_NODE"),     # the AllowedBy node you trust
        org: { legal_name: "Notes Interop Ltd", country: "FR" },
        routes: [
          AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"),
          AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
          AllowedBy.route("POST", "/notes", "notes:write", class: "write", level: 1, resource: "note:new",
                                                           summary: "Add a note", body: { text: "the note" }),
          AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2,
                                                                   resource: "note:{id}", summary: "Delete a note")
        ],
        templates: { "notes:read" => "Read your notes", "notes:write" => "Write new notes",
                     "notes:delete" => "Delete note {scope}" },
        title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5"))
      )
    end
  end

  set :lock, true # the notes are in memory: one request at a time
  set(:notes, Hash.new { |people, person| people[person] = [] })
  set :last_id, 0
  use AllowedBy::Middleware, -> { NotesApp.allowedby }
  register AllowedBy::SinatraGuard # the handler of a mapped route never runs unchecked

  helpers do
    # The notes of the person the request is for; a route without one (level 0) is refused, never keyed by nil.
    def mine
      person = allowedby_context.human_id or halt 403, JSON.generate({ error: "no person: this route needs one" })
      settings.notes[person]
    end
  end

  before { content_type :json }

  get "/health" do
    JSON.generate({ ok: true })
  end

  get "/me" do
    JSON.generate({ agent: allowedby_context.agent, operator: allowedby_context.operator,
                    level: allowedby_context.level })
  end

  get "/notes" do
    JSON.generate({ notes: mine })
  end

  post "/notes" do
    raw = request.body.read.to_s
    text = JSON.parse(raw.empty? ? "{}" : raw)["text"]
    unless text.is_a?(String) && text.length.between?(1, 2000)
      halt 400, JSON.generate({ error: "text: a string of 1 to 2000 characters" })
    end
    id = (settings.last_id += 1).to_s
    mine << { id: id, text: text }
    status 201
    JSON.generate({ id: id })
  end

  delete "/notes/:id" do
    mine.reject! { |note| note[:id] == params["id"] }
    JSON.generate({ deleted: params["id"] })
  end

  not_found { JSON.generate({ error: "not found" }) }
end
```

**Puma and WEBrick.** The SDK is thread-safe: one service per process, shared by every thread. In Puma's cluster
mode the refresh thread is started again in each worker on its first request, which does not wait for it: a service
built before the fork (`preload_app!`) gives each worker its cache, one built in each worker waits for its first
refresh there. Serve any of the apps above with
`bundle exec puma -b tcp://127.0.0.1:9292 config.ru` or `bundle exec rackup -s webrick -o 127.0.0.1 config.ru`, from
its folder. Name the address: Puma otherwise listens on every interface (`0.0.0.0`), as rackup does outside
development, and `localhost` can be `::1` on Windows. In a container without host networking, bind `0.0.0.0`.

## The context

The handler of an accepted request receives an `AllowedBy::Context`, a frozen value object.

| Field | Type | What |
|---|---|---|
| `human_id` | String or nil | The person's pairwise id at your service (the same person, the same id, every time; another id at another service). nil on a level-0 route. |
| `level` | Integer | The effective level: the lowest of the grant's, the person's registration's and the nodes' maximum. |
| `agent` | String | The agent (its passport `sub`). |
| `operator` | String | Who runs the agent (a verified domain, or a node-scoped id). |
| `capabilities` | Array of String | The capabilities of the grant. |
| `display` | Hash or nil | What the person read and signed: `{"summary", "lines", "lang"}`. |
| `gid`, `rev`, `jti` | String, Integer, String | The grant (leaf of the chain), its revision, its document id. |
| `chain` | Array | `[[gid, rev], ...]`, leaf first (a sub-agent's chain has two). |
| `human_iss` | String | The person's home node. |
| `proof_jti`, `run`, `call` | String, String or nil, Integer or nil | The request proof's id and the agent's own audit ids (ABY-2 §5 step 10). |
| `route` | Hash | The route of the map that matched. |
| `params` | Hash of String to String | The route's path values as checked (CONTRACT §2 item 7): each `{name}` of the route's template, from the normalised path, decoded once (`/t/acme%20co` gives `"acme co"`, `%2520` gives `"%20"`). Frozen; empty when the route has no parameter. Act on these values, never on your own reading of the raw path, which can differ (`DELETE /notes/7/.` is checked as `/notes/7`). |
| `tenant` | String or nil | The route's `{tenant}` value, as in `params`; nil when the route has none. |
| `acting_for` | nil | An extended feature (company mandates) this SDK does not implement. |
| `linked_account` | String or nil | On a `require_link` route, the account the person is linked to (see Account linking), also when the path names none; nil on other routes. |

## Production

Keep the keys in a file, share the replay state between instances, and check that your app reaches the node.

```ruby
# frozen_string_literal: true

# A production configuration (docs/sdk/ruby.md, "Production"): the keys kept across restarts and shared by every
# instance, the replay and single-use state in Redis, your logger. Build it once per process (after the fork in
# Puma cluster mode; the SDK restarts its refresh thread itself if you build it before).

require "allowedby"
require "logger"
require "redis"

module NotesProduction
  def self.allowedby(env = ENV)
    log = Logger.new($stderr)
    AllowedBy.new(
      origin: env.fetch("ALLOWEDBY_ORIGIN"), # https://notes.example.com, exactly as agents call it
      node: env.fetch("ALLOWEDBY_NODE"),     # the node you trust, e.g. https://node.example.org
      org: { legal_name: "Notes Ltd", country: "FR", website: "https://notes.example.com",
             privacy_policy: "https://notes.example.com/privacy" },
      routes: [
        AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*", summary: "List your notes"),
        AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2,
                                                                 resource: "note:{id}", summary: "Delete a note")
      ],
      templates: { "notes:read" => "Read your notes", "notes:delete" => "Delete note {scope}" },
      key_file: env.fetch("ALLOWEDBY_KEY_FILE", "/var/lib/notes/allowedby-keys.json"), # a volume, mode 0600
      store: AllowedBy::RedisStore.new(Redis.new(url: env.fetch("REDIS_URL"))),        # shared by instances
      refresh_seconds: 5,
      logger: ->(message) { log.warn(message) } # "[verifier] refresh failed: ..." when the node is unreachable
    )
  end
end
```

- **Keys** (`key_file:`). The signing key (Ed25519) signs your organisation profile and your approval requests; the
  disclosure key (P-256) is kept for the SDKs that receive personal data, not published by this one. The file is created on first use, atomically, mode 0600,
  first writer wins, in the Python SDK's format (`{"signing": {"pem"}, "disclosure": {"pem"}}`), so one file
  works in every SDK. The folder needs hard links: on a file system without them the first start fails and says so; create the file
  elsewhere and point `key_file` at it, or write it from your secret manager. An existing file works anywhere.
  Without `key_file` the keys are new at every start: agents must fetch your discovery document again.
  Keep the file out of git and in a volume shared by your instances.
- **Store** (`store:`). Replayed proofs, single-use approvals and counters live in a store. `MemoryStore` (the
  default) is for one process only: with several processes or machines, an instance that has not seen a proof
  accepts its replay. Use `AllowedBy::RedisStore.new(Redis.new(url: ...))`. A store that cannot answer refuses the
  request (`503 status_stale`, `Retry-After: 5`), never accepts it.
- **Trust** (`node:` or `trust_list:`). By default the SDK trusts one node and pins its key on first fetch. For a
  signed list of nodes (OAID-5: anchors, programs, vouching, witnesses), pass
  `trust_list: AllowedBy::TrustList.load("trust.jws", your_public_jwk)`.
- **Refresh** (`refresh_seconds:`, default 5, at most 60). A background thread fetches the node's statement and
  status lists; no request waits on the network, except the approval a serious route creates. `AllowedBy.new`
  returns once the first refresh is over (done or failed, at most 5 s), so a service that starts cold (a new
  instance, one that scales to zero) holds them before its first request. With no fresh list
  (older than 60 s for `write-hard` and `irreversible`, 3600 s otherwise) requests are refused with
  `503 status_stale` (fail closed).
- **Logging** (`logger:`, any `#call(message)`, default standard error). `[verifier] refresh failed: <reason>` on
  every failed refresh; one line per checked request with its outcome code. Tokens, keys and bodies are never
  logged.
- **Origin.** `origin:` is the public URL agents call (scheme, host, port). Behind a proxy, it is the proxy's
  public URL: the SDK ignores `Host` and `X-Forwarded-*` headers.
- **Several instances.** One `key_file` and one `RedisStore` for all; each instance refreshes on its own.

## Agents

This is a service SDK: there is no agent SDK in Ruby yet; agents use the Python or TypeScript agent SDK (see
`examples/agent_call.py` in the quick start).

## Errors

Every refusal is `application/problem+json` (RFC 9457) with `type: https://allowedby.org/errors/<code>`, the same
codes and statuses in every AllowedBy SDK; a `401` that an approval can fix carries `WWW-Authenticate: AllowedBy`.

| Code | Status | Meaning | What to do |
|---|---|---|---|
| `invalid_request` | 400 | Malformed request, or the body of a mapped route is not a JSON object. | Send a JSON object body. |
| `passport_required` | 401 | The agent sent no passport. | The caller is not an AllowedBy agent, or calls a protected route without one. |
| `grant_required` | 401 | No approval for this action. The challenge says what is needed. | Normal first call. The agent asks the person. |
| `grant_insufficient` | 401 | The approval does not cover this resource, amount or request (or a one-time approval is for another request). | The agent asks for a wider approval. |
| `level_insufficient` | 401 | The person's level is below the route's. | The person verifies their identity on the approval page. |
| `mandate_required` | 401 | The route needs a company mandate, or the mandate does not cover this. This SDK accepts no mandate: a grant acting for a company is refused. | The person approves for themselves. |
| `expired`, `actor_expired` | 401 | The approval, or the agent's key, expired. | The agent rebinds or asks again. |
| `not_yet_valid` | 401 | The approval starts in the future. | Check the clocks. |
| `revoked` | 401 | The person withdrew the approval. | The agent asks again. |
| `single_use_consumed` | 401 | A one-time approval was already used. | Expected on retries of a serious action. |
| `class_lifetime_exceeded` | 401 | The approval lasts longer than this class allows. | Lower the requested period. |
| `invalid_signature` | 401 | Bad, expired or replayed proof; tampered grant; no current AllowedBy-Nonce where the route needs one (the answer's `AllowedBy-Nonce` header holds a fresh one). | Check the agent's clock (proofs must be within -120 s/+60 s) and the URL your app sees (scheme, host, port must match `origin`). |
| `untrusted_node` | 401 | The approval comes from a node you do not trust, or none is trusted yet. | Check `node:` or your trust list, and that the first refresh succeeded. |
| `insufficient_witnesses` | 401 | The trust list asks for witnessed node logs and this node's is not. | Check `witnesses_min` in your trust list. |
| `qes_required`, `authority_required` | 401 | A qualified signature, or the organisation's co-approvers, are needed. | Not available in this SDK. |
| `budget_exceeded` | 403 | A tenant budget is used up, or the request has no amount in its currency. Refused before any approval is asked. | Wait for the next period, or raise the budget ([Tenants and tenant budgets](#tenants-and-tenant-budgets)). |
| `capability_denied` | 403 | No such route, or the account refuses this operator or amount. | Check the route map. |
| `tier_insufficient` | 403 | The passkey or the agent's key custody is not of the required kind (e.g. `authn: "hardware"`). | The person uses a hardware passkey, or the agent a stronger key custody. |
| `human_not_linked` | 403 | The route needs a linked account (`require_link`), and the person has not linked theirs, or linked another one than the path names. | The person links their account: [Account linking](#account-linking). |
| `rate_limited` | 429 | Too many requests from this agent or operator. `Retry-After: 60`. | The agent slows down; raise `rate:` if the limits are too low for your API ([Rate limits](#rate-limits)). |
| `envelope_too_large` | 431 | `Allowed-By` and `AllowedBy-Proof` over 8 KiB, or a chain of more than two JWS (deeper than 1, ABY-2 §2). | A sub-agent delegates only from a root grant: one level. |
| `status_stale` | 503 | Your copy of the node's revocation list is too old (or the shared store is unreachable); serious actions are paused. `Retry-After: 5`. | Check that your app reaches the node and Redis; look for `[verifier] refresh failed` in your logs. |

A body over `max_body` (1 MiB) on a mapped route is refused with `413` and code `invalid_request`. A
configuration the SDK cannot honour raises `AllowedBy::ConfigError` at start, with what to fix.

## Testing

Run the CONF-1 vectors and the interop test, and test your own app with the in-memory node of
`allowedby/testing`.

From `sdks/ruby` (Linux, macOS and Windows PowerShell alike):

```bash
bundle install
bundle exec rake test        # unit tests, every framework adapter, fuzzing, and the vectors
bundle exec rake vectors     # only the vectors: prints "481/481 cases passed"
bundle exec rubocop          # lint, every offence fails
```

The Redis tests need a server: `REDIS_URL=redis://localhost:6379/0 bundle exec rake test` (PowerShell:
`$env:REDIS_URL = "redis://localhost:6379/0"; bundle exec rake test`), or
`docker run --rm -p 6379:6379 redis:7.4-alpine` first. Without `REDIS_URL` they are skipped.

The interop test runs an example app against a real node, the reference agent and a person with a software
passkey (26 scenarios), from the repository root:

```bash
pip install -r requirements.txt
ruby sdks/ruby/test/frameworks.rb rack-puma   # one run; no name: every run of examples/frameworks.json
```

Set `INTEROP_PORT_BASE` to move its ports.

**Your own app, without a browser.** `AllowedBy::Testing::Node` issues an agent's passport and a person's
approvals with real signatures, and answers the SDK's fetches through the `http:` option. A complete Minitest file
(`examples/notes_app_test.rb`, run in CI):

```ruby
# frozen_string_literal: true

# Testing your own app without a browser or a network (docs/sdk/ruby.md, "Testing"): AllowedBy::Testing::Node is
# an in-memory node that issues an agent's passport and a person's approvals, and answers the SDK's fetches.
#
#   bundle exec ruby -Ilib examples/notes_app_test.rb

require "minitest/autorun"
require "rack/test"
require "json"
require "allowedby"
require "allowedby/testing"

class NotesAppTest < Minitest::Test
  include Rack::Test::Methods

  ORIGIN = "https://notes.example"

  def setup
    @node = AllowedBy::Testing::Node.new
    @aby = AllowedBy.new(
      origin: ORIGIN, node: @node.origin, org: { legal_name: "Notes Ltd", country: "FR" },
      routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")],
      templates: { "notes:read" => "Read your notes" },
      http: @node, start: false # the test node answers; no background thread
    )
    @aby.verifier.refresh # fetch the node's statement and status list now
    @agent = @node.agent
  end

  def app
    notes_app = lambda do |env|
      # the person's id at this service; none on a level-0 route: refused, never used as a key
      who = env["allowedby.context"].human_id or return [403, {}, []]
      [200, { "content-type" => "application/json" }, [JSON.generate({ "who" => who })]]
    end
    AllowedBy::Middleware.new(notes_app, @aby)
  end

  def test_an_approved_agent_reads_the_notes
    grant = @node.grant(@agent, audience: ORIGIN,
                                capabilities: [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }])
    @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant).each { |name, value| header name, value }
    get "/notes"
    assert_equal 200, last_response.status
    assert_equal @node.human_id(ORIGIN), JSON.parse(last_response.body)["who"]
  end

  def test_without_the_persons_approval_the_agent_is_asked_to_get_one
    @agent.headers("GET", "#{ORIGIN}/notes").each { |name, value| header name, value } # the passport alone
    get "/notes"
    assert_equal 401, last_response.status
    assert_match(/error="grant_required"/, last_response.headers["www-authenticate"])
  end

  def test_a_revoked_approval_is_refused_after_the_next_refresh
    grant = @node.grant(@agent, audience: ORIGIN,
                                capabilities: [{ "cap" => "notes:read", "constraints" => { "scope" => "note:*" } }])
    @node.revoke(grant)
    @aby.verifier.refresh
    @agent.headers("GET", "#{ORIGIN}/notes", allowed_by: grant).each { |name, value| header name, value }
    get "/notes"
    assert_equal 401, last_response.status
    assert_equal "https://allowedby.org/errors/revoked", JSON.parse(last_response.body)["type"]
  end
end
```

## Reference

Everything public, in `require "allowedby"` (and `require "allowedby/testing"` for the test helpers).

**Building the service**

- `AllowedBy.new(origin:, node:, org:, routes:, templates:, key_file: nil, store: nil, trust_list: nil,
  refresh_seconds: 5, node_max_level: 3, clock: nil, title: nil, version: "1.0.0", description: nil,
  rfc9421: false, logger: nil, http: nil, start: true, unprotected: [], link_authorize: nil, nonce: false,
  rate: nil, tenants: {})` -> `AllowedBy::Service`. `clock`: `-> Integer` seconds;
  `rfc9421`: accept the RFC 9421 Web Bot Auth signature instead of the proof JWT; `http`: the HTTP client, any
  `#call(method, url, body, headers) -> [status, body]`; `start`: run the background refresh; `nonce`:
  AllowedBy-Nonce on irreversible routes and routes with `nonce:` ([AllowedBy-Nonce](#allowedby-nonce)); `rate`:
  `{actor: [n, seconds], operator: [n, seconds]}` ([Rate limits](#rate-limits)); `tenants`: the accounts named by
  `{tenant}` ([Tenants and tenant budgets](#tenants-and-tenant-budgets)).
- `AllowedBy.route(method, path, capability = nil, **options)` -> a frozen Hash (see Routes and templates).
- `AllowedBy::ConfigError` (an `ArgumentError`): the configuration is refused.

**`AllowedBy::Service`**

- `check(method, path, headers, body = nil, query = nil)` -> `[Context, nil]` when allowed, `[nil, [status,
  headers, body_hash]]` to send back; `[nil, nil]` outside the route map. `POST /allowedby/link` is the SDK's own:
  its answer, accepted or not, is the second member.
- `release(context)` -> true when what the check charged for this accepted request was given back (the SDK refused it
  itself before its handler started); `started(context)` -> false when it was given back already, or forgotten (it
  must not reach a handler); `forget(context)` once the request is answered (its refund state goes; without it, the
  state of at most 10 000 requests is kept): see Refunds, under Framework recipes. `refund(context)` -> true when the
  tenant budget this accepted request counted was given back (the handler refused it).
- `link_start(account, ttl = 600)` -> a linking code for one of your accounts; `unlink(account)` -> true when the
  account was linked, its link and pending codes removed; `link(headers, body, query = nil, mount: "")` -> the answer
  to `POST /allowedby/link` (see [Account linking](#account-linking)).
- `handle(method, path, mount = "")` -> the SDK's own endpoints as `[status, headers, body_hash]`, or nil.
- `route_for(method, path)`, `variant_of(method, path)`, `protects?(method, path)`, `well_known(mount = "")`, `openapi(mount = "")`, `api_catalog(mount = "")`, `challenge(request, reject)`,
  `problem(code, status, detail = nil, headers = {}, **members)`.
- `origin`, `node`, `host`, `routes`, `templates`, `key` (`AllowedBy::Key`), `verifier`, `title`, `version`.

**Frameworks**

- `AllowedBy::Middleware.new(app, service_or_callable, max_body: 1 << 20)`; `AllowedBy::Middleware::ENV_KEY`
  (`"allowedby.context"`).
- `AllowedBy::Railtie` (`config.allowedby.service`, `config.allowedby.enabled`),
  `AllowedBy::ControllerHelpers#allowedby_context` and `#require_allowedby!` (a `before_action`),
  `bin/rails generate allowedby:install`.

**Verification**

- `AllowedBy::Verifier`: `verify(request)` -> `Context` or raises `AllowedBy::Reject`; `refresh`,
  `start_refresh`, `ensure_refresh` (restarts it after a fork), `stop_refresh`; `install_node(statement_jws, max_level, origin:)`,
  `install_status(uri, jws)` (statements and status lists obtained another way); `nodes`, `status`, `store`,
  `nonce` (an `AllowedBy::Nonce`, nil with nonces off), `rate` (an `AllowedBy::RateLimit`).
- `AllowedBy::Request.new(http_method:, path:, query:, headers:, body:)`; `AllowedBy::Context` (see The context).
- `AllowedBy::Reject` (`code`, `status`, `why`, `route`, `actor_sub`, `nonce`: the fresh nonce of the answer); `AllowedBy::STATUS` (code -> status);
  `AllowedBy::CHALLENGE_CODES`.
- `AllowedBy::TrustList.new(jws, key)`, `.load(path, key)`, `.sign(key, payload)`; `AllowedBy::TrustResolver`.

**State**

- Store interface: `add(key, expires, now) -> bool`, `get(key, now)`, `charge([[key, inc, max, expires]], now)
  -> bool`, all with the SDK's clock. `AllowedBy::MemoryStore.new(max_keys: 200_000)`,
  `AllowedBy::RedisStore.new(redis, prefix: "allowedby:")`; `AllowedBy::StoreError`.
- `AllowedBy::KeyFile.load(path)` -> `[Key, OpenSSL::PKey::EC]`; `AllowedBy::Key` (`generate`, `from_pem`,
  `sign`, `alg`, `kid`, `jwk`, `to_pem`, `derive(info)`: a 32-byte key derived from it, HKDF-SHA256).
- `AllowedBy::Nonce.new(key)` (`.key_for(signing_key)`, `issue(now)`, `current?(value, now)`, `LIFETIME` 300);
  `AllowedBy::RateLimit.new(rate = nil)` (`.limits(rate)`, `take(actor, operator, now)` -> bool, `limits`,
  `DEFAULTS`, `MAX_KEYS`).

**Building blocks** (what the verifier uses; stable, for tools and tests)

- `AllowedBy::JCS.dump(value)`, `.bytes(value)` (RFC 8785); `AllowedBy::JWS.sign`, `.parse`, `.payload`;
  `AllowedBy::JWE.encrypt(jwk, plaintext)`, `.decrypt(pkey, token)` (ECDH-ES+A256KW, A256GCM);
  `AllowedBy::Crypto.verify_raw`, `.thumbprint`, `.public_key`; `AllowedBy::Grants.core`, `.core_hash`,
  `.request_digest`, `.make_proof`; `AllowedBy::WebAuthn.check`; `AllowedBy::Capabilities` (route matching,
  constraints, `render_display`); `AllowedBy::HTTP`.

**Testing** (`require "allowedby/testing"`)

- `AllowedBy::Testing::Node.new(name: "node.test", clock:, level: 2, authn: "hardware")`: `origin`, `agent`,
  `grant(agent, audience:, capabilities:, level:, initiator:, single_use:, ttl:)`, `sub_grant(parent, agent,
  capabilities:, ttl:)` (a sub-agent's grant, ABY-1 §4), `revoke(token)`,
  `human_id(audience)`, `approvals`, `call` (the `http:` client).
- `AllowedBy::Testing::Agent`: `headers(method, url, allowed_by:, body:)`, `passport`, `sub`, `key`.

**Version**: `AllowedBy::VERSION` (`0.1.0`), `AllowedBy::SPEC_VERSION` (`0.2.14`).

### Account linking

An extended feature (CONTRACT 1.8), as ABY-3 §6 specifies it: the person links their AllowedBy identity to one of
your accounts once, and routes with `require_link: true` accept them only for that account.

1. While the person is signed in, your account page calls `aby.link_start(account)` and shows the code it returns
   (96 random bits, valid `ttl` seconds, 600 by default, single use).
2. The person gives the code to their agent, which sends `POST /allowedby/link` with `{"code": "<code>"}`. The
   middleware serves it (and `check` answers it in an app without the middleware). An unknown, spent, revoked or
   expired code is refused (`400 invalid_request`) before any approval is asked for.
3. The request is then checked as a route of the map (`aby:link`, `write`, level 1, resource `aby:link`), on a
   single-use grant only: without one, the service asks the node for the approval itself, bound to this request.
4. Accepted, the code is spent, the account's other pending codes are revoked, and the pair (the person's home
   node, their pairwise id here) is linked to the account in place of any other: `200 {"linked": true}`.

A request for a `require_link` route is then refused (`403 human_not_linked`) unless its pair is linked, and linked
to the account the route's `account_param` names when the path has one (`/accounts/{account}/...`, compared decoded
once, as `context.params`). The same pairwise id from another home node is another person. A grant that names
no person for this service (no id for this origin in `human.id`, or an empty one) is refused on the link endpoint and
on a `require_link` route (`401 grant_insufficient`): an empty id would link, or match, every grant that lacks it.
Rule 5 (Framework recipes) counts such a route as covered by another only when that one names the same account parameter in the
same segment of its path. The approvals the
service creates for such an account name the linked person (`human_hint`, AMH-1 §7). The handler reads the account
from `context.linked_account`, also on a route whose path names none. `link_authorize: ->(account, route, params) { ...
}`, a service option, is your own authorisation of that account for the route (a shared resource, a suspended
account): only a literal `true` passes, anything else (an exception included, logged without its message) is `403
human_not_linked`, and it is never called for a person who is not linked. Only `POST /allowedby/link` itself, read on
its normalised path (`/allowedby/%6Cink` is the same), is the link endpoint: `/allowedby/link/` or `//allowedby/link`
are paths of your app, outside the map, and no other caller is ever answered on its `aby:link` route. `/.well-known/allowedby` names
the endpoint (`link`), `/openapi.json` describes it, and the person approves the sentence of `templates["aby:link"]`
(a default is given). Codes and links are kept in the process's memory, bounded: 100 000 links, the oldest dropped
first, and 10 000 pending codes. A new code never revokes an older one (ABY-3 §6), so when 10 000 codes are pending
`link_start` raises `ArgumentError` until some expire or are used: catch it on the account page (and show the page's
code once per visit rather than on every reload).

**Removing a link** (ABY-3 §6, CONTRACT 1.17). When you delete an account, or the person asks to be forgotten, call
`aby.unlink(account)`: the stored pair and the account's pending linking codes go, in one step, and a `require_link`
route refuses the person (`403 human_not_linked`) until they link again with a new code. It answers `true` when the
account was linked, `false` for one that was not (a no-op, but its pending codes still go), and raises
`ArgumentError` for an account that is not a non-empty String, as `link_start` does. Behind several instances, serve the account page and the link endpoint from one, or keep
the link with your own accounts. The extended interop app (`examples/interop_ext/config.ru`):

```ruby
# frozen_string_literal: true

# The extended interop app (sdks/interop/ext/reference_app.py, in Ruby) for sdks/interop/ext/interop_ext.py: account
# linking and its removal (ABY-3 §6), AllowedBy-Nonce (ABY-2 §3.2), level profiles (OAID-7 §5.3), rate limits, tenants
# and tenant budgets (ORG-1 §3.3, §5.3). Routes: GET /me (level 0), GET /accounts/{account}/notes (needs a linked
# person, for that account only), POST /drafts (with an AllowedBy-Nonce), GET /vault/eu/{id} and GET /vault/na/{id}
# (level 3 for the EU or the North-America profile), POST /t/{tenant}/orders (an amount at /total; tenants umbrella as
# the map says, hooli with a ceiling of 50.00, budget with 100.00 EUR a day), POST /allowedby/link (the SDK's own), and
# POST /interop/link-code and POST /interop/unlink, outside the route map (TEST ONLY: they stand for the signed-in
# account page, which shows the code and removes the link). Nonces on; rate limits: 20 calls a minute per agent, 1000
# per operator.
#
#   PORT=18790 bundle exec puma -b tcp://127.0.0.1:18790 config.ru

require "allowedby"
require "json"

aby = AllowedBy.new(
  origin: ENV.fetch("ALLOWEDBY_ORIGIN"),
  node: ENV.fetch("ALLOWEDBY_NODE"),
  org: { legal_name: "Notes Interop Ltd", country: "FR" },
  routes: [
    AllowedBy.route("GET", "/me", level: 0, summary: "Who is calling"),
    AllowedBy.route("GET", "/accounts/{account}/notes", "notes:read", level: 1, resource: "account:{account}",
                                                                      require_link: true,
                                                                      summary: "List the notes of an account"),
    AllowedBy.route("POST", "/drafts", "drafts:write", class: "write", resource: "draft:new", nonce: true,
                                                       summary: "Save a draft", body: { text: "the draft" }),
    AllowedBy.route("GET", "/vault/eu/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware",
                                                           level_profile: "eu", summary: "Open a vault (EU level 3)"),
    AllowedBy.route("GET", "/vault/na/{id}", "vault:read", level: 3, resource: "vault:{id}", authn: "hardware",
                                                           level_profile: "na",
                                                           summary: "Open a vault (North-America level 3)"),
    AllowedBy.route("POST", "/t/{tenant}/orders", "orders:place", class: "write", resource: "tenant:{tenant}:order:new",
                                                                  amount_field: "/total", summary: "Place an order")
  ],
  templates: { "notes:read" => "Read your notes", "drafts:write" => "Save your drafts",
               "vault:read" => "Open {scope}",
               "orders:place" => "Place orders on {scope}, up to {amount.max} {amount.currency} per {amount.per}" },
  title: "Notes Interop API", refresh_seconds: Integer(ENV.fetch("ALLOWEDBY_REFRESH_SECONDS", "5")),
  nonce: true, rate: { actor: [20, 60], operator: [1000, 60] },
  tenants: { umbrella: { name: "Umbrella" },
             hooli: { name: "Hooli", routes: { "orders:place" => { amount_max: "50.00" } } },
             budget: { name: "Budget Co",
                       budgets: { "orders:place" => { max: "100.00", currency: "EUR", per: "day" } } } }
)

use AllowedBy::Middleware, aby

run(lambda do |env|
  request = Rack::Request.new(env)
  context = env["allowedby.context"] # nil on a path outside the route map
  status, body = case [request.request_method, request.path_info]
                 in ["POST", "/interop/link-code"] # TEST ONLY: the signed-in account page
                   account = begin
                     JSON.parse(request.body.read.to_s)["account"]
                   rescue JSON::ParserError, NoMethodError, TypeError
                     nil
                   end
                   if account.is_a?(String) && !account.empty?
                     [200, { code: aby.link_start(account) }]
                   else
                     [400, { error: "account" }]
                   end
                 in ["POST", "/interop/unlink"] # TEST ONLY: the account page removes the link (ABY-3 §6)
                   account = begin
                     JSON.parse(request.body.read.to_s)["account"]
                   rescue JSON::ParserError, NoMethodError, TypeError
                     nil
                   end
                   if account.is_a?(String) && !account.empty?
                     [200, { was_linked: aby.unlink(account) }]
                   else
                     [400, { error: "account" }]
                   end
                 in ["GET", "/me"] if context
                   [200, { agent: context.agent, operator: context.operator, level: context.level }]
                 in ["GET", %r{\A/accounts/[^/]+/notes\z}] if context
                   [200, { account: context.params["account"], notes: [] }]
                 in ["POST", "/drafts"] if context
                   [200, { saved: true }]
                 in ["GET", %r{\A/vault/(?:eu|na)/[^/]+\z}] if context
                   [200, { vault: context.params["id"] }]
                 in ["POST", %r{\A/t/[^/]+/orders\z}] if context
                   total = begin
                     JSON.parse(request.body.read.to_s)["total"]
                   rescue JSON::ParserError, NoMethodError, TypeError
                     nil
                   end
                   [200, { ordered: total, account: context.tenant }]
                 else [404, { error: "not found" }]
                 end
  [status, { "content-type" => "application/json" }, [JSON.generate(body)]]
end)
```

CI runs every vector file of the features this SDK implements (`features` of `vectors/ext/profiles.json`: linking's
`linking.json`, `linking-person.json`, `linking-endpoint.json`, unlink's `linking-unlink.json`, and `nonce.json`, `level-profiles.json`,
`rate-limits.json`, `tenants.json`, `tenant-budgets.json`; `test/vectors_ext_test.rb`), `sdks/interop/ext/interop_ext.py
--features linking,unlink,nonce,level_profiles,rate,tenants,tenant_budgets` against that app (with a real node, agent and passkey) and mutation testing of
their code (`test/mutate.rb`, every change killed or listed as equivalent in `test/mutants_equivalent.txt`).

### AllowedBy-Nonce

An extended feature, as ABY-2 §3.2 specifies it: a route can ask that each proof carries a nonce the service issued
a moment before, so a proof made in advance is refused. `AllowedBy.new(..., nonce: true)` turns nonces on: every
`irreversible` route then asks for one, and so does every route with `nonce: true` (on any class). A route with
`nonce: true` while the service has nonces off raises `ConfigError` at start.

A request without a current nonce is refused with `401 invalid_signature` and a fresh nonce in the answer's
`AllowedBy-Nonce` header; the agent signs the request again with it (the `nonce` member of the proof JWT, or with RFC
9421 the request's `AllowedBy-Nonce` header, which counts only when the signature covers it; a covered value that is
not base64url is refused). The AllowedBy agent runtimes retry once, on any route. A nonce is current for 300 s from
its issue. Nonces are stateless (the issue time and a MAC), so every instance that shares the `key_file` takes the
nonces of the others, and a restart keeps those it handed out current: the nonce key is HKDF-SHA256 of the signing
key's raw private key (info `allowedby/nonce/v1`, used for nothing else), the same in every AllowedBy SDK. Without a
`key_file` each process has its own key, and a nonce is good only on the process that issued it. A nonce is not
single use: within its 300 s, the replay set (one use per proof) is what stops a proof from being sent twice.

### Level profiles

Level 3 is eIDAS high in the EU and its North-American counterpart elsewhere (OAID-7 §5.3). `level_profile: "eu"`
or `"na"`, on a level-3 route only, accepts only a person whose registration's level source is of that profile;
another one, or none, is refused with `401 level_insufficient` (the approval the service creates for a serious
route asks the node for that profile). A level-3 route without `level_profile` takes either.

### Rate limits

Every service limits the calls of each agent (its passport's `sub`) and of each operator (`operator.id`), by default
600 and 6000 calls per 60 s. `AllowedBy.new(..., rate: { actor: [20, 60], operator: [1000, 60] })` sets them, each
optional; another key, or a value that is not two positive integers, raises `ConfigError` (a misspelt limit would
leave the default in place). A call over either limit is refused with `429 rate_limited` and `Retry-After: 60`. The
window slides on the SDK's clock: a call at t sees those at x with t - x < seconds. A call counts once its proof is
verified and is no replay, whatever is decided after it (a call then refused as `grant_required` or `revoked`
counts); a call refused by the limit itself, or before it (a bad proof, a missing nonce, an expired agent key),
counts for neither limit. The counts are kept in the process's memory, for at most 10 000 agents and as many
operators (the one seen least recently dropped first): behind several instances, each counts its own calls.

### Tenants and tenant budgets

An extended feature, as ORG-1 §3.3 and §5.3 specify it: one route map serves many accounts of yours (your
customers' companies), and each can tighten the rules on its own routes. The account is the route's `{tenant}` path
parameter (`context.tenant`). The extended interop app above has three: `umbrella` as the route map says, `hooli` with
an amount ceiling of 50.00 on `orders:place`, and `budget` with a budget of 100.00 EUR a day on it.

A tenant's overrides only tighten its routes: `level` (the higher one counts), `authn` (the stronger),
`require_link` (true wins), `max_lifetime` (the shorter), `amount_max` (above
it, or with no amount, `403 capability_denied`), `operators` (an allowlist of `operator.id`; any other operator gets
`403 capability_denied`). A level-0 route has no capability (it needs no grant; `AllowedBy.route` refuses one),
so no override reaches it. `mandate`, and `members_only` with `org` (a mandate from that organisation on every
route of the tenant), are accepted, but until this SDK verifies mandates (CONTRACT: company mandates), such a tenant
route refuses every request with `401 mandate_required`, before any challenge: no one is asked to approve what cannot
succeed. `members_only` is tenant-wide: it reaches the tenant's level-0
routes too, which a passport alone calls, so those refuse every request with `401 mandate_required`, asking no
approval. `qes` is refused when the service is built: this SDK has no EU
trusted list to check qualified signatures with. A resource that names the tenant (`tenant:{tenant}:...`) keeps one
tenant's approvals off another's routes.

A budget, `{max, currency, per: day | week | month, tz}`, caps the amounts the service accepts on a capability for
one tenant, per calendar period in `tz`: any IANA zone this machine knows (`Europe/Paris`; UTC by default), a period
running from local midnight to local midnight, so a day that changes the clocks lasts 23 or 25 hours. A zone the
machine does not know is refused when the service is built. Every route of that capability needs `amount_field`.
The count is kept in the verifier's store, so every instance that shares a `RedisStore` shares it. A request with no
amount in the budget's currency, or over what is left, is refused with `403 budget_exceeded`, and the refusal comes
before any challenge: no one is asked to approve what cannot succeed. A refused request is not counted; `release`
gives the amount back with the rest, and `refund(context)` gives it back when your handler refuses the request (a
wrong total, an unknown order). The store down: `503 status_stale` with `Retry-After: 5`, and what the check had
charged is given back.

The option is checked when the service is built: a tenant id outside `[A-Za-z0-9_-]{1,64}`, another key (`authority`
and `authority_policy_revision` among them: authority policies are not implemented here), a `name` that is not 1-200
characters, an `org` that is not an https origin with no path, a capability the map does not have, a value of
another shape, or an override or budget on a capability with a route that has no `{tenant}` (where it would never
apply; the error names the route) raises `ConfigError`. The SDK keeps its own frozen copy, with string keys: your
hash is never written.

### Implemented

| CONTRACT §2 (core) | Ruby SDK |
|---|---|
| 1. Configuration, refused with a message | Yes (`AllowedBy.new`, `ConfigError`) |
| 2. Route map, classes and amount thresholds, levels, params | Yes (`AllowedBy.route`) |
| 3. Discovery: `/.well-known/allowedby`, `/openapi.json`, `/.well-known/api-catalog` | Yes |
| 4. Verification, ABY-2 §5 steps 1-10, proof JWT and RFC 9421, EdDSA and ES256 only | Yes: 481/481 CONF-1 `verifier` vectors, `challenge-scope.json` included |
| 5. Challenges, service-initiated approvals for serious routes | Yes |
| 6. Background refresh, fail closed, `[verifier] refresh failed` | Yes |
| 7. Read-only context | Yes (`AllowedBy::Context`, frozen) |
| 8. Store: memory (thread-safe) and shared | Yes: `MemoryStore`, `RedisStore` |
| 9. Keys and `keyFile` in the Python format | Yes (`key_file:`) |
| 10. Framework middleware | Yes: Rack, Rails, Sinatra |

Extended features (CONTRACT §2) implemented: account linking (`/allowedby/link`, `require_link`, `account_param`,
`unlink`; see [Account linking](#account-linking)), [AllowedBy-Nonce](#allowedby-nonce) (`nonce`), [level
profiles](#level-profiles) (`level_profile`), [rate limits](#rate-limits) (`rate`) and [tenants and tenant
budgets](#tenants-and-tenant-budgets) (`tenants`). Not implemented: the disclosure callback and JWE decryption of
personal data (the JWE primitives exist, `/allowedby/callback` is not served), authority policies, company mandates
(refused), the audit sink, the admin console. Asking for one raises `ConfigError` naming it. Time zones: a grant's `amount.tz`
and `window.tz` other than UTC never match (fail closed); tenant budgets take any IANA zone (tzinfo).
