@evup/auth 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  Auto-generated by `npm run release:sdk` from Conventional Commits.
4
4
 
5
+ ## auth-v0.3.0 — 2026-11-26
6
+
7
+ ### Features
8
+
9
+ - **sdk:** client credentials helper (@evup/auth/m2m) and client tokens in the resource verifier ([086f387](https://github.com/tamnt1707/evup-auth/commit/086f38747390a29a45d5621996f8ea7239170c03))
10
+
11
+ ### Bug fixes
12
+
13
+ - **m2m:** review fixes ([851068c](https://github.com/tamnt1707/evup-auth/commit/851068cadf61b4c423eca78a7f07e248f0927d4c))
14
+
15
+ ## auth-v0.2.1 — 2026-11-26
16
+
17
+ ### Other
18
+
19
+ - **auth:** keep the SDK README about using the SDK ([c458680](https://github.com/tamnt1707/evup-auth/commit/c4586801892e3c186f4aa2bec8bd14aaade87617))
20
+
5
21
  ## auth-v0.2.0 — 2026-11-26
6
22
 
7
23
  ### Features
package/README.md CHANGED
@@ -7,10 +7,6 @@ An SDK that lets your app sign users in with **EvUp Account** (`auth.evup.cloud`
7
7
  - **Web standards only** (`fetch`, `Request`/`Response`, WebCrypto, `Headers`): runs on Cloudflare Workers, Bun, Deno, Node >= 20. No `node:` imports in runtime code.
8
8
  - **Thin adapters** for Hono, Astro, Next.js (App Router); other frameworks use the core with about 10 lines (see [Recipes for other frameworks](#recipes-for-other-frameworks)).
9
9
 
10
- > AI assistants: this guide is served as Markdown at `<origin>/llms-full.txt` (index at `<origin>/llms.txt`), with `<origin>` your EvUp Account origin.
11
-
12
- > Published on npm as `@evup/auth` (MIT). In this monorepo it is the workspace `@evup/auth` at `packages/auth`. The EvUp auth server does **not** use this SDK.
13
-
14
10
  ## Table of contents
15
11
 
16
12
  1. [Installation](#installation)
@@ -23,11 +19,12 @@ An SDK that lets your app sign users in with **EvUp Account** (`auth.evup.cloud`
23
19
  8. [Access denied and waitlist](#access-denied-and-waitlist)
24
20
  9. [Signing out](#signing-out)
25
21
  10. [MCP / API resource server](#mcp--api-resource-server)
26
- 11. [Configuration reference](#configuration-reference)
27
- 12. [Errors](#errors)
28
- 13. [Security notes](#security-notes)
29
- 14. [Local development with a local IdP](#local-development-with-a-local-idp)
30
- 15. [FAQ](#faq)
22
+ 11. [Machine-to-machine (client_credentials)](#machine-to-machine-client_credentials)
23
+ 12. [Configuration reference](#configuration-reference)
24
+ 13. [Errors](#errors)
25
+ 14. [Security notes](#security-notes)
26
+ 15. [Local development with a local IdP](#local-development-with-a-local-idp)
27
+ 16. [FAQ](#faq)
31
28
 
32
29
  ## Installation
33
30
 
@@ -47,6 +44,7 @@ Import paths:
47
44
  | `@evup/auth/astro` | the `evup` integration, `createEvupMiddleware` |
48
45
  | `@evup/auth/next` | `handlers`, `getSession`, `getUser`, `withEvupAuth` |
49
46
  | `@evup/auth/resource` | `createEvupResource` (MCP / API server) |
47
+ | `@evup/auth/m2m` | `createEvupClientCredentials` (server-to-server tokens, no user) |
50
48
 
51
49
  ## Registering your app on EvUp
52
50
 
@@ -551,7 +549,7 @@ Or `createEvupClient().signOut()` / `auth.signOut(request, { returnTo })`. The S
551
549
 
552
550
  `returnTo` (a relative path) is only used when the EvUp sign-out page **cannot** be used (the IdP does not publish `end_session_endpoint`, or it cannot be reached); in that case the user goes to `returnTo` (default `/`). To send users back to a page after sign-out, register that URL as a *post-logout redirect URI* and set `postLogoutRedirectUri`.
553
551
 
554
- ### What EvUp's `/oauth2/end-session` accepts (read from `@better-auth/oauth-provider`)
552
+ ### What EvUp's `/oauth2/end-session` accepts
555
553
 
556
554
  - **Parameters** (GET or POST form): `id_token_hint`, `client_id`, `post_logout_redirect_uri`, `state`.
557
555
  - **`id_token_hint`**: an id_token signed by EvUp itself (signature checked through JWKS; `exp` is **not** checked, so an expired id_token still works), correct `iss`, `aud` containing the client, with `sid` and `sub` claims. If it is valid and matches the current browser session, EvUp **ends the session immediately** without asking anything.
@@ -559,7 +557,7 @@ Or `createEvupClient().signOut()` / `auth.signOut(request, { returnTo })`. The S
559
557
  - **`client_id`**: optional when there is a hint (by default derived from the hint's `aud`/`azp`); it must be an existing, non-disabled client with **`enable_end_session` turned on**, otherwise EvUp returns an `invalid_client` error ("The client is not allowed to initiate logout").
560
558
  - **`post_logout_redirect_uri`**: must match, **character for character**, an entry in the app's *post-sign-out redirect URLs* (the sign-in redirect list is not used). EvUp only redirects on a match; if it does not match, the user is still signed out but stops at EvUp's "Logged out. The requested post-logout redirect was not registered." page. Only `client_id` needs to accompany it; `http://` is only allowed for localhost.
561
559
  - **`state`**: if sent, EvUp appends it to `post_logout_redirect_uri` when redirecting. The SDK does not use this `state`.
562
- - **Back-channel logout** (`backchannel_logout_uri`): SDK v0.1 has no receiver yet. The session in the app ends on the next refresh (when EvUp returns `invalid_grant`), that is, after about 1 hour at most.
560
+ - **Back-channel logout** (`backchannel_logout_uri`): the SDK has no receiver yet. The session in the app ends on the next refresh (when EvUp returns `invalid_grant`), that is, after about 1 hour at most.
563
561
 
564
562
  ## MCP / API resource server
565
563
 
@@ -567,7 +565,7 @@ Use this when your app has its own MCP server or API that clients (Claude Code,
567
565
 
568
566
  **1. Register:** in the app's detail page, card **API resources → Add resource**, enter the URL that the server publishes as its `resource` (for example `https://api.example.com/mcp`; add a separate entry for dev, for example `http://localhost:8787/mcp`). Users can only obtain a token for the resource if they pass the app's access rules (in `restricted` mode, only members).
569
567
 
570
- **2. The token** EvUp issues for the resource: a JWT signed with the key at `jwks_uri`, header `typ: "at+jwt"`, `iss` = issuer, `aud` containing the resource URL (may be an array), `azp` = client id, `scope` separated by spaces, `sub` = user id, `permissions` = RBAC permissions, lives 600 seconds. The scopes that a token for an app's resource can carry are `openid profile email offline_access`; for fine-grained authorization use `permissions`.
568
+ **2. The token** EvUp issues for the resource: a JWT signed with the key at `jwks_uri`, header `typ: "at+jwt"`, `iss` = issuer, `aud` containing the resource URL (may be an array), `azp` = client id, `scope` separated by spaces, `sub` = user id, `permissions` = RBAC permissions, lives 600 seconds. The scopes that a token for an app's resource can carry are `openid profile email offline_access`; for fine-grained authorization use `permissions`. A token can also be a **client token** (no user, from the `client_credentials` grant: `sub` is the client id and there is no `permissions`); `createEvupResource` refuses those unless you set `accept`, see [Machine-to-machine](#machine-to-machine-client_credentials).
571
569
 
572
570
  **3. The SDK** (`createEvupResource`) verifies exactly as EvUp's own resource server does: `typ at+jwt`, `iss` must match exactly, `aud` containing the resource, `sub`, `exp`, `azp`, `scope` are required; tokens bound with DPoP (`cnf`) are rejected; the JWKS comes from discovery, is cached per isolate, and is reloaded automatically when an unknown `kid` appears (keys rotate every 90 days).
573
571
 
@@ -670,6 +668,66 @@ export const GET = () => resource.metadataResponse();
670
668
 
671
669
  An MCP client calls `POST /mcp` without a token, gets a `401` with `WWW-Authenticate: Bearer resource_metadata="..."`, fetches the metadata to learn the `authorization_servers`, registers (DCR) or uses an existing client, goes through EvUp's sign-in and consent with `resource=<your URL>` (RFC 8707), then calls again with `Authorization: Bearer <JWT>`. That is why the `resource` URL you register must **exactly** match the URL the client uses to call.
672
670
 
671
+ ## Machine-to-machine (client_credentials)
672
+
673
+ Use this when a **server** has to call an API with no signed-in user: a cron job, a queue consumer, a backend calling another app's API. The server exchanges its own `client_id` and `client_secret` for a short-lived access token (OAuth `client_credentials`, RFC 6749 section 4.4). For work on behalf of a user, use the user's session token instead (see the FAQ).
674
+
675
+ **1. Admin setup.** An EvUp admin opens the *calling* app's detail page (it must be a *Web app (server)*, a client with a secret), turns on **Machine-to-machine → Allow client credentials**, then **Add API**: pick an API resource of any app and the scopes the app may use there (`api:read`, `api:write`; their meaning is up to each API, and the token's `aud` pins which API). The API itself must be registered first in the **API resources** card of the app that serves it. Switching it off keeps the list, so switching on again restores it.
676
+
677
+ **2. The calling side** (`createEvupClientCredentials`):
678
+
679
+ ```ts
680
+ import { createEvupClientCredentials } from "@evup/auth/m2m";
681
+
682
+ // EVUP_CLIENT_ID and EVUP_CLIENT_SECRET are read from the environment
683
+ const payments = createEvupClientCredentials({
684
+ resource: "https://payments.evup.cloud/api", // the API resource, exactly as registered
685
+ scopes: ["api:write"], // optional: omit to get every scope granted for the resource
686
+ });
687
+
688
+ const token = await payments.getToken(); // a string; cached, renewed 60 s before it expires
689
+ ```
690
+
691
+ Hono:
692
+
693
+ ```ts
694
+ app.post("/checkout", async (c) => {
695
+ const res = await payments.fetch("https://payments.evup.cloud/api/charges", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ amount: 1000 }) });
696
+ return c.json(await res.json(), res.status);
697
+ });
698
+ ```
699
+
700
+ Plain fetch:
701
+
702
+ ```ts
703
+ const res = await fetch("https://payments.evup.cloud/api/charges", { headers: { authorization: `Bearer ${await payments.getToken()}` } });
704
+ ```
705
+
706
+ The token is cached until `refreshSkew` (60) seconds before it expires, concurrent callers share one request, a failure is never cached, and `clear()` drops the cache. `payments.fetch(input, init)` adds the `Authorization` header; if the API answers `401` with `invalid_token` it fetches a new token and retries **once** (only when the body can be sent again: no body, or a string, `URLSearchParams`, `FormData`, `Blob` or buffer, never a stream). A token is replaced this way at most once, and only when it is at least 30 seconds old: a younger token that is rejected means the API is misconfigured (for example it does not set `accept: "client"`), and the `401` is returned as is instead of requesting a token on every call. Create one instance per resource and keep it for the life of the isolate.
707
+
708
+ **3. The API side**: opt in to client tokens with `accept`, and authorize callers by `token.clientId`:
709
+
710
+ ```ts
711
+ import { createEvupResource } from "@evup/auth/resource";
712
+ import { evupResource } from "@evup/auth/hono";
713
+
714
+ const api = createEvupResource({ resource: "https://payments.evup.cloud/api", accept: "client", scopes: ["api:read"] });
715
+
716
+ app.use("/api/*", evupResource(api));
717
+ app.get("/api/charges", (c) => {
718
+ const token = c.var.evupToken; // { kind: "client", sub: <client id>, clientId, scopes, permissions: [] ... }
719
+ return c.json({ caller: token.clientId });
720
+ });
721
+ ```
722
+
723
+ `accept` is `"user"` (default: client tokens are refused with `401 invalid_token`, so code that treats `sub` as a user id never meets a client id), `"client"` (only client tokens) or `"any"` (both; check `token.kind`). A client token has `kind: "client"`, `sub` = the client id and **no permissions** (`permissions` is always `[]`): there is no user, so no RBAC.
724
+
725
+ **Token facts.** `client_secret_basic` (the SDK sends the id and secret form-encoded, RFC 6749 section 2.3.1); `resource` is required and is exactly one API resource of an app the admin linked to the calling app; the JWT carries `sub` = `azp` = `client_id`, `aud` = the resource, `scope`; it lives **600 seconds** and there is **no refresh token**, the SDK requests a new one. The existing token-endpoint rate limits apply; the cache keeps you far below them.
726
+
727
+ **Secret rotation and switching off.** After the app's secret is rotated the old secret fails at once (`invalid_client`); tokens already issued stay valid until they expire (at most 10 minutes). The same goes for switching machine-to-machine off, removing the API from the app's list, or removing the API resource: new tokens are refused immediately, issued ones live until `exp`.
728
+
729
+ **Errors.** `createEvupClientCredentials` throws `EvupAuthError` (`config`) at creation for a missing id or secret, a bad `resource` or `issuer`, or empty `scopes`. A refused or failed token request rejects with `token_request_failed`: `oauthError` is the OAuth `error` (`invalid_client`, `invalid_scope`, `invalid_target`, `unauthorized_client`...) and `description` the `error_description`; the message never contains the secret or a token. A discovery problem is `discovery_failed`.
730
+
673
731
  ## Configuration reference
674
732
 
675
733
  `createEvupAuth(config)` (`@evup/auth/server`):
@@ -716,7 +774,23 @@ type EvupUser = {
716
774
  type Session = { user: EvupUser; accessToken: string; expiresAt: number /* ms epoch */; scope: string };
717
775
  ```
718
776
 
719
- `createEvupResource(config)` (`@evup/auth/resource`): `{ resource, issuer?, scopes?, resourceName?, clockTolerance? = 30, fetch? }` → `{ metadataPath, metadata(), metadataResponse(), preflightResponse(), verify(req | string), handle(req, next) }`. A valid token: `{ sub, clientId, scopes, permissions, exp, claims }` (`exp` in seconds).
777
+ `createEvupResource(config)` (`@evup/auth/resource`): `{ resource, issuer?, scopes?, resourceName?, clockTolerance? = 30, accept? = "user", fetch? }` → `{ metadataPath, metadata(), metadataResponse(), preflightResponse(), verify(req | string), handle(req, next) }`. A valid token: `{ sub, kind, clientId, scopes, permissions, exp, claims }` (`exp` in seconds). `accept` chooses which tokens are valid: `"user"` (default), `"client"` (client_credentials tokens) or `"any"`; `kind` is `"user"` or `"client"` (`sub` is the client id and `permissions` is `[]` for a client token).
778
+
779
+ `createEvupClientCredentials(config)` (`@evup/auth/m2m`):
780
+
781
+ | Option | Default | Meaning |
782
+ |---|---|---|
783
+ | `resource` | required | the API resource URL, exactly as registered. `https`, or `http` for localhost |
784
+ | `scopes` | none | omit to get every scope the admin granted for the resource; if given, must not be empty |
785
+ | `clientId` | `EVUP_CLIENT_ID` | |
786
+ | `clientSecret` | `EVUP_CLIENT_SECRET` | required |
787
+ | `issuer` | `https://auth.evup.cloud/api/auth` | |
788
+ | `refreshSkew` | `60` | seconds before `exp` a cached token is replaced |
789
+ | `env` | `process.env` | where `EVUP_*` is read from (only string values are read) |
790
+ | `fetch` | global `fetch` | used for discovery, the token request and `payments.fetch()` |
791
+ | `now` | `Date.now` | clock in ms, for tests |
792
+
793
+ → `{ getToken({ forceRefresh? }), getTokenInfo({ forceRefresh? }) /* { accessToken, expiresAt (seconds), scopes } */, fetch(input, init), clear() }`.
720
794
 
721
795
  Session behavior:
722
796
 
@@ -728,7 +802,7 @@ Session behavior:
728
802
 
729
803
  ## Errors
730
804
 
731
- `EvupAuthError` (`@evup/auth/server`, also exported from `@evup/auth/resource`) has `code`, `message`, `description?` (the OAuth `error_description` if present) and `cause`.
805
+ `EvupAuthError` (`@evup/auth/server`, also exported from `@evup/auth/resource` and `@evup/auth/m2m`) has `code`, `message`, `description?` (the OAuth `error_description` if present), `oauthError?` (the OAuth `error` of a refused token request) and `cause`.
732
806
 
733
807
  | `code` | When |
734
808
  |---|---|
@@ -736,7 +810,8 @@ Session behavior:
736
810
  | `access_denied` | EvUp denied the user (callback `error=access_denied`) |
737
811
  | `invalid_state` | transaction cookie missing/expired, `state` or `iss` mismatch |
738
812
  | `callback_failed` | code exchange failed, id_token invalid (`nonce`, `aud`...), session too large for the cookie |
739
- | `discovery_failed` | the issuer's discovery or JWKS could not be loaded (the callback returns 502; `verify` throws) |
813
+ | `discovery_failed` | the issuer's discovery or JWKS could not be loaded (the callback returns 502; `verify` throws; a token request rejects) |
814
+ | `token_request_failed` | the `client_credentials` token request was refused or failed (`@evup/auth/m2m`); `oauthError` has the OAuth `error`, `description` the `error_description` |
740
815
 
741
816
  Errors in the callback never leak details to the user: they see a "Sign-in failed" page (400/502) or "Access denied" (403); `onAccessDenied` replaces the 403 page and `onError` receives every other error (see the configuration table). Refresh errors are not `EvupAuthError`: they are handled as described in [Session behavior](#configuration-reference).
742
817
 
@@ -754,7 +829,7 @@ Errors in the callback never leak details to the user: they see a "Sign-in faile
754
829
 
755
830
  ## Local development with a local IdP
756
831
 
757
- Run EvUp locally (`npm run dev` in the auth repo, default `http://localhost:4400`) and point the SDK at it:
832
+ If you run an EvUp Account instance locally (for example on `http://localhost:4400`), point the SDK at it:
758
833
 
759
834
  ```ts
760
835
  createEvupAuth({
@@ -769,12 +844,6 @@ createEvupAuth({
769
844
  - Register in the app: redirect URI `http://localhost:3000/auth/callback`, post-logout `http://localhost:3000/`. Use a separate dev app instead of the production app.
770
845
  - Dev resource: add `http://localhost:8787/mcp` as a separate entry in **API resources**.
771
846
 
772
- Run the package's tests: `npm test -w @evup/auth` (completely offline). The test that reads the real discovery of `auth.evup.cloud` (a single public `GET`) only runs when `EVUP_LIVE_TEST=1` is set.
773
-
774
- ## Releasing
775
-
776
- The package has its own version and is released from the repo root with `npm run release:sdk` (preview: `-- --dry-run`). The tag `auth-vX.Y.Z` triggers `.github/workflows/release-sdk.yml`: build, test, `npm publish`, then a GitHub Release from the package's `CHANGELOG.md`. Publishing uses npm Trusted Publishing (OIDC): on npmjs.com the package `@evup/auth` trusts this repository and the `release-sdk.yml` workflow, so no `NPM_TOKEN` is stored (fallback: an `NPM_TOKEN` secret via `NODE_AUTH_TOKEN`). The workflow skips `npm publish` when the version is already on npm (for example the first version, published by hand) and still creates the GitHub Release. `--provenance` is off while the repository is private.
777
-
778
847
  ## FAQ
779
848
 
780
849
  **Why are users signed out after about 1 hour?** A session without a refresh token (you removed `offline_access` from `scopes`) expires with the access token. Keep `offline_access` (the default).
@@ -791,4 +860,4 @@ The package has its own version and is released from the repo root with `npm run
791
860
 
792
861
  **A `secret` shorter than 32 characters?** `createEvupAuth` throws `EvupAuthError` (`config`) right at creation if the secret is passed directly or is already present in `env`; if the variable is not yet available at creation (Workers), the error comes on the first request.
793
862
 
794
- **Is `client_credentials` / machine-to-machine supported?** No: EvUp does not have this grant. Use the user's refresh token or an API key.
863
+ **Is `client_credentials` / machine-to-machine supported?** Yes, for web apps an administrator enabled; see [Machine-to-machine](#machine-to-machine-client_credentials).
package/dist/errors.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- export type EvupAuthErrorCode = "access_denied" | "invalid_state" | "callback_failed" | "config" | "discovery_failed";
1
+ export type EvupAuthErrorCode = "access_denied" | "invalid_state" | "callback_failed" | "config" | "discovery_failed" | "token_request_failed";
2
2
  /** Every failure the SDK reports on purpose. `code` is stable; `message` is for logs. */
3
3
  export declare class EvupAuthError extends Error {
4
4
  readonly code: EvupAuthErrorCode;
5
5
  /** The OAuth `error_description` the IdP sent, when there was one. */
6
6
  readonly description?: string;
7
+ /** The OAuth `error` code the IdP answered a token request with (`invalid_client`, `invalid_scope`, ...), when there was one. */
8
+ readonly oauthError?: string;
7
9
  constructor(code: EvupAuthErrorCode, message: string, options?: {
8
10
  cause?: unknown;
9
11
  description?: string;
12
+ oauthError?: string;
10
13
  });
11
14
  }
package/dist/errors.js CHANGED
@@ -3,10 +3,13 @@ export class EvupAuthError extends Error {
3
3
  code;
4
4
  /** The OAuth `error_description` the IdP sent, when there was one. */
5
5
  description;
6
+ /** The OAuth `error` code the IdP answered a token request with (`invalid_client`, `invalid_scope`, ...), when there was one. */
7
+ oauthError;
6
8
  constructor(code, message, options) {
7
9
  super(message, options?.cause === undefined ? undefined : { cause: options.cause });
8
10
  this.name = "EvupAuthError";
9
11
  this.code = code;
10
12
  this.description = options?.description;
13
+ this.oauthError = options?.oauthError;
11
14
  }
12
15
  }
@@ -0,0 +1,45 @@
1
+ export { EvupAuthError } from "../errors.js";
2
+ export type EvupClientCredentialsConfig = {
3
+ /** Default env EVUP_CLIENT_ID. */
4
+ clientId?: string;
5
+ /** Default env EVUP_CLIENT_SECRET. Required. */
6
+ clientSecret?: string;
7
+ /** The API resource URL (registered on the app that serves it). Required. https, or http on localhost. */
8
+ resource: string;
9
+ /** Omit to get every scope the administrator granted for this resource. */
10
+ scopes?: string[];
11
+ /** Default "https://auth.evup.cloud/api/auth". */
12
+ issuer?: string;
13
+ /** Seconds before `exp` a cached token is replaced. Default 60. */
14
+ refreshSkew?: number;
15
+ /** Where EVUP_* is read from; default process.env (same as createEvupAuth). */
16
+ env?: object;
17
+ fetch?: typeof fetch;
18
+ /** Clock for tests (ms). */
19
+ now?: () => number;
20
+ };
21
+ export type EvupClientToken = {
22
+ accessToken: string;
23
+ /** Expiry, seconds since the epoch. */
24
+ expiresAt: number;
25
+ scopes: string[];
26
+ };
27
+ export interface EvupClientCredentials {
28
+ /** A valid access token: cached until `refreshSkew` seconds before it expires, one request at a time. */
29
+ getToken(opts?: {
30
+ forceRefresh?: boolean;
31
+ }): Promise<string>;
32
+ getTokenInfo(opts?: {
33
+ forceRefresh?: boolean;
34
+ }): Promise<EvupClientToken>;
35
+ /** `fetch` with `Authorization: Bearer <token>`. A 401 `invalid_token` answer gets one retry with a fresh token (only when the body can be sent again). */
36
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
37
+ /** Drops the cached token and the cached discovery document. */
38
+ clear(): void;
39
+ }
40
+ /**
41
+ * Machine-to-machine access tokens (OAuth client_credentials) for a server that calls an API registered on EvUp Account. Every instance has its own
42
+ * cache: it requests one token per resource, reuses it until shortly before it expires, and shares one in-flight request between concurrent callers.
43
+ * The grant has no refresh token: a new token is requested instead.
44
+ */
45
+ export declare function createEvupClientCredentials(config: EvupClientCredentialsConfig): EvupClientCredentials;
@@ -0,0 +1,172 @@
1
+ import { EvupAuthError } from "../errors.js";
2
+ import { DEFAULT_ISSUER, isLoopbackHost, processEnv } from "../server/config.js";
3
+ export { EvupAuthError } from "../errors.js";
4
+ const DISCOVERY_TTL_MS = 60 * 60 * 1000;
5
+ const TIMEOUT_MS = 10_000;
6
+ /** A rejected token is only replaced when it is at least this old: a younger one means the API (not an expired token) is the problem, and a retry per call would hammer the token endpoint. */
7
+ const RETRY_MIN_AGE_MS = 30_000;
8
+ const fromEnv = (env, key) => {
9
+ const value = env[key];
10
+ return typeof value === "string" && value.length > 0 ? value : undefined;
11
+ };
12
+ /** RFC 6749 section 2.3.1: the client id and secret are form-urlencoded before they are joined with ":" and base64-encoded. */
13
+ const formEncode = (value) => encodeURIComponent(value).replace(/%20/g, "+");
14
+ function absolute(name, value) {
15
+ let url;
16
+ try {
17
+ url = new URL(value);
18
+ }
19
+ catch {
20
+ throw new EvupAuthError("config", `${name} must be an absolute URL, got "${value}"`);
21
+ }
22
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) {
23
+ throw new EvupAuthError("config", `${name} must use https (http is allowed for localhost only)`);
24
+ }
25
+ return url;
26
+ }
27
+ /** Whether the request body can be sent a second time: none, or an in-memory one (never a stream, and not a Request that carries one). */
28
+ function replayable(input, init) {
29
+ const body = init?.body;
30
+ if (body === undefined || body === null)
31
+ return !(input instanceof Request && input.body !== null);
32
+ return (typeof body === "string" ||
33
+ body instanceof URLSearchParams ||
34
+ (typeof FormData !== "undefined" && body instanceof FormData) ||
35
+ (typeof Blob !== "undefined" && body instanceof Blob) ||
36
+ body instanceof ArrayBuffer ||
37
+ ArrayBuffer.isView(body));
38
+ }
39
+ /**
40
+ * Machine-to-machine access tokens (OAuth client_credentials) for a server that calls an API registered on EvUp Account. Every instance has its own
41
+ * cache: it requests one token per resource, reuses it until shortly before it expires, and shares one in-flight request between concurrent callers.
42
+ * The grant has no refresh token: a new token is requested instead.
43
+ */
44
+ export function createEvupClientCredentials(config) {
45
+ const env = config.env ?? processEnv();
46
+ const clientId = config.clientId ?? fromEnv(env, "EVUP_CLIENT_ID");
47
+ const clientSecret = config.clientSecret ?? fromEnv(env, "EVUP_CLIENT_SECRET");
48
+ if (!clientId)
49
+ throw new EvupAuthError("config", "clientId is missing: pass it or set EVUP_CLIENT_ID");
50
+ if (!clientSecret)
51
+ throw new EvupAuthError("config", "clientSecret is missing: pass it or set EVUP_CLIENT_SECRET");
52
+ if (!config.resource)
53
+ throw new EvupAuthError("config", "resource is required");
54
+ absolute("resource", config.resource);
55
+ if (config.scopes !== undefined && config.scopes.length === 0)
56
+ throw new EvupAuthError("config", "scopes must not be empty: omit it to get every scope granted for the resource");
57
+ const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
58
+ absolute("issuer", issuer);
59
+ const skew = config.refreshSkew ?? 60;
60
+ const now = config.now ?? Date.now;
61
+ const doFetch = (input, init) => (config.fetch ?? fetch)(input, init);
62
+ const basic = `Basic ${btoa(`${formEncode(clientId)}:${formEncode(clientSecret)}`)}`;
63
+ let discovery = null;
64
+ let cache = null;
65
+ let pending = null;
66
+ let generation = 0;
67
+ async function tokenEndpoint() {
68
+ if (discovery && discovery.until > now())
69
+ return discovery.tokenEndpoint;
70
+ try {
71
+ const res = await doFetch(`${issuer}/.well-known/openid-configuration`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(TIMEOUT_MS) });
72
+ if (!res.ok)
73
+ throw new Error(`discovery answered ${res.status}`);
74
+ const doc = (await res.json());
75
+ if (doc.issuer !== issuer)
76
+ throw new Error("the discovery issuer does not match the configured issuer");
77
+ if (typeof doc.token_endpoint !== "string")
78
+ throw new Error("discovery has no token_endpoint");
79
+ discovery = { tokenEndpoint: doc.token_endpoint, until: now() + DISCOVERY_TTL_MS };
80
+ return doc.token_endpoint;
81
+ }
82
+ catch (cause) {
83
+ throw new EvupAuthError("discovery_failed", `Could not load the OpenID configuration of ${issuer}`, { cause });
84
+ }
85
+ }
86
+ async function request(forced) {
87
+ const endpoint = await tokenEndpoint();
88
+ const body = new URLSearchParams({ grant_type: "client_credentials", resource: config.resource });
89
+ if (config.scopes)
90
+ body.set("scope", config.scopes.join(" "));
91
+ let res;
92
+ try {
93
+ res = await doFetch(endpoint, {
94
+ method: "POST",
95
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json", authorization: basic },
96
+ body: body.toString(),
97
+ signal: AbortSignal.timeout(TIMEOUT_MS),
98
+ });
99
+ }
100
+ catch (cause) {
101
+ throw new EvupAuthError("token_request_failed", "token request failed: the token endpoint could not be reached", { cause });
102
+ }
103
+ const out = (await res.json().catch(() => null));
104
+ if (!res.ok) {
105
+ const oauthError = typeof out?.error === "string" ? out.error : undefined;
106
+ const description = typeof out?.error_description === "string" ? out.error_description : undefined;
107
+ throw new EvupAuthError("token_request_failed", `token request failed: ${res.status}${oauthError ? ` ${oauthError}` : ""}`, { oauthError, description });
108
+ }
109
+ const lifetime = out?.expires_in;
110
+ if (typeof out?.access_token !== "string" || !out.access_token || typeof out.token_type !== "string" || out.token_type.toLowerCase() !== "bearer" || typeof lifetime !== "number" || !(lifetime > 0)) {
111
+ throw new EvupAuthError("token_request_failed", "token request failed: invalid token response");
112
+ }
113
+ const issuedAt = now();
114
+ const scopes = typeof out.scope === "string" ? out.scope.split(" ").filter(Boolean) : [...(config.scopes ?? [])];
115
+ return { accessToken: out.access_token, expiresAt: Math.floor(issuedAt / 1000) + lifetime, scopes, issuedAt, lifetime, forced };
116
+ }
117
+ /** Reusable until `skew` seconds before `exp`; a token that lives no longer than the skew is reused for half its life. */
118
+ function fresh(t) {
119
+ if (t.lifetime <= skew)
120
+ return now() < t.issuedAt + (t.lifetime * 1000) / 2;
121
+ return now() / 1000 < t.expiresAt - skew;
122
+ }
123
+ function load(force) {
124
+ if (!force && cache && fresh(cache))
125
+ return Promise.resolve(cache);
126
+ if (!pending) {
127
+ const started = generation;
128
+ const run = request(force)
129
+ .then((token) => {
130
+ if (started === generation)
131
+ cache = token;
132
+ return token;
133
+ })
134
+ .finally(() => {
135
+ if (pending === run)
136
+ pending = null;
137
+ });
138
+ pending = run;
139
+ }
140
+ return pending;
141
+ }
142
+ const getTokenInfo = async (opts) => {
143
+ const t = await load(opts?.forceRefresh === true);
144
+ return { accessToken: t.accessToken, expiresAt: t.expiresAt, scopes: [...t.scopes] };
145
+ };
146
+ return {
147
+ getToken: async (opts) => (await load(opts?.forceRefresh === true)).accessToken,
148
+ getTokenInfo,
149
+ async fetch(input, init) {
150
+ const send = async (forceRefresh) => {
151
+ const request = new Request(input, init);
152
+ const token = await load(forceRefresh);
153
+ request.headers.set("authorization", `Bearer ${token.accessToken}`);
154
+ return { token, response: await doFetch(request) };
155
+ };
156
+ const first = await send(false);
157
+ if (first.response.status !== 401 || !/invalid_token/.test(first.response.headers.get("www-authenticate") ?? "") || !replayable(input, init))
158
+ return first.response;
159
+ // At most one forced refresh per token: not when this token already came from one, nor when it is younger than RETRY_MIN_AGE_MS
160
+ if (first.token.forced || now() - first.token.issuedAt < RETRY_MIN_AGE_MS)
161
+ return first.response;
162
+ await first.response.body?.cancel().catch(() => undefined);
163
+ return (await send(true)).response;
164
+ },
165
+ clear() {
166
+ generation++;
167
+ cache = null;
168
+ discovery = null;
169
+ pending = null;
170
+ },
171
+ };
172
+ }
@@ -10,14 +10,22 @@ export type EvupResourceConfig = {
10
10
  resourceName?: string;
11
11
  /** Seconds of clock skew accepted on `exp` / `nbf`. Default 30. */
12
12
  clockTolerance?: number;
13
+ /**
14
+ * Which tokens are accepted: tokens for a signed-in user, client tokens from the client_credentials grant (machine-to-machine), or both.
15
+ * Default "user": a client token is refused unless you opt in, because code that treats `sub` as a user id must not meet a client id.
16
+ */
17
+ accept?: "user" | "client" | "any";
13
18
  fetch?: typeof fetch;
14
19
  };
15
20
  export type EvupAccessToken = {
16
- /** The user id. */
21
+ /** The user id, or for a client token the client id. */
17
22
  sub: string;
23
+ /** "client" for a token of the client_credentials grant (`sub` is the client id), "user" for a token issued to a signed-in user. */
24
+ kind: "user" | "client";
18
25
  /** The OAuth client the token was issued to (`azp`). */
19
26
  clientId: string;
20
27
  scopes: string[];
28
+ /** RBAC permissions of the user in the app; always [] for a client token. */
21
29
  permissions: string[];
22
30
  /** Expiry, seconds since the epoch. */
23
31
  exp: number;
@@ -63,6 +63,9 @@ export function createEvupResource(config) {
63
63
  }
64
64
  const issuer = (config.issuer ?? DEFAULT_ISSUER).replace(/\/+$/, "");
65
65
  const required = config.scopes ?? [];
66
+ const accept = config.accept === undefined ? "user" : config.accept;
67
+ if (accept !== "user" && accept !== "client" && accept !== "any")
68
+ throw new EvupAuthError("config", `accept must be "user", "client" or "any", got "${String(config.accept)}"`);
66
69
  const tolerance = config.clockTolerance ?? 30;
67
70
  const pathname = resourceUrl.pathname === "/" ? "" : resourceUrl.pathname.replace(/\/+$/, "");
68
71
  const metadataPath = `${METADATA_PREFIX}${pathname}`;
@@ -148,13 +151,20 @@ export function createEvupResource(config) {
148
151
  const { sub, azp, scope, exp } = payload;
149
152
  if (typeof sub !== "string" || typeof azp !== "string" || typeof scope !== "string" || typeof exp !== "number")
150
153
  return invalid("The access token is invalid");
154
+ // A client token (client_credentials) names the client as its subject (RFC 9068 section 2.2); user ids and client ids never collide
155
+ const clientId = typeof payload.client_id === "string" ? payload.client_id : azp;
156
+ const kind = sub === clientId ? "client" : "user";
157
+ if (accept === "user" && kind === "client")
158
+ return invalid("This resource does not accept client tokens");
159
+ if (accept === "client" && kind === "user")
160
+ return invalid("This resource only accepts client tokens");
151
161
  const granted = scopeList(scope);
152
162
  if (required.some((s) => !granted.includes(s))) {
153
163
  const description = `The access token lacks a required scope: ${required.join(" ")}`;
154
164
  return failure(403, "insufficient_scope", description, challenge(prmUrl, { error: "insufficient_scope", description, scope: required.join(" ") }));
155
165
  }
156
- const permissions = Array.isArray(payload.permissions) ? payload.permissions.filter((p) => typeof p === "string") : [];
157
- return { ok: true, token: { sub, clientId: azp, scopes: granted, permissions, exp, claims: payload } };
166
+ const permissions = kind === "client" ? [] : Array.isArray(payload.permissions) ? payload.permissions.filter((p) => typeof p === "string") : [];
167
+ return { ok: true, token: { sub, kind, clientId: azp, scopes: granted, permissions, exp, claims: payload } };
158
168
  }
159
169
  return {
160
170
  metadataPath,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evup/auth",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "SDK for apps and resource servers that sign in with EvUp Account (OIDC authorization code + PKCE, RFC 9728 resource servers).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -50,6 +50,10 @@
50
50
  "types": "./dist/resource/index.d.ts",
51
51
  "default": "./dist/resource/index.js"
52
52
  },
53
+ "./m2m": {
54
+ "types": "./dist/m2m/index.d.ts",
55
+ "default": "./dist/m2m/index.js"
56
+ },
53
57
  "./package.json": "./package.json"
54
58
  },
55
59
  "scripts": {