# Go SDK

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

82 public declarations, 82 with a doc comment.

## `allowedbychi/allowedbychi.go`

`sdks/go/allowedbychi/allowedbychi.go`

```go
func Middleware(s *allowedby.Service) func(http.Handler) http.Handler
```

Middleware serves the SDK's endpoints, checks every route of the map and the route chi dispatches to, and calls the
next handler with the request's body intact. Register it after any middleware that rewrites the path (StripSlashes,
CleanPath), so that it asks chi about the path chi will route. Wrapped around the router (no chi route context), it
is aby.Handler: it does not see the route, and refuses every path below a protected parameter. chi runs Use
middleware for unrouted paths too, so the discovery paths are served.

## `allowedbyecho/allowedbyecho.go`

`sdks/go/allowedbyecho/allowedbyecho.go`

```go
func Middleware(s *allowedby.Service) echo.MiddlewareFunc
```

Middleware serves the SDK's endpoints, checks every route of the map, and calls the next handler with the
request's body intact. Echo runs Use middleware for unrouted paths too, so the discovery paths are served.

A last :param of an Echo route takes the rest of the path, slashes included (DELETE /notes/7/x runs the handler of
/notes/:id, with id "7/x"): the middleware asks Echo which route it dispatches to, with Use and with Pre, and
refuses a protected one it did not verify. With Pre, register it after any middleware that rewrites the path.

```go
func Context(c echo.Context) (allowedby.Context, bool)
```

Context is the AllowedBy context of an accepted request (allowedby.ContextOf). A request that a middleware after
the SDK's changed (another method, or another path once normalised: values the person never approved) has none: it
is refused (400, allowedby.Changed), so return when ok is false.

## `allowedbygin/allowedbygin.go`

`sdks/go/allowedbygin/allowedbygin.go`

```go
func Middleware(s *allowedby.Service, e *gin.Engine) gin.HandlerFunc
```

Middleware serves the SDK's endpoints, checks every route of the map, and passes the rest of the chain the request
with its body intact. It needs the engine to know which handler serves each route of the map, and refuses a request
it did not check that Gin would give to one of them. Register it with Engine.Use, so it also runs for the discovery
paths, which Gin otherwise answers with 404. Register every route before the first request: the handlers of the map
are resolved then, once.

```go
func Context(c *gin.Context) (allowedby.Context, bool)
```

Context is the AllowedBy context of an accepted request (allowedby.ContextOf). A request that a middleware after
the SDK's changed (another method, or another path once normalised: values the person never approved) has none: it
is refused (400, allowedby.Changed) and the chain aborted, so return when ok is false.

## `allowedbyredis/allowedbyredis.go`

`sdks/go/allowedbyredis/allowedbyredis.go`

```go
type Store struct {
}
```

Store is an allowedby.Store over a Redis client (a \*redis.Client, \*redis.ClusterClient or \*redis.Ring).

```go
func New(c redis.UniversalClient, prefix string) *Store
```

New makes a Store; prefix namespaces its keys (e.g. "allowedby:").

```go
func (s *Store) Add(ctx context.Context, key string, until, now int64) (bool, error)
```

Add implements allowedby.Store.

```go
func (s *Store) Get(ctx context.Context, key string, now int64) (*big.Int, error)
```

Get implements allowedby.Store.

```go
func (s *Store) Charge(ctx context.Context, charges []allowedby.Charge, now int64) (bool, error)
```

Charge implements allowedby.Store with optimistic locking (WATCH, MULTI, EXEC): totals are computed exactly
(amounts have up to 21 digits, beyond what a Lua number holds) and written only if no other instance changed a
key in between; on a conflict it tries again.

## `allowedbytest/allowedbytest.go`

`sdks/go/allowedbytest/allowedbytest.go`

```go
type Node struct {
}
```

Node is a fake AllowedBy node on a local test server.

```go
type ApprovalRequest struct {
	AID        string
	ServiceKid string         // the kid of the service key that signed the request
	Body       map[string]any // the request as sent
}
```

ApprovalRequest is a service-initiated approval request the node received (AMH-1 §3).

```go
const RPID = "approve.allowedby.test"
```

RPID is the WebAuthn relying party of the node's fake passkey.

```go
func NewNode(t testing.TB) *Node
```

NewNode starts a node; it stops when the test ends.

```go
func (n *Node) URL() string
```

URL is the node's origin, for allowedby.Options.Node.

```go
func (n *Node) Name() string
```

