nextidp 0.1.5 → 0.4.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +86 -0
  3. package/dist/cjs/access-token.d.ts +29 -4
  4. package/dist/cjs/access-token.js +53 -10
  5. package/dist/cjs/config.d.ts +36 -0
  6. package/dist/cjs/config.js +36 -1
  7. package/dist/cjs/discovery.d.ts +2 -0
  8. package/dist/cjs/discovery.js +2 -0
  9. package/dist/cjs/errors.d.ts +16 -3
  10. package/dist/cjs/errors.js +7 -1
  11. package/dist/cjs/exchange.d.ts +21 -0
  12. package/dist/cjs/exchange.js +76 -0
  13. package/dist/cjs/express.d.ts +12 -1
  14. package/dist/cjs/express.js +7 -0
  15. package/dist/cjs/fastify.d.ts +13 -1
  16. package/dist/cjs/fastify.js +14 -0
  17. package/dist/cjs/hono.d.ts +12 -1
  18. package/dist/cjs/hono.js +8 -0
  19. package/dist/cjs/id-token.js +1 -1
  20. package/dist/cjs/idp.d.ts +27 -1
  21. package/dist/cjs/idp.js +76 -8
  22. package/dist/cjs/index.d.ts +3 -2
  23. package/dist/cjs/nestjs.d.ts +2 -1
  24. package/dist/cjs/next.d.ts +12 -1
  25. package/dist/cjs/next.js +4 -0
  26. package/dist/cjs/node-adapter.d.ts +2 -0
  27. package/dist/cjs/node-adapter.js +8 -0
  28. package/dist/cjs/node.d.ts +7 -1
  29. package/dist/cjs/node.js +1 -0
  30. package/dist/cjs/pushed-authorization.d.ts +9 -0
  31. package/dist/cjs/pushed-authorization.js +66 -0
  32. package/dist/cjs/service.d.ts +3 -0
  33. package/dist/cjs/service.js +13 -41
  34. package/dist/cjs/token-cache.d.ts +18 -0
  35. package/dist/cjs/token-cache.js +75 -0
  36. package/dist/cjs/tokens.d.ts +13 -0
  37. package/dist/cjs/tokens.js +19 -0
  38. package/dist/esm/access-token.d.ts +29 -4
  39. package/dist/esm/access-token.js +50 -9
  40. package/dist/esm/config.d.ts +36 -0
  41. package/dist/esm/config.js +35 -1
  42. package/dist/esm/discovery.d.ts +2 -0
  43. package/dist/esm/discovery.js +2 -0
  44. package/dist/esm/errors.d.ts +16 -3
  45. package/dist/esm/errors.js +7 -1
  46. package/dist/esm/exchange.d.ts +21 -0
  47. package/dist/esm/exchange.js +52 -0
  48. package/dist/esm/express.d.ts +12 -1
  49. package/dist/esm/express.js +7 -0
  50. package/dist/esm/fastify.d.ts +13 -1
  51. package/dist/esm/fastify.js +15 -1
  52. package/dist/esm/hono.d.ts +12 -1
  53. package/dist/esm/hono.js +8 -0
  54. package/dist/esm/id-token.js +1 -1
  55. package/dist/esm/idp.d.ts +27 -1
  56. package/dist/esm/idp.js +79 -9
  57. package/dist/esm/index.d.ts +3 -2
  58. package/dist/esm/nestjs.d.ts +2 -1
  59. package/dist/esm/next.d.ts +12 -1
  60. package/dist/esm/next.js +4 -0
  61. package/dist/esm/node-adapter.d.ts +2 -0
  62. package/dist/esm/node-adapter.js +8 -0
  63. package/dist/esm/node.d.ts +7 -1
  64. package/dist/esm/node.js +1 -0
  65. package/dist/esm/pushed-authorization.d.ts +9 -0
  66. package/dist/esm/pushed-authorization.js +32 -0
  67. package/dist/esm/service.d.ts +3 -0
  68. package/dist/esm/service.js +11 -41
  69. package/dist/esm/token-cache.d.ts +18 -0
  70. package/dist/esm/token-cache.js +50 -0
  71. package/dist/esm/tokens.d.ts +13 -0
  72. package/dist/esm/tokens.js +16 -0
  73. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - Access, ID and logout tokens signed with `Ed25519` are accepted: RFC 9864's fully specified
