C# and .NET SDK#
The public API of sdks/dotnet, with its doc comments. Guide: docs/sdk/dotnet.md.
187 public declarations, 163 with a doc comment.
src/AllowedBy.AspNetCore/AllowedByAspNetCore.cs#
sdks/dotnet/src/AllowedBy.AspNetCore/AllowedByAspNetCore.cs
public static class AllowedByServiceCollectionExtensionsRegisters AllowedBy in the service collection.
public static IServiceCollection AddAllowedBy(this IServiceCollection services, Action<AllowedByOptions> configure)Adds the AllowedBy service, configured in code: builder.Services.AddAllowedBy(o => { ... }).
public static IServiceCollection AddAllowedBy(this IServiceCollection services, IConfiguration section, Action<AllowedByOptions>? configure = null)Adds the AllowedBy service, bound from configuration (e.g. builder.Configuration.GetSection("AllowedBy")),
then adjusted in code if configure is given.
public static partial void Info(ILogger logger, string line)public static partial void Warning(ILogger logger, string line)public Endpoint? Endpointpublic static class AllowedByApplicationBuilderExtensionsAdds the AllowedBy middleware to the pipeline.
public static IApplicationBuilder UseAllowedBy(this IApplicationBuilder app)The SDK's endpoints first (discovery), then the check on every route of the map, then your app. Paths outside the map reach the app unchanged; the body is read once and given back intact.
public interface IAllowedByFeatureWhere the middleware leaves the accepted context.
public static class AllowedByHttpContextExtensionsReads the verified context.
public static AllowedByContext? GetAllowedBy(this HttpContext context)The verified AllowedBy context of this request, or null when the request is outside the route map (it was not checked: your own authentication applies).
public sealed class FromAllowedByAttribute : Attribute, IBindingSourceMetadata, IFromServiceMetadataBinds a handler parameter to the verified AllowedByContext of the request, in controllers
and minimal APIs: ([FromAllowedBy] AllowedByContext ctx) => ....
public BindingSource BindingSourcepublic string? HintThe fix the refusal names, from route templates only (never a value of the request); null for the default.
public bool MovedAn accepted request whose method, or whole path (path base included: a Map branch moves a prefix from the path to the path base), is no longer the one checked. Read when the router selects its endpoint: a rewrite to an alias or a longer path would run the handler on values that were never checked.
public string Methodpublic string Pathpublic string PathBasepublic string QueryStringpublic string RawTargetpublic string Protocolpublic string Schemepublic IHeaderDictionary Headerspublic Stream Bodypublic Task BeforeHandlerAsync(CancellationToken ct)The guard refused the request: refunded when it moves from fresh to given back (never once its handler started).
public Endpoint? Wrap(Endpoint? endpoint)The endpoint, whose delegate notes that the handler started; one that runs nothing, or is wrapped already, as it is.
public AllowedByMiddleware(RequestDelegate next, AllowedByService aby, EndpointDataSource? endpoints = null, EndpointMap? map = null)Made when the host builds the pipeline, after every UseEndpoints and Map call of any hosting model and before the server takes a request: a short-circuited endpoint of a protected handler stops the host here.
public async Task InvokeAsync(HttpContext ctx)src/AllowedBy.AspNetCore/EndpointGuard.cs#
sdks/dotnet/src/AllowedBy.AspNetCore/EndpointGuard.cs
public Endpoint? Endpointpublic bool ShortCircuitedA short-circuited endpoint of a protected handler is among these endpoints.
public HashSet<string> OwnThe routes whose own handler is known: an endpoint that is no catch-all of the route and takes a value for each of its parameters (CONTRACT §2.10 rule 5).
public bool Anypublic bool For(string key)public System.Collections.Concurrent.ConcurrentDictionary<string, string?> CheckedFor each route a checked request was accepted for: null when the endpoint runs for it, else why not.
public static bool Decides(Endpoint? e)The router selected an endpoint made for this path: not a fallback, no catch-all parameter.
public bool SeesHandlersWhether the app has endpoints to judge at all.
public Endpoint? Check(Endpoint? endpoint, AllowedByRouteInfo? accepted, bool preflight = false, (string Method, string Path)? request = null, bool moved = false)Throws when endpoint runs the handler of a route of the map and the request was not
accepted for one of the routes that handler serves. The path it came by does not matter: a handler of a protected
route reached by a wider template acts on that template's values (CONTRACT §2.10), and Unprotected does not lift it.
endpoint: What the router selected.
accepted: The route this request was accepted for.
preflight: The request is a CORS preflight (OPTIONS with Origin and Access-Control-Request-Method).
Returns: The endpoint to run: endpoint, or for a CORS preflight of a protected endpoint a copy
with its metadata whose delegate refuses the request.
request: The method and the path the app routes; unknown, a fallback that reaches a route is refused.
moved: An accepted request whose method or path changed after the check: it reaches no protected
handler (the values were never checked), only the app's own pages (an error page re-executed after it).
public void RefuseShortCircuits()Throws at startup when a short-circuited endpoint (.ShortCircuit()) runs the handler of a route of
the map: the router runs it itself, before any middleware, so AllowedBy could never check its requests.
src/AllowedBy.Redis/RedisStore.cs#
sdks/dotnet/src/AllowedBy.Redis/RedisStore.cs
public sealed class RedisStore : IAllowedByStoreThe AllowedBy store in Redis, shared by every instance: the replay set, single-use consumption and
counters (ABY-2 §3.3, ABY-1 §7, ABY-3 §3). Each operation is a compare-and-set transaction (WATCH-style
conditions on the exact values read), retried on contention, so check-and-set stays atomic across instances.
Expiry follows the SDK's clock (now), never Redis's: each value carries its own deadline; the Redis TTL
only frees memory afterwards.
public RedisStore(IConnectionMultiplexer redis, string prefix = "{allowedby}:", int database = -1)A store on redis.
redis: The connection (share one per process).
prefix: Key prefix. The default's hash tag keeps every key in one slot, as Redis Cluster
transactions need.
database: Redis database number (-1: the connection's default).
public async ValueTask<bool> AddAsync(string key, long until, long now, CancellationToken cancellationToken = default)public async ValueTask<decimal> GetAsync(string key, long now, CancellationToken cancellationToken = default)public async ValueTask<bool> ChargeAsync(IReadOnlyList<AllowedByCharge> charges, long now, CancellationToken cancellationToken = default)src/AllowedBy/AllowedByContext.cs#
sdks/dotnet/src/AllowedBy/AllowedByContext.cs
public sealed class AllowedByContextWhat the service learns from an accepted request (ORG-1 §4.1), with the audit fields of ABY-2 §5 step 10. Read-only. Your handler receives it only after every check passed.
public string AgentThe agent's identifier (its passport sub, e.g. did:oaid:node.example.org:01K...).
public string OperatorWho runs the agent (the operator id from the passport, e.g. a verified domain).
public string? HumanIdThe person's pairwise identifier for this service: stable for one person and one service, different at every other service. Null on level-0 routes (no person involved).
public int LevelThe level the person reached for this request: 0 (agent only) to 3 (eIDAS high).
public IReadOnlyList<string> CapabilitiesThe capabilities of the grant used (empty on level-0 routes).
public AllowedByDisplay? DisplayThe words the person approved (AMH-1 §4), or null on level-0 routes.
public string? GidThe grant id (stable across revisions), or null on level-0 routes.
public int? RevThe grant revision (0 at issuance, +1 at each rebind).
public string? JtiThe grant document's own id (one per revision).
public string? ActingForThe organisation the person acts for under a company mandate. Always null in this SDK (mandates are not supported yet: a route that needs one fails at construction).
public string? TenantThe {tenant} path parameter of the route, when it has one, decoded once as in Params.
public AllowedByRouteInfo? RouteThe route of the map that matched: method and path pattern.
public IReadOnlyDictionary<string, string> ParamsThe values of the route's path parameters, as the request was checked: from the normalised path, each
decoded once (a%20b is a b, %2561 is %61; CONTRACT §2 item 7). Dispatch on these, never
on a second reading of the path, and never decode them again.
public IReadOnlyList<AllowedByChainLink> ChainThe delegation chain, leaf first: each grant's gid and revision.
public string? HumanIssuerThe person's home node (the issuer of their registration).
public string? LinkedAccountOn a route with AllowedByRoute.RequireLink: the account of yours the person linked (ABY-3
§6), which the route accepted them for. Null on other routes.
public string? ProofJtiThe proof's jti (or the RFC 9421 nonce): one per request, for your audit log.
public string? RunThe agent's run id from the proof, when it sent one (audit only, not verified).
public long? CallThe agent's call counter within the run, when it sent one (audit only).
public sealed record AllowedByDisplay(string Summary, IReadOnlyList<string> Lines, string Lang)The words the person approved: a summary, one line per capability, and their language.
Summary: The sentence the person read.
Lines: One line per capability.
Lang: The language of the text.
public sealed record AllowedByRouteInfo(string Method, string Path, string? Capability, string Class, int Level)A route of the map: its method and path pattern, capability and class for this request.
Method: HTTP method.
Path: Path pattern, e.g. /notes/{id}.
Capability: The capability, or null on level 0.
Class: The class of this request.
Level: The route's level.
public sealed record AllowedByChainLink(string Gid, int? Rev)One grant of a delegation chain.
Gid: The grant id.
Rev: Its revision.
src/AllowedBy/AllowedByOptions.cs#
sdks/dotnet/src/AllowedBy/AllowedByOptions.cs
public sealed class AllowedByOptionsThe configuration of an AllowedByService: bindable from appsettings.json (section
"AllowedBy") or set in code. Invalid values fail at construction with a message that says what to fix.
public string OriginYour public origin, as agents call it: https://notes.example (scheme, host, port; no path).
public string NodeThe node you trust (trust on first use of its key): https://node.example.org.
public AllowedByOrg OrgYour organisation, signed into /.well-known/allowedby (ORG-1 §2).
public IList<AllowedByRoute> RoutesThe route map (ABY-3 §4.1). Requests outside it reach your app unchanged.
public IList<AllowedByUnprotected> UnprotectedYour own pages that the SDK would otherwise refuse (CONTRACT §2.10): a path as the app routes it, exact or
with whole-segment {name} parameters and a literal, for one method or all. An entry lifts, for its method, the
refusal of a longer path of a route where no handler is judged (without ASP.NET Core, or no endpoint selected). No
entry lifts a method override onto a mapped route, nor the refusal of a protected route's handler. An entry that
overlaps a route of the map, has no literal segment, is a template for a longer path of a route without naming its method, or (exact)
may be read as another path fails construction.
public IDictionary<string, AllowedByTemplate> TemplatesThe sentence the person signs, per capability (AMH-1 §4): a string, or summary and lines per
language. Placeholders: {scope}, {amount.max}, {amount.currency}, {fields}...
public string? KeyFileA private JSON file keeping the signing and disclosure keys across restarts and shared by every
instance: created on first use (mode 0600, first writer wins), the same format as the Python SDK's
key_file. Without it the keys are new at each start.
public IAllowedByStore? StoreThe replay set, single-use set and counters. Default: MemoryStore (one process only).
public Func<string, AllowedByRouteInfo, IReadOnlyDictionary<string, string>, bool>? LinkAuthorizeAccount linking (ABY-3 §6), your own authorisation of a linked account for a request on a route with
AllowedByRoute.RequireLink (Python link_authorize): (account, route, params) => bool,
where params are the route's path values, decoded once. Only true passes: false, or an exception the callback
throws (logged by its type only), refuses the request with 403 human_not_linked. Called only for a person linked to an account (and to the one the route's account parameter
names, when the path has it). Without it, a route whose path names no account accepts any linked person.
public string? TrustListA signed OAID-5 trust list (compact JWS, oaid-trust+jwt) replacing trust on first use of
Node. Needs TrustListKey.
public string? TrustListKeyThe public JWK (JSON text) of your own key that signed TrustList.
public int RefreshSecondsSeconds between background refreshes of the node statement and status lists (1 to 60; default 5).
public int NodeMaxLevelThe highest level you accept from Node (0-3; default 3).
public TimeProvider ClockThe clock of every time check (proof windows, expiry, store deadlines). Default: the system clock.
public string? TitleOpenAPI title (default: "<legal name> API").
public string VersionOpenAPI version of your API (default 1.0.0).
public string? DescriptionOpenAPI description of your API.
public bool Rfc9421Also accept the RFC 9421 Web Bot Auth profile in place of the proof JWT (ABY-2 §3.1).
public bool NonceAllowedBy-Nonce (ABY-2 §3.2): every irreversible route, and each route with
AllowedByRoute.Nonce, then refuses a proof without a current nonce (401 invalid_signature, with
a fresh one in AllowedBy-Nonce). Nonces are derived from the signing key: with a KeyFile, every
instance takes the others' nonces, and a restart keeps them current. Default off.
public IDictionary<string, int[]>? RateRate limits: actor (per agent, the passport's sub) and operator (per
operator.id), each [calls, seconds], a sliding window on Clock. Default
actor: [600, 60], operator: [6000, 60]; a call over either is 429 rate_limited. Any other key, or
a value that is not two positive integers, fails construction.
public int MaxBodyBytesThe largest request body the SDK reads on a route of the map (1 KiB to 64 MiB, default 1 MiB); larger is 400.
public HttpClient? HttpClientThe HTTP client used to reach the node (default: the SDK's own, 10 s timeout, no redirects).
public Action<string>? LogWhere the SDK writes its log lines (refresh failures, refusals): codes and routes, never tokens,
keys or bodies. Default: standard output, as the reference. The ASP.NET Core adapter routes them to
ILogger.
public sealed class AllowedByUnprotectedA page of the app's own, outside AllowedBy (AllowedByOptions.Unprotected).
public string? MethodThe method; null for every method.
public string PathThe path as the app routes it (without the path base, like the route map), e.g. /notes/{id}/comments.
public static implicit operator AllowedByUnprotected(string path)o.Unprotected = ["/reports/{id}/export"]: every method.
public static AllowedByUnprotected FromString(string path)A path, for every method.
public sealed class AllowedByOrgYour organisation (ORG-1 §2).
public string LegalNameRegistered legal name (required).
public string CountryISO 3166-1 alpha-2 country code, e.g. FR (required).
public string? Websitehttps URL of your website.
public string? Supporthttps URL of your support page.
public string? PrivacyPolicyhttps URL of your privacy policy (default: <origin>/privacy).
public sealed class AllowedByTemplateThe words of one capability: Text as shorthand for English, or Summary and
Lines per language. In configuration a plain string is the shorthand.
public string? TextShorthand: the same English sentence for summary and line.
public IDictionary<string, string> SummaryThe summary per language code.
public IDictionary<string, string> LinesThe line per language code.
public static implicit operator AllowedByTemplate(string text)templates["notes:read"] = "Read your notes".
public static AllowedByTemplate FromString(string text)The same English sentence for summary and line.
public sealed class AllowedByTemplateConverter : System.ComponentModel.TypeConverterLets configuration give a template as a plain string ("Template": "Read your notes").
src/AllowedBy/AllowedByRequest.cs#
sdks/dotnet/src/AllowedBy/AllowedByRequest.cs
public sealed class AllowedByRequestAn HTTP request as the SDK checks it, independent of any web framework.
public AllowedByRequest(string method, string path, string? query, IEnumerable<KeyValuePair<string, string>> headers, ReadOnlyMemory<byte> body, string? routePath = null, string? pathBase = null)A request to check.
method: HTTP method, upper case.
path: The path as sent, still percent-encoded (e.g. /notes/a%20b), without the query.
query: The query string as sent, without '?', or null.
headers: Request headers; repeated names are joined with ", " (RFC 9110 §5.3).
body: The body bytes as received (empty when none).
routePath: The path as the app routes it, when a framework strips a path base
(pathBase) or earlier middleware rewrote it; default path. The route map
is matched on it; the proof is checked against path, what the agent signed.
pathBase: The path base the framework removed from path (e.g. "/api").
public string RoutePathThe path the app routes on (the route map is matched on it).
public string PathBaseThe path base removed before routing ("" when none).
public string MethodHTTP method, upper case.
public string PathThe path as sent (percent-encoded).
public string? QueryThe raw query, or null.
public ReadOnlyMemory<byte> BodyThe body as received.
public string? Header(string name)A header value, or null (names are case-insensitive).
src/AllowedBy/AllowedByResponse.cs#
sdks/dotnet/src/AllowedBy/AllowedByResponse.cs
public sealed class AllowedByResponseA response the SDK sends itself: a discovery document, or a refusal (problem+json, with the challenge
in WWW-Authenticate when there is one).
public int StatusHTTP status.
public IReadOnlyDictionary<string, string> HeadersHeaders to send, Content-Type included.
public ReadOnlyMemory<byte> BodyThe body bytes (JSON).
public string? CodeFor a refusal, its code (e.g. grant_required); null for a discovery document.
public sealed class AllowedByResultThe outcome of AllowedByService.CheckAsync.
public bool AllowedTrue when the app may handle the request: accepted, or outside the route map.
public AllowedByContext? ContextThe verified context; null when refused or outside the route map.
public AllowedByResponse? RefusalThe response to send back as is when refused (it carries the challenge).
public bool InRouteMapWhether the request matched a route of the map.
src/AllowedBy/AllowedByService.cs#
sdks/dotnet/src/AllowedBy/AllowedByService.cs
public sealed partial class AllowedByService : IDisposableThe AllowedBy service SDK (Python allowedby.sdk.AllowedBy): publishes the discovery documents,
verifies every request of the route map offline (ABY-2 §5), answers challenges (ABY-2 §6) and creates the
approval itself for write-hard and irreversible routes. Thread-safe; create one per process.
public AllowedByService(AllowedByOptions options)Validates the configuration and prepares the keys and documents. Throws
ArgumentException (or InvalidOperationException for an unreadable key file) with
what to fix. Call RunAsync (the ASP.NET Core adapter does) to keep the node's statement and
status lists fresh: the first checks wait for its first refresh (done or failed, at most 5 s after it starts);
without it every agent request is refused (untrusted_node).
public string OriginYour public origin, normalised.
public string SigningKeyIdThe kid of the key that signs your approval requests and organisation profile.
public IAllowedByStore StoreThe store in use.
public TimeSpan RefreshIntervalHow often the background refresh runs.
public int MaxBodyBytesThe largest body the SDK reads on a route of the map.
public AllowedByResponse? Handle(string method, string path)The SDK's own endpoints: GET|HEAD /.well-known/allowedby, /openapi.json and
/.well-known/api-catalog. Returns the response, or null when the path is not one of them.
public bool InRouteMap(string method, string path)Whether a request is on a route of the map (only those are checked; the others reach your app).
public bool IsUnprotected(string method, string path)Whether AllowedByOptions.Unprotected declares this request (method, and the path the app
routes, without the path base) the app's own: it lifts the refusal of a longer path of a route for that method. It
never lifts a method override onto a mapped route, nor the refusal of a protected route's handler. Never true for
a route of the map.
public IReadOnlyList<AllowedByRouteInfo> RouteMapThe route map: method, path pattern, capability, most serious class and level of each route, the SDK's
own POST /allowedby/link last.
public string LinkStart(string account, int ttl = 600)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, single use) then
links their identity to account. The code is single use and valid ttl seconds
(1 to 86400). A new code revokes no older one; using one revokes the account's other pending codes. Throws
ArgumentException for a bad account or ttl, and InvalidOperationException when 10,000
codes are pending: catch it, and show one code per visit of the account page.
public bool Unlink(string account)Account linking (ABY-3 §6, Removing a link): removes the link of one of your accounts, when you delete the
account or the person asks to be forgotten. The stored pair (home node, pairwise id) and the account's pending
linking codes go: a AllowedByRoute.RequireLink route then refuses the person (403 human_not_linked) until they link again with a new code. Returns false when the account was not linked
(nothing else changes but its pending codes). Throws ArgumentException for an account
LinkStart(string, int) refuses.
public bool IsLinkRequest(string method, string path)public async Task<AllowedByResponse> LinkAsync(AllowedByRequest request, CancellationToken cancellationToken = default)POST /allowedby/link (ABY-3 §6), which the ASP.NET Core adapter serves: the code is checked first (an
unknown, spent, revoked or expired one is refused with 400 invalid_request before any approval is asked for),
then the request is checked as any route (a single-use grant for aby:link), then the code is spent, the
account's other pending codes are revoked and the pair (home node, pairwise id) is linked to the code's account,
in place of any other. 200 {"linked": true}, or the refusal to send back.
public bool MustCheck(AllowedByRequest request)Whether a request must go through CheckAsync (its body is not looked at): on the map by
its method, by the path the app routes or the path that was sent, or by a method it may be overridden to
(CONTRACT §2.10). An adapter reads the body only for these.
public Task<AllowedByResult> CheckAsync(AllowedByRequest request, CancellationToken cancellationToken = default)Checks one request (Python sdk.check): outside the route map it is allowed with no context
(your own authentication applies); on the map, a non-empty body must be a JSON object, then ABY-2 §5 runs.
A refusal carries the response to send back as is.
public Task RefreshAsync(CancellationToken cancellationToken = default)One refresh of the node statement (or trust list), program lists, vouches, witnesses and status lists. Never call it on the request path.
public async Task RunAsync(CancellationToken stoppingToken)Refreshes every AllowedByOptions.RefreshSeconds until cancelled. A failed refresh is
logged ([verifier] refresh failed) and never stops the loop or the app. Until its first refresh is over
(done or failed, at most 5 s), checks wait for it, so a service that starts cold (a new instance, or one that
scales to zero) answers its first request from a filled cache (CONTRACT §2 item 4).
public void Dispose()Releases the keys and the HTTP client the SDK created.
src/AllowedBy/Routes.cs#
sdks/dotnet/src/AllowedBy/Routes.cs
public sealed class AllowedByRouteOne line of the route map (ABY-3 §4.1): which capability, class and level a method and path need.
Build it with Routes.Route, or bind it from configuration; the service validates every route at
construction and refuses options this SDK does not enforce yet.
public string MethodHTTP method: GET, POST, PUT, PATCH, DELETE.
public string PathPath pattern, e.g. /notes/{id}; {name} is one path segment.
public string? CapabilityThe capability (namespace:action); null for a level-0 route (the agent's passport is enough).
public string Classread, write, write-hard or irreversible (ABY-3 §4).
public IList<AllowedByAmountClass>? ClassByAmountA class by amount, read at AmountField: thresholds in order, the last without
UpTo. Replaces Class when set.
public int LevelThe person's level: 0 (agent only), 1 (passkey), 2 (verified identity), 3 (eIDAS high).
public string? ResourceThe resource the call acts on, e.g. note:{id}; default <namespace>:*.
public string? AmountFieldJSON pointer of the amount in the body (e.g. /total): the grant must cap it.
public string CurrencyFieldJSON pointer of the currency in the body (default /currency).
public string? AuthnMinimum authenticator class of the person's passkey: synced or hardware.
public int TierMinimum custody tier of the agent's key (OAID-3).
public int? MaxLifetimeLongest grant lifetime this route accepts, seconds (60 s to 30 days; default: the class's).
public string? LevelProfileOn a level-3 route, the level-3 profile the registration must come from: eu or na
(OAID-7 §5.3).
public bool QesNot supported yet (a qualified electronic signature, OAID-7 §10, needs an EU trusted list this SDK does not have): setting it fails construction.
public AllowedByTemplate? TemplateThe sentence the person signs for this route's capability (a string, or summary and lines per
language). Same as an entry of AllowedByOptions.Templates; handy in configuration files,
where a capability cannot be a key (':' separates configuration sections).
public string? SummaryWhat the operation does, for agents (OpenAPI summary).
public IDictionary<string, string>? BodyEach JSON body member and its description, for agents (OpenAPI request body).
public bool MandateNot supported yet (company mandates, ORG-1 §6): setting it fails construction.
public IList<string>? DiscloseNot supported yet (personal data, ORG-1 §4): setting it fails construction.
public IList<string>? DiscloseOptionalNot supported yet (personal data, ORG-1 §4): setting it fails construction.
public bool RequireLinkThe person must have linked their identity to one of your accounts (account linking, ABY-3 §6):
403 human_not_linked otherwise, and for an account other than the one AccountParam names. A
level-0 route has no person to link: setting it there fails construction.
public string AccountParamThe path parameter that names one of your accounts (default account). With
RequireLink, on a path that has it, only the pair linked to that account is accepted (on a path
without it, any linked pair); the approvals the SDK creates for the route name the person linked to it. A name
other than the default must be a parameter of Path, as written: construction fails otherwise, and
for a parameter that differs from it only by case.
public bool AuthorityNot supported yet (authority policies, ABY-1 §5): setting it fails construction.
public bool NonceAllowedBy-Nonce (ABY-2 §3.2): a proof without a current service nonce is refused here, whatever the
class (irreversible routes ask for one anyway). Needs AllowedByOptions.Nonce: construction fails
without it.
public sealed class AllowedByAmountClassOne threshold of a class by amount: amounts up to UpTo (a decimal string) take
Class; the last threshold has no UpTo.
public string? UpToUpper bound, inclusive, as a decimal string (e.g. "1000.00"); null on the last threshold.
public string ClassThe class for amounts in this band.
public static class RoutesThe route helper, same arguments as Python's route(): using static AllowedBy.Routes; then
Route("GET", "/notes", "notes:read", resource: "note:*").
public static AllowedByRoute Route(string method, string path, string? capability = null, string cls = "read", int level = 1, string? resource = null, string? amountField = null, string currencyField = "/currency", string? authn = null, int tier = 0, int? maxLifetime = null, string? summary = null, IDictionary<string, string>? body = null, IList<AllowedByAmountClass>? classByAmount = null, string? levelProfile = null, bool qes = false, bool requireLink = false, string accountParam = "account", bool nonce = false)One line of the route map, validated now (ABY-3 §4.1). Throws ArgumentException with
what to fix.
method: HTTP method.
path: Path pattern with {param} segments.
capability: Capability, or null for level 0.
cls: Class: read, write, write-hard or irreversible.
level: Level 0-3.
resource: Resource, e.g. note:{id}.
amountField: JSON pointer of the amount.
currencyField: JSON pointer of the currency.
authn: synced or hardware.
tier: Minimum custody tier.
maxLifetime: Longest grant lifetime, seconds.
summary: OpenAPI summary.
body: OpenAPI body members.
classByAmount: Class by amount thresholds.
levelProfile: eu or na, on level 3.
qes: Qualified signature: not supported yet, true fails.
requireLink: The person must have linked their account (ABY-3 §6).
accountParam: The path parameter naming one of your accounts (default account).
nonce: AllowedBy-Nonce on this route (ABY-2 §3.2).
src/AllowedBy/Store.cs#
sdks/dotnet/src/AllowedBy/Store.cs
public sealed record AllowedByCharge(string Key, decimal Increment, decimal? Max, long Until)One increment of a counter, applied with the others of the same request or not at all.
Key: The counter (a JSON array of its parts, e.g. ["count","<gid>"]).
Increment: What this request adds. Negative, with no Max, when the SDK refunds what
a request it refused itself was charged (CONTRACT, Refund on the SDK's own refusal): a store applies it exactly.
Max: The most the total may reach; null for no ceiling.
Until: Unix time after which the counter is forgotten.
public interface IAllowedByStoreThe replay set, the single-use set and the counters (ABY-2 §3.3, ABY-1 §7, ABY-3 §3). Every
operation receives now from the SDK's clock and never reads the store's own wall clock, so an injected
clock also governs expiry. An exception from the store refuses the request (fail closed).
ValueTask<bool> AddAsync(string key, long until, long now, CancellationToken cancellationToken = default)Adds key until until unless a live entry exists: an atomic
check-and-set. Returns false when the key was already there (a replay, a second use).
ValueTask<decimal> GetAsync(string key, long now, CancellationToken cancellationToken = default)The current value of a counter (0 when absent or expired).
ValueTask<bool> ChargeAsync(IReadOnlyList<AllowedByCharge> charges, long now, CancellationToken cancellationToken = default)All or nothing: adds every increment when every total stays within its max, atomically. An increment may be negative (a refund, with no max), and is applied exactly.
public sealed class MemoryStore : IAllowedByStoreThe store in this process's memory, thread-safe. It is for one process only: with several instances
behind a load balancer a replayed proof or a single-use grant could be accepted once per instance; use a shared
store (AllowedBy.Redis) there.
public MemoryStore(int maxKeys = 200_000)A store of at most maxKeys live entries; when full of live entries it refuses
new ones rather than forget a replay (fail closed).
public ValueTask<bool> AddAsync(string key, long until, long now, CancellationToken cancellationToken = default)public ValueTask<decimal> GetAsync(string key, long now, CancellationToken cancellationToken = default)public ValueTask<bool> ChargeAsync(IReadOnlyList<AllowedByCharge> charges, long now, CancellationToken cancellationToken = default)