Name is the node's name, the `iss` of what it signs.

```go
func (n *Node) Approvals() []ApprovalRequest
```

Approvals lists the service-initiated approval requests the node received, oldest first.

```go
func (n *Node) SetStale(stale bool)
```

SetStale makes the status list two hours old (every class then fails closed with status_stale).

```go
func (n *Node) Revoke(idx int64)
```

Revoke sets the status bit at idx (a passport's or a grant's `status.status_list.idx`).

```go
type Agent struct {
	Sub      string // passport subject
	Operator string
	Passport string // the oaid-passport+jwt
	Index    int64  // the passport's status index (Node.Revoke)
}
```

Agent is a fake agent: its key and the passport the node issued for it.

```go
func (n *Node) NewAgent() *Agent
```

NewAgent makes an agent with an Ed25519 key and a tier-0 passport from this node, operated by acme.example.

```go
func (a *Agent) Request(method, url string, body []byte, allowedBy string) *http.Request
```

Request builds a request signed by the agent (ABY-2 §3): Allowed-By (a passport or a grant) and a fresh proof for
this method, URL and body. url is the full URL at the service's public origin.

```go
func (a *Agent) RequestWithNonce(method, url string, body []byte, allowedBy, nonce string) *http.Request
```

RequestWithNonce is Request with the service's AllowedBy-Nonce in the proof (ABY-2 §3.2), as an agent sends it
after a nonce challenge; "" sends none.

```go
func (a *Agent) RequestAt(at time.Time, method, url string, body []byte, allowedBy string) *http.Request
```

RequestAt is Request with a proof signed at a given time (its iat), for testing the service's time checks.

```go
type GrantSpec struct {
	Origin     string         // the service origin (the audience)
	Capability string         // e.g. notes:read
	Scope      string         // e.g. note:*
	Amount     map[string]any // optional amount constraint {max, currency, per, field}
	Class      string         // the class the route has
	Level      int            // the identity level the person proved
	Lifetime   time.Duration  // default 1 hour
	// SingleUse binds the grant to one request (request_digest), for write-hard and irreversible routes;
	// ServiceKid is then the kid of the service key that asked (the grant's initiator).
	SingleUse  string
	ServiceKid string
	// ActingFor is the grant's `acting_for` member (ORG-1 §6), for testing that it is refused.
	ActingFor map[string]any
	// NoHumanID leaves out the person's pairwise id for Origin (human.id), for testing that it is refused.
	NoHumanID bool
}
```

GrantSpec describes a grant the person approved.

```go
const HumanID = "test-person-pairwise-id"
```

HumanID is the pairwise id the fake person has at every service of this node.

```go
func (n *Node) Grant(a *Agent, g GrantSpec) string
```

Grant issues a grant to the agent (ABY-1): the node's countersignature over a core the fake person signed with
its passkey (WebAuthn, ES256). It returns the compact JWS.

```go
func RequestDigest(method, htu, query string, body []byte) string
```

RequestDigest is ABY-1 §7 `request_digest` for a request at the service (htu without the query).

## `context.go`

`sdks/go/context.go`

```go
type Context struct {
	// HumanID is the person's pairwise id for this service (the same person always has the same id here, and a
	// different one at every other service). It is empty at level 0 (identity routes), where an agent calls with no
	// person: key data by Human, which says so, never by HumanID alone.
	HumanID string
	// Level is the identity level the approval proves: 0 (agent only), 1 passkey, 2 verified identity, 3 eIDAS high.
	Level int
	// Agent is the agent's passport subject (did:oaid:...).
	Agent string
	// Operator is the operator that runs the agent (its verified domain, or a node-scoped id).
	Operator string
	// Capabilities lists what the approval allows.
	Capabilities []string
	// Display is the sentence the person signed, nil on identity routes.
	Display *Display
	// GID, Rev and JTI identify the approval (grant id, revision, document id).
	GID string
	Rev int64
	JTI string
	// ActingFor is the organisation the person acts for under a company mandate. Always nil: mandates are not
	// supported by the Go SDK yet.
	ActingFor *ActingFor
	// Tenant is the {tenant} path parameter when the route has one, decoded once as in Params (empty otherwise).
	// Options.Tenants tightens the route and caps its amounts for that tenant (ORG-1 §3.3, §5.3).
	Tenant string
	// Route is the route pattern that matched, e.g. "DELETE /notes/{id}".
	Route string
	// Chain is the grant chain, leaf first, with each grant's revision.
	Chain []ChainLink
	// HumanIssuer is the person's home node.
	HumanIssuer string
	// ProofJTI is the request proof's jti; Run and Call are the agent's own audit labels when it sent them.
	ProofJTI string
	Run      string
	Call     *int64
	// Params are the route's path values as the SDK checked them (CONTRACT §2 item 7): each {name} of the route's
	// template, from the normalised path (RFC 3986 §6.2.2, as for the scope), percent-decoded once (%41 gives A,
	// %20 a space; a path whose values would still hold a % once decoded, or an encoded /, is refused before the
	// app). Act on these values, never on your own reading of the raw path, which can differ. Empty, never nil, for a
	// route without parameters.
	Params map[string]string
	// LinkedAccount is, on a route with RequireLink, the account of yours the person is linked to (account linking,
	// ABY-3 §6): act for that account. Empty on other routes.
	LinkedAccount string
}
```