6
+ name for an Edwards-curve signature. The name it deprecates, `EdDSA`, still works for now and
7
+ will be dropped in a later release, as nextidp for Python already has.
8
+
9
+ ## 0.3.0
10
+
11
+ ### Pushed authorization requests
12
+
13
+ - `pushedAuthorization`: `/login` posts the sign-in's parameters to the auth server's PAR
14
+ endpoint first (RFC 9126), authenticated as at the token endpoint (Basic for a confidential
15
+ client, `client_id` alone for a public one), and sends the browser to authorize with only
16
+ `client_id` and the `request_uri` it got back. `false` by default; `"auto"` pushes when
17
+ discovery advertises `pushed_authorization_request_endpoint`; `true` requires it.
18
+ - The push is made when `/login` is opened, tried once, and never followed by an ordinary
19
+ authorize request: a refusal, no answer, or (with `true`) no endpoint answers 503 and
20
+ reports an `IdpError` with the new code `pushed_authorization_failed` through `onError`.
21
+
22
+ ## 0.2.0
23
+
24
+ ### MCP servers
25
+
26
+ - `resourceMetadata` (IDP_RESOURCE_METADATA): an API publishes its protected resource
27
+ metadata (RFC 9728), the document MCP clients read to find the auth server, at
28
+ `/.well-known/oauth-protected-resource` followed by the audience's path: `resource`,
29
+ `authorization_servers`, `bearer_methods_supported`, and with `{ scopes, name }`,
30
+ `scopes_supported` (never `offline_access`) and `resource_name`. Readable from any origin.
31
+ The audience must then be an http(s) URL.
32
+ - Each adapter serves it: `resourceMetadata()` in `nextidp/express` and `nextidp/hono`
33
+ (middleware), `nextidp/fastify` (a plugin, for the whole app), `nextidp/node` (`(req, res)`,
34
+ true when it answered) and `nextidp/next` (`{ GET, OPTIONS }` for a catch-all route). The
35
+ core has `resourceMetadataDocument()` and `resourceMetadataResponse(request)`.
36
+ - Token refusals name the protected resource metadata in `WWW-Authenticate`
37
+ (`resource_metadata="…"`), and every scope the route needs (`scope="…"`) on the 401 too,
38
+ not only the 403. `IdpError` carries both (`scopes`, `resourceMetadata`).
39
+ - `exchangeToken({ subjectToken, resource, scopes })`: token exchange (RFC 8693) with this
40
+ service's own credentials, for an MCP server that calls another API as the person. Kept
41
+ until a minute before it expires and never past the subject token, per subject, API and
42
+ scopes, one request shared between concurrent calls; a refusal is never kept and throws
43
+ `token_exchange_failed`.
44
+ - `AccessToken.raw`: the token as the caller sent it, for `exchangeToken`.
45
+
3
46
  ## 0.1.5
4
47
 
5
48
  ### Fastify
package/README.md CHANGED
@@ -295,6 +295,29 @@ cookie.
295
295
 
296
296
  `auth.signInPath(returnTo, { prompt, reauthenticate })` builds these links.
297
297
 
298
+ ### Pushing the sign-in first (PAR)
299
+
300
+ With `pushedAuthorization`, `/auth/login` posts the sign-in's parameters to the auth server
301
+ first (RFC 9126), authenticated as at the token endpoint, and sends the browser to authorize
302
+ with only `client_id` and the one-time `request_uri` it got back. Nothing the browser carries,
303
+ keeps in its history or leaves in a log can then be read or changed.
304
+
305
+ ```ts
306
+ const auth = idp({ /* … */ pushedAuthorization: true });
307
+ ```
308
+
309
+ - `false` (the default): an ordinary authorize request. PKCE, `state` and `nonce` already
310
+ protect the flow; pushing costs one more request per sign-in.
311
+ - `"auto"`: push when the auth server's discovery advertises
312
+ `pushed_authorization_request_endpoint` (Next-Identity Server does), sign in the ordinary
313
+ way when it doesn't.
314
+ - `true`: always push; without the endpoint, every sign-in fails.
315
+
316
+ The push is made when `/auth/login` is opened (a `request_uri` works once, for a minute), and
317
+ tried once. If it's refused or gets no answer, `/auth/login` answers 503, as when discovery
318
+ fails, and `onError` gets an `IdpError` with the code `pushed_authorization_failed`: it never
319
+ falls back to an ordinary authorize request.
320
+
298
321
  ## The session
299
322
 
