@udibo/oauth2 0.45.1 → 0.46.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.
@@ -47,7 +47,29 @@ export interface DevIdpClientConfig {
47
47
  * service-account user, never a human owner.
48
48
  */
49
49
  ownerUserId?: string;
50
+ /**
51
+ * `"opaque"` (the default) issues random access tokens that only this
52
+ * server can resolve, through introspection or UserInfo. `"jwt"` issues
53
+ * RFC 9068 `at+jwt` access tokens signed with the key `/jwks` publishes,
54
+ * so an API can verify them offline with `JwksTokenReader`. Every grant
55
+ * and `/__admin/tokens` honour it.
56
+ */
57
+ accessTokenFormat?: DevIdpAccessTokenFormat;
58
+ /**
59
+ * The `aud` claim of this client's JWT access tokens. Defaults to the
60
+ * client id. Only meaningful with `accessTokenFormat: "jwt"`; the config
61
+ * parser refuses it on an opaque client.
62
+ */
63
+ audience?: string;
50
64
  }
65
+ /** How a client's access tokens are minted. */
66
+ export type DevIdpAccessTokenFormat = "opaque" | "jwt";
67
+ /**
68
+ * The `aud` a client's JWT access tokens carry: its `audience`, else its id.
69
+ * `undefined` for a client whose access tokens are opaque, which ignores any
70
+ * `audience` it sets.
71
+ */
72
+ export declare function jwtAudienceOf(client: DevIdpClientConfig): string | undefined;
51
73
  /**
52
74
  * A fully resolved configuration. Every field the server needs is present:
53
75
  * {@link parseDevIdpConfig} fills the defaults so nothing downstream has to.
@@ -6,6 +6,16 @@
6
6
  * @module
7
7
  */
8
8
  import { readFile } from "node:fs/promises";
9
+ /**
10
+ * The `aud` a client's JWT access tokens carry: its `audience`, else its id.
11
+ * `undefined` for a client whose access tokens are opaque, which ignores any
12
+ * `audience` it sets.
13
+ */
14
+ export function jwtAudienceOf(client) {
15
+ if (client.accessTokenFormat !== "jwt")
16
+ return undefined;
17
+ return client.audience ?? client.id;
18
+ }
9
19
  const DEFAULT_PORT = 9000;
10
20
  const DEFAULT_HOSTNAME = "127.0.0.1";
11
21
  const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
@@ -35,7 +45,15 @@ const CONFIG_FIELDS = [
35
45
  "clients",
36
46
  ];
37
47
  const USER_FIELDS = ["id", "username", "password", "claims"];
38
- const CLIENT_FIELDS = ["id", "secret", "redirectUris", "grants", "ownerUserId"];
48
+ const CLIENT_FIELDS = [
49
+ "id",
50
+ "secret",
51
+ "redirectUris",
52
+ "grants",
53
+ "ownerUserId",
54
+ "accessTokenFormat",
55
+ "audience",
56
+ ];
39
57
  /**
40
58
  * The configuration used when `idp dev` runs without `--config`: one
41
59
  * confidential client, one public client, and one user, all on well-known
@@ -68,11 +86,13 @@ export function defaultDevIdpConfig() {
68
86
  redirectUris: [...DEFAULT_REDIRECT_URIS],
69
87
  grants: ["authorization_code", "refresh_token", "client_credentials"],
70
88
  ownerUserId: "user-alice",
89
+ accessTokenFormat: "opaque",
71
90
  },
72
91
  {
73
92
  id: "dev-public-client",
74
93
  redirectUris: [...DEFAULT_REDIRECT_URIS],
75
94
  grants: [...DEFAULT_CLIENT_GRANTS],
95
+ accessTokenFormat: "opaque",
76
96
  },
77
97
  ],
78
98
  };
@@ -159,14 +179,30 @@ function parseClient(value, path) {
159
179
  if (grants.includes("authorization_code") && redirectUris.length === 0) {
160
180
  fail(`${path}.redirectUris`, "must list at least one URI for a client using the authorization_code grant");
161
181
  }
182
+ const id = string(source.id, `${path}.id`);
183
+ const accessTokenFormat = source.accessTokenFormat === undefined
184
+ ? "opaque"
185
+ : parseAccessTokenFormat(source.accessTokenFormat, `${path}.accessTokenFormat`);
186
+ const audience = optionalString(source.audience, `${path}.audience`);
187
+ if (audience !== undefined && accessTokenFormat !== "jwt") {
188
+ fail(`${path}.audience`, 'only applies with "accessTokenFormat": "jwt" (opaque tokens carry no audience)');
189
+ }
162
190
  return {
163
- id: string(source.id, `${path}.id`),
191
+ id,
164
192
  secret: optionalString(source.secret, `${path}.secret`),
165
193
  redirectUris,
166
194
  grants,
167
195
  ownerUserId: optionalString(source.ownerUserId, `${path}.ownerUserId`),
196
+ accessTokenFormat,
197
+ ...(accessTokenFormat === "jwt" ? { audience: audience ?? id } : {}),
168
198
  };
169
199
  }
200
+ function parseAccessTokenFormat(value, path) {
201
+ if (value !== "opaque" && value !== "jwt") {
202
+ fail(path, 'must be "opaque" or "jwt"');
203
+ }
204
+ return value;
205
+ }
170
206
  function parseConsent(value, path) {
171
207
  const consent = string(value, path);
172
208
  if (consent !== "auto" && consent !== "prompt") {
@@ -5,7 +5,7 @@
5
5
  * @module
6
6
  */