Context is what a handler learns from an accepted request (ORG-1 §4.1), with the audit fields of ABY-2 §5 step
10. Get it with ContextFrom; it is a copy, so changing it changes nothing else.

```go
func Started(r *http.Request)
```

Started tells the SDK that an accepted request has been handed to its handler, or has ended: from now on nothing
is refunded for it (CONTRACT §2 item 10). An adapter whose router routes after the SDK's check (allowedbychi) calls
it when the request ends; the SDK's own middleware and CheckRouted otherwise start the request themselves.

```go
type Display struct {
	Summary string   `json:"summary"`
	Lines   []string `json:"lines"`
	Lang    string   `json:"lang"`
}
```

Display is the text a person approved (AMH-1 §4).

```go
type ActingFor struct {
	Org  string
	Name string
	Role string
}
```

ActingFor is the organisation a person acts for (ORG-1 §6).

```go
type ChainLink struct {
	GID string
	Rev int64
}
```

ChainLink is one grant of a delegation chain.

```go
func ContextFrom(ctx context.Context) (Context, bool)
```

ContextFrom returns the AllowedBy context of an accepted request. ok is false on paths outside the route map,
which reach the application without any AllowedBy check (the application's own authentication applies), and when
the request was changed after it was accepted, as far as the SDK can see from ctx: the accepted request's method or
path rewritten in place, or (chi) a router that chose another method or path. ContextOf also compares the request
the handler got.

```go
func ContextOf(r *http.Request) (Context, bool)
```

ContextOf is ContextFrom for the request a handler got: ok is false too when its method or path, normalised, is not
the one the SDK accepted (a step after the SDK rewrote it, overrode its method, or passed on another request
built with WithContext or Clone). Changed answers 400 for such a request.

```go
func Changed(w http.ResponseWriter, r *http.Request) bool
```

Changed refuses (400 invalid_request) a request that the SDK accepted and that was then changed (plan 14): its
method or its path, normalised, is not the one checked, so its handler would act on values the person never
approved. It reports whether it refused; the refusal never repeats the path. Call it before a handler that runs
behind a step the SDK does not see (RequireUnchanged does), or use ContextOf. A request the SDK did not accept is
never refused here.

```go
func RequireUnchanged(next http.Handler) http.Handler
```

RequireUnchanged runs next only for a request that Changed does not refuse. Put it right before a handler, after
any step behind the SDK that could rewrite the request: around a handler of a ServeMux
(mux.Handle("GET /notes/{id}", step(allowedby.RequireUnchanged(h)))), or as the last Use of a chi router. The SDK
sees through it: around a handler, the handler is still known as itself (CONTRACT §2.10 rule 5), and
aby.Handler(allowedby.RequireUnchanged(mux)) still checks the routes the mux chooses. Never put a step of your own
between aby.Handler and a ServeMux: the SDK then no longer sees the mux.

```go
func (c Context) Human() (id string, ok bool)
```

Human is the person's pairwise id, and false when the request has no person: a level-0 route proves an agent
only, and HumanID is then empty. Data kept for a person is keyed by this id; when ok is false, refuse (or store
nothing) rather than key anyone's data by an empty id.

## `discovery.go`

`sdks/go/discovery.go`

```go
type Org struct {
	LegalName     string // required, at most 200 characters
	Country       string // required, ISO 3166-1 alpha-2, e.g. FR
	Website       string // optional https URL
	Support       string // optional https URL
	PrivacyPolicy string // optional https URL; default <origin>/privacy
	Logo          *Logo  // optional
}
```

Org is the organisation behind the service (ORG-1 §2), published as a signed profile in /.well-known/allowedby
and shown to people on the approval page.

```go
type Logo struct {
	URI    string
	SHA256 string
}
```

Logo is the organisation's logo: where it is and the base64url SHA-256 of the file.

## `dispatch.go`

`sdks/go/dispatch.go`

```go
type Dispatch struct {
	Pattern string
	Handler any
}
```

Dispatch is what a router chose for a request: the route's pattern, in the framework's own syntax (:id, {id},
{id:regex}, \*rest), and its handler (any value that identifies it: a func, a pointer, a name). "" and nil: none.

```go
var Unknown any = unknownHandler{}
```

Unknown is the Handler of a route whose handler the router cannot name (an Echo route given a Name of its own).
CheckRouted cannot tell whether it is a protected handler, so it fails closed. A request it did not verify is
refused when it goes to such a route, and, when a route of the map has it, when it goes to any route; a catch-all of
the whole site stays the application's own.

```go
type Router interface {
	Find(host, method, path string) Dispatch
}
```

Router is what an adapter tells CheckRouted about its framework's router: what it would dispatch a request (a host,
a method and a path) to; a router without virtual hosts ignores the host. Make it one pointer per router (a Router
that is not comparable is resolved again on every request, and learns nothing from checked requests):
CheckRouted resolves the handlers of the route map once per Router (and HostKey) and keeps them, so register every
route before the first request.

