@evup/auth 0.2.1 → 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 +10 -0
- package/README.md +89 -10
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +3 -0
- package/dist/m2m/index.d.ts +45 -0
- package/dist/m2m/index.js +172 -0
- package/dist/resource/index.d.ts +9 -1
- package/dist/resource/index.js +12 -2
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
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
|
+
|
|
5
15
|
## auth-v0.2.1 — 2026-11-26
|
|
6
16
|
|
|
7
17
|
### Other
|
package/README.md
CHANGED
|
@@ -19,11 +19,12 @@ An SDK that lets your app sign users in with **EvUp Account** (`auth.evup.cloud`
|
|
|
19
19
|
8. [Access denied and waitlist](#access-denied-and-waitlist)
|
|
20
20
|
9. [Signing out](#signing-out)
|
|
21
21
|
10. [MCP / API resource server](#mcp--api-resource-server)
|
|
22
|
-
11. [
|
|
23
|
-
12. [
|
|
24
|
-
13. [
|
|
25
|
-
14. [
|
|
26
|
-
15. [
|
|
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)
|
|
27
28
|
|
|
28
29
|
## Installation
|
|
29
30
|
|
|
@@ -43,6 +44,7 @@ Import paths:
|
|
|
43
44
|
| `@evup/auth/astro` | the `evup` integration, `createEvupMiddleware` |
|
|
44
45
|
| `@evup/auth/next` | `handlers`, `getSession`, `getUser`, `withEvupAuth` |
|
|
45
46
|
| `@evup/auth/resource` | `createEvupResource` (MCP / API server) |
|
|
47
|
+
| `@evup/auth/m2m` | `createEvupClientCredentials` (server-to-server tokens, no user) |
|
|
46
48
|
|
|
47
49
|
## Registering your app on EvUp
|
|
48
50
|
|
|
@@ -563,7 +565,7 @@ Use this when your app has its own MCP server or API that clients (Claude Code,
|
|
|
563
565
|
|
|
564
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).
|
|
565
567
|
|
|
566
|
-
**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).
|
|
567
569
|
|
|
568
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).
|
|
569
571
|
|
|
@@ -666,6 +668,66 @@ export const GET = () => resource.metadataResponse();
|
|
|
666
668
|
|
|
667
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.
|
|
668
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
|
+
|
|
669
731
|
## Configuration reference
|
|
670
732
|
|
|
671
733
|
`createEvupAuth(config)` (`@evup/auth/server`):
|
|
@@ -712,7 +774,23 @@ type EvupUser = {
|
|
|
712
774
|
type Session = { user: EvupUser; accessToken: string; expiresAt: number /* ms epoch */; scope: string };
|
|
713
775
|
```
|
|
714
776
|
|
|
715
|
-
`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() }`.
|
|
716
794
|
|
|
717
795
|
Session behavior:
|
|
718
796
|
|
|
@@ -724,7 +802,7 @@ Session behavior:
|
|
|
724
802
|
|
|
725
803
|
## Errors
|
|
726
804
|
|
|
727
|
-
`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`.
|
|
728
806
|
|
|
729
807
|
| `code` | When |
|
|
730
808
|
|---|---|
|
|
@@ -732,7 +810,8 @@ Session behavior:
|
|
|
732
810
|
| `access_denied` | EvUp denied the user (callback `error=access_denied`) |
|
|
733
811
|
| `invalid_state` | transaction cookie missing/expired, `state` or `iss` mismatch |
|
|
734
812
|
| `callback_failed` | code exchange failed, id_token invalid (`nonce`, `aud`...), session too large for the cookie |
|
|
735
|
-
| `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` |
|
|
736
815
|
|
|
737
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).
|
|
738
817
|
|
|
@@ -781,4 +860,4 @@ createEvupAuth({
|
|
|
781
860
|
|
|
782
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.
|
|
783
862
|
|
|
784
|
-
**Is `client_credentials` / machine-to-machine supported?**
|
|
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
|
+
}
|
package/dist/resource/index.d.ts
CHANGED
|
@@ -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;
|
package/dist/resource/index.js
CHANGED
|
@@ -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.
|
|
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": {
|