300
323
  ```ts
@@ -335,6 +358,7 @@ Pass them to `idp({...})`, or set the variable in brackets. A function works too
335
358
  | `resource` (IDP_RESOURCE) | none | An API's URI (RFC 8707): the access token is then a JWT for it. |
336
359
  | `audience` (IDP_AUDIENCE) | none: required to check tokens | For an API: its own URI, exactly as in the auth server's `OAUTH_RESOURCES`. Every token must name it. Never taken from `resource`, which is the API an app asks tokens *for*. |
337
360
  | `acceptOwnTokens` | `false` | For an API: also accept an opaque token issued to its own `clientId` that doesn't name `audience`. |
361
+ | `resourceMetadata` (IDP_RESOURCE_METADATA) | `false` | For an API, an MCP server above all: publish its protected resource metadata (RFC 9728), `{ scopes, name }` for what it lists ([below](#an-mcp-server)). |
338
362
  | `basePath` | `/auth` | Where the routes live. |
339
363
  | `afterSignIn` | `/` | Where a sign-in lands without a `returnTo`. |
340
364
  | `afterSignOut` | `/` | Where sign-out lands: also the post-logout redirect URI. |
@@ -342,6 +366,7 @@ Pass them to `idp({...})`, or set the variable in brackets. A function works too
342
366
  | `signOutOfIdp` | `false` | Sign out of the auth server too, unless the form says otherwise. |
343
367
  | `reauthenticateAfterSignOut` | `false` | After a sign-out, the next sign-in asks for the password again (`prompt=login`), unless its link says `reauthenticate=false` ([above](#asking-for-the-password-again)). |
344
368
  | `userinfo` | `false` | Fill the session's email, name and picture from userinfo: one more request at sign-in, and at each refresh that brings a new ID token ([above](#the-session)). |
369
+ | `pushedAuthorization` | `false` | Push each sign-in's parameters first (PAR, RFC 9126), so the browser carries only a `request_uri`: `true`, or `"auto"` when discovery advertises it ([above](#pushing-the-sign-in-first-par)). |
345
370
  | `sessionMaxAge` | 7 days | Renewed at every refresh. |
346
371
  | `cookiePrefix` | `nextidp` | Cookies are `__Host-nextidp.session` on https. |
347
372
  | `store` | none: sessions live in the cookie | Keep sessions in a store instead ([below](#sessions-in-a-store-and-back-channel-logout)). |
@@ -461,9 +486,13 @@ type AccessToken = {
461
486
  audience: string[];
462
487
  expiresAt: number | undefined;
463
488
  claims: Record<string, unknown>;
489
+ raw: string; // the token as sent: for exchangeToken, never to pass on
464
490
  };
465
491
  ```
466
492
 
493
+ A refusal's challenge names every scope the route needs (`scope="orders:read"`), on the 401
494
+ as well as the 403, and with `resourceMetadata` on, the metadata too.
495
+
467
496
  **Opaque tokens.** A token asked for without `resource` isn't a JWT, and only introspection
468
497
  can check it. Pass the API's own `clientId` and `clientSecret` (a confidential client) for
469
498
  that. The auth server answers only for tokens this client was issued, or tokens for an API
@@ -472,6 +501,63 @@ was issued for something else passes only with `acceptOwnTokens: true`. Answers
472
501
  for a minute at most, so a revoked token is refused within a minute. For APIs, prefer JWTs:
473
502
  ask for tokens with `resource`.
474
503
 