```go
type Routing struct {
	Method   string
	Patterns []string
	Params   []string
}
```

Routing is how a router routes a request: its method (HEAD as GET), the patterns it matched, in order (a mount's,
then the route's), and the values it took, "name=value" in order, exactly as the router reads them (decoded or
not), so that two routings compare like with like.

```go
type RouteReader interface {
	Router
	Routings(r *http.Request) []Routing
	Routed(ctx context.Context) (Routing, bool)
}
```

RouteReader is a Router that tells how it routed a request (plan 14). Routings is what it will route an accepted
request on (one per reading of its path); Routed, from the context the handler gets, what it routed the handler's
request on so far, or false before it began. ContextFrom gives no context to a handler whose routing is not, or
does not begin, one of the accepted request's: a step after the SDK moved it to another method, route or value.

```go
type HostRouter interface {
	Router
	HostKey(host string) string
}
```

HostRouter is a Router with virtual hosts. HostKey is the host whose routes serve a request's host, "" for the
routes of every host. Its values must come from the application's routes, never from what a client sends: they key
what CheckRouted keeps.

```go
func (s *Service) CheckRouted(w http.ResponseWriter, r *http.Request, router Router, chosen func(*http.Request) []Dispatch) (*http.Request, bool)
```

CheckRouted is Check for an adapter that sees its router (CONTRACT §2.10 rule 5). A request the SDK did not verify
is refused (400) when the router chose the handler of a route of the map (for any method), wherever the router uses
it (an alias, a catch-all that serves a route of the map), or when a route of the map whose handler is not known is
near its path (cannot tell). A request verified as a route is refused when it would run the handler of another route
of the map, or a catch-all (unless the router named a matched rule of the route's own shape); an unknown handler is
learnt for its route, unless another route without a known handler, which that route does not cover, could be the
one it serves. A page of another handler is the application's own, a site-wide fallback among them while the routes
it reaches have known handlers of their own. When the handler cannot be identified, a pattern that could serve a
protected route is enough. chosen is what the router dispatches this request to; several readings when the adapter
cannot tell which: the request is refused when one of them would be. A request the SDK itself refuses here after
the check is refunded (CONTRACT §2 item 10); one it passes on is started (nothing is refunded from then on), unless
router is a RouteReader: its adapter calls Started when the request ends.

```go
type Endpoint struct {
	Method, Pattern string
	Handler         any
}
```

Endpoint is a route a router has: its method, its pattern in the router's syntax, and its handler.

```go
type EndpointLister interface {
	Router
	Endpoints() []Endpoint
}
```

EndpointLister is a Router that can list its routes (chi.Walk). CheckRouted then also finds the handler of a route of
the map whose parameters a sample path cannot satisfy, such as a regular expression ({id:[a-z]+}).

```go
type OwnPath struct {
	Method, Path string
}
```

OwnPath is a page of the application that the rules of CONTRACT §2.10 would refuse (Options.Unprotected): a path
exactly as sent (/notes/new/), or a template of whole-segment parameters (/notes/{id}/comments) for pages below a
protected route. Method "" is every method.

## `display.go`

`sdks/go/display.go`

```go
type Template struct {
	Summary map[string]string `json:"summary"`
	Lines   map[string]string `json:"lines"`
}
```

Template is the sentence a person reads and signs for one capability (AMH-1 §4, ABY-3 §5), per language:
Summary is the approval's headline, Lines one line per capability. Placeholders: {scope}, {fields},
{amount.max}, {amount.currency}, {amount.per}.

```go
func Text(en string) Template
```

Text is a Template in English only, the same sentence as summary and line.

## `linking.go`

`sdks/go/linking.go`

```go
func (s *Service) LinkStart(account string, ttl time.Duration) (string, error)
```

LinkStart returns a linking code for one of the application's accounts (ABY-3 §6), valid ttl (0: 600 s, the
contract's default; at most a day): the signed-in account page shows it, and the person gives it to their agent,
which sends it to POST /allowedby/link under a single-use approval of aby:link. The code is single use; using it
links the person to the account and revokes the account's other pending codes. It fails when account is empty,
or when 10 000 codes are pending.

## `rate.go`

`sdks/go/rate.go`

```go
type RateLimit struct {
	Calls int
	Per   time.Duration
}
```

RateLimit is at most Calls calls in any window of Per (whole seconds, 1 s or more).

## `registered.go`

`sdks/go/registered.go`

```go
func (s *Service) Handle(mux *http.ServeMux, pattern string, h http.Handler)
```

Handle registers h on mux for pattern ("GET /notes/{id}", or a path alone for every method, as the map writes the
path) through Registered.

```go
func (s *Service) HandleFunc(mux *http.ServeMux, pattern string, f func(http.ResponseWriter, *http.Request))
```

HandleFunc registers f on mux for pattern, as Handle.

```go
func (s *Service) Registered(pattern string, h http.Handler) http.Handler
```

Registered is h registered for pattern ("METHOD /path", or "/path" for every method), for a router that takes an
http.Handler (chi: r.Method("GET", "/notes/{id}", aby.Registered("GET /notes/{id}", h))). The path is the route's
as the map writes it, a mount prefix included. It panics, as http.ServeMux does, on a nil handler, a pattern without
a path, or a method and path that name no route of the map (the message names the nearest). Use it on every route
of the handler: a use through the router's own API is known by its code, as without registration.

## `route.go`

`sdks/go/route.go`

```go
type Class string
```

Class says how serious an action is (ABY-3 §4). It sets how long an approval may last and who asks for it.

```go
const (
	// Read looks at data. An approval lasts up to 30 days; the agent asks its own node.
	Read Class = "read"
	// Write changes data that can be changed back. An approval lasts up to 7 days; the agent asks its own node.
	Write Class = "write"
	// WriteHard is a change that is hard to undo. The service asks for an approval of the exact request, used once.
	WriteHard Class = "write-hard"
	// Irreversible is money or a final step. The service asks for an approval of the exact request, used once.
	Irreversible Class = "irreversible"
)
```

The four classes, least to most serious.

```go
type Threshold struct {
	UpTo  string `json:"up_to,omitempty"`
	Class Class  `json:"class"`
}
```

Threshold is one step of a class chosen by amount (ABY-3 §4.1): requests up to UpTo (a decimal string) take
Class. The last step has no UpTo.

```go
type Route struct {
	Method     string // GET, POST, PUT, PATCH, DELETE (HEAD is answered by the GET route)
	Path       string // e.g. /notes/{id}: a {param} is one path segment
	Capability string // e.g. notes:delete; empty for an identity route
	Class      Class  // read, write, write-hard or irreversible; or use Classes
	// Classes picks the class from the amount at AmountField: [{UpTo: "1000.00", Class: WriteHard},
	// {Class: Irreversible}]. With no readable amount, the last (most serious) class applies.
	Classes []Threshold
	Level   int // 1 passkey, 2 verified identity, 3 eIDAS high (0 on identity routes)
	// Resource names what the route acts on, for `scope` (ABY-3 §2), e.g. note:{id}. Default: "<namespace>:*".
	Resource string
	// AmountField is the JSON Pointer of the amount in the request body (e.g. /total): the grant must cap it.
	AmountField string
	// CurrencyField is the JSON Pointer of the currency (default /currency).
	CurrencyField string
	// Authn requires a passkey class: "synced" or "hardware" (OAID-7 §4).
	Authn string
	// Tier is the agent key custody tier the route needs (OAID-6), 0 by default.
	Tier int
	// MaxLifetime caps how long an approval for this route may last (60 s to 30 days; default: the class's).
	MaxLifetime time.Duration
	// LevelProfile requires the "eu" or "na" profile of level 3 (OAID-7 §5.3), on level-3 routes only.
	LevelProfile string
	// Summary and Body describe the route to agents in /openapi.json: what it does, and each JSON body member.
	Summary string
	Body    map[string]string
	// RequireLink needs the person's AllowedBy identity linked to one of your accounts (account linking, ABY-3 §6,
	// Service.LinkStart): 403 human_not_linked otherwise. When the path has the AccountParam parameter, the person must
	// be linked to that account. Routes with a capability only (a level-0 route has no person to link).
	RequireLink bool
	// AccountParam is the path parameter that names one of your accounts (default "account"): with RequireLink, the
	// linked account must be that one; approvals the service asks for name the person linked to it (AMH-1 §7).
	AccountParam string
	// Nonce asks for an AllowedBy-Nonce on this route (ABY-2 §3.2): a proof without a current one is refused with
	// 401 invalid_signature and a fresh nonce. Needs Options.Nonce; irreversible routes ask for one then anyway.
	Nonce bool
	// The options below are part of the reference SDK and not implemented in Go yet (CONTRACT §2 "extended").
	// New returns an error naming the option when one is set: accepting it without enforcing it would fail open.
	Mandate          bool     // company mandates (ORG-1 §6)
	Disclose         []string // personal data (ORG-1 §4)
	DiscloseOptional []string // personal data the person may share
	Authority        bool     // organisational co-approvers (ABY-1 §5)
	QES              bool     // qualified electronic signature (OAID-7 §10)
}
```

Route is one line of the route map (ABY-3 §4.1): what an agent needs before it may call Method Path.

A route without a Capability is an identity route (level 0): the agent's passport is enough, no person approves.
A route with a Capability needs a person's approval at Level 1 to 3 and an explicit Class: New refuses a route
that leaves either out, so a forgotten field never makes a route weaker than meant.

## `service.go`

`sdks/go/service.go`

```go
const (
	Version     = "0.1.0"
	SpecVersion = "0.2.14"
)
```

Version is this SDK's version; it implements the AllowedBy specification set SpecVersion.

```go
type Options struct {
	// Origin is the service's public origin, as agents call it: https://api.example.com.
	Origin string
	// Node is the AllowedBy node the service trusts (trust on first use of its key) and asks for approvals.
	Node string
	// Org is the organisation behind the service, published as a signed profile.
	Org Org
	// Routes is the route map: every route an agent may call, and what it needs.
	Routes []Route
	// Templates holds the sentence a person signs for each capability of the route map (Text for English only).
	Templates map[string]Template
	// KeyFile keeps the signing key and the disclosure key across restarts, shared by every instance: a private JSON
	// file created on first use (mode 0600, first writer wins), the same format in every SDK. Without it both keys
	// are new at each start.
	KeyFile string
	// Store holds the replay set, single-use consumption and counters. Default: a MemoryStore, for one process
	// only. Several instances must share a store (allowedbyredis).
	Store Store
	// TrustList replaces trust on first use of Node with a signed OAID-5 trust list (ParseTrustList).
	TrustList *TrustList
	// RefreshInterval is how often node statements and status lists are fetched, in the background: default 5 s,
	// at least 1 s and at most 60 s (OAID-5 §6).
	RefreshInterval time.Duration
	// NodeMaxLevel caps the level accepted from Node under trust on first use (1 to 3; default 3).
	NodeMaxLevel int
	// Clock is the time every check uses (default time.Now).
	Clock func() time.Time
	// Title, Version and Description describe the API in /openapi.json.
	Title, Version, Description string
	// RFC9421 also accepts RFC 9421 HTTP Message Signatures (Web Bot Auth profile, ABY-2 §3.1) instead of the proof.
	RFC9421 bool
	// Unprotected lists your own pages that would be refused as a variant of a protected route, or for being below one.
	Unprotected []OwnPath
	// HTTPClient makes the background fetches and the approval requests (default: 10 s timeout, no redirects).
	HTTPClient *http.Client
	// Logger receives refresh failures and refusals (codes only: never tokens, keys, bodies or personal data).
	// Default: slog.Default().
	Logger *slog.Logger
	// MaxBodyBytes bounds the request body read on routes of the map (default 1 MiB).
	MaxBodyBytes int64
	// Nonce turns AllowedBy-Nonce on (ABY-2 §3.2): routes with Nonce, and every irreversible route, then refuse a
	// proof without a current nonce (401 invalid_signature, with a fresh one in the AllowedBy-Nonce header). Nonces
	// are current for 300 s on every instance that shares the key file (KeyFile), and across a restart.
	Nonce bool
	// Rate limits the calls per agent ("actor", the passport's sub) and per operator ("operator"), in a window that
	// slides on Clock: 429 rate_limited past either. Default {"actor": {600, time.Minute}, "operator": {6000,
	// time.Minute}}; a key you leave out keeps its default, any other key is refused. Per process, like MemoryStore.
	Rate map[string]RateLimit
	// LinkAuthorize is your own rule for account linking (ABY-3 §6): on a route with RequireLink, the person linked to
	// account may call route with these path values (as checked: decoded once, a copy)? Only true lets the person
	// through: false, or a panic in it (recovered), answers 403 human_not_linked. It is only asked for a person who is
	// linked (to the account the path names, if it names one). nil: yes.
	LinkAuthorize func(account string, route Route, params map[string]string) bool
	// Tenants are the accounts the service hosts, by id, named by the path parameter {tenant} (ORG-1 §3.3): each may
	// tighten routes (TenantRoute) and cap the amounts accepted per period (Budget, ORG-1 §5.3). Validated and copied
	// by New: anything it would not enforce is refused, and so is an override or a budget on a capability that has a
	// route without {tenant}, where it would never apply.
	Tenants map[string]Tenant
}
```

Options configures a Service. Origin, Node, Org, Routes and Templates are required.

```go
type Service struct {
}
```

Service is an AllowedBy-protected service: its discovery documents, the verification of every request on its
route map, and the challenges. Make one with New, mount Handler, and Close it on shutdown.

```go
func New(opts Options) (*Service, error)
```

New validates the options, loads or creates the keys, and starts the background refresh. Invalid options fail
here, with a message that says what to fix. It returns once the first refresh is over (done or failed, at most
5 s), so a service that starts cold (a new instance, or one that scales to zero) holds node keys and status lists
before its first request: nothing is fetched at request time (ARCH-1 §4, SDK contract §2 item 4).

```go
func (s *Service) Close() error
```

Close stops the background refresh.

```go
func (s *Service) Refresh(ctx context.Context) error
```

Refresh fetches the node statements (trust on first use, or the trust list) and the status lists now. The
background loop calls it every RefreshInterval (New waits for its first run); call it yourself to fetch at once,
after a change at the node for example. It never runs on the request path. Errors are what could not be fetched;
the cache keeps what it had.

```go
func (s *Service) Handler(next http.Handler) http.Handler
```

Handler is the net/http middleware: the SDK's own endpoints (/.well-known/allowedby, /openapi.json,
/.well-known/api-catalog), then the check on every route of the map, then next. Paths outside the map reach
next unchanged. The body is read once and given back to next intact; the accepted Context is in the request's
context (ContextFrom).

