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
@@ -41,6 +41,17 @@ export type FastifyIdp = Idp & {
41
41
  requireToken(requirements?: TokenRequirements): IdpHook;
42
42
  /** The access token `requireToken` checked for this request. */
43
43
  tokenOf(request: FastifyRequest): AccessToken | undefined;
44
+ /**
45
+ * For an API with `resourceMetadata` on: a plugin that answers its protected resource
46
+ * metadata (RFC 9728) at `/.well-known/oauth-protected-resource` and the audience's path, so
47
+ * MCP clients find the auth server. Register it on the app itself, not under a prefix: the
48
+ * well-known path is at the root, whatever prefix the API's routes have.
49
+ *
50
+ * ```ts
51
+ * await app.register(auth.resourceMetadata());
52
+ * ```
53
+ */
54
+ resourceMetadata(): FastifyPluginAsync;
44
55
  };
45
56
  /**
46
57
  * The client for a Fastify app or API. An app that signs people in needs the sign-in settings
@@ -57,9 +68,10 @@ export type FastifyIdp = Idp & {
57
68
  * ```
58
69
  */
59
70
  export declare function idp(options?: IdpOptions | (() => IdpOptions)): FastifyIdp;
60
- export type { AccessToken, TokenRequirements } from "./access-token.js";
71
+ export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
61
72
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
62
73
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
74
+ export type { ExchangeTokenOptions } from "./exchange.js";
63
75
  export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
64
76
  export type { SessionOptions } from "./node-adapter.js";
65
77
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -2,7 +2,7 @@ import { tokenRefusal } from "./access-token.js";
2
2
  import { isIdpError, isTokenError } from "./errors.js";
3
3
  import { createIdp } from "./idp.js";
4
4
  import { nodeAdapter } from "./node-adapter.js";
