@hyper.authio/server 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ # @hyper.authio/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Protect a Node.js API with Authio, in any framework: token validation, the caller with every form of permission
4
+ Authio issues, authorization rules, a webhook receiver, and calls to downstream APIs. For Express, use
5
+ [`@hyper.authio/express`](../express/README.md), built on this package.
6
+
7
+ ```bash
8
+ npm install @hyper.authio/server
9
+ ```
10
+
11
+ ## Validate tokens
12
+
13
+ ```ts
14
+ import { createAuthioVerifier, AuthioBearerError } from "@hyper.authio/server";
15
+
16
+ const verifier = createAuthioVerifier({
17
+ issuer: "https://auth.example.com/realms/acme",
18
+ audiences: "https://orders.example.com", // the API's resource identifier (RFC 8707)
19
+ });
20
+
21
+ try {
22
+ const user = await verifier.verifyAuthorizationHeader(request.headers.authorization);
23
+ } catch (error) {
24
+ if (error instanceof AuthioBearerError) {
25
+ response.setHeader("WWW-Authenticate", error.wwwAuthenticate);
26
+ response.statusCode = 401;
27
+ }
28
+ }
29
+ ```
30
+
31
+ | Option | Default | |
32
+ | --- | --- | --- |
33
+ | `audiences` | | Required, unless `resource` is set. |
34
+ | `resource` | | The API's own resource identifier (RFC 8707); added to `audiences` and used for RFC 9728. |
35
+ | `resourceMetadata` | off | `true` (or the URL) adds `resource_metadata="{origin}/.well-known/oauth-protected-resource{path}"` to `401` challenges (RFC 9728). |
36
+ | `requiredScopes` | | Scopes every request must carry (all); `authioBearer` answers `403 insufficient_scope`. |
37
+ | `clientEncryptionKey`, `clientEncryptionKeyPath` | | Decrypts access tokens Authio encrypts to this key (RSA-OAEP, RSA-OAEP-256) and validates them locally. RSA1_5 is refused (`legacy_algorithm`), even with `allowLegacyEncryptionAlgorithms`. |
38
+ | `introspection` | `none` | `none`: local JWT validation. `activeCheck`: then confirmed active by introspection (cached per `jti`), so a revoked token, an ended session or a suspension is refused before the token expires. `introspectionOnly`: introspection alone, for opaque tokens (or encrypted ones without the key). |
39
+ | `client` | | The API's confidential client, needed by introspection: an `AuthioClient` or `{ clientId, clientSecret }` (or a private key). It must be the resource server's introspection client. |
40
+ | `introspectionCacheDuration` | 30 s | Never past the token's expiry; only active answers are kept. |
41
+ | `clockSkew` | 30 s | |
42
+ | `validAlgorithms` | RS*, PS*, ES* | |
43
+ | `rejectNonAccessTokens` | `true` | Refuses a token whose `typ` is not `Bearer` (an ID token, for one). |
44
+ | `roleClaims` | `["role"]` | Claims holding flat role names (a Role claim mapper). |
45
+ | `groupClaims` | `["groups"]` | Claims holding group names (a Group claim mapper). |
46
+
47
+ A refusal is an `AuthioBearerError` whose `wwwAuthenticate` is `Bearer` when the request had no token, and
48
+ `Bearer error="invalid_token", error_description="…"` otherwise (plus `resource_metadata` when turned on). Its
49
+ `reason` names why, with the outcome names of `conformance/tokens.json` (`expired`, `invalid_audience`,
50
+ `not_access_token`, `reference_token`, `decryption_failed`, …, and `inactive` / `unconfirmed` for introspection). A
51
+ token addressed elsewhere is described with the audience the API accepts; introspection failures fail closed.
52
+
53
+ ### Protected resource metadata (RFC 9728)
54
+
55
+ ```ts
56
+ import { createProtectedResourceMetadata, protectedResourceMetadataPath } from "@hyper.authio/server";
57
+
58
+ const verifier = createAuthioVerifier({ issuer, resource: "https://orders.example.com/api", resourceMetadata: true });
59
+ const path = protectedResourceMetadataPath(verifier.resource!); // /.well-known/oauth-protected-resource/api
60
+ const document = createProtectedResourceMetadata({ issuer, resource: verifier.resource!, scopesSupported: ["orders:read"] });
61
+ ```
62
+
63
+ ## The caller
64
+
65
+ `AuthioUser` reads every form of permission, the same way from a JWT or an introspection answer:
66
+
67
+ ```ts
68
+ user.subject; user.clientId; user.scopes;
69
+ user.kind; // "user" | "client" | "consumer" | "account_credential"
70
+ user.credentialForm; // "client_secret" | "personal_access_token" | "api_key" | "consumer_api_key" (machines only)
71
+ user.consumerName; user.credentialId; user.credentialName; user.ownerUserId; user.ownerUsername; user.accountId;
72
+ user.credentialRealm; user.credentialClient; // what an account credential is limited to
73
+ user.impersonated; user.impersonator; // an administrator acting as the person (act.sub)
74
+ user.delegated; user.delegationId; user.actorChain; // clients acting for the person (act.client_id), outermost first
75
+ user.authTime; // auth_time, in seconds
76
+ user.roles; // *_resource_access roles, then flat role claims
77
+ user.permissions; // { orders: ["read", "write"] }
78
+ user.resourceAccess; // per-source entries: user, realm, client, plan, consumer, secret, system
79
+ user.groups; // from the group claims
80
+ user.organizationId; user.organizationAlias; user.authenticationLevel; user.authenticationMethods; user.actor;
81
+ user.claims; // every claim, for claim-mapper claims and the person's own claims
82
+
83
+ user.hasPermission("orders", "read");
84
+ user.hasPermission("orders", "read", { sources: ["realm", "client"] });
85
+ user.hasRole("admin", { sources: ["user"] });
86
+ user.hasGroup("finance");
87
+ user.hasClaim("department", "finance", "sales");
88
+ ```
89
+
90
+ The raw token is kept as `user.token`, not enumerable, so it stays out of logs and JSON. The caller fields follow
91
+ `conformance/callers.json`; `AuthioUser.fromIntrospection(answer)` reads an introspection answer the same way.
92
+
93
+ ## Authorize
94
+
95
+ ```ts
96
+ import { authorize, requirePermission, requireGroup, requireAuthenticationLevel, allOf, anyOf, AuthioForbiddenError } from "@hyper.authio/server";
97
+
98
+ const refusal = authorize(user, requirePermission("orders", "write"), anyOf(requireGroup("finance"), requireAuthenticationLevel(2)));
99
+
100
+ if (refusal) {
101
+ const error = new AuthioForbiddenError(refusal);
102
+ // 403, with error.wwwAuthenticate when the refusal is about scopes (insufficient_scope) or the sign-in
103
+ // (insufficient_user_authentication); toProblemDetails(error) for an RFC 9457 body.
104
+ }
105
+ ```
106
+
107
+ Rules: `requireScope`, `requireRole`, `requirePermission`, `requireGroup`, `requireClaim`, `requireOrganization`,
108
+ `requireAuthenticationLevel`, `requireAuthenticationMethod`, `requireRecentAuthentication`, `requireCallerKind`,
109
+ `requireClient`, combined with `allOf` and `anyOf`. `authorize` checks every rule and joins their messages.
110
+
111
+ **Step-up (RFC 9470)**: `requireAuthenticationLevel(2, { maxAge: 300 })`, `requireAuthenticationMethod("otp")` and
112
+ `requireRecentAuthentication(300)` refuse with `insufficient_user_authentication`, `acrValues` (the level asked for;
113
+ `2` for `mfa`/`otp`/`mca`, `3` for `swk`/`hwk`) and `maxAge`, so the challenge reads
114
+ `Bearer error="insufficient_user_authentication", error_description="…", acr_values="2", max_age=300`. A client
115
+ answers it with `createStepUpAuthorizationUrl` from `@hyper.authio/client`.
116
+
117
+ ## Webhooks
118
+
119
+ ```ts
120
+ import { createAuthioWebhooks } from "@hyper.authio/server";
121
+
122
+ const webhooks = createAuthioWebhooks({ secret: process.env.AUTHIO_WEBHOOK_SECRET })
123
+ .on("user_created", async (event) => { /* event.data.username */ })
124
+ .on("*", (event) => log(event.type));
125
+
126
+ const outcome = await webhooks.handle({ body: rawBody, headers: request.headers });
127
+ response.statusCode = outcome.status; // 200 handled or duplicate, 400, 401, 413, 500
128
+ ```
129
+
130
+ Deliveries are deduplicated by `X-Authio-Event-Id` for 24 hours in memory (or a store you pass); a handler that
131
+ throws releases the id so the redelivery runs. Several `secrets` are accepted while one is rotated.
132
+
133
+ ## Downstream APIs
134
+
135
+ ```ts
136
+ import { createForwardingFetch, createOnBehalfOf } from "@hyper.authio/server";
137
+
138
+ const sameAudience = createForwardingFetch(user); // forwards the caller's own token
139
+ const billing = createOnBehalfOf({ client: authioClient, resource: "https://billing.example.com", scopes: "invoices:read" });
140
+ await billing.fetch(user)("https://billing.example.com/invoices"); // exchanged once, cached, retried once on 401
141
+ ```
142
+
143
+ ## License
144
+
145
+ MIT