```go
func (s *Service) Check(w http.ResponseWriter, r *http.Request) (*http.Request, bool)
```

Check is the middleware as a function, for framework adapters: it serves the SDK's endpoints and refusals
itself (ok false: the response is written), or returns the request to pass on (ok true), with the accepted
Context in its context on routes of the map.

The request it passes on is started (CONTRACT §2 item 10: nothing is refunded from then on). It does not see which
handler the router will choose, so it refuses (400) a path that goes on below a protected parameter (/notes/7/x,
for /notes/{id}); CheckRouted does not.

## `store.go`

`sdks/go/store.go`

```go
type Store interface {
	// Add records key until `until` (Unix seconds) unless it is already recorded and still live. It returns false
	// when the key was already there: a replay, a second use. The check and the write are one atomic step.
	Add(ctx context.Context, key string, until, now int64) (bool, error)
	// Get returns the live value of a counter (0 when absent or expired).
	Get(ctx context.Context, key string, now int64) (*big.Int, error)
	// Charge adds every increment when every resulting total stays within its maximum, else changes nothing and
	// returns false. All or nothing, atomically. A refund (CONTRACT §2 item 10: the SDK refused a request it had
	// accepted, before its handler started) is a Charge of negative increments with no maximum: apply it exactly,
	// whatever the totals become.
	Charge(ctx context.Context, charges []Charge, now int64) (bool, error)
}
```