7
7
  import { generateSigningKey, importSigningKeyJwk, } from "../../server/signing-keys.js";
8
- import { defaultDevIdpConfig, loadDevIdpConfig, } from "./config.js";
8
+ import { defaultDevIdpConfig, jwtAudienceOf, loadDevIdpConfig, } from "./config.js";
9
9
  import { ADMIN_TOKEN_HEADER, isLoopbackHostname, startDevIdentityProvider, } from "./server.js";
10
10
  const SIGNING_KEY_VARIABLE = "OIDC_SIGNING_KEY";
11
11
  const ADMIN_TOKEN_VARIABLE = "IDP_ADMIN_TOKEN";
@@ -92,7 +92,9 @@ function describeSeed(config) {
92
92
  if (config.clients.length === 0)
93
93
  lines.push(" (none)");
94
94
  for (const client of config.clients) {
95
- lines.push(` ${client.id} ${client.secret ? `secret: ${client.secret}` : "public client"}`, ` grants: ${client.grants.join(", ")}`, ` redirect URIs: ${client.redirectUris.join(", ") || "(none)"}`);
95
+ lines.push(` ${client.id} ${client.secret ? `secret: ${client.secret}` : "public client"}`, ` grants: ${client.grants.join(", ")}`, ` redirect URIs: ${client.redirectUris.join(", ") || "(none)"}`, jwtAudienceOf(client) === undefined
96
+ ? " access tokens: opaque"
97
+ : ` access tokens: jwt, audience ${jwtAudienceOf(client)}`);
96
98
  }
97
99
  return lines;
98
100
  }
@@ -16,7 +16,7 @@
16
16
  * @module
17
17
  */
18
18
  import { type SigningKey } from "../../server/signing-keys.ts";
19
- import type { DevIdpConfig } from "./config.ts";
19
+ import { type DevIdpConfig } from "./config.ts";
20
20
  /** Header the admin endpoints require, carrying the token printed at startup. */
21
21
  export declare const ADMIN_TOKEN_HEADER = "x-admin-token";