5
- import { pathOf, urlOf } from "./node-http.js";
5
+ import { pathOf, sendWebResponse, urlOf } from "./node-http.js";
6
6
  function authorizationOf(request) {
7
7
  const value = request.headers.authorization;
8
8
  return Array.isArray(value) ? void 0 : value;
@@ -52,6 +52,20 @@ function idp(options) {
52
52
  Object.assign(plugin, { [/* @__PURE__ */ Symbol.for("skip-override")]: true });
53
53
  return plugin;
54
54
  },
55
+ resourceMetadata() {
56
+ const plugin = async (app) => {
57
+ app.addHook("onRequest", async (request, reply) => {
58
+ const response = core.resourceMetadataResponse(
59
+ new Request(new URL(request.url, "http://localhost"), { method: request.method })
60
+ );
61
+ if (!response) return;
62
+ reply.hijack();
63
+ await sendWebResponse(reply.raw, response);
64
+ });
65
+ };
66
+ Object.assign(plugin, { [/* @__PURE__ */ Symbol.for("skip-override")]: true });
67
+ return plugin;
68
+ },
55
69
  requireSession() {
56
70
  return async (request, reply) => {
57
71
  const session = await sessionFor(request, reply);
@@ -37,6 +37,16 @@ export type HonoIdp = Idp & {
37
37
  * WWW-Authenticate (RFC 6750); one that can't be checked now (the auth server is down) 503.
38
38
  */
39
39
  requireToken(requirements?: TokenRequirements): MiddlewareHandler<IdpEnv>;
40
+ /**
41
+ * For an API with `resourceMetadata` on: answers its protected resource metadata (RFC 9728)
42
+ * at `/.well-known/oauth-protected-resource` and the audience's path, so MCP clients find the
43
+ * auth server; every other request goes on.
44
+ *
45
+ * ```ts
46
+ * app.use(auth.resourceMetadata());
47
+ * ```
48
+ */
49
+ resourceMetadata(): MiddlewareHandler<IdpEnv>;
40
50
  };
41
51
  /**
42
52
  * The client for a Hono app or API:
@@ -56,9 +66,10 @@ export type HonoIdp = Idp & {
56
66
  * `idp(() => ({ env: workerEnv }))`.
57
67
  */
58
68
  export declare function idp(options?: IdpOptions | (() => IdpOptions)): HonoIdp;
59
- export type { AccessToken, TokenRequirements } from "./access-token.js";
69
+ export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
60
70
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
61
71
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
72
+ export type { ExchangeTokenOptions } from "./exchange.js";
62
73
  export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
63
74
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
64
75
  export type { IdpUser, Session } from "./session.js";
package/dist/esm/hono.js CHANGED
@@ -61,6 +61,14 @@ function idp(options) {
61
61
  putCookies(c, setCookies);
62
62
  };
63
63
  },
64
+ resourceMetadata() {
65
+ return async (c, next) => {
66
+ const response = core.resourceMetadataResponse(c.req.raw);
67
+ if (response) return response;
68
+ await next();
69
+ return void 0;
70
+ };
71
+ },
64
72
  requireToken(requirements = {}) {
65
73
  return async (c, next) => {
66
74
  let token;
@@ -1,7 +1,7 @@
1
1
  import { createRemoteJWKSet, jwtVerify } from "jose";
2
2
  import { IdpError } from "./errors.js";
3
3
  import { sameString } from "./pkce.js";
4
- const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "EdDSA"];
4
+ const ALLOWED_ALGORITHMS = ["RS256", "PS256", "ES256", "Ed25519", "EdDSA"];
5
5
  function signingAlgorithms(listed) {
6
6
  const algorithms = listed ? listed.filter((alg) => ALLOWED_ALGORITHMS.includes(alg)) : [];
7
7
  return algorithms.length > 0 ? algorithms : ["RS256"];
package/dist/esm/idp.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { type AccessToken, type TokenRequirements } from "./access-token.js";
1
+ import { type AccessToken, type ResourceMetadata, type TokenRequirements } from "./access-token.js";
2
2
  import { type ApiConfig, type IdpConfig, type IdpOptions } from "./config.js";
3
3
  import { IdpError } from "./errors.js";
4
+ import { type ExchangeTokenOptions } from "./exchange.js";
4
5
  import { type InterceptableClient, type ServiceTokenOptions, type UseServiceTokenOptions } from "./service.js";
5
6
  import { type Session } from "./session.js";
6
7
  /** Where cookies are read from: a request, its headers, or the Cookie header itself. */
@@ -53,6 +54,31 @@ export type Idp = {
53
54
  verifyBearer(authorization: string | null | undefined, requirements?: TokenRequirements): Promise<AccessToken>;
54
55
  /** The 401 or 403 for a refused token, with its WWW-Authenticate challenge (RFC 6750). */
55
56
  tokenErrorResponse(error: IdpError): Response;
57
+ /**
58
+ * This API's protected resource metadata (RFC 9728), with `resourceMetadata` on: the auth
59
+ * server to sign in with, and the scopes. MCP clients read it to find the auth server.
60
+ */
61
+ resourceMetadataDocument(): ResourceMetadata;
62
+ /**
63
+ * The answer to a request for the protected resource metadata (at
64
+ * `/.well-known/oauth-protected-resource` and the audience's path), or undefined for any
65
+ * other request, or while `resourceMetadata` is off. The adapters' `resourceMetadata()`
66
+ * serve it.
67
+ */
68
+ resourceMetadataResponse(request: Request): Response | undefined;
69
+ /**
70
+ * Token exchange (RFC 8693), for an MCP server that calls another API as the person: the
71
+ * access token it was called with, traded for one meant for `resource`, with this
72
+ * service's credentials (`clientId` and `clientSecret`) and within the policy the auth
73
+ * server has for it. Kept until a minute before it expires, never past the token it came
74
+ * from; calls at the same time share one request. Throws IdpError("token_exchange_failed")
75
+ * when the auth server refuses or doesn't answer.
76
+ *
77
+ * ```ts
78
+ * const crm = await auth.exchangeToken({ subjectToken: token.raw, resource: "https://crm.example.com" });
79
+ * ```
80
+ */
81
+ exchangeToken(options: ExchangeTokenOptions): Promise<string>;
56
82
  /**
57
83
  * This service's own access token (client credentials), to call another API as itself.
58
84
  * Kept until a minute before it expires, per scopes and API; calls at the same time share
package/dist/esm/idp.js CHANGED
@@ -3,6 +3,8 @@ import {
3
3
  introspect,
4
4
  isJwt,
5
5
  requireScopes,
6
+ resourceMetadataDocument,
7
+ resourceMetadataResponse,
6
8
  tokenRefusal,
7
9
  verifyJwtAccessToken
8
10
  } from "./access-token.js";
@@ -19,11 +21,13 @@ import {
19
21
  writeCookie
20
22
  } from "./cookies.js";
21
23
  import { createDiscovery } from "./discovery.js";
22
- import { IdpError, isIdpError } from "./errors.js";
24
+ import { IdpError, isIdpError, isTokenError } from "./errors.js";
25
+ import { createTokenExchange } from "./exchange.js";
23
26
  import { createIdpHttp } from "./http.js";
24
27
  import { createKeys, verifyIdToken } from "./id-token.js";
25
28
  import { verifyLogoutToken } from "./logout-token.js";
26
29
  import { challengeFor, randomToken, sameString } from "./pkce.js";
30
+ import { pushAuthorizationRequest } from "./pushed-authorization.js";
27
31
  import { safePath } from "./return-path.js";
28
32
  import { Sealer } from "./sealed.js";
29
33
  import {
@@ -102,6 +106,7 @@ function createIdp(options = {}) {
102
106
  let state;
103
107
  let apiState;
104
108
  let serviceTokens;
109
+ let tokenExchange;
105
110
  const shared = /* @__PURE__ */ new Map();
106
111
  let resolvedOptions;
107
112
  const optionsOf = () => {
@@ -151,6 +156,13 @@ function createIdp(options = {}) {
151
156
  serviceTokens = createServiceTokens({ http, discovery, config });
152
157
  return serviceTokens;
153
158
  };
159
+ const exchangeReady = () => {
160
+ if (tokenExchange) return tokenExchange;
161
+ const config = resolveServiceConfig(optionsOf());
162
+ const { http, discovery } = sharedFor(config.issuer);
163
+ tokenExchange = createTokenExchange({ http, discovery, config });
164
+ return tokenExchange;
165
+ };
154
166
  const introspectCached = async (s, discovery, token) => {
155
167
  const key = await sha256(token);
156
168
  const now = Date.now();
@@ -171,11 +183,21 @@ function createIdp(options = {}) {
171
183
  });
172
184
  return checked;
173
185
  };
186
+ const refusalFor = (error, s, requirements) => new IdpError(error.code, error.message, {
187
+ status: error.status,
188
+ cause: error.cause,
189
+ scopes: requirements.scopes?.length ? requirements.scopes : error.scopes,
190
+ resourceMetadata: s.config.resourceMetadata?.url
191
+ });
174
192
  const verifyAccessToken = async (token, requirements = {}) => {
175
193
  const s = apiReady();
176
- const discovery = await s.discovery();
177
- const checked = isJwt(token) ? await verifyJwtAccessToken(token, s.keys(discovery.jwks_uri), s.config) : await introspectCached(s, discovery, token);
178
- return requireScopes(checked, requirements.scopes);
194
+ try {
195
+ const discovery = await s.discovery();
196
+ const checked = isJwt(token) ? await verifyJwtAccessToken(token, s.keys(discovery.jwks_uri), s.config) : await introspectCached(s, discovery, token);
197
+ return { ...requireScopes(checked, requirements.scopes), raw: token };
198
+ } catch (error) {
199
+ throw isTokenError(error) ? refusalFor(error, s, requirements) : error;
200
+ }
179
201
  };
180
202
  const fail = (error) => {
181
203
  const idpError = isIdpError(error) ? error : new IdpError("token_failed", "Something went wrong.", { cause: error });
@@ -277,6 +299,13 @@ function createIdp(options = {}) {
277
299
  setCookies: clear()
278
300
  };
279
301
  }
302
+ function pushEndpoint(s, discovery) {
303
+ const setting = s.config.pushedAuthorization;
304
+ if (setting === false) return void 0;
305
+ const endpoint = discovery.pushed_authorization_request_endpoint;
306
+ if (endpoint) return endpoint;
307
+ return setting === true ? "missing" : void 0;
308
+ }
280
309
  async function login(s, request, url) {
281
310
  const returnTo = safePath(url.searchParams.get("returnTo")) ?? s.config.afterSignIn;
282
311
  const { prompt, setCookies } = promptOf(s, request, url);
@@ -288,8 +317,7 @@ function createIdp(options = {}) {
288
317
  return plain(503, "The sign-in service can't be reached. Try again in a moment.");
289
318
  }
290
319
  const flow = { verifier: randomToken(), state: randomToken(), nonce: randomToken(), returnTo };
291
- const authorize = new URL(discovery.authorization_endpoint);
292
- authorize.search = new URLSearchParams({
320
+ const parameters = new URLSearchParams({
293
321
  response_type: "code",
294
322
  client_id: s.config.clientId,
295
323
  redirect_uri: s.config.redirectUri,
@@ -300,7 +328,33 @@ function createIdp(options = {}) {
300
328
  code_challenge_method: "S256",
301
329
  ...s.config.resource ? { resource: s.config.resource } : {},
302
330
  ...prompt ? { prompt } : {}
303
- }).toString();
331
+ });
332
+ const authorize = new URL(discovery.authorization_endpoint);
333
+ const push = pushEndpoint(s, discovery);
334
+ if (push === "missing") {
335
+ fail(
336
+ new IdpError(
337
+ "pushed_authorization_failed",
338
+ "pushedAuthorization is true, and the auth server doesn't advertise pushed_authorization_request_endpoint."
339
+ )
340
+ );
341
+ return plain(503, "The sign-in service can't be reached. Try again in a moment.");
342
+ }
343
+ if (push) {
344
+ let requestUri;
345
+ try {
346
+ requestUri = await pushAuthorizationRequest(s.http, push, s.client, parameters);
347
+ } catch (error) {
348
+ fail(error);
349
+ return plain(503, "The sign-in service can't be reached. Try again in a moment.");
350
+ }
351
+ authorize.search = new URLSearchParams({
352
+ client_id: s.config.clientId,
353
+ request_uri: requestUri
354
+ }).toString();
355
+ } else {
356
+ authorize.search = parameters.toString();
357
+ }
304
358
  const sealed = await s.sealer.seal(flow, FLOW_PURPOSE, FLOW_MAX_AGE);
305
359
  return redirect(authorize.toString(), 302, [
306
360
  // Lax: the cookie comes back on the top-level redirect from the auth server.
@@ -509,10 +563,14 @@ function createIdp(options = {}) {
509
563
  },
510
564
  apiConfig: () => apiReady().config,
511
565
  verifyAccessToken,
512
- async verifyBearer(authorization, requirements) {
566
+ async verifyBearer(authorization, requirements = {}) {
513
567
  const token = bearerToken(authorization);
514
568
  if (!token) {
515
- throw new IdpError("missing_token", "An access token is required.", { status: 401 });
569
+ throw refusalFor(
570
+ new IdpError("missing_token", "An access token is required.", { status: 401 }),
571
+ apiReady(),
572
+ requirements
573
+ );
516
574
  }
517
575
  return verifyAccessToken(token, requirements);
518
576
  },
@@ -523,6 +581,18 @@ function createIdp(options = {}) {
523
581
  headers: refusal.headers
524
582
  });
525
583
  },
584
+ resourceMetadataDocument() {
585
+ const document = resourceMetadataDocument(apiReady().config);
586
+ if (!document) {
587
+ throw new IdpError(
588
+ "misconfigured",
589
+ "nextidp is misconfigured: resourceMetadata (IDP_RESOURCE_METADATA) is off."
590
+ );
591
+ }
592
+ return document;
593
+ },
594
+ resourceMetadataResponse: (request) => resourceMetadataResponse(apiReady().config, request),
595
+ exchangeToken: async (options2) => exchangeReady().exchange(options2),
526
596
  serviceToken: async (options2) => serviceReady().get(options2),
527
597
  dropServiceToken(token) {
528
598
  serviceTokens?.drop(token);
@@ -1,7 +1,8 @@
1
- export { type AccessToken, bearerChallenge, bearerToken, type TokenRequirements, } from "./access-token.js";
2
- export type { ApiConfig, IdpConfig, IdpOptions, ServiceConfig } from "./config.js";
1
+ export { type AccessToken, bearerChallenge, bearerToken, type ResourceMetadata, type TokenRequirements, } from "./access-token.js";
2
+ export type { ApiConfig, IdpConfig, IdpOptions, ResourceMetadataConfig, ServiceConfig, } from "./config.js";
3
3
  export { DEFAULT_SCOPES } from "./config.js";
4
4
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
5
+ export type { ExchangeTokenOptions } from "./exchange.js";
5
6
  export { type CookieSource, createIdp as idp, type Idp, type Refreshed, type SignInPathOptions, } from "./idp.js";
6
7
  export { safePath } from "./return-path.js";
7
8
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -46,8 +46,9 @@ export declare class IdpModule {
46
46
  static forRoot(auth?: Idp | IdpOptions, options?: IdpModuleOptions): DynamicModule;
47
47
  static forRootAsync(options: IdpModuleAsyncOptions): DynamicModule;
48
48
  }
49
- export type { AccessToken, TokenRequirements } from "./access-token.js";
49
+ export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
50
50
  export type { ApiConfig, IdpOptions } from "./config.js";
51
51
  export { IdpError, isIdpError, isTokenError, type TokenErrorCode } from "./errors.js";
52
+ export type { ExchangeTokenOptions } from "./exchange.js";
52
53
  export { createIdp as idp, type Idp } from "./idp.js";
53
54
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
@@ -39,6 +39,16 @@ export type NextIdp = Idp & {
39
39
  * );
40
40
  * ```
41
41
  */
42
+ /**
43
+ * For an API with `resourceMetadata` on: its protected resource metadata (RFC 9728), so MCP
44
+ * clients find the auth server. In
45
+ * `app/.well-known/oauth-protected-resource/[[...path]]/route.ts`:
46
+ * `export const { GET, OPTIONS } = auth.resourceMetadata();`
47
+ */
48
+ resourceMetadata(): {
49
+ GET: (request: Request) => Response;
50
+ OPTIONS: (request: Request) => Response;
51
+ };
42
52
  withToken<Context extends object = object>(requirements: TokenRequirements, handler: (request: NextRequest, context: Context & {
43
53
  token: AccessToken;
44
54
  }) => Response | Promise<Response>): (request: NextRequest, context: Context) => Promise<Response>;
@@ -52,9 +62,10 @@ export type NextIdp = Idp & {
52
62
  * ```
53
63
  */
54
64
  export declare function idp(options?: IdpOptions | (() => IdpOptions)): NextIdp;
55
- export type { AccessToken, TokenRequirements } from "./access-token.js";
65
+ export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
56
66
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
57
67
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
68
+ export type { ExchangeTokenOptions } from "./exchange.js";
58
69
  export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
59
70
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
60
71
  export type { IdpUser, Session } from "./session.js";
package/dist/esm/next.js CHANGED
@@ -35,6 +35,10 @@ function idp(options) {
35
35
  return {
36
36
  ...core,
37
37
  routes: () => ({ GET: handle, POST: handle }),
38
+ resourceMetadata() {
39
+ const answer = (request) => core.resourceMetadataResponse(request) ?? new Response("Not found", { status: 404 });
40
+ return { GET: answer, OPTIONS: answer };
41
+ },
38
42
  session,
39
43
  async requireSession(returnTo) {
40
44
  const current = await session();
@@ -12,5 +12,7 @@ export type NodeAdapter = {
12
12
  handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
13
13
  session(req: IncomingMessage, res: ServerResponse, options?: SessionOptions): Promise<Session | null>;
14
14
  turnAway(req: IncomingMessage, res: ServerResponse, returnTo?: string): void;
15
+ /** Answers a request for the protected resource metadata and returns true; else false. */
16
+ resourceMetadata(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
15
17
  };
16
18
  export declare function nodeAdapter(core: Idp): NodeAdapter;
@@ -26,6 +26,14 @@ function nodeAdapter(core) {
26
26
  await sendWebResponse(res, await core.handler(request));
27
27
  return true;
28
28
  },
29
+ async resourceMetadata(req, res) {
30
+ const response = core.resourceMetadataResponse(
31
+ new Request(new URL(req.url ?? "/", "http://localhost"), { method: req.method ?? "GET" })
32
+ );
33
+ if (!response) return false;
34
+ await sendWebResponse(res, response);
35
+ return true;
36
+ },
29
37
  session(req, res, { refresh = true } = {}) {
30
38
  const known = sessions.get(req);
31
39
  if (known) return known;
@@ -21,6 +21,11 @@ export type NodeIdp = Idp & {
21
21
  * response is sent.
22
22
  */
23
23
  requireSession(req: IncomingMessage, res: ServerResponse, returnTo?: string): Promise<Session | null>;
24
+ /**
25
+ * For an API with `resourceMetadata` on: answers a request for its protected resource
26
+ * metadata (RFC 9728) and returns true; any other path is left to you, and it returns false.
27
+ */
28
+ resourceMetadata(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
24
29
  };
25
30
  /**
26
31
  * The client for an app on Node's own HTTP server:
@@ -40,9 +45,10 @@ export type NodeIdp = Idp & {
40
45
  * ```
41
46
  */
42
47
  export declare function idp(options?: IdpOptions | (() => IdpOptions)): NodeIdp;
43
- export type { AccessToken, TokenRequirements } from "./access-token.js";
48
+ export type { AccessToken, ResourceMetadata, TokenRequirements } from "./access-token.js";
44
49
  export type { ApiConfig, IdpConfig, IdpOptions } from "./config.js";
45
50
  export { IdpError, type IdpErrorCode, isIdpError, isSignInErrorCode, isTokenError, SIGN_IN_ERROR_CODES, type SignInErrorCode, type TokenErrorCode, } from "./errors.js";
51
+ export type { ExchangeTokenOptions } from "./exchange.js";
46
52
  export type { Idp, Refreshed, SignInPathOptions } from "./idp.js";
47
53
  export type { SessionOptions } from "./node-adapter.js";
48
54
  export type { InterceptableClient, ServiceTokenOptions, UseServiceTokenOptions, } from "./service.js";
package/dist/esm/node.js CHANGED
@@ -7,6 +7,7 @@ function idp(options) {
7
7
  ...core,
8
8
  handle: node.handle,
9
9
  session: node.session,
10
+ resourceMetadata: node.resourceMetadata,
10
11
  async requireSession(req, res, returnTo) {
11
12
  const session = await node.session(req, res);
12
13
  if (!session) node.turnAway(req, res, returnTo);
@@ -0,0 +1,9 @@
1
+ import type { Http } from "./http.js";
2
+ import { type Client } from "./tokens.js";
3
+ /**
4
+ * Posts the authorization request's parameters, authenticated as at the token endpoint (Basic
5
+ * for a confidential client, client_id in the body for a public one), and returns the
6
+ * request_uri. One attempt, no retries: a request_uri works once, for 60 seconds on
7
+ * Next-Identity Server, so it's asked for at the moment of the redirect.
8
+ */
9
+ export declare function pushAuthorizationRequest(http: Http, endpoint: string, client: Client, parameters: URLSearchParams): Promise<string>;
@@ -0,0 +1,32 @@
1
+ import * as v from "valibot";
2
+ import { IdpError } from "./errors.js";
3
+ import { authenticate, oauthError } from "./tokens.js";
4
+ const PushedRequestSchema = v.object({
5
+ request_uri: v.pipe(v.string(), v.nonEmpty()),
6
+ expires_in: v.number()
7
+ });
8
+ async function pushAuthorizationRequest(http, endpoint, client, parameters) {
9
+ const form = new URLSearchParams(parameters);
10
+ const headers = authenticate(client, form);
11
+ let answer;
12
+ try {
13
+ answer = await http.postForm(endpoint, form, headers);
14
+ } catch (cause) {
15
+ throw new IdpError("pushed_authorization_failed", "The PAR endpoint didn't answer.", { cause });
16
+ }
17
+ if (!answer.ok) {
18
+ throw new IdpError(
19
+ "pushed_authorization_failed",
20
+ `The PAR endpoint refused: ${oauthError(answer.data) ?? answer.status}.`,
21
+ { status: answer.status }
22
+ );
23
+ }
24
+ const parsed = v.safeParse(PushedRequestSchema, answer.data);
25
+ if (!parsed.success) {
26
+ throw new IdpError("pushed_authorization_failed", "The PAR endpoint's answer isn't valid.");
27
+ }
28
+ return parsed.output.request_uri;
29
+ }
30
+ export {
31
+ pushAuthorizationRequest
32
+ };
@@ -40,6 +40,9 @@ export type InterceptableClient = {
40
40
  };
41
41
  };
42
42
  };
43
+ /** The scopes as the token endpoint gets them, sorted, so the same set is one key. */
44
+ export declare function scopeOf(scopes: readonly string[] | undefined): string | undefined;
45
+ export declare function resourceOf(resource: string | undefined): string | undefined;
43
46
  export type ServiceTokens = {
44
47
  get(options?: ServiceTokenOptions): Promise<string>;
45
48
  drop(token: string): void;
@@ -1,7 +1,7 @@
1
1
  import { bearerToken } from "./access-token.js";
2
2
  import { IdpError } from "./errors.js";
3
+ import { createTokenCache, issued } from "./token-cache.js";
3
4
  import { clientCredentials } from "./tokens.js";
4
- const RENEW_BEFORE_S = 60;
5
5
  const MAX_KEPT = 100;
6
6
  function misconfigured(problem) {
7
7
  return new IdpError("misconfigured", `nextidp is misconfigured: ${problem}.`);
@@ -19,54 +19,22 @@ function resourceOf(resource) {
19
19
  return resource;
20
20
  }
21
21
  function createServiceTokens(deps) {
22
- const kept = /* @__PURE__ */ new Map();
22
+ const cache = createTokenCache(MAX_KEPT);
23
23
  const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
24
- const issue = async (scope, resource) => {
25
- const tokens = await clientCredentials(deps.http, await deps.discovery(), client, {
26
- scope,
27
- resource
28
- });
29
- const lifetime = tokens.expires_in ?? 0;
30
- const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
31
- return { token: tokens.access_token, until: Date.now() + Math.max(0, renewIn) * 1e3 };
32
- };
33
- const prune = (now) => {
34
- for (const [key, entry] of kept) {
35
- if (entry.issued && entry.issued.until <= now) kept.delete(key);
36
- }
37
- const oldest = kept.keys().next();
38
- if (kept.size >= MAX_KEPT && !oldest.done) kept.delete(oldest.value);
39
- };
40
24
  return {
41
25
  async get(options = {}) {
42
26
  const scope = scopeOf(options.scopes);
43
27
  const resource = resourceOf(options.resource ?? deps.config.resource);
44
28
  const key = JSON.stringify([resource ?? null, scope ?? null]);
45
- const now = Date.now();
46
- const known = kept.get(key);
47
- if (known && !options.fresh) {
48
- if (!known.issued) return (await known.pending).token;
49
- if (known.issued.until > now) return known.issued.token;
50
- }
51
- if (kept.size >= MAX_KEPT) prune(now);
52
- const entry = { pending: issue(scope, resource) };
53
- entry.pending.then(
54
- (issued) => {
55
- entry.issued = issued;
56
- },
57
- () => void 0
29
+ return cache.get(
30
+ key,
31
+ async () => issued(
32
+ await clientCredentials(deps.http, await deps.discovery(), client, { scope, resource })
33
+ ),
34
+ options.fresh
58
35
  );
59
- kept.set(key, entry);
60
- try {
61
- return (await entry.pending).token;
62
- } catch (error) {
63
- if (kept.get(key) === entry) kept.delete(key);
64
- throw error;
65
- }
66
- },
67
- drop(token) {
68
- for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
69
36
  },
37
+ drop: (token) => cache.drop(token),
70
38
  defaultResource: deps.config.resource
71
39
  };
72
40
  }
@@ -144,5 +112,7 @@ function useServiceToken(tokens, client, options = {}) {
144
112
  }
145
113
  export {
146
114
  createServiceTokens,
115
+ resourceOf,
116
+ scopeOf,
147
117
  useServiceToken
148
118
  };
@@ -0,0 +1,18 @@
1
+ import type { TokenResponse } from "./tokens.js";
2
+ export type Issued = {
3
+ token: string;
4
+ until: number;
5
+ };
6
+ /**
7
+ * What to keep of a token endpoint's answer: the token, and when to stop using it. One that
8
+ * says no lifetime isn't kept at all. `notAfter` (seconds since the epoch) caps it, for a
9
+ * token that must not outlive another.
10
+ */
11
+ export declare function issued(tokens: TokenResponse, notAfter?: number): Issued;
12
+ export type TokenCache = {
13
+ /** The token kept under `key`, or a new one from `issue`; calls at once share one request. */
14
+ get(key: string, issue: () => Promise<Issued>, fresh?: boolean): Promise<string>;
15
+ /** Forgets a token, wherever it's kept. */
16
+ drop(token: string): void;
17
+ };
18
+ export declare function createTokenCache(maxKept: number): TokenCache;
@@ -0,0 +1,50 @@
1
+ const RENEW_BEFORE_S = 60;
2
+ function issued(tokens, notAfter) {
3
+ const lifetime = tokens.expires_in ?? 0;
4
+ const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
5
+ let until = Date.now() + Math.max(0, renewIn) * 1e3;
6
+ if (notAfter !== void 0) until = Math.min(until, (notAfter - RENEW_BEFORE_S) * 1e3);
7
+ return { token: tokens.access_token, until };
8
+ }
9
+ function createTokenCache(maxKept) {
10
+ const kept = /* @__PURE__ */ new Map();
11
+ const prune = (now) => {
12
+ for (const [key, entry] of kept) {
13
+ if (entry.issued && entry.issued.until <= now) kept.delete(key);
14
+ }
15
+ const oldest = kept.keys().next();
16
+ if (kept.size >= maxKept && !oldest.done) kept.delete(oldest.value);
17
+ };
18
+ return {
19
+ async get(key, issue, fresh = false) {
20
+ const now = Date.now();
21
+ const known = kept.get(key);
22
+ if (known && !fresh) {
23
+ if (!known.issued) return (await known.pending).token;
24
+ if (known.issued.until > now) return known.issued.token;
25
+ }
26
+ if (kept.size >= maxKept) prune(now);
27
+ const entry = { pending: issue() };
28
+ entry.pending.then(
29
+ (value) => {
30
+ entry.issued = value;
31
+ },
32
+ () => void 0
33
+ );
34
+ kept.set(key, entry);
35
+ try {
36
+ return (await entry.pending).token;
37
+ } catch (error) {
38
+ if (kept.get(key) === entry) kept.delete(key);
39
+ throw error;
40
+ }
41
+ },
42
+ drop(token) {
43
+ for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
44
+ }
45
+ };
46
+ }
47
+ export {
48
+ createTokenCache,
49
+ issued
50
+ };