Store keeps the replay set, single-use consumption and counters (ABY-2 §3.3, ABY-1 §7, ABY-3 §3). Every `now` is
the SDK's clock (Options.Clock), never the store's own, so an injected clock governs expiry too. Every instance of
a service that runs on several machines must share one store, or a proof replayed to another instance is
accepted there: MemoryStore is for one process only; use a shared store (allowedbyredis) otherwise.

An error from any method refuses the request (fail closed).

```go
type Charge struct {
	Key   string
	Inc   *big.Int
	Max   *big.Int
	Until int64
}
```

Charge is one counter increment: Key's total plus Inc must stay at or below Max (nil: no maximum). The total is
kept until Until (Unix seconds). Amounts are in millionths of the currency unit; counts in units. Inc is negative
in a refund, with no maximum.

```go
type MemoryStore struct {
	// MaxKeys bounds the number of entries (default 200000).
	MaxKeys int
}
```

MemoryStore is a Store for one process, safe for concurrent use. It holds at most MaxKeys live entries and refuses
new ones beyond that with an error (fail closed) rather than forget a live one.

```go
func NewMemoryStore() *MemoryStore
```

NewMemoryStore returns an empty MemoryStore.

```go
func (m *MemoryStore) Add(_ context.Context, key string, until, now int64) (bool, error)
```