504
+ ## An MCP server
505
+
506
+ An MCP client (Claude, Cursor, VS Code) finds the auth server from the MCP server itself:
507
+ its first call gets a 401 naming the server's protected resource metadata (RFC 9728), which
508
+ names the auth server. Turn it on, with the scopes the tools need:
509
+
510
+ ```ts
511
+ // nextidp/express; the same in nextidp/hono, nextidp/fastify, nextidp/node and nextidp/next
512
+ const auth = idp({
513
+ issuer: "https://auth.example.com",
514
+ audience: "https://mcp.example.com/mcp", // exactly as in OAUTH_RESOURCES, marked mcp
515
+ resourceMetadata: { scopes: ["orders:read"], name: "Orders" },
516
+ });
517
+
518
+ app.use(auth.resourceMetadata()); // GET /.well-known/oauth-protected-resource/mcp
519
+ app.post("/mcp", auth.requireToken({ scopes: ["orders:read"] }), mcpHandler);
520
+ ```
521
+
522
+ - **The document** is served at `/.well-known/oauth-protected-resource` followed by the
523
+ audience's path, as RFC 9728 places it, to any origin (an MCP client in a browser reads it
524
+ too): `resource`, `authorization_servers`, `scopes_supported` (never `offline_access`),
525
+ `resource_name`. The audience must be an http(s) URL.
526
+ - **Each adapter serves it:** `app.use(auth.resourceMetadata())` in Express and Hono,
527
+ `await app.register(auth.resourceMetadata())` in Fastify (on the app, not under a prefix),
528
+ `if (await auth.resourceMetadata(req, res)) return;` on Node's own server, and in Next.js
529
+ `export const { GET, OPTIONS } = auth.resourceMetadata();` in
530
+ `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`. Anywhere else,
531
+ `auth.resourceMetadataResponse(request)` answers a Web `Request` (undefined for any other
532
+ path).
533
+ - **Every 401 and 403** then says `resource_metadata="<its URL>"` in `WWW-Authenticate`,
534
+ with every scope the route needs.
535
+
536
+ ### Calling another API for the person
537
+
538
+ An MCP server mustn't pass the person's token on: it was issued for the MCP server alone.
539
+ With token exchange (RFC 8693) it trades the token for one meant for the API it calls, as the
540
+ same person, with its own client (a confidential one: `clientId` and `clientSecret`), within
541
+ the policy the auth server has for that client (`tokenExchange` in Next-Identity Server's
542
+ provisioning file):
543
+
544
+ ```ts
545
+ const token = auth.tokenOf(req); // checked by requireToken
546
+ const crm = await auth.exchangeToken({
547
+ subjectToken: token.raw,
548
+ resource: "https://crm.example.com",
549
+ scopes: ["crm:read"], // optional: within the token's and the policy's
550
+ });
551
+ await fetch("https://crm.example.com/contacts", { headers: { authorization: `Bearer ${crm}` } });
552
+ ```
553
+
554
+ The exchanged token is kept until a minute before it expires, and never past the token it
555
+ came from, per token, API and scopes; calls at the same time share one request, and a refusal
556
+ isn't kept. A refusal throws `IdpError` with the code `token_exchange_failed` and the auth
557
+ server's error code in the message. The example in
558
+ [apps/example-mcp](https://github.com/sajanv88/next-identity-server/tree/main/apps/example-mcp)
559
+ is a whole MCP server built this way.
560
+
475
561
  ## Calling an API as a service
476
562
 
477
563
  A service that calls another API as itself, with no person involved, gets its own tokens
@@ -17,6 +17,11 @@ export type AccessToken = {
17
17
  expiresAt: number | undefined;
18
18
  /** Every claim, or every field of the introspection answer. */
19
19
  claims: Record<string, unknown>;
20
+ /**
21
+ * The token itself, as the caller sent it: for `exchangeToken`, never to pass on to
22
+ * another API. Don't log it.
23
+ */
24
+ raw: string;
20
25
  };
21
26
  export type TokenRequirements = {
22
27
  /** Every one of these scopes must be granted. */
@@ -25,7 +30,7 @@ export type TokenRequirements = {
25
30
  /** The token in an `Authorization: Bearer …` header, or undefined. */
26
31
  export declare function bearerToken(authorization: string | null | undefined): string | undefined;
27
32
  /** Throws insufficient_scope (403) unless every required scope was granted. */
28
- export declare function requireScopes(token: AccessToken, required?: readonly string[]): AccessToken;
33
+ export declare function requireScopes<T extends Pick<AccessToken, "scopes">>(token: T, required?: readonly string[]): T;
29
34
  /** Whether a token is a JWT (three parts, a header that decodes) rather than opaque. */
30
35
  export declare function isJwt(token: string): boolean;
31
36
  /**
@@ -33,18 +38,38 @@ export declare function isJwt(token: string): boolean;
33
38
  * token) passes for one; a signature by one of the issuer's keys (asymmetric algorithms
34
39
  * only); `iss`; `aud` naming this API; and not expired (60 seconds of clock skew).
35
40
  */
36
- export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<AccessToken>;
41
+ export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<Omit<AccessToken, "raw">>;
37
42
  /**
38
43
  * Asks the auth server whether an opaque token is active, with this API's client
39
44
  * credentials. The auth server answers only for tokens this client issued, or tokens for an
40
45
  * API this client is linked to; to anything else it answers inactive.
41
46
  */
42
- export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<AccessToken>;
47
+ export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<Omit<AccessToken, "raw">>;
43
48
  /**
44
49
  * The WWW-Authenticate challenge for a refused request (RFC 6750 3): no error code when
45
- * there was no token at all, else invalid_token or insufficient_scope with the scopes needed.
50
+ * there was no token at all, else invalid_token or insufficient_scope; then the scopes the
51
+ * route needs, every one of them, and the protected resource metadata (RFC 9728 5.1) when
52
+ * the API publishes it, which is how an MCP client finds the auth server.
46
53
  */
47
54
  export declare function bearerChallenge(error: IdpError): string;
55
+ /** The protected resource metadata document (RFC 9728 2). */
56
+ export type ResourceMetadata = {
57
+ resource: string;
58
+ authorization_servers: string[];
59
+ bearer_methods_supported: ["header"];
60
+ scopes_supported?: string[];
61
+ resource_name?: string;
62
+ };
63
+ export declare function resourceMetadataDocument(config: Pick<ApiConfig, "issuer" | "audience" | "resourceMetadata">): ResourceMetadata | undefined;
64
+ /**
65
+ * The answer for a request to the protected resource metadata's path, or undefined for any
66
+ * other request (or while it's off). Public and the same for everyone, so any origin may read
67
+ * it: MCP clients in a browser (the MCP Inspector) fetch it too.
68
+ */
69
+ export declare function resourceMetadataResponse(config: Pick<ApiConfig, "issuer" | "audience" | "resourceMetadata">, request: {
70
+ method: string;
71
+ url: string;
72
+ }): Response | undefined;
48
73
  /** The status, challenge and JSON body to answer a refused request with. */
49
74
  export declare function tokenRefusal(error: IdpError): {
50
75
  status: 401 | 403;
@@ -33,6 +33,8 @@ __export(access_token_exports, {
33
33
  introspect: () => introspect,
34
34
  isJwt: () => isJwt,
35
35
  requireScopes: () => requireScopes,
36
+ resourceMetadataDocument: () => resourceMetadataDocument,
37
+ resourceMetadataResponse: () => resourceMetadataResponse,
36
38
  tokenRefusal: () => tokenRefusal,
37
39
  verifyJwtAccessToken: () => verifyJwtAccessToken
38
40
  });
@@ -41,7 +43,7 @@ var import_jose = require("jose");
41
43
  var v = __toESM(require("valibot"), 1);
42
44
  var import_errors = require("./errors.js");
43
45
  const ACCESS_TOKEN_TYPES = /* @__PURE__ */ new Set(["at+jwt", "application/at+jwt"]);
44
- const ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
46
+ const ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
45
47
  const BEARER = /^Bearer +([A-Za-z0-9\-._~+/]+=*)\s*$/i;
46
48
  const invalid = (message, cause) => new import_errors.IdpError("invalid_token", message, { status: 401, cause });
47
49
  function bearerToken(authorization) {
@@ -162,15 +164,54 @@ function quoted(value) {
162
164
  return `"${value.replace(/[\\"]/g, "\\$&")}"`;
163
165
  }
164
166
  function bearerChallenge(error) {
165
- if (error.code === "missing_token") return "Bearer";
166
- const parts = [
167
- `error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`
168
- ];
169
- parts.push(`error_description=${quoted(error.message)}`);
170
- if (error.code === "insufficient_scope" && error.scopes?.length) {
171
- parts.push(`scope=${quoted(error.scopes.join(" "))}`);
172
- }
173
- return `Bearer ${parts.join(", ")}`;
167
+ const parts = [];
168
+ if (error.code !== "missing_token") {
169
+ parts.push(
170
+ `error=${quoted(error.code === "insufficient_scope" ? "insufficient_scope" : "invalid_token")}`,
171
+ `error_description=${quoted(error.message)}`
172
+ );
173
+ }
174
+ if (error.scopes?.length) parts.push(`scope=${quoted(error.scopes.join(" "))}`);
175
+ if (error.resourceMetadata) parts.push(`resource_metadata=${quoted(error.resourceMetadata)}`);
176
+ return parts.length > 0 ? `Bearer ${parts.join(", ")}` : "Bearer";
177
+ }
178
+ function resourceMetadataDocument(config) {
179
+ const metadata = config.resourceMetadata;
180
+ if (!metadata) return void 0;
181
+ return {
182
+ // Exactly as the auth server lists it: clients compare it as a string.
183
+ resource: config.audience,
184
+ authorization_servers: [config.issuer],
185
+ bearer_methods_supported: ["header"],
186
+ ...metadata.scopes.length > 0 ? { scopes_supported: metadata.scopes } : {},
187
+ ...metadata.name ? { resource_name: metadata.name } : {}
188
+ };
189
+ }
190
+ const METADATA_CORS = {
191
+ "access-control-allow-origin": "*",
192
+ "access-control-allow-methods": "GET, HEAD, OPTIONS",
193
+ "access-control-allow-headers": "*"
194
+ };
195
+ function resourceMetadataResponse(config, request) {
196
+ const document = resourceMetadataDocument(config);
197
+ if (!document || !config.resourceMetadata) return void 0;
198
+ if (new URL(request.url).pathname.replace(/\/+$/, "") !== config.resourceMetadata.path) {
199
+ return void 0;
200
+ }
201
+ if (request.method === "OPTIONS") {
202
+ return new Response(null, { status: 204, headers: METADATA_CORS });
203
+ }
204
+ if (request.method !== "GET" && request.method !== "HEAD") {
205
+ return new Response(null, { status: 405, headers: { allow: "GET, HEAD, OPTIONS" } });
206
+ }
207
+ return new Response(request.method === "HEAD" ? null : JSON.stringify(document), {
208
+ status: 200,
209
+ headers: {
210
+ "content-type": "application/json",
211
+ "cache-control": "public, max-age=3600",
212
+ ...METADATA_CORS
213
+ }
214
+ });
174
215
  }
175
216
  function tokenRefusal(error) {
176
217
  const status = error.code === "insufficient_scope" ? 403 : 401;
@@ -191,6 +232,8 @@ function tokenRefusal(error) {
191
232
  introspect,
192
233
  isJwt,
193
234
  requireScopes,
235
+ resourceMetadataDocument,
236
+ resourceMetadataResponse,
194
237
  tokenRefusal,
195
238
  verifyJwtAccessToken
196
239
  });
@@ -32,6 +32,18 @@ export type IdpOptions = {
32
32
  * so only tokens for this API pass.
33
33
  */
34
34
  acceptOwnTokens?: boolean | undefined;
35
+ /**
36
+ * For an API, an MCP server above all: publish its protected resource metadata (RFC 9728),
37
+ * which tells a client which auth server to sign in with. `audience` must then be an http(s)
38
+ * URL: the document is served at `/.well-known/oauth-protected-resource` followed by its
39
+ * path (each adapter's `resourceMetadata()`), and every 401 and 403 names it in
40
+ * `WWW-Authenticate`. `scopes` are listed as `scopes_supported`, `name` as `resource_name`.
41
+ * Default off (IDP_RESOURCE_METADATA=true turns it on).
42
+ */
43
+ resourceMetadata?: boolean | {
44
+ scopes?: readonly string[] | undefined;
45
+ name?: string | undefined;
46
+ } | undefined;
35
47
  /** Where nextidp's routes live. Default `/auth`: the redirect URI is `<appUrl>/auth/callback`. */
36
48
  basePath?: string | undefined;
37
49
  /** Where a sign-in lands when it wasn't asked to return somewhere. Default `/`. */
@@ -57,6 +69,17 @@ export type IdpOptions = {
57
69
  * `onError` is told. Costs one more request. Default false.
58
70
  */
59
71
  userinfo?: boolean | undefined;
72
+ /**
73
+ * Start each sign-in with a pushed authorization request (RFC 9126): `/login` posts the
74
+ * sign-in's parameters to the auth server first, authenticated as at the token endpoint,
75
+ * and sends the browser to authorize with only `client_id` and the `request_uri` it got
76
+ * back, so nothing in the browser, its history or a log can be read or changed. `"auto"`
77
+ * pushes when discovery advertises the endpoint; `true` requires it, and a sign-in fails
78
+ * without it. A push that fails is a 503, never an ordinary authorize request instead.
79
+ * PKCE, `state` and `nonce` already protect the flow; this costs one more request per
80
+ * sign-in. Default false.
81
+ */
82
+ pushedAuthorization?: boolean | "auto" | undefined;
60
83
  /** How long the session cookie lasts, in seconds, renewed at every refresh. Default 7 days. */
61
84
  sessionMaxAge?: number | undefined;
62
85
  /** The start of this app's cookie names. Default `nextidp`. */
@@ -87,7 +110,19 @@ export type ApiConfig = {
87
110
  clientSecret: string | undefined;
88
111
  /** See IdpOptions.acceptOwnTokens. */
89
112
  acceptOwnTokens: boolean;
113
+ /** See IdpOptions.resourceMetadata: where it's served, and what it says. */
114
+ resourceMetadata: ResourceMetadataConfig | undefined;
115
+ };
116
+ export type ResourceMetadataConfig = {
117
+ /** The document's URL: the audience's origin, the well-known path, then its path. */
118
+ url: string;
119
+ /** Its path alone, for matching a request. */
120
+ path: string;
121
+ scopes: string[];
122
+ name: string | undefined;
90
123
  };
124
+ /** RFC 9728 3.1: the well-known path goes between the host and the resource's own path. */
125
+ export declare const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
91
126
  /** What a service needs to get tokens of its own: a confidential client. */
92
127
  export type ServiceConfig = {
93
128
  issuer: string;
@@ -116,6 +151,7 @@ export type IdpConfig = {
116
151
  signOutOfIdp: boolean;
117
152
  reauthenticateAfterSignOut: boolean;
118
153
  userinfo: boolean;
154
+ pushedAuthorization: boolean | "auto";
119
155
  sessionMaxAge: number;
120
156
  /** https: cookies are Secure, with `__Host-` names (`__Secure-` for `signedOut`). */
121
157
  secure: boolean;
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var config_exports = {};
20
20
  __export(config_exports, {
21
21
  DEFAULT_SCOPES: () => DEFAULT_SCOPES,
22
+ RESOURCE_METADATA_PATH: () => RESOURCE_METADATA_PATH,
22
23
  resolveApiConfig: () => resolveApiConfig,
23
24
  resolveConfig: () => resolveConfig,
24
25
  resolveServiceConfig: () => resolveServiceConfig
@@ -26,6 +27,7 @@ __export(config_exports, {
26
27
  module.exports = __toCommonJS(config_exports);
27
28
  var import_errors = require("./errors.js");
28
29
  var import_return_path = require("./return-path.js");
30
+ const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
29
31
  const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
30
32
  const SEVEN_DAYS = 7 * 24 * 60 * 60;
31
33
  const MIN_SECRET_LENGTH = 32;
@@ -114,15 +116,42 @@ function resolveApiConfig(options) {
114
116
  if (!audience && !problems.some((p) => p.startsWith("audience"))) {
115
117
  problems.push("audience (IDP_AUDIENCE) is required to check access tokens: this API's URI");
116
118
  }
119
+ const resourceMetadata = audience ? resourceMetadataConfig(options, env, audience, problems) : void 0;
117
120
  if (problems.length > 0 || !issuer || !audience) throw misconfigured(problems);
118
121
  return {
119
122
  issuer: issuer.href.replace(/\/+$/, ""),
120
123
  audience,
121
124
  clientId: pick(options.clientId, env, "IDP_CLIENT_ID"),
122
125
  clientSecret: pick(options.clientSecret, env, "IDP_CLIENT_SECRET"),
123
- acceptOwnTokens: options.acceptOwnTokens ?? false
126
+ acceptOwnTokens: options.acceptOwnTokens ?? false,
127
+ resourceMetadata
124
128
  };
125
129
  }
130
+ function resourceMetadataConfig(options, env, audience, problems) {
131
+ const setting = options.resourceMetadata ?? pick(void 0, env, "IDP_RESOURCE_METADATA");
132
+ if (setting === void 0 || setting === false || setting === "false") return void 0;
133
+ if (typeof setting === "string" && setting !== "true") {
134
+ problems.push('resourceMetadata (IDP_RESOURCE_METADATA) must be "true" or "false"');
135
+ return void 0;
136
+ }
137
+ const url = URL.canParse(audience) ? new URL(audience) : void 0;
138
+ if (!url || url.protocol !== "https:" && url.protocol !== "http:" || url.search || url.hash) {
139
+ problems.push(
140
+ "resourceMetadata needs audience (IDP_AUDIENCE) to be an http(s) URL with no query, like https://mcp.example.com/mcp"
141
+ );
142
+ return void 0;
143
+ }
144
+ const own = url.pathname.replace(/\/+$/, "");
145
+ const path2 = `${RESOURCE_METADATA_PATH}${own}`;
146
+ const details = typeof setting === "object" ? setting : {};
147
+ const scopes = [...new Set((details.scopes ?? []).map((scope) => scope.trim()))].filter(
148
+ (scope) => scope !== "" && scope !== "offline_access"
149
+ );
150
+ if (scopes.some((scope) => /\s/.test(scope))) {
151
+ problems.push("resourceMetadata's scopes can't hold spaces");
152
+ }
153
+ return { url: `${url.origin}${path2}`, path: path2, scopes, name: details.name?.trim() || void 0 };
154
+ }
126
155
  function resolveServiceConfig(options) {
127
156
  const env = envOf(options);
128
157
  const problems = [];
@@ -184,6 +213,10 @@ function resolveConfig(options) {
184
213
  const afterSignIn = path(options.afterSignIn, "afterSignIn", "/", problems);
185
214
  const afterSignOut = path(options.afterSignOut, "afterSignOut", "/", problems);
186
215
  const errorPath = path(options.errorPath, "errorPath", "/", problems);
216
+ const pushedAuthorization = options.pushedAuthorization ?? false;
217
+ if (pushedAuthorization !== true && pushedAuthorization !== false && pushedAuthorization !== "auto") {
218
+ problems.push('pushedAuthorization must be true, false or "auto"');
219
+ }
187
220
  const sessionMaxAge = options.sessionMaxAge ?? SEVEN_DAYS;
188
221
  if (!Number.isInteger(sessionMaxAge) || sessionMaxAge < 60) {
189
222
  problems.push("sessionMaxAge must be a whole number of seconds, at least 60");
@@ -219,6 +252,7 @@ function resolveConfig(options) {
219
252
  signOutOfIdp: options.signOutOfIdp ?? false,
220
253
  reauthenticateAfterSignOut: options.reauthenticateAfterSignOut ?? false,
221
254
  userinfo: options.userinfo ?? false,
255
+ pushedAuthorization,
222
256
  sessionMaxAge,
223
257
  secure,
224
258
  cookies: {
@@ -234,6 +268,7 @@ function resolveConfig(options) {
234
268
  // Annotate the CommonJS export names for ESM import in node:
235
269
  0 && (module.exports = {
236
270
  DEFAULT_SCOPES,
271
+ RESOURCE_METADATA_PATH,
237
272
  resolveApiConfig,
238
273
  resolveConfig,
239
274
  resolveServiceConfig
@@ -11,6 +11,8 @@ declare const DiscoverySchema: v.ObjectSchema<{
11
11
  readonly introspection_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
12
12
  /** RP-initiated logout: where to send someone to sign out of the auth server too. */
13
13
  readonly end_session_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
14
+ /** RFC 9126: where a sign-in's parameters can be pushed first (`pushedAuthorization`). */
15
+ readonly pushed_authorization_request_endpoint: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.UrlAction<string, undefined>]>, undefined>;
14
16
  readonly id_token_signing_alg_values_supported: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
15
17
  }, undefined>;
16
18
  export type Discovery = v.InferOutput<typeof DiscoverySchema>;
@@ -46,6 +46,8 @@ const DiscoverySchema = v.object({
46
46
  introspection_endpoint: v.optional(Url),
47
47
  /** RP-initiated logout: where to send someone to sign out of the auth server too. */
48
48
  end_session_endpoint: v.optional(Url),
49
+ /** RFC 9126: where a sign-in's parameters can be pushed first (`pushedAuthorization`). */
50
+ pushed_authorization_request_endpoint: v.optional(Url),
49
51
  id_token_signing_alg_values_supported: v.optional(v.array(v.string()))
50
52
  });
51
53
  const ONE_HOUR = 60 * 60 * 1e3;
@@ -32,6 +32,13 @@ export type IdpErrorCode = SignInErrorCode
32
32
  | "insufficient_scope"
33
33
  /** The token endpoint refused this service's client credentials, or didn't answer. */
34
34
  | "service_token_failed"
35
+ /** The token endpoint refused a token exchange (RFC 8693), or didn't answer. */
36
+ | "token_exchange_failed"
37
+ /**
38
+ * A sign-in's pushed authorization request (RFC 9126) was refused or got no answer, or
39
+ * `pushedAuthorization: true` and the auth server doesn't advertise the endpoint.
40
+ */
41
+ | "pushed_authorization_failed"
35
42
  /** A back-channel logout request's token didn't verify, or isn't a logout token. */
36
43
  | "invalid_logout_token";
37
44
  /** The three codes an API answers a caller with; see `tokenErrorResponse`. */
@@ -52,12 +59,18 @@ export declare class IdpError extends Error {
52
59
  * the status to answer the caller with (401 or 403).
53
60
  */
54
61
  readonly status: number | undefined;
55
- /** For insufficient_scope: the scopes the route needs, for the WWW-Authenticate challenge. */
62
+ /** For a token error: the scopes the route needs, for the WWW-Authenticate challenge. */
56
63
  readonly scopes: readonly string[] | undefined;
64
+ /**
65
+ * For a token error: this API's protected resource metadata (RFC 9728), named in the
66
+ * challenge so a client (an MCP client) can find the auth server.
67
+ */
68
+ readonly resourceMetadata: string | undefined;
57
69
  constructor(code: IdpErrorCode, message: string, options?: {
58
- status?: number;
70
+ status?: number | undefined;
59
71
  cause?: unknown;
60
- scopes?: readonly string[];
72
+ scopes?: readonly string[] | undefined;
73
+ resourceMetadata?: string | undefined;
61
74
  });
62
75
  }
63
76
  export declare function isIdpError(error: unknown): error is IdpError;
@@ -47,13 +47,19 @@ class IdpError extends Error {
47
47
  * the status to answer the caller with (401 or 403).
48
48
  */
49
49
  status;
50
- /** For insufficient_scope: the scopes the route needs, for the WWW-Authenticate challenge. */
50
+ /** For a token error: the scopes the route needs, for the WWW-Authenticate challenge. */
51
51
  scopes;
52
+ /**
53
+ * For a token error: this API's protected resource metadata (RFC 9728), named in the
54
+ * challenge so a client (an MCP client) can find the auth server.
55
+ */
56
+ resourceMetadata;
52
57
  constructor(code, message, options) {
53
58
  super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
54
59
  this.code = code;
55
60
  this.status = options?.status;
56
61
  this.scopes = options?.scopes;
62
+ this.resourceMetadata = options?.resourceMetadata;
57
63
  }
58
64
  }
59
65
  function isIdpError(error) {
@@ -0,0 +1,21 @@
1
+ import type { ServiceConfig } from "./config.js";
2
+ import type { Discovery } from "./discovery.js";
3
+ import type { Http } from "./http.js";
4
+ export type ExchangeTokenOptions = {
5
+ /** The access token this API was called with (the person's). */
6
+ subjectToken: string;
7
+ /** The API to get a token for, exactly as the auth server lists it (RFC 8707). */
8
+ resource: string;
9
+ /** The scopes to pass on (default: all the policy allows of the subject's). */
10
+ scopes?: readonly string[] | undefined;
11
+ /** Ask again even if a token is kept. */
12
+ fresh?: boolean | undefined;
13
+ };
14
+ export type TokenExchange = {
15
+ exchange(options: ExchangeTokenOptions): Promise<string>;
16
+ };
17
+ export declare function createTokenExchange(deps: {
18
+ http: Http;
19
+ discovery: () => Promise<Discovery>;
20
+ config: ServiceConfig;
21
+ }): TokenExchange;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var exchange_exports = {};
20
+ __export(exchange_exports, {
21
+ createTokenExchange: () => createTokenExchange
22
+ });
23
+ module.exports = __toCommonJS(exchange_exports);
24
+ var import_errors = require("./errors.js");
25
+ var import_service = require("./service.js");
26
+ var import_token_cache = require("./token-cache.js");
27
+ var import_tokens = require("./tokens.js");
28
+ const MAX_KEPT = 500;
29
+ function expiryOf(token) {
30
+ const [, payload] = token.split(".");
31
+ if (!payload) return void 0;
32
+ try {
33
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
34
+ const exp = JSON.parse(json).exp;
35
+ return typeof exp === "number" ? exp : void 0;
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ async function sha256(value) {
41
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
42
+ return btoa(String.fromCharCode(...new Uint8Array(digest)));
43
+ }
44
+ function createTokenExchange(deps) {
45
+ const cache = (0, import_token_cache.createTokenCache)(MAX_KEPT);
46
+ const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
47
+ return {
48
+ async exchange(options) {
49
+ const resource = (0, import_service.resourceOf)(options.resource);
50
+ if (!resource) {
51
+ throw new import_errors.IdpError(
52
+ "misconfigured",
53
+ "nextidp is misconfigured: exchangeToken needs resource."
54
+ );
55
+ }
56
+ const scope = (0, import_service.scopeOf)(options.scopes);
57
+ const key = JSON.stringify([await sha256(options.subjectToken), resource, scope ?? null]);
58
+ return cache.get(
59
+ key,
60
+ async () => (0, import_token_cache.issued)(
61
+ await (0, import_tokens.exchangeAccessToken)(deps.http, await deps.discovery(), client, {
62
+ subjectToken: options.subjectToken,
63
+ resource,
64
+ scope
65
+ }),
66
+ expiryOf(options.subjectToken)
67
+ ),
68
+ options.fresh
69
+ );
70
+ }
71
+ };
72
+ }
73
+ // Annotate the CommonJS export names for ESM import in node:
74
+ 0 && (module.exports = {
75
+ createTokenExchange
76
+ });