# Ruby SDK

The public API of `sdks/ruby`, with its doc comments. Guide: [docs/sdk/ruby.md](https://docs.allowedby.com/sdk/ruby).

325 public declarations, 239 with a doc comment.

## `lib/allowedby/capabilities.rb`

`sdks/ruby/lib/allowedby/capabilities.rb`

```ruby
module Capabilities
```

ABY-3: capabilities, constraints, route matching, the display a person signs. Ported from the Python reference
(sdks/python/src/allowedby/verifier.py, core.py) with the same results.

```ruby
AllowedBy::Capabilities::CLASS_MAX
```

ABY-1 §2: the longest a grant of each class may last.

```ruby
def match_route(routes, method, path)  # AllowedBy::Capabilities
```

The route of the map for a method and a normalised path, with its path parameters, or [nil, nil].

```ruby
def top_class(route)  # AllowedBy::Capabilities
```

The most serious class a route can have (a route classed by amount: its last threshold).

```ruby
def resolve_class(route, body)  # AllowedBy::Capabilities
```

ABY-3 §4, §4.1: a route classed by amount takes its class from the request before anything that depends on
the class. No readable amount: the last, most serious class.

```ruby
def resource_of(route, params)  # AllowedBy::Capabilities
```



```ruby
def seg_match(pat, ids)  # AllowedBy::Capabilities
```



```ruby
def scope_ok(pattern, resource)  # AllowedBy::Capabilities
```



```ruby
def scope_within(outer, inner)  # AllowedBy::Capabilities
```

Every resource the pattern `inner` names is named by `outer`: `**` only within `**`, `*` within `*` or `**`.

```ruby
def zone_ok(tz)  # AllowedBy::Capabilities
```

Time zones: this SDK keeps to the standard library, which has no IANA database, so only UTC is known. A
constraint naming another zone never matches (fail closed, as the Python SDK does for a zone it lacks).

```ruby
def constraints_ok(cons)  # AllowedBy::Capabilities
```

ABY-3 §2 grammar for constraint values that end up in the text the person signs.

```ruby
def in_window(window, time)  # AllowedBy::Capabilities
```

ABY-3 §2 `window`: time t is in [from, to) (a window may wrap midnight, e.g. 22:00-06:00).

```ruby
def period(per, time)  # AllowedBy::Capabilities
```

The calendar period holding time t (UTC): day, ISO week, month; and when it ends.

```ruby
def satisfies(cap, route, body, resource, gid, now)  # AllowedBy::Capabilities
```

ABY-3 §3: does this capability cover this request? -> the counter charges [key, increment, max, keep_until]
when it does (count and cumulative amounts, kept under the root gid), else nil.

```ruby
def field_ok(fields, ptr)  # AllowedBy::Capabilities
```

A body member a `fields` constraint allows: one of the fields, or inside one.

```ruby
def attenuates(child, parent)  # AllowedBy::Capabilities
```

ABY-3 §3: a child capability is equal to or narrower than its parent (ABY-1 §4).

```ruby
def narrower(name, child, parent)  # AllowedBy::Capabilities
```



```ruby
def window_within(child, parent)  # AllowedBy::Capabilities
```



```ruby
def render_display(caps, lang, templates)  # AllowedBy::Capabilities
```

AMH-1 §4 / ABY-3 §5: the only source of the text the person signs. Raises ArgumentError.

```ruby
def render_one(template, cons)  # AllowedBy::Capabilities
```



## `lib/allowedby/crypto.rb`

`sdks/ruby/lib/allowedby/crypto.rb`

```ruby
module Crypto
```

Keys and signatures with the OpenSSL standard library: Ed25519 (EdDSA) and P-256 (ES256) for JWS, plus the
WebAuthn encodings of passkey signatures (DER ES256, Ed25519, RSA PKCS#1 v1.5).

```ruby
AllowedBy::Crypto::JWS_ALGS
```

OAID-1 §3.1: the only JWS algorithms. alg "none", RS256, HS256 and anything else are refused.

```ruby
def alg_for(jwk)  # AllowedBy::Crypto
```



```ruby
def thumbprint(jwk)  # AllowedBy::Crypto
```

RFC 7638 thumbprint, the `kid` of every key in AllowedBy. Raises ArgumentError.

```ruby
def public_key(jwk)  # AllowedBy::Crypto
```

An OpenSSL public key from a JWK: Ed25519, P-256, or RSA (passkeys only). Raises ArgumentError.

```ruby
def fixed(b64, size)  # AllowedBy::Crypto
```



```ruby
def rsa_spki(jwk)  # AllowedBy::Crypto
```



```ruby
def verify_raw(alg, jwk, data, sig)  # AllowedBy::Crypto
```

A JWS signature check, algorithm pinned to the key: EdDSA for Ed25519, ES256 (raw r||s, 64 bytes) for
P-256. Never raises; false for anything else.

```ruby
def webauthn_ok(jwk, auth_data, cdj, sig)  # AllowedBy::Crypto
```

WebAuthn signature over authenticatorData || SHA-256(clientDataJSON), in the passkey's own encoding (DER for
ES256, ABY-1 §3.3). Never raises.

```ruby
def raw_to_der(sig)  # AllowedBy::Crypto
```



```ruby
def der_to_raw(der)  # AllowedBy::Crypto
```



```ruby
def p256_from_scalar(d_bytes)  # AllowedBy::Crypto
```

A P-256 private key from its 32-byte scalar (test vectors and JWK `d`).

```ruby
def public_jwk(pkey)  # AllowedBy::Crypto
```

The public JWK of an OpenSSL key (Ed25519 or P-256), without kid.

```ruby
class Key
```

A signing key: Ed25519 (EdDSA, the default) or P-256 (ES256). Its private part never appears in #inspect.

```ruby
attr_reader :alg, :kid, :jwk  # AllowedBy::Key
```



```ruby
def self.generate(kind = "Ed25519")  # AllowedBy::Key
```



```ruby
def self.from_pem(pem)  # AllowedBy::Key
```



```ruby
def self.from_ed25519_seed(seed)  # AllowedBy::Key
```



```ruby
def initialize(pkey)  # AllowedBy::Key
```



```ruby
def sign(data)  # AllowedBy::Key
```



```ruby
def derive(info)  # AllowedBy::Key
```

A key derived from this one for one use, named by `info`: HKDF-SHA256 (RFC 5869) of the raw private key
(Ed25519: its 32-byte seed; P-256: its scalar, 32 bytes big-endian, so no key encoding changes it), no salt
(32 zero bytes), 32 bytes. The nonce key (sdks/CONTRACT.md, Extended: AllowedBy-Nonce). The Ed25519 seed is read
from the key's PKCS#8 form (RFC 8410: the fixed prefix, then the seed): Ruby 3.2's openssl has no raw_private_key.

```ruby
def to_pem  # AllowedBy::Key
```

PKCS#8 PEM, the key file format shared with the Python SDK (load_keys).

```ruby
def inspect  # AllowedBy::Key
```



```ruby
module JWS
```

Compact JWS (RFC 7515) with JCS header and payload, as every AllowedBy document.

```ruby
def sign(key, typ, payload, extra = {})  # AllowedBy::JWS
```



```ruby
def parse(token)  # AllowedBy::JWS
```

[header, payload, signing input bytes, signature bytes]. Raises ArgumentError.

```ruby
def payload(token)  # AllowedBy::JWS
```



```ruby
module JWE
```

JWE compact serialization, ECDH-ES+A256KW with A256GCM (OAID-7 §7): what a node encrypts personal data to
the service's disclosure key with.

```ruby
def encrypt(jwk, plaintext)  # AllowedBy::JWE
```



```ruby
def decrypt(pkey, token)  # AllowedBy::JWE
```

The plaintext bytes. Raises ArgumentError for any malformed or forged token.

```ruby
def concat_kdf(shared)  # AllowedBy::JWE
```

NIST SP 800-56A Concat KDF, one SHA-256 round (RFC 7518 §4.6.2; no apu/apv).

```ruby
def key_wrap(kek, key)  # AllowedBy::JWE
```

RFC 3394 AES key wrap with a 256-bit KEK.

```ruby
def key_unwrap(kek, data)  # AllowedBy::JWE
```



```ruby
def aes_block(kek, block, direction)  # AllowedBy::JWE
```



```ruby
def xor_t(block, t)  # AllowedBy::JWE
```



## `lib/allowedby/grants.rb`

`sdks/ruby/lib/allowedby/grants.rb`

```ruby
module Grants
```

Grant cores, request digests and proofs (ABY-1 §3, ABY-2 §3, §4).

```ruby
AllowedBy::Grants::CORE_EXCLUDED
```

ABY-1 §3.1: what the human signs is the grant without these members (and `actor` reduced to who runs it).

```ruby
def core(grant)  # AllowedBy::Grants
```



```ruby
def core_hash(grant)  # AllowedBy::Grants
```

base64url SHA-256(JCS(core)): the WebAuthn challenge of one grant (ABY-1 §3.2).

```ruby
def batch_challenge(hashes)  # AllowedBy::Grants
```

ABY-1 §3.2 / AMH-1 §11: SHA-256(JCS({"batch": [h1, ..., hn]})).

```ruby
def request_digest(htm, htu, query, body)  # AllowedBy::Grants
```

ABY-1 §7: what a single-use grant is bound to. query: without "?", nil or "" when there is none.

```ruby
def content_digest(body)  # AllowedBy::Grants
```

RFC 9530 Content-Digest: sha-256 of the content as transmitted.

```ruby
def make_proof(key, htm, htu, allowed_by: nil, body: nil, iat: Time.now.to_i, extra: {})  # AllowedBy::Grants
```

ABY-2 §3 proof JWT. body: the bytes as transmitted, or nil.

```ruby
module WebAuthn
```

WebAuthn assertion checks of ABY-1 §3.3 (CHANGES-0.2 §15).

```ruby
def check(sig, challenge:, origin:, rp_id:, jwk:, type: "webauthn.get")  # AllowedBy::WebAuthn
```

sig: {authenticator_data, client_data_json, signature} in base64url. -> nil when valid, else the reason.

## `lib/allowedby/handlers.rb`

`sdks/ruby/lib/allowedby/handlers.rb`

```ruby
class HandlerMap
```

CONTRACT §2.10 rule 5, for an adapter that sees the handler its router chose (the Rails and Sinatra guards): which
route of the map each handler serves, and whether a request may run one. A handler is what the router runs (a
controller action, a Sinatra block), whatever the method and path that reached it.

```ruby
AllowedBy::HandlerMap::PROBE
```

A word no route of an app is written with: a sample path with one of its words replaced by it shows a catch-all.

```ruby
AllowedBy::HandlerMap::AUTHN_RANK
```

How strong an authenticator a route asks for: none (or software), synced, hardware.

```ruby
AllowedBy::HandlerMap::SITE_WIDE
```

A rule that takes any path from the root (`/*path`, a Sinatra `/*`): a site-wide fallback.

```ruby
def initialize(service, resolve, declared: [], guarded: [], log: ->(_) {})  # AllowedBy::HandlerMap
```

resolve: -> (method, path) -> [[handler, the rule it matched through], ...] the router may run there. declared:
[[route, handler], ...] the router lists as written like a route of the map; guarded: other handlers an unchecked
request never runs (a glob written over a route of the map). log: -> (message), told once of each catch-all.

```ruby
def protected?(handler)  # AllowedBy::HandlerMap
```

A handler an unchecked request never runs (on a longer path too: this is what refuses one that reaches a
catch-all of a route): a route's own, a glob written over a route, a catch-all under a route's prefix (it can
only be another handler of that route), or a site-wide fallback for a route whose own handler is not known (it
may be that route's handler). Once a route's own handler is known (a rule of its own
shape, a sample, a checked request), a site-wide fallback is not protected for it: it keeps serving other pages.

```ruby
def handlers  # AllowedBy::HandlerMap
```



```ruby
def foreign?(handlers, route)  # AllowedBy::HandlerMap
```

Whether one of these handlers is protected and not the route's own (nil: no route), or the route's own and also
a handler of another route it does not cover: what a `pass` may not reach.

```ruby
def blind_near?(at)  # AllowedBy::HandlerMap
```

A route of the map, of any method, that no handler serves (its samples reach none and none was learnt), whose
template the path extends: the SDK cannot tell what runs there for it (CONTRACT §2.10 rule 5), refused.
at: [method, path or paths] (a mounted app: the path it sees, and with its prefix).

```ruby
def allow?(chosen, route, own_shape: ->(_) { false }, at: nil)  # AllowedBy::HandlerMap
```

Whether a request checked for this route (nil: not checked) may run these handlers (the ones the router may try,
in order). A handler known as the route's own runs (one it shares with other routes, only when this route covers
them all); another route's handler never does. A catch-all for the route runs for it through a rule of the
route's own shape (own_shape: -> (handler) -> bool), and is then that route's own handler; otherwise it is never
learnt, and runs, unrecorded, only while it is the only handler found for the route. Any other handler is learnt
as this
route's when no route owns it and the route covers every other route, of any method, whose handler is not known
(CONTRACT §2.10 rule 5, "covers"). Reading is lock-free; deciding again and recording a learnt handler are one
step under the lock.
An unchecked request (route nil) never runs a protected handler, nor a catch-all for a route whose path it
extends (`/admin/anything` near a mapped `/admin` served by a fallback): the router cannot tell which route it
stands for. at: [method, path] of that request.

```ruby
def self.shape?(template, rule)  # AllowedBy::HandlerMap
```

The route's template has this rule's shape: the same words, a parameter (":name") for each of its parameters.

## `lib/allowedby/http.rb`

`sdks/ruby/lib/allowedby/http.rb`

```ruby
class HTTP
```

The HTTP client the SDK uses to reach its node (statements, status lists, approvals): Net::HTTP, http(s)
only, bounded time and size. Replace it with any object answering #call(method, url, body, headers) ->
[status, body] (tests use AllowedBy::Testing::Node).

```ruby
class Error < StandardError
```

Any network failure: refused connection, timeout, TLS, an answer too large.

```ruby
def initialize(open_timeout: 5, read_timeout: 10)  # AllowedBy::HTTP
```



```ruby
def call(method, url, body = nil, headers = {})  # AllowedBy::HTTP
```



## `lib/allowedby/jcs.rb`

`sdks/ruby/lib/allowedby/jcs.rb`

```ruby
module JCS
```

RFC 8785 JSON Canonicalization Scheme: the bytes every signature and hash in AllowedBy is computed over.

```ruby
def dump(value)  # AllowedBy::JCS
```

The canonical JSON text of a value. Raises TypeError for a value JSON cannot hold, ArgumentError for a
non-finite number or a string that is not UTF-8.

```ruby
def bytes(value)  # AllowedBy::JCS
```

The canonical UTF-8 bytes of a value.

```ruby
def object(hash)  # AllowedBy::JCS
```



```ruby
def string(str)  # AllowedBy::JCS
```



```ruby
def utf8(str)  # AllowedBy::JCS
```



```ruby
def number(value)  # AllowedBy::JCS
```

ECMAScript Number.prototype.toString for a double (RFC 8785 §3.2.2.3).

## `lib/allowedby/keys.rb`

`sdks/ruby/lib/allowedby/keys.rb`

```ruby
module KeyFile
```

The service's two keys: the signing key (Ed25519: approval requests, the organisation profile) and the
disclosure key (P-256, ECDH-ES+A256KW / A256GCM: personal data is encrypted to it, ORG-1 §4).

```ruby
def load(path)  # AllowedBy::KeyFile
```

[signing Key, disclosure OpenSSL::PKey::EC] from `path`, created with fresh keys on first use: written once,
atomically, mode 0600, first writer wins, so instances started together all use the keys on disk. The
format is the Python SDK's (sdk.load_keys): {"signing": {"pem"}, "disclosure": {"pem"}}, PKCS#8 PEM.

```ruby
def create(path)  # AllowedBy::KeyFile
```



```ruby
AllowedBy::KeyFile::NO_LINKS
```

What `link` raises on a file system without hard links (EPERM: Linux FAT mounts; EINVAL: Windows FAT).

```ruby
def publish(tmp, path, link: File.method(:link))  # AllowedBy::KeyFile
```

Gives the complete file its name, or leaves the file another instance created first: one atomic step, never a
check then a rename. The caller reads the file on disk in both cases; any other error is raised as it is.

```ruby
def disclosure_jwk(pkey, kid = "d1")  # AllowedBy::KeyFile
```

The public JWK of the disclosure key, as published in /.well-known/allowedby.

## `lib/allowedby/link_endpoint.rb`

`sdks/ruby/lib/allowedby/link_endpoint.rb`

```ruby
class Service
```

Account linking's part of the service (ABY-3 §6; CONTRACT 1.8, Extended): link_start for the app,
POST /allowedby/link for the agent. The codes and the links are kept by AllowedBy::Linking.

```ruby
def link_start(account, ttl = 600)  # AllowedBy::Service
```

Account linking (ABY-3 §6). Your signed-in account page calls this and shows the code: the person gives it to
their agent, which sends it to POST /allowedby/link; their approval (aby:link) then links their identity to
`account`, and routes with `require_link: true` accept them. ttl: seconds the code is valid (600 by default).

```ruby
def unlink(account)  # AllowedBy::Service
```

ABY-3 §6, Removing a link: when you delete the account, or the person asks to be forgotten. The stored pair and
the account's pending linking codes go; a require_link route then refuses the person (403 human_not_linked)
until they link again with a new code. -> false when the account was not linked (a no-op but for its pending
codes). Raises ArgumentError for an account that is not a non-empty String, as link_start does.

```ruby
def link_path?(method, path)  # AllowedBy::Service
```

Whether the request is for POST /allowedby/link, the SDK's own route (any spelling of the path).

```ruby
def link(headers, body, query = nil, mount: "")  # AllowedBy::Service
```

POST /allowedby/link (ABY-3 §6), which the middleware serves, and `check` too: the code is checked first,
before any approval is asked for (400 invalid_request); then the request is checked as any route (aby:link,
write, level 1, a single-use grant, the approval created by the service); accepted, the code is spent and the
person linked to its account.
headers: name => value, any case. body: the bytes as received. -> [status, headers, body]

## `lib/allowedby/linking.rb`

`sdks/ruby/lib/allowedby/linking.rb`

```ruby
class Linking
```

Account linking (ABY-3 §6; CONTRACT 1.8, Extended): the linking codes of the app's accounts, and the pair
(home node, pairwise id) linked to each account. Kept in this process's memory, bounded, thread-safe: several
instances behind one origin each keep their own (link on the instance that serves the account page, or keep one).

```ruby
def initialize(clock, max_codes: MAX_CODES, max_links: MAX_LINKS)  # AllowedBy::Linking
```

clock: -> Integer seconds, the service's own (an injected clock governs expiry too). max_codes, max_links: the
bounds (tests set smaller ones).

```ruby
def start(account, ttl)  # AllowedBy::Linking
```

ABY-3 §6 step 1: a new code for the account, unguessable (96 random bits), valid ttl seconds, single use. An
older code of the account stays valid until one of them is used. Raises ArgumentError when MAX_CODES codes are
pending, none expired (nothing is revoked to make room: ABY-3 §6 step 1).

```ruby
def pending(code)  # AllowedBy::Linking
```

ABY-3 §6 step 3: the account of a pending code, or nil for one that is unknown, spent, revoked, or at or past
its issue time plus its lifetime.

```ruby
def spend(code, iss, hid)  # AllowedBy::Linking
```

ABY-3 §6 step 5, in one step: the code is spent, the account's other pending codes are revoked, and the pair is
linked to the account in place of any other pair of that account. -> the account, or nil when the code is no
longer pending (spent by a request accepted at the same moment).

```ruby
def linked?(iss, hid, account)  # AllowedBy::Linking
```

Whether the pair is linked, and to `account` when one is named (nil: the route names none). Both members of the
pair count: the same pairwise id from another home node is another person.

```ruby
def account_of(iss, hid, account)  # AllowedBy::Linking
```

The account the pair is linked to, when it is `account` or the route names none (nil), else nil.

```ruby
def remove(account)  # AllowedBy::Linking
```

ABY-3 §6, Removing a link: the account's pair and its pending codes go, in one step. -> true when it was linked;
an account that was not is a no-op (false; its pending codes still go). Raises ArgumentError for an account that
is not a non-empty String, as start does.

```ruby
def pair_of(account)  # AllowedBy::Linking
```

The pair linked to the account, or nil: the approvals the service creates name it (`human_hint`, AMH-1 §7).

## `lib/allowedby/middleware.rb`

`sdks/ruby/lib/allowedby/middleware.rb`

```ruby
class Middleware
```

Rack middleware (Rack 2 and 3): the SDK's endpoints first, then the check on every route of the map, then your
app. Paths outside the map reach the app unchanged, body unread. The body of a mapped route is read once and
given back to the app intact. The accepted Context is env["allowedby.context"].

```
  use AllowedBy::Middleware, service          # config.ru, Sinatra
  use AllowedBy::Middleware, -> { service }   # resolved on the first request (Rails, forking servers)
```

```ruby
AllowedBy::Middleware::TARGET_KEY
```

The method and whole path (SCRIPT_NAME + PATH_INFO, normalised) an accepted request was checked for.

```ruby
AllowedBy::Middleware::SERVICE_KEY
```

The service that checked the request: its verifier holds the request's refund state (CONTRACT 1.10).

```ruby
AllowedBy::Middleware::MOVED
```

What a guard answers for an accepted request moved after the check (the path is never repeated).

```ruby
AllowedBy::Middleware::REFUNDED
```

What a guard answers for an accepted request that cannot run again: refused already (its approval given back),
or answered and forgotten, or past the bound of the refund state (still spent). The detail claims neither.

```ruby
AllowedBy::Middleware::QUERY_OVERRIDE
```

A `_method` key of a query (`_method=`, `_method[]=`), not a key that ends in it (`payment_method=`).

```ruby
AllowedBy::Middleware::OVERRIDE_VERBS
```

The verbs a request can be overridden to, and the headers that do it.

```ruby
AllowedBy::Middleware::FORM_TYPE
```

What Rack parses as a form: no Content-Type at all, urlencoded, any multipart.

```ruby
def initialize(app, service, max_body: MAX_BODY, router: nil)  # AllowedBy::Middleware
```

router: -> (env, service) -> true when the app's router gives the request to handlers that serve no route of the
map (the Railtie passes one; an app that registers AllowedBy::SinatraGuard is found by itself). It then decides
for a path longer than a mapped one, which is otherwise refused (CONTRACT §2.10 rule 2).

```ruby
def call(env)  # AllowedBy::Middleware
```



```ruby
def self.target(env)  # AllowedBy::Middleware
```

The method and the whole path, normalised (RFC 3986 §6.2.2, as the check), a request has now: a mount that moves
a prefix from PATH_INFO to SCRIPT_NAME leaves it as it is (at the mount's root, Rack::URLMap leaves PATH_INFO
empty and Rails' router makes it "/"), and so does another spelling of the same path.

```ruby
def self.checker(env, fallback)  # AllowedBy::Middleware
```

The service that checked this request (the one whose refund state it has), or `fallback` when none did.

```ruby
def self.moved?(env)  # AllowedBy::Middleware
```

Plan 14: an accepted request whose method or path is no longer the one checked, changed by a step after the
middleware (a rewrite, Rack::MethodOverride): its handler would act on values the person never approved. The
Rails and Sinatra guards refuse it, whatever handler the router chose; a plain Rack app is not seen.

## `lib/allowedby/nonce.rb`

`sdks/ruby/lib/allowedby/nonce.rb`

```ruby
class Nonce
```

ABY-2 §3.2, AllowedBy-Nonce (sdks/CONTRACT.md, Extended): the service's nonces, stateless. A nonce is
base64url(t || HMAC-SHA256(key, t)[0:16]), t its issue time in seconds as 8 bytes big-endian. It is current for
LIFETIME seconds from its issue on every instance that shares the key file (the key is derived from the signing
key), and across a restart.

```ruby
def self.key_for(key)  # AllowedBy::Nonce
```

The nonce key of a signing key (Key#derive): used for nothing else.

```ruby
def initialize(key)  # AllowedBy::Nonce
```

key: 32 bytes (Nonce.key_for).

```ruby
def issue(now)  # AllowedBy::Nonce
```

A nonce issued at `now`.

```ruby
def current?(value, now)  # AllowedBy::Nonce
```

Whether `value` is a nonce of this service issued at most LIFETIME seconds before `now`, and not after it.

```ruby
def inspect  # AllowedBy::Nonce
```



## `lib/allowedby/rails.rb`

`sdks/ruby/lib/allowedby/rails.rb`

```ruby
module ControllerHelpers
```

Controller helpers. `allowedby_context` is the accepted Context of this request (nil outside the route map).
`before_action :require_allowedby!` on the actions of protected routes refuses any request that reached them
without the middleware's check (a path the route map does not name, e.g. another Rails route to the same
action): a second line of defence, fail closed.

```ruby
def allowedby_context  # AllowedBy::ControllerHelpers
```



```ruby
def require_allowedby!  # AllowedBy::ControllerHelpers
```



```ruby
module ControllerGuard
```

Which controller actions serve the routes of the map, asked of the Rails router. Such an action never runs without
the middleware's check, whichever path reached it: a glob (`/notes/*id`), an optional segment, another route or a
mount. A catch-all that serves only unmapped paths is not such an action. An action that serves a mapped and,
on purpose, an unchecked path opts out with `skip_before_action :refuse_unchecked_allowedby_action`.

```ruby
AllowedBy::ControllerGuard::BUILD
```

Which route of the map each action serves (CONTRACT §2.10 rule 5), kept until the routes are drawn again (a
reload in development).
Read without a lock; built and published under one, checked again inside it: two first requests never learn in
two maps.

```ruby
def self.map(service)  # AllowedBy::ControllerGuard
```



```ruby
def self.actions(service)  # AllowedBy::ControllerGuard
```

The actions an unchecked request never runs.

```ruby
def self.clears?(env, service)  # AllowedBy::ControllerGuard
```

The middleware's `router`: true when Rails gives this longer path to controller actions that serve no route of
the map and that this guard covers. Anything else the routes may run (a Rack endpoint, an engine, a redirect, a
controller without the guard) is not: the request is refused (CONTRACT §2.10 rule 2).

```ruby
def self.picks(set, env, method, path)  # AllowedBy::ControllerGuard
```

What Rails may run for a path: [controller, action] of each route up to the first that is sure to match (a
route with a lambda constraint may pass to the next one), nil for what is not a controller action.

```ruby
def self.covers?(pick)  # AllowedBy::ControllerGuard
```



```ruby
def dispatch(name, request, response)  # AllowedBy::ControllerGuard
```

An action cannot hand a longer path over to the next route (X-Cascade): that one was not looked at.

```ruby
def self.resolve(method, path)  # AllowedBy::ControllerGuard
```

What the router answers for a call: [[[controller, action], the rule it matched]], or [] for none.

```ruby
def self.rule_of(method, path, action)  # AllowedBy::ControllerGuard
```

The rule (its path spec) of the first route of this action that matches the path, "" when none is found.

```ruby
def self.declared(service)  # AllowedBy::ControllerGuard
```

The routes written like a mapped one (`/notes/:id` for `/notes/{id}`), whatever their constraints: no sample
value satisfies every constraint. -> [[route of the map, [controller, action], glob?], ...]

```ruby
def self.written_like?(tpl, spec)  # AllowedBy::ControllerGuard
```



```ruby
class Railtie < ::Rails::Railtie
```

Rails integration. In config/initializers/allowedby.rb (bin/rails generate allowedby:install writes it):

```
  Rails.application.config.allowedby.service = AllowedBy.new(origin: ..., node: ..., org: ..., routes: [...],
                                                             templates: {...})

```
The middleware is added to the stack when the service is set; controllers get `allowedby_context` and
`require_allowedby!`.

## `lib/allowedby/rate.rb`

`sdks/ruby/lib/allowedby/rate.rb`

```ruby
class RateLimit
```

Rate limits (sdks/CONTRACT.md, Extended): at most n calls per sliding window of s seconds per agent (the passport's
`sub`) and per operator (`operator.id`), on the verifier's clock: a call at t sees those at x with t - x &lt; s. Both
limits are checked, then both counted, as one step; a call refused by a limit counts for neither. In this process,
as the Python reference's (core.RateLimit): each server of several counts its own calls. At most MAX_KEYS agents
and as many operators are held, the one seen least recently dropped first.

```ruby
def self.limits(rate)  # AllowedBy::RateLimit
```

The service option `rate`, {actor: [n, seconds], operator: [n, seconds]}, each optional, over DEFAULTS. Any other
key, or a value that is not two positive integers, raises ConfigError: a misspelt limit would leave the default.

```ruby
attr_reader :limits  # AllowedBy::RateLimit
```



```ruby
def initialize(rate = nil)  # AllowedBy::RateLimit
```



```ruby
def take(actor, operator, now)  # AllowedBy::RateLimit
```

Counts this call for its agent and its operator, or for neither: false when either limit is reached.

## `lib/allowedby/service.rb`

`sdks/ruby/lib/allowedby/service.rb`

```ruby
AllowedBy::EXTENDED_ROUTE_OPTIONS
```

Route options the Python SDK accepts and this SDK does not enforce yet: accepting one and not enforcing it
would fail open, so the configuration is refused (CONTRACT §2).

```ruby
AllowedBy::ROUTE_KEYS
```

The members of a route as AllowedBy.route builds it.

```ruby
AllowedBy::ROUTE_LEVEL
```

The Python SDK's service options that are route options here (CONTRACT §2, Extended: account linking).

```ruby
AllowedBy::ISO_3166
```

ISO 3166-1 alpha-2 (ORG-1 §2 `country`)

```ruby
AllowedBy::TITLES
```

Titles of the problem documents (RFC 9457); the reason, when there is one, is in `detail`.

```ruby
def route(method, path, capability = nil, **opts)  # AllowedBy
```

One line of the route map (ABY-3 §4.1). level 0: the agent's passport is enough (no person).

```
  AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")
  AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2, resource: "note:{id}")

```
class (or cls): read, write, write-hard, irreversible; or, for payments, amount thresholds
[{"up_to" => "1000.00", "class" => "write-hard"}, {"class" => "irreversible"}] read at amount_field.
level 0-3; resource: the ABY-3 resource, with {params} from the path (default "&lt;namespace>:\*");
amount_field / currency_field: JSON Pointers into the body; authn: synced or hardware passkeys only; tier: the
agent's custody tier; max_lifetime: seconds (60 s to 30 days); level_profile: eu or na on level 3; summary and
body describe the route to agents (OpenAPI). require_link: the person must have linked their identity to one of
your accounts (ABY-3 §6), and to the one the path parameter account_param names when the path has it (default
"account"). nonce: the proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2), which needs the
service's nonces on (every irreversible route asks for one then). Raises ConfigError naming what to fix.

```ruby
def link_options(where, path, capability, level, opts)  # AllowedBy
```

ABY-3 §6: require_link (true or false) on a route of level 1 or more (at level 0 there is no person, and the
verifier never looks further); account_param, a parameter of the path, with it only. -> the members of the route.

```ruby
def pointer?(value)  # AllowedBy
```



```ruby
def new(**)  # AllowedBy
```

Build the service SDK object: AllowedBy.new(origin:, node:, org:, routes:, templates:, ...). See Service.

```ruby
class Service
```

What a service embeds: publishes the discovery documents, verifies every request of its route map offline,
answers challenges and creates the approval for serious actions (ABY-2 §5, §6). Thread-safe.

```ruby
AllowedBy::Service::SCOPE_BAD_ESCAPE
```

Where what routers read apart from a last segment starts: ".json", ";a", "%00"... No pattern that is matched
against a path may backtrack: their cost is linear in the length of the path.
ABY-2 §6 (0.2.10): an escape in a path value of a challenge's scope that is malformed or decodes to a control
character or "/"; and what each value, decoded, must be: an ABY-3 §2 scope segment, so that an approval of the
scope can satisfy the route. The whole scope is at most SCOPE_MAX bytes.

```ruby
AllowedBy::Service::PLAIN_TARGET
```

CONTRACT §2.10 (10): the bytes a request target's path may hold as sent (RFC 3986 pchar, "/" and "%").

```ruby
attr_reader :origin, :node, :host, :routes, :templates, :key, :verifier, :title, :version  # AllowedBy::Service
```



```ruby
def initialize(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: {}, **extended)  # AllowedBy::Service
```

origin: this service's public origin, as agents call it (https://api.example.com).
node: the AllowedBy node it trusts (https://node.example.org), pinned on first fetch.
org: {legal_name:, country:} and optionally website, support, privacy_policy, logo (ORG-1 §2).
routes: AllowedBy.route(...) lines. templates: {capability => "sentence"} or {summary: {lang:}, lines: {lang:}}.
key_file: keeps the signing and disclosure keys across restarts and instances (created on first use, 0600).
store: MemoryStore (one process) or RedisStore (several). trust_list: a TrustList instead of `node` alone.
refresh_seconds: background refresh period (1-60). node_max_level: the highest level accepted from the node.
clock: -> Integer seconds. title, version, description: the OpenAPI info. rfc9421: accept the Web Bot Auth
profile. logger: #call(message) (default: standard error). http: the HTTP client (tests).
unprotected: your own pages that look like a variant of a protected route or extend one, served without a check:
exact paths or templates, for every method or one: ["/notes.csv", ["GET", "/notes/{id}/photo"]]. Logged at start.
nonce: AllowedBy-Nonce (ABY-2 §3.2) on every irreversible route and on the routes with `nonce` (default off).
rate: the rate limits, {actor: [n, seconds], operator: [n, seconds]}, each optional (default 600 and 6000 calls
per 60 s). tenants: {id => {name:, routes: {capability => overrides}, budgets: {capability => {max:, currency:,
per:, tz:}}, org:, members_only:}}, the accounts named by the path parameter {tenant} (ORG-1 §3.3, §5.3).

```ruby
def well_known(mount = "")  # AllowedBy::Service
```

GET /.well-known/allowedby (ABY-3 §4): vocabulary, templates, keys, the signed organisation profile.
mount: the prefix the app is mounted under (SCRIPT_NAME), part of every published URL.

```ruby
def published  # AllowedBy::Service
```

The route map as published: the app's routes, then the SDK's own (POST /allowedby/link, ABY-3 §6).

```ruby
def openapi(mount = "")  # AllowedBy::Service
```

OpenAPI 3.1 for the route map (ABY-3 §5.1): each operation's `security` names the capability it needs,
`x-allowedby` adds class, level and amount.

```ruby
def api_catalog(mount = "")  # AllowedBy::Service
```

RFC 9727 API catalog: where this origin's APIs and their descriptions are.

```ruby
def handle(method, path, mount = "")  # AllowedBy::Service
```

The SDK's own endpoints. -> [status, headers, body] or nil when the path is not one of them.

```ruby
def target_refusal(path)  # AllowedBy::Service
```

CONTRACT §2.10 (10): a request target whose path holds a byte that is not plain (a raw non-ASCII byte, a space, a
control character, a quote, a backslash...) is refused before routing and verification. -> refusal or nil.

```ruby
def report(message)  # AllowedBy::Service
```

A line for the service's log (an adapter's warning at start). Never a value of a request.

```ruby
def route_for(method, path, routes = @routes)  # AllowedBy::Service
```

The route of the map a request falls under, or nil (the app's own paths, unchanged).

```ruby
def variant_of(method, path, routes = @routes)  # AllowedBy::Service
```

The route of the map another router could reach with this request although the map does not name it: the path
read with its dot segments kept, with reserved characters decoded (`%2F`, `%3A`, several times over), without
control characters, with a repeated or trailing "/" dropped, or without a suffix (`/notes.json`, `/notes;a`:
Rails routes `/notes`, `/notes/`, `//notes` and `/notes.json` to the same action); or the method in another
case. Such a request is refused (400), never handed to the app unchecked. -> route or nil.

```ruby
def extension_of(method, path, routes = @routes)  # AllowedBy::Service
```

The route of the map that a longer path reaches when a router gives a parameter several segments (`/notes/{id}`
and `/notes/7/x`: a wildcard, a splat, a path converter). The SDK cannot see the router: the request is refused
unless `unprotected:` names the path (CONTRACT §2.10 rule 2). `/notes/7` below a literal `/notes` is the app's.

```ruby
def longer_only?(method, path)  # AllowedBy::Service
```

True when rule 2 alone refuses the request and an adapter that sees the route its router chooses may decide
instead (CONTRACT §2.10 rule 2). An odd or very long path stays refused.

```ruby
def taken_as(method, path)  # AllowedBy::Service
```

The mapped paths this longer path may stand for, its parameters taken from its own segments: the handler the
router gives them to is the protected one, whatever a parameter's pattern accepts.

```ruby
def unprotected?(method, path, variants: false)  # AllowedBy::Service
```

A page the application declares as its own (`unprotected:`, CONTRACT §2.10 rule 3). An exact entry is for that
very path; a template only for a plain path: no empty segment, control character, encoded separator or dot
segment. variants: whether the question is about a variant of a route (an exact entry only).

```ruby
def protects?(method, path, routes = @routes)  # AllowedBy::Service
```

True when the request is the SDK's to check or refuse: a route of the map, a variant of one (variant_of) or an
extension of one (extension_of).

```ruby
def samples  # AllowedBy::Service
```

Calls of each route of the map, its parameters filled in with values of the usual kinds: [method, path]. The
Rails and Sinatra guards ask their router which handler serves them: it never runs unchecked, whichever path
reached it.

```ruby
def check(method, path, headers, body = nil, query = nil, mount: "", longer: false)  # AllowedBy::Service
```

-> [Context, nil] when the request is allowed, or [nil, [status, headers, body]] to send back. A path outside
the route map is allowed with a nil context (your own authentication applies). headers: name => value, any
case. body: the bytes as received ("" or nil when there is none). query: without "?".
mount: the prefix the app is mounted under (SCRIPT_NAME); the route map names paths without it.
longer: the adapter has seen the route its router chose for this longer path (longer_only?): not refused here.
An accepted context: call forget(ctx) once the request is answered (CONTRACT 1.10; the middleware does), or its
refund state stays, with the context, until the bound of 10 000 drops it.

```ruby
def verified(route, method, path, headers, body, query, mount)  # AllowedBy::Service
```

The check of a request for this route of the verifier's map, once the path is known to be plain. -> as check.

```ruby
AllowedBy::Service::BUDGET_FIRST
```

The refusals a challenge would answer, after which a used-up tenant budget is answered instead (a single-use
approval spent, or a dead agent key, is not the budget's to answer).

```ruby
def stale(req, route, err)  # AllowedBy::Service
```



```ruby
def budget_of(route, path, body)  # AllowedBy::Service
```

ORG-1 §5.3: the tenant budget of this request's route, if any. -> {budget, tenant, key, amount, until}: the amount
at the route's amount_field, nil when it is absent or in another currency than the budget's (ORG-1 §5.1: never
converted), which no budget can count.

```ruby
def over_budget(req, route, bud, charge: nil)  # AllowedBy::Service
```

nil when the amount fits what is left of the budget (with charge, the accepted context: once it is counted, in
the verifier's store, which every instance that shares it shares), else the 403 budget_exceeded. Only a charge
counts: what is used is read for the message of a refusal, or to refuse before a challenge. Raises StoreError.

```ruby
def money(value)  # AllowedBy::Service
```

Two decimals, exactly (a Float would round a large amount).

```ruby
def release(ctx)  # AllowedBy::Service
```

sdks/CONTRACT.md, Refund on the SDK's own refusal (ABY-2 §5 step 9), for an adapter: `release(ctx)` when the SDK
itself refuses an accepted request before its handler starts (it gives back exactly what the check charged, once;
-> true when given back), `started(ctx)` just before the handler runs (-> false for a request given back
already: it must not reach a handler). Nothing is given back once a request started, or for the app's own
refusals.

```ruby
def refund(ctx)  # AllowedBy::Service
```

The handler refused an accepted request (a wrong total, an unknown invoice): the tenant budget it counted is
given back (ORG-1 §5.3), once. -> true when given back. The rest of what the check charged stays spent.

```ruby
def started(ctx)  # AllowedBy::Service
```

The handler is about to run: nothing is given back from now on. -> false when this request was given back or
forgotten already: it must not reach a handler.

```ruby
def forget(ctx)  # AllowedBy::Service
```

The request is answered: its refund state goes (the middleware does this itself). An adapter of your own calls it
once it has the app's answer, or the state stays until the bound of 10 000 drops it.

```ruby
def problem(code, status, detail = nil, headers = {}, **extra)  # AllowedBy::Service
```

A problem document (RFC 9457) as [status, headers, body].

```ruby
def challenge(req, rej)  # AllowedBy::Service
```

ABY-2 §6, §7: the answer to a refused request, with the challenge when a person's approval can fix it. For a
write-hard or irreversible route the service creates the approval itself, bound to this exact request.

## `lib/allowedby/sinatra.rb`

`sdks/ruby/lib/allowedby/sinatra.rb`

```ruby
module SinatraGuard
```

Sinatra extension: `register AllowedBy::SinatraGuard` (require "allowedby/sinatra"), with the service in
`set :allowedby, -> { service }`. The handler of a mapped route never runs without the middleware's check,
whichever path reached it: a splat (`/notes/*`), an optional segment, `strict_paths false` or a mount. A
catch-all that serves only unmapped paths is untouched.

```ruby
def self.registered(app)  # AllowedBy::SinatraGuard
```



```ruby
def self.router_of(app)  # AllowedBy::SinatraGuard
```

The middleware's `router` when the next app is a Sinatra app with this guard and nothing else runs before or
after its routes (its own middleware, a downstream app); nil otherwise: longer paths are then refused.

```ruby
def self.clears?(klass, env, service)  # AllowedBy::SinatraGuard
```

True when the app's routes give this longer path to no handler of a mapped route.

```ruby
AllowedBy::SinatraGuard::BUILD
```

Which route of the map each handler serves (CONTRACT §2.10 rule 5), for this app's prefix: asked of the router
once per class, service and prefix, again when the class has more routes.
Read without a lock; built and published under one, checked again inside it: two first requests never learn in
two maps.

```ruby
def self.handler_map(klass, service, prefix)  # AllowedBy::SinatraGuard
```



```ruby
def self.declared(klass, service, prefix)  # AllowedBy::SinatraGuard
```

The routes of the app written like a route of the map (`/notes/:id` for `/notes/{id}`): that route's own
handlers, whatever their conditions. -> [[route of the map, handler], ...]

```ruby
def self.sinatra_routes(klass, method)  # AllowedBy::SinatraGuard
```



```ruby
def self.handlers_for(klass, method, calls)  # AllowedBy::SinatraGuard
```

The handlers these calls run, for this method (HEAD runs what GET is).

```ruby
def self.handlers(klass, method, path, every: false)  # AllowedBy::SinatraGuard
```

The handlers Sinatra may run for a path: up to the first route without conditions, in this class and the ones
above. A handler is the block of the route: two routes with one block are one handler (CONTRACT §2.10 rule 2).
every: all the routes of the path, as `pass` can reach any of them.

```ruby
def self.matched(klass, method, path, every: false)  # AllowedBy::SinatraGuard
```

[[handler, its route's pattern], ...] for a path, as `handlers`.

```ruby
def self.handler_of(pattern, wrapper)  # AllowedBy::SinatraGuard
```

The block Sinatra compiled the route from, or the route itself when it cannot be found.

```ruby
def self.serves?(chosen, mapped)  # AllowedBy::SinatraGuard
```

Whether one of the chosen handlers is one of these.

```ruby
module Helpers
```

The helpers of the extension.

```ruby
def allowedby_context  # AllowedBy::SinatraGuard::Helpers
```



```ruby
def pass(&)  # AllowedBy::SinatraGuard::Helpers
```

`pass` hands the request to the next routes of its path, which the guard did not look at: refused when one of
them is the handler of another route of the map, and an unchecked one always on a longer path the router
decided.
A checked request passes only to handlers its route owns, or that no route of the map does.

## `lib/allowedby/store.rb`

`sdks/ruby/lib/allowedby/store.rb`

```ruby
module Store
```

The state a verifier keeps (ABY-2 §3.3, ABY-1 §7, ABY-3 §3): the replay set of proofs, single-use grants and
counters. Every method takes `now` from the SDK's clock, never the store's own, so an injected clock governs
expiry too. A store:

```
  add(key, expires, now)  -> true when added, false when the key is live (a replay, a second use)
  get(key, now)           -> the live value, or 0
  charge(charges, now)    -> all or nothing: [[key, increment, max or nil, expires]], true when every total
                             stays within its max

```
A refund (sdks/CONTRACT.md, Refund on the SDK's own refusal) is a charge too: the receipt of the check, each
increment negated, with no max, applied exactly (the single-use mark back to 0, the totals back by the amount).
A store that does not take it returns false or raises StoreError: the approval then stays spent.

Keys are arrays of strings and numbers. A store that cannot answer raises StoreError: the request is refused.

```ruby
def self.key(parts)  # AllowedBy::Store
```



```ruby
class MemoryStore
```

For one process only (thread-safe: Puma's threads share it). Several processes or machines need a shared
store such as RedisStore, or a replayed proof is accepted by the instance that has not seen it.

```ruby
def initialize(max_keys: 200_000)  # AllowedBy::MemoryStore
```



```ruby
def add(key, expires, now)  # AllowedBy::MemoryStore
```



```ruby
def get(key, now)  # AllowedBy::MemoryStore
```



```ruby
def charge(charges, now)  # AllowedBy::MemoryStore
```



```ruby
class RedisStore
```

The same store in Redis, shared by every instance and process. Pass a connected client of the `redis` gem
(redis-rb 5 or later): `AllowedBy::RedisStore.new(Redis.new(url: ENV["REDIS_URL"]))`. The gem is not a
dependency of this one: bring your own.

add is one Lua script (atomic); charge is a WATCH/MULTI transaction retried on conflict, with amounts kept as
exact fractions ("4200/1") because Lua numbers are doubles. Each key expires in Redis a minute after its own
deadline, measured from the SDK's clock.

```ruby
def initialize(redis, prefix: "allowedby:", retries: 20)  # AllowedBy::RedisStore
```



```ruby
def add(key, expires, now)  # AllowedBy::RedisStore
```



```ruby
def get(key, now)  # AllowedBy::RedisStore
```



```ruby
def charge(charges, now)  # AllowedBy::RedisStore
```



## `lib/allowedby/tenants.rb`

`sdks/ruby/lib/allowedby/tenants.rb`

```ruby
module Tenants
```

Tenants and tenant budgets (ORG-1 §3.3, §5.3; sdks/CONTRACT.md, Extended), ported from the Python reference
(sdk.py _check_tenants, verifier.py effective_route): the service option `tenants`, checked when the service is
built, the route a tenant's overrides make of the provider's (never looser), and the budgets' periods.

```ruby
AllowedBy::Tenants::LATER
```

The tenant keys of authority policies (ABY-1 §5): an extended feature this SDK does not implement yet.

```ruby
def check(tenants, routes)  # AllowedBy::Tenants
```

The `tenants` option, checked against the route map: a frozen copy with string keys, the caller's never written.
Every key is one the verifier enforces and every value has its shape; anything else raises ConfigError, as a
misspelt override would leave the route as loose as the provider's (CONTRACT: every option is enforced or
refused).

```ruby
def check_tenant(where, tenant, caps, routes)  # AllowedBy::Tenants
```



```ruby
def check_override(where, override)  # AllowedBy::Tenants
```



```ruby
def override_ok?(override)  # AllowedBy::Tenants
```



```ruby
def budget_refusal(budget, cap, routes)  # AllowedBy::Tenants
```

ORG-1 §5.3: a budget {max, currency, per: day | week | month, tz?} on `cap`, every route of which reads an amount
(a route without one could never be called: the budget refuses a request it cannot count). -> why it is
refused, or nil.

```ruby
def effective(route, tenant, tenants)  # AllowedBy::Tenants
```

The route a tenant's overrides make of the provider's: tighter only (ORG-1 §3.1 `overridable`, §3.3): the higher
level, the stronger authn, mandate and require_link (true wins), a shorter lifetime, an amount ceiling, an
operator allowlist. A members_only tenant with an org needs a mandate from it on every route, level 0 included
(it is tenant-wide, not keyed by capability). The route itself when the tenant changes nothing.

```ruby
def zone(tz)  # AllowedBy::Tenants
```

A budget's IANA time zone (tzinfo: the system's zoneinfo, or the tzinfo-data gem), UTC when it names none; nil
for a name this machine does not know.

```ruby
def period_id(per, time, tz)  # AllowedBy::Tenants
```

The calendar period holding time t in tz: the day, the ISO week (from Monday) or the month (ABY-3 §2), as the
Python reference names it (core.period_id).

```ruby
def period_end(per, time, tz)  # AllowedBy::Tenants
```

When that period ends, in epoch seconds: the local midnight after it, so a day that changes the clocks lasts 23
or 25 hours.

```ruby
def midnight(zone, date)  # AllowedBy::Tenants
```

The first instant of a local date: its midnight, the earlier one when the clocks go back over it, and the first
time the day has when they skip it (a change at 00:00).

```ruby
def budget_key(tenant, cap, budget, time)  # AllowedBy::Tenants
```

The store key of a tenant budget's count this period. Its currency and tz are in it: a budget moved to another
currency or zone starts a new count, never one that mixes them (the Python reference's key).

```ruby
def origin?(value)  # AllowedBy::Tenants
```

An https origin with no path, query, fragment or user (http on this machine only): a URL keys are fetched from.

```ruby
def plain(value)  # AllowedBy::Tenants
```

A deep copy with string keys (a Ruby caller may write symbols), never the caller's objects.

## `lib/allowedby/testing.rb`

`sdks/ruby/lib/allowedby/testing.rb`

```ruby
module Testing
```

Test helpers: an in-memory AllowedBy node, a person with a software passkey and an agent, so you can test your
own app end to end without a browser or a network. TEST ONLY: the keys are generated per run and the "node"
answers only through the `http:` option of AllowedBy.new.

```
  require "allowedby/testing"
  node = AllowedBy::Testing::Node.new
  aby = AllowedBy.new(origin: "https://notes.test", node: node.origin, http: node, start: false, ...)
  aby.verifier.refresh
  agent = node.agent
  grant = node.grant(agent, audience: "https://notes.test", capabilities: [{ "cap" => "notes:read",
                     "constraints" => { "scope" => "note:*" } }])
  headers = agent.headers("GET", "https://notes.test/notes", allowed_by: grant)
```

```ruby
class Agent
```

An agent: its key and its passport. #headers signs one request (ABY-2 §3).

```ruby
attr_reader :key, :passport, :sub  # AllowedBy::Testing::Agent
```



```ruby
def initialize(key, passport, sub, clock)  # AllowedBy::Testing::Agent
```



```ruby
def headers(method, url, allowed_by: @passport, body: nil)  # AllowedBy::Testing::Agent
```

The Allowed-By and AllowedBy-Proof headers for one request. url: the full URL (the query is not signed).

```ruby
class Node
```

A node that issues passports, human registrations and countersigned grants, and serves its statement, its
status list and service-initiated approvals to the SDK through #call (the `http:` option).

```ruby
attr_reader :name, :origin, :approvals, :passkey, :credential_id  # AllowedBy::Testing::Node
```



```ruby
def initialize(name: "node.test", clock: -> { Time.now.to_i }, level: 2, authn: "hardware")  # AllowedBy::Testing::Node
```



```ruby
def status_uri  # AllowedBy::Testing::Node
```



```ruby
def statement  # AllowedBy::Testing::Node
```



```ruby
def status_list  # AllowedBy::Testing::Node
```



```ruby
def revoke(token)  # AllowedBy::Testing::Node
```

Revoke a grant or a passport (the next refresh of the SDK sees it).

```ruby
def agent(operator: "agent.test", tier: 0, ttl: 3600)  # AllowedBy::Testing::Node
```

A new agent with a tier-0 passport (OAID-3) from this node.

```ruby
def registration  # AllowedBy::Testing::Node
```

The person's registration (OAID-7 §4): their passkey, their level.

```ruby
def human_id(audience)  # AllowedBy::Testing::Node
```

The person's pairwise id at an audience (what the service sees as human_id).

```ruby
def grant(agent, audience:, capabilities:, level: @level, initiator: nil, single_use: nil, ttl: 3600, templates: nil, batch: nil, **overrides)  # AllowedBy::Testing::Node
```

A grant the person approved with a passkey tap and this node countersigned (ABY-1 §3).
initiator: the service key's kid for a service-initiated grant (write-hard, irreversible), else nil.
single_use: the request_digest it is bound to (ABY-1 §7). Other members override the grant's.

```ruby
def sub_grant(parent, agent, capabilities:, ttl: 1800, **overrides)  # AllowedBy::Testing::Node
```

A sub-agent's grant under `parent` (ABY-1 §4), countersigned by this node: one level deeper, the parent's
person, audience and approval, no signature of the person's own. Other members override the grant's (a test
of a malformed chain).

```ruby
def assertion(challenge, rp_id: @name, flags: 0x05)  # AllowedBy::Testing::Node
```

A WebAuthn assertion by the person's passkey over `challenge` (ABY-1 §3.3).

```ruby
def call(method, url, body = nil, headers = {})  # AllowedBy::Testing::Node
```

The SDK's HTTP client (the `http:` option): statement, status list, approval creation.

## `lib/allowedby/trust.rb`

`sdks/ruby/lib/allowedby/trust.rb`

```ruby
class TrustList
```

OAID-5 §2: a signed trust list (`oaid-trust+jwt`) instead of trust on first use. `key` is the service's own
public JWK that signed it (configuration integrity). Raises ConfigError.

```ruby
attr_reader :payload, :exp, :anchors, :denied, :vouching, :programs, :witnesses_min  # AllowedBy::TrustList
```



```ruby
def self.load(path, key)  # AllowedBy::TrustList
```



```ruby
def self.sign(key, payload)  # AllowedBy::TrustList
```



```ruby
def initialize(jws, key)  # AllowedBy::TrustList
```



```ruby
class TrustResolver
```

OAID-5 §3: which nodes a trust list trusts, at which level: anchors, then program lists, then vouching depth
by depth, then `witnesses_min`. Pure: every document comes from the callables, so the same code runs in the
background refresh (HTTP) and against the test vectors.

```ruby
def initialize(trust_list, statement:, program:, vouches:, checkpoint:)  # AllowedBy::TrustResolver
```

statement: name -> parsed statement {"name", "kid", "payload", "origin"} or nil
program: url -> program list JWS or nil
vouches: statement -> [vouch JWS] the node published
checkpoint: statement -> the node's latest checkpoint (C2SP signed note) or nil

```ruby
def resolve(now)  # AllowedBy::TrustResolver
```

-> {name => {"statement", "max_level", "via", "depth", "witness_ok"}}

```ruby
module Checkpoint
```

C2SP signed notes: the checkpoints a node's transparency log publishes (OAID-4) and their witness
cosignatures.

```ruby
def parse(note)  # AllowedBy::Checkpoint
```

-> [body with its final newline, [[signer, signature bytes]]] or [nil, []]

```ruby
def keyhash(name, sigtype, jwk)  # AllowedBy::Checkpoint
```



```ruby
def role_keys(statement, role)  # AllowedBy::Checkpoint
```



```ruby
def signed_by_node?(body, lines, statement)  # AllowedBy::Checkpoint
```

The checkpoint's origin line is the node's log origin, signed by one of its `checkpoint` keys.

```ruby
def cosigned?(body, signer, sig, timestamp, statement)  # AllowedBy::Checkpoint
```



## `lib/allowedby/util.rb`

`sdks/ruby/lib/allowedby/util.rb`

```ruby
class ConfigError < ArgumentError
```

Raised for a configuration the SDK refuses at construction: the message says what to fix.

```ruby
class StoreError < StandardError
```

Raised by a store that cannot answer (a lost Redis connection): the request is refused, never accepted.

```ruby
module Util
```

Encodings and small helpers shared by every part of the SDK.

```ruby
def b64u(bytes)  # AllowedBy::Util
```

base64url without padding (RFC 7515 §2).

```ruby
def b64u_dec(str)  # AllowedBy::Util
```

Strict base64url: the URL-safe alphabet only, no padding, no whitespace. Raises ArgumentError.

```ruby
def b64_dec(str)  # AllowedBy::Util
```

Standard base64 with padding, strict (RFC 4648 §4). Raises ArgumentError.

```ruby
def b64(bytes)  # AllowedBy::Util
```



```ruby
def sha256(data)  # AllowedBy::Util
```



```ruby
def parse_json(bytes)  # AllowedBy::Util
```

JSON from bytes: valid UTF-8, any JSON value. Raises ArgumentError. Like the Python reference (json.loads),
a repeated member keeps its last value.

```ruby
def secure_eq(left, right)  # AllowedBy::Util
```

Constant-time equality of two strings (digests, challenges, tokens).

```ruby
def clip(value, max = 80)  # AllowedBy::Util
```

An attacker-supplied value, safe to put in a message: printable and bounded.

```ruby
def dec(value)  # AllowedBy::Util
```

An amount as text (ABY-3 §2): at most 15 digits before the point and 6 after, as an exact Rational.

```ruby
def pointer(doc, ptr)  # AllowedBy::Util
```

RFC 6901 JSON Pointer; nil when the member is missing.

```ruby
def json_leaves(doc, prefix = "")  # AllowedBy::Util
```

The JSON Pointers of every leaf member of an object (what `fields` constrains, ABY-3 §2).

```ruby
def norm_path(path)  # AllowedBy::Util
```

RFC 3986 §6.2.2 for a path: percent-encoding normalised (unreserved decoded, hex upper), dot segments
removed. Bytes outside printable ASCII are percent-encoded first, so the result is always ASCII.

```ruby
def pct_path(path)  # AllowedBy::Util
```

The percent-encoding part of norm_path alone: dot segments are still there, as a router that does not remove
them sees the path.

```ruby
AllowedBy::Util::HEX
```

The value of each hex digit, by its byte.

```ruby
AllowedBy::Util::CONTROLS
```

C0, DEL, C1, U+2028 and U+2029 in a path, as sent or encoded any number of times.

```ruby
def decode_once(value)  # AllowedBy::Util
```

One percent-decoding of a path value (CONTRACT §2 item 7, as Python's unquote): each %XX becomes its byte once
(`%2520` gives `%20`, `%2F` a "/" inside the value), any other "%" stays, and bytes that are not UTF-8 become
U+FFFD.

```ruby
def decoded_path(path)  # AllowedBy::Util
```

A path with every percent-encoding decoded, again and again until none is left (bytes). One pass: a byte that
completes an encoding is replaced by what it stands for, which may complete another one (%252525...).

```ruby
def normalize_origin(origin)  # AllowedBy::Util
```

scheme://host[:port] with the scheme and host lowercased and the default port removed (ABY-2 §3 `htu`).
Raises ArgumentError for anything else (a path, a query, credentials).

```ruby
def local_host?(host)  # AllowedBy::Util
```

True for this machine's names, where plain http is allowed in development: localhost and \*.localhost are the
loopback (RFC 6761), as in the Python reference (core.is_local), and the loopback addresses.

```ruby
def origin_host(origin)  # AllowedBy::Util
```

The host part of an origin, for local_host?.

```ruby
def netloc(origin)  # AllowedBy::Util
```

host[:port] of an origin (the realm, the node name).

```ruby
def deep_freeze(value)  # AllowedBy::Util
```

A deep copy that cannot be changed: what the handler receives is read-only.

## `lib/allowedby/verifier.rb`

`sdks/ruby/lib/allowedby/verifier.rb`

```ruby
AllowedBy::STATUS
```

Status of every refusal code (ABY-2 §6), the same as the Python reference (verifier.STATUS).

```ruby
AllowedBy::CHALLENGE_CODES
```

The codes that answer with an AllowedBy challenge (WWW-Authenticate with what to ask the person for).

```ruby
class Reject < StandardError
```

A refused request: `code` is the ABY-2 error code, `status` its HTTP status, `why` a short reason without
secrets or personal data.

```ruby
attr_reader :code, :why, :route, :actor_sub, :status, :nonce  # AllowedBy::Reject
```

nonce: a fresh AllowedBy-Nonce for the answer's header (ABY-2 §3.2), when the refusal asks for one.

```ruby
def initialize(code, why = nil, route: nil, actor_sub: nil, nonce: nil)  # AllowedBy::Reject
```



```ruby
def self.build(**fields)  # AllowedBy
```



```ruby
def initialize(mount: "", **rest)  # AllowedBy
```



```ruby
def full_path  # AllowedBy
```



```ruby
def header(name)  # AllowedBy
```



```ruby
class Verifier
```

ABY-2 §5: verifies every request offline against the route map. Node statements and status lists are fetched
by a background thread, never while handling a request (OAID-5 §3): with an empty cache a request is
refused (`untrusted_node`, `status_stale`). Ported from sdks/python/src/allowedby/verifier.py (Verifier.verify).

```ruby
AllowedBy::Verifier::MAX_TICKETS
```

Accepted requests in flight whose refund state is kept (CONTRACT 1.10), oldest dropped first: the middleware and
the link endpoint forget each one when it is answered (an adapter of your own calls Service#forget), so only an
integration that never forgets reaches the bound. A request without a ticket (forgotten, dropped) never starts:
fail closed.

```ruby
attr_reader :origin, :routes, :store, :nodes, :status, :service_kids, :nonce, :rate  # AllowedBy::Verifier
```



```ruby
def initialize(origin:, routes:, service_kids:, trusted_nodes: {}, dev_webauthn_origins: {}, refresh_seconds: 5, clock: nil, store: nil, trust_list: nil, templates: {}, rfc9421: false, http: nil, logger: nil, start: true, linked: nil, nonce: nil, rate: nil, tenants: {})  # AllowedBy::Verifier
```

trusted_nodes: {node origin => max_level}, each node's `node` key pinned on first fetch (trust on first use);
trust_list: a TrustList (OAID-5), which then replaces trusted_nodes. http: #call(method, url, body, headers)
-> [status, body] (default Net::HTTP). start: run the background refresh. With it, the first refresh is over
(done or failed) before the constructor returns, at most STARTUP_WAIT seconds, so a service that starts cold
(a new instance, one that scales to zero) holds node keys and status lists before its first request: nothing
is fetched at request time (ARCH-1 §4, CONTRACT §2 item 4). linked: ->(iss, human_id, route, params) -> the
account the pair is linked to (a String, which the context's linked_account carries), or nil: a require_link
route refuses a request it answers nil or false for (ABY-3 §6). nonce: a Nonce, when the service's nonces are on
(ABY-2 §3.2): a route with `nonce`, and every irreversible route, then needs a current one. rate: a RateLimit
(default: RateLimit::DEFAULTS). tenants: the service's tenants (Tenants.check), whose overrides tighten the routes
that name one ({tenant}, ORG-1 §3.3).

```ruby
def now  # AllowedBy::Verifier
```



```ruby
def start_refresh  # AllowedBy::Verifier
```

Starts the refresh thread (once; again after a fork or if it died). Only the constructor waits for its first
refresh: a thread started again (in a forked worker, from the middleware) serves the cache the worker
inherited, and no request waits on the network.

```ruby
def ensure_refresh  # AllowedBy::Verifier
```

The middleware calls this on every request: a refresh thread that was started is started again in a forked
worker (Puma cluster mode, Unicorn), where threads do not survive the fork. Cheap when it runs.

```ruby
def stop_refresh  # AllowedBy::Verifier
```



```ruby
def refresh  # AllowedBy::Verifier
```

Fetch node statements (trust on first use or the trust list) and status lists. Background only; also
callable directly (tests, a deploy hook). A failure keeps the cache: staleness rules apply.

```ruby
def parse_statement(jws, origin)  # AllowedBy::Verifier
```

A node statement (OAID-2 §3), self-signed by its single `node` key, unexpired.
-> {"name", "kid", "payload", "origin"}. Raises ArgumentError with the reason.

```ruby
def node_entry(statement, max_level, via: "tofu", witness_ok: true)  # AllowedBy::Verifier
```

The cache entry of a trusted node. Keys whose kid is not their thumbprint are dropped.

```ruby
def install_node(jws, max_level, origin:)  # AllowedBy::Verifier
```

Trust a node from its statement, as a refresh does (tests, or a statement obtained out of band).

```ruby
def install_status(uri, jws, into = nil, node: nil)  # AllowedBy::Verifier
```

Take a status list (`statuslist+jwt`) signed by an `issue` key of the node whose statement names `uri`.
-> true when accepted. A list older than the one held is ignored (no rollback).
node: the node the list was fetched for (the refresh passes it). Without it, the single node whose statement
names `uri`; refused when several do, so one node never decides with which keys another node's list is read.

```ruby
def verify(req, link: false)  # AllowedBy::Verifier
```

-> Context, or raises Reject. link: the caller is the link endpoint (Service#link): only it is answered on the
SDK's own aby:link route (ABY-3 §6), whose code is checked first.

```ruby
def node_doc(token, typ, role)  # AllowedBy::Verifier
```



```ruby
def bit(ref, cls, at)  # AllowedBy::Verifier
```



```ruby
def registration(token, at, cls)  # AllowedBy::Verifier
```

A human registration (OAID-7 §4) from a trusted home node, unrevoked. -> [payload, effective level]

```ruby
def human(grant, at, cls)  # AllowedBy::Verifier
```

ABY-1 §3.3 steps 1-2 on the root, a batch signature included (§3.2). -> [registration, level]

```ruby
def assertion(reg, sig, challenge)  # AllowedBy::Verifier
```

ABY-1 §3.3 step 2 for one assertion under one registration. -> nil when valid, else the reason.

```ruby
def release(ctx)  # AllowedBy::Verifier
```

sdks/CONTRACT.md, Refund on the SDK's own refusal (ABY-2 §5 step 9): the SDK refused this accepted request
itself before its handler started (rule 5, a method or path changed after the check). Gives back exactly what
the check charged for it, once: the single-use mark, the grant's count and amount totals, as negative increments
with no max. -> true when given back. Nothing is given back for a request whose handler started (start), twice,
or when the store does not take it: the approval then stays spent, logged without request data.

```ruby
def attach(ctx, charge)  # AllowedBy::Verifier
```

ORG-1 §5.3: the tenant budget's charge of this accepted request (Service#check counts it after the check), given
back with the rest by release, or alone by refund_budget.

```ruby
def refund_budget(ctx)  # AllowedBy::Verifier
```

The handler refused this accepted request: its tenant budget's charge is given back, once (ORG-1 §5.3). -> true
when given back; false when there is none, it was given back already, or the store does not take it (the amount
then stays counted, logged without request data).

```ruby
def start(ctx)  # AllowedBy::Verifier
```

The adapter is about to hand this accepted request to its handler: from now on nothing is given back for it.
False for a request given back already: its approval is usable again, so it never reaches a handler (a layer
that dispatches it once more). False too for one whose state is gone (answered and forgotten, or dropped at the
bound): nothing can tell it was not given back. True again for one already started (the same handler, again).

```ruby
def forget(ctx)  # AllowedBy::Verifier
```

This accepted request is answered: its refund state goes (nothing is given back after this, and it never starts
again: a later dispatch of it is refused).

## `lib/allowedby/version.rb`

`sdks/ruby/lib/allowedby/version.rb`

```ruby
AllowedBy::VERSION
```

The version of this gem (semver).

```ruby
AllowedBy::SPEC_VERSION
```

The AllowedBy specification set this gem implements (specs/README.md).