Add implements Store.

```go
func (m *MemoryStore) Get(_ context.Context, key string, now int64) (*big.Int, error)
```

Get implements Store.

```go
func (m *MemoryStore) Charge(_ context.Context, charges []Charge, now int64) (bool, error)
```

Charge implements Store.

## `tenants.go`

`sdks/go/tenants.go`

```go
type Tenant struct {
	// Name is how people know the tenant (1-200 characters): in budget refusals. Default: its id.
	Name string
	// Routes tightens the route map for this tenant, per capability.
	Routes map[string]TenantRoute
	// MembersOnly: every route of the tenant needs a mandate from Org (until this SDK verifies mandates, it refuses
	// every request on them with mandate_required).
	MembersOnly bool
	// Org is the organisation that owns the tenant, an https origin (no path).
	Org string
	// Budgets caps the amounts accepted per capability and calendar period (ORG-1 §5.3).
	Budgets map[string]Budget
}
```

Tenant is one account of Options.Tenants. Every field is optional.

```go
type TenantRoute struct {
	Level       int           // the higher of this and the route's counts (0-3)
	Authn       string        // "hardware" or "synced": the stronger of this and the route's counts
	Mandate     bool          // a mandate from an organisation (refused with mandate_required until this SDK verifies them)
	RequireLink bool          // a linked person (ABY-3 §6), level 1 at least
	MaxLifetime time.Duration // the longest approval, whole seconds: the shorter of this and the route's counts
	AmountMax   string        // a ceiling on the amount ("1000.00"): above it, 403 capability_denied
	Operators   []string      // nil: any operator; else only these operator.id values (403 capability_denied)
	QES         bool          // not supported by the Go SDK yet: refused by New
	Authority   bool          // not supported by the Go SDK yet: refused by New
}
```