22
22
  /**
@@ -22,12 +22,13 @@ import { ClientCredentialsGrant } from "../../server/grants/client-credentials.j
22
22
  import { PasswordGrant } from "../../server/grants/password.js";
23
23
  import { RefreshTokenGrant } from "../../server/grants/refresh-token.js";
24
24
  import { satisfiesAuthenticationRequest } from "../../server/authentication-request.js";
25
- import { StaticSigningKeyProvider, } from "../../server/signing-keys.js";
25
+ import { createJwtAccessTokenGenerator, StaticSigningKeyProvider, } from "../../server/signing-keys.js";
26
26
  import { generateCodeChallenge, generateCodeVerifier, generateState, } from "../../utils/pkce.js";
27
27
  import { DEFAULT_MAX_BODY_BYTES, readBoundedBody } from "../../utils/_body.js";
28
28
  import { timingSafeEqualString } from "../../utils/crypto.js";
29
29
  import { safeReturnTo } from "../../utils/url.js";
30
30
  import { MemoryAuthorizationCodeService, MemoryClientService, MemoryTokenService, MemoryUserService, } from "../../testing/services.js";
31
+ import { jwtAudienceOf } from "./config.js";
31
32
  import { consentPage, htmlResponse, loginPage, messagePage, statusPage, } from "./pages.js";
32
33
  const SESSION_COOKIE = "dev_idp_session";
33
34
  const CONSENT_COOKIE = "dev_idp_consent";
@@ -52,16 +53,49 @@ function newSession(userId, signedInFor) {
52
53
  ...(signedInFor === undefined ? {} : { signedInFor }),
53
54
  };
54
55
  }
56
+ class DevIdpTokenService extends MemoryTokenService {
57
+ #jwtAudiences;
58
+ #signingKeys;
59
+ #issuer;
60
+ constructor(options, jwt) {
61
+ super(options);
62
+ this.#jwtAudiences = jwt.audiences;
63
+ this.#signingKeys = jwt.signingKeys;
64
+ this.#issuer = jwt.issuer;
65
+ }
66
+ generateAccessToken(client, user, scope, authenticationContext, expiresAt, resource) {
67
+ const audience = this.#jwtAudiences.get(client.id);
68
+ if (audience === undefined) {
69
+ return super.generateAccessToken(client, user, scope);
70
+ }
71
+ return createJwtAccessTokenGenerator({
72
+ signingKeys: this.#signingKeys,
73
+ issuer: this.#issuer.value,
74
+ audience,
75
+ lifetimeSeconds: this.accessTokenLifetime,
76
+ })(client, user, scope, authenticationContext, expiresAt, resource);
77
+ }
78
+ }
79
+ function jwtAudiences(config) {
80
+ const audiences = new Map();
81
+ for (const client of config.clients) {
82
+ const audience = jwtAudienceOf(client);
83
+ if (audience !== undefined)
84
+ audiences.set(client.id, audience);
85
+ }
86
+ return audiences;
87
+ }
55
88
  async function createState(config, signingKey, issuer) {
56
89
  const userService = new MemoryUserService();
57
90
  const clientService = new MemoryClientService(userService);
58
91
  const authorizationCodeService = new MemoryAuthorizationCodeService({ clientService, userService });
59
- const tokenService = new MemoryTokenService({
92
+ const signingKeys = new StaticSigningKeyProvider(signingKey);
93
+ const tokenService = new DevIdpTokenService({
60
94
  clientService,
61
95
  userService,
62
96
  accessTokenLifetime: config.accessTokenLifetime,
63
97
  authorizationCodeService,
64
- });
98
+ }, { audiences: jwtAudiences(config), signingKeys, issuer });
65
99
  const grants = {};
66
100
  if (config.grants.authorization_code) {
67
101
  grants.authorization_code = new AuthorizationCodeGrant({
@@ -95,7 +129,7 @@ async function createState(config, signingKey, issuer) {
95
129
  }),
96
130
  grants,
97
131
  scopesSupported: config.scopesSupported,
98
- signingKeys: new StaticSigningKeyProvider(signingKey),
132
+ signingKeys,
99
133
  userClaims: (user) => ({
100
134
  preferred_username: user.username,
101
135
  ...user.claims,
@@ -446,6 +480,8 @@ function adminState(state, config, issuer) {
446
480
  confidential: client.secret !== undefined,
447
481
  redirectUris: client.redirectUris,
448
482
  grants: client.grants,
483
+ accessTokenFormat: client.accessTokenFormat ?? "opaque",
484
+ audience: jwtAudienceOf(client),
449
485
  })),
450
486
  sessions: state.sessions.size,
451
487
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.45.1",
3
+ "version": "0.46.0",
4
4
  "description": "A flexible OAuth2 toolkit: framework-agnostic authorization & resource servers, a typed client, Hono adapters (including a backend-for-frontend), Express adapters, and React bindings.",
5
5
  "keywords": [
6
6
  "authorization-server",