TenantRoute tightens a route for one tenant, never loosens it (ORG-1 §3.3).

```go
type Budget struct {
	Max      string // a decimal amount, "5000.00"
	Currency string // ISO 4217, "EUR"
	Per      string // "day", "week" or "month"
	TZ       string // the calendar's time zone, "Europe/Paris"; "" is UTC
}
```

Budget is a tenant budget (ORG-1 §5.3): at most Max in Currency per day, week or month in TZ (IANA, default UTC).

```go
func (s *Service) RefundBudget(r *http.Request)
```

RefundBudget gives the tenant budget back for an accepted request your handler refused (a wrong total, an unknown
invoice): the amount the service counted for it (ORG-1 §5.3), once. The approval itself stays spent: only the SDK's
own refusals before the handler give that back (CONTRACT §2 item 10). A request with no tenant budget, or one the SDK
refunded already, is left as it is. A refund the store does not take leaves the amount counted, and is logged.

## `trust.go`

`sdks/go/trust.go`

```go
type TrustList struct {
}
```

TrustList is a signed trust list (OAID-5 §2, typ oaid-trust+jwt): the nodes a service trusts, instead of trust on
first use of its one node. It lists anchors, program lists, denied nodes, vouching rules and witnesses_min.

```go
func ParseTrustList(jws string, signer map[string]any) (*TrustList, error)
```

ParseTrustList verifies a trust list signed by signer, the public JWK of the service key that signed it
(configuration integrity).
