@udibo/oauth2 0.56.0 → 0.57.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.
@@ -38,6 +38,12 @@ export interface DevIdpClientConfig {
38
38
  * on `127.0.0.1` or `[::1]` also matches the same URI on any port.
39
39
  */
40
40
  redirectUris: string[];
41
+ /**
42
+ * Where the end-session endpoint may send the browser after a logout this
43
+ * client starts, matched as exact strings. Every entry of `redirectUris` is
44
+ * accepted as well, so list only the extra ones (a "signed out" page).
45
+ */
46
+ postLogoutRedirectUris?: string[];
41
47
  /** Grant types this client may use. */
42
48
  grants: string[];
43
49
  /**
@@ -70,6 +76,20 @@ export type DevIdpAccessTokenFormat = "opaque" | "jwt";
70
76
  * `audience` it sets.
71
77
  */
72
78
  export declare function jwtAudienceOf(client: DevIdpClientConfig): string | undefined;
79
+ /**
80
+ * Every URI the end-session endpoint accepts as this client's
81
+ * `post_logout_redirect_uri`: its `postLogoutRedirectUris`, then its
82
+ * `redirectUris`.
83
+ */
84
+ export declare function postLogoutRedirectUrisOf(client: DevIdpClientConfig): string[];
85
+ /**
86
+ * The browser origins the provider answers CORS for: the `http(s)` origin of
87
+ * every client redirect URI and post-logout redirect URI, plus each
88
+ * `corsOrigins` entry that is itself a bare `http(s)` origin. Compare a
89
+ * request's `Origin` header to these as exact strings; `null` and `*` are
90
+ * never members.
91
+ */
92
+ export declare function corsOriginsOf(config: DevIdpConfig): Set<string>;
73
93
  /**
74
94
  * A fully resolved configuration. Every field the server needs is present:
75
95
  * {@link parseDevIdpConfig} fills the defaults so nothing downstream has to.
@@ -105,6 +125,13 @@ export interface DevIdpConfig {
105
125
  users: DevIdpUserConfig[];
106
126
  /** Clients to register. */
107
127
  clients: DevIdpClientConfig[];
128
+ /**
129
+ * Browser origins allowed to call the discovery, token, revocation, UserInfo
130
+ * and JWKS endpoints cross-origin, beyond the origins of the clients'
131
+ * redirect URIs, which are always allowed. Each is a bare `http(s)` origin
132
+ * such as `http://localhost:4200`; the config parser refuses anything else.
133
+ */
134
+ corsOrigins?: string[];
108
135
  }
109
136
  /**
110
137
  * The configuration used when `idp dev` runs without `--config`: one
@@ -16,6 +16,56 @@ export function jwtAudienceOf(client) {
16
16
  return undefined;
17
17
  return client.audience ?? client.id;
18
18
  }
19
+ /**
20
+ * Every URI the end-session endpoint accepts as this client's
21
+ * `post_logout_redirect_uri`: its `postLogoutRedirectUris`, then its
22
+ * `redirectUris`.
23
+ */
24
+ export function postLogoutRedirectUrisOf(client) {
25
+ return [
26
+ ...new Set([
27
+ ...(client.postLogoutRedirectUris ?? []),
28
+ ...client.redirectUris,
29
+ ]),
30
+ ];
31
+ }
32
+ function webOriginOf(uri) {
33
+ let url;
34
+ try {
35
+ url = new URL(uri);
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ return url.protocol === "http:" || url.protocol === "https:"
41
+ ? url.origin
42
+ : undefined;
43
+ }
44
+ function isExactWebOrigin(entry) {
45
+ return !entry.includes("*") && webOriginOf(entry) === entry;
46
+ }
47
+ /**
48
+ * The browser origins the provider answers CORS for: the `http(s)` origin of
49
+ * every client redirect URI and post-logout redirect URI, plus each
50
+ * `corsOrigins` entry that is itself a bare `http(s)` origin. Compare a
51
+ * request's `Origin` header to these as exact strings; `null` and `*` are
52
+ * never members.
53
+ */
54
+ export function corsOriginsOf(config) {
55
+ const origins = new Set();
56
+ for (const client of config.clients) {
57
+ for (const uri of postLogoutRedirectUrisOf(client)) {
58
+ const origin = webOriginOf(uri);
59
+ if (origin !== undefined)
60
+ origins.add(origin);
61
+ }
62
+ }
63
+ for (const entry of config.corsOrigins ?? []) {
64
+ if (isExactWebOrigin(entry))
65
+ origins.add(entry);
66
+ }
67
+ return origins;
68
+ }
19
69
  const DEFAULT_PORT = 9000;
20
70
  const DEFAULT_HOSTNAME = "127.0.0.1";
21
71
  const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
@@ -43,12 +93,14 @@ const CONFIG_FIELDS = [
43
93
  "signingKey",
44
94
  "users",
45
95
  "clients",
96
+ "corsOrigins",
46
97
  ];
47
98
  const USER_FIELDS = ["id", "username", "password", "claims"];
48
99
  const CLIENT_FIELDS = [
49
100
  "id",
50
101
  "secret",
51
102
  "redirectUris",
103
+ "postLogoutRedirectUris",
52
104
  "grants",
53
105
  "ownerUserId",
54
106
  "accessTokenFormat",
@@ -191,6 +243,11 @@ function parseClient(value, path) {
191
243
  id,
192
244
  secret: optionalString(source.secret, `${path}.secret`),
193
245
  redirectUris,
246
+ ...(source.postLogoutRedirectUris === undefined
247
+ ? {}
248
+ : {
249
+ postLogoutRedirectUris: stringArray(source.postLogoutRedirectUris, `${path}.postLogoutRedirectUris`),
250
+ }),
194
251
  grants,
195
252
  ownerUserId: optionalString(source.ownerUserId, `${path}.ownerUserId`),
196
253
  accessTokenFormat,
@@ -203,6 +260,14 @@ function parseAccessTokenFormat(value, path) {
203
260
  }
204
261
  return value;
205
262
  }
263
+ function parseCorsOrigins(value, path) {
264
+ return stringArray(value, path).map((entry, index) => {
265
+ if (!isExactWebOrigin(entry)) {
266
+ fail(`${path}[${index}]`, 'must be an http(s) origin with no path or wildcard, such as "http://localhost:3000"');
267
+ }
268
+ return entry;
269
+ });
270
+ }
206
271
  function parseConsent(value, path) {
207
272
  const consent = string(value, path);
208
273
  if (consent !== "auto" && consent !== "prompt") {
@@ -273,6 +338,9 @@ export function parseDevIdpConfig(value) {
273
338
  : parseSigningKey(source.signingKey, "config.signingKey"),
274
339
  users,
275
340
  clients,
341
+ corsOrigins: source.corsOrigins === undefined
342
+ ? []
343
+ : parseCorsOrigins(source.corsOrigins, "config.corsOrigins"),
276
344
  };
277
345
  }
278
346
  /**
@@ -157,7 +157,8 @@ export function statusPage(options) {
157
157
  <span class="mono">/revoke</span>,
158
158
  <span class="mono">/introspect</span></li>
159
159
  <li><span class="mono">/login</span>,
160
- <span class="mono">/logout</span></li>
160
+ <span class="mono">/end_session</span>
161
+ (also served at <span class="mono">/logout</span>)</li>
161
162
  </ul>
162
163
  <h2>Users</h2>
163
164
  <ul>
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The development identity provider itself: a real {@link AuthorizationServer}
3
3
  * over the in-memory services, served on a socket with a sign-in page, an
4
- * optional consent screen, and a test-control surface under `/__admin/`.
4
+ * optional consent screen, RP-initiated logout, CORS for the configured
5
+ * clients' origins, and a test-control surface under `/__admin/`.
5
6
  *
6
7
  * Everything here is packaging — the protocol behavior is the same code an
7
8
  * application runs in production. What makes it a development tool is the
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The development identity provider itself: a real {@link AuthorizationServer}
3
3
  * over the in-memory services, served on a socket with a sign-in page, an
4
- * optional consent screen, and a test-control surface under `/__admin/`.
4
+ * optional consent screen, RP-initiated logout, CORS for the configured
5
+ * clients' origins, and a test-control surface under `/__admin/`.
5
6
  *
6
7
  * Everything here is packaging — the protocol behavior is the same code an
7
8
  * application runs in production. What makes it a development tool is the
@@ -22,13 +23,13 @@ import { ClientCredentialsGrant } from "../../server/grants/client-credentials.j
22
23
  import { PasswordGrant } from "../../server/grants/password.js";
23
24
  import { RefreshTokenGrant } from "../../server/grants/refresh-token.js";
24
25
  import { satisfiesAuthenticationRequest } from "../../server/authentication-request.js";
25
- import { createJwtAccessTokenGenerator, StaticSigningKeyProvider, } from "../../server/signing-keys.js";
26
+ import { createJwtAccessTokenGenerator, StaticSigningKeyProvider, verifyJwt, } from "../../server/signing-keys.js";
26
27
  import { generateCodeChallenge, generateCodeVerifier, generateState, } from "../../utils/pkce.js";
27
28
  import { DEFAULT_MAX_BODY_BYTES, readBoundedBody } from "../../utils/_body.js";
28
29
  import { timingSafeEqualString } from "../../utils/crypto.js";
29
30
  import { safeReturnTo } from "../../utils/url.js";
30
31
  import { MemoryAuthorizationCodeService, MemoryClientService, MemoryTokenService, MemoryUserService, } from "../../testing/services.js";
31
- import { jwtAudienceOf } from "./config.js";
32
+ import { corsOriginsOf, jwtAudienceOf, postLogoutRedirectUrisOf, } from "./config.js";
32
33
  import { consentPage, htmlResponse, loginPage, messagePage, statusPage, } from "./pages.js";
33
34
  const SESSION_COOKIE = "dev_idp_session";
34
35
  const CONSENT_COOKIE = "dev_idp_consent";
@@ -90,6 +91,7 @@ async function createState(config, signingKey, issuer) {
90
91
  const clientService = new MemoryClientService(userService);
91
92
  const authorizationCodeService = new MemoryAuthorizationCodeService({ clientService, userService });
92
93
  const signingKeys = new StaticSigningKeyProvider(signingKey);
94
+ const sessions = new Map();
93
95
  const tokenService = new DevIdpTokenService({
94
96
  clientService,
95
97
  userService,
@@ -134,6 +136,14 @@ async function createState(config, signingKey, issuer) {
134
136
  preferred_username: user.username,
135
137
  ...user.claims,
136
138
  }),
139
+ endSession: ({ request }) => {
140
+ const sessionId = readCookie(request, SESSION_COOKIE);
141
+ if (sessionId)
142
+ sessions.delete(sessionId);
143
+ return {
144
+ headers: { "set-cookie": cookie(SESSION_COOKIE, "", { maxAge: 0 }) },
145
+ };
146
+ },
137
147
  });
138
148
  const secrets = new Map();
139
149
  for (const user of config.users) {
@@ -148,6 +158,7 @@ async function createState(config, signingKey, issuer) {
148
158
  id: client.id,
149
159
  grants: client.grants,
150
160
  redirectUris: client.redirectUris,
161
+ postLogoutRedirectUris: postLogoutRedirectUrisOf(client),
151
162
  }, client.secret, client.ownerUserId);
152
163
  if (client.secret)
153
164
  secrets.set(client.id, client.secret);
@@ -156,7 +167,7 @@ async function createState(config, signingKey, issuer) {
156
167
  server,
157
168
  userService,
158
169
  clientService,
159
- sessions: new Map(),
170
+ sessions,
160
171
  consents: new Map(),
161
172
  secrets,
162
173
  };
@@ -217,6 +228,32 @@ function rejectUnauthorizedAdmin(request, adminToken) {
217
228
  }
218
229
  return undefined;
219
230
  }
231
+ const CORS_PATHS = new Set([
232
+ "/.well-known/openid-configuration",
233
+ "/.well-known/oauth-authorization-server",
234
+ "/token",
235
+ "/revoke",
236
+ "/userinfo",
237
+ "/jwks",
238
+ ]);
239
+ const CORS_PREFLIGHT_MAX_AGE = 600;
240
+ function varyOnOrigin(headers) {
241
+ headers.append("vary", "Origin");
242
+ }
243
+ function answerPreflight(origin, allowed) {
244
+ const headers = new Headers({ "cache-control": "no-store" });
245
+ varyOnOrigin(headers);
246
+ if (!allowed) {
247
+ return Response.json({
248
+ error: `origin ${origin} is not allowed; register a redirect URI on it or list it in "corsOrigins"`,
249
+ }, { status: 403, headers });
250
+ }
251
+ headers.set("access-control-allow-origin", origin);
252
+ headers.set("access-control-allow-methods", "GET, POST");
253
+ headers.set("access-control-allow-headers", "authorization, content-type");
254
+ headers.set("access-control-max-age", String(CORS_PREFLIGHT_MAX_AGE));
255
+ return new Response(null, { status: 204, headers });
256
+ }
220
257
  function pathAndQuery(request) {
221
258
  const { pathname, search } = new URL(request.url);
222
259
  return `${pathname}${search}`;
@@ -342,27 +379,47 @@ async function handleConsentSubmission(state, request) {
342
379
  }),
343
380
  });
344
381
  }
345
- function handleLogout(state, config, request) {
346
- const sessionId = readCookie(request, SESSION_COOKIE);
347
- if (sessionId)
348
- state.sessions.delete(sessionId);
349
- const expired = cookie(SESSION_COOKIE, "", { maxAge: 0 });
350
- const postLogout = new URL(request.url).searchParams.get("post_logout_redirect_uri");
351
- if (postLogout) {
352
- const registered = config.clients.some((client) => client.redirectUris.includes(postLogout));
353
- if (registered) {
354
- return redirect(postLogout, { "set-cookie": expired });
355
- }
356
- return htmlResponse(messagePage("Invalid logout request", "post_logout_redirect_uri must exactly match a redirect URI registered by one of the configured clients."), 400);
357
- }
358
- return new Response(messagePage("Signed out", "The session was dropped."), {
359
- status: 200,
360
- headers: {
361
- "content-type": "text/html; charset=utf-8",
362
- "cache-control": "no-store",
363
- "set-cookie": expired,
364
- },
382
+ async function endSessionParameters(request) {
383
+ if (request.method !== "POST")
384
+ return new URL(request.url).searchParams;
385
+ return new URLSearchParams(new TextDecoder().decode(await readBody(request)));
386
+ }
387
+ async function namesClient(params, signingKey) {
388
+ if (params.get("client_id"))
389
+ return true;
390
+ const hint = params.get("id_token_hint");
391
+ if (!hint)
392
+ return false;
393
+ const claims = await verifyJwt(hint, signingKey.publicJwk, {
394
+ ignoreExpiration: true,
365
395
  });
396
+ return claims !== undefined;
397
+ }
398
+ async function handleEndSession(state, config, signingKey, request) {
399
+ const params = await endSessionParameters(request);
400
+ const requested = params.get("post_logout_redirect_uri");
401
+ if (requested && !(await namesClient(params, signingKey))) {
402
+ const registrant = config.clients.find((client) => postLogoutRedirectUrisOf(client).includes(requested));
403
+ if (registrant)
404
+ params.set("client_id", registrant.id);
405
+ }
406
+ const url = new URL(request.url);
407
+ url.search = params.toString();
408
+ const response = await state.server.handleEndSessionRequest(new Request(url, { headers: request.headers }));
409
+ if (response.status === 302) {
410
+ return new Response(null, { status: 303, headers: response.headers });
411
+ }
412
+ if (response.status !== 204)
413
+ return response;
414
+ const headers = new Headers(response.headers);
415
+ headers.set("content-type", "text/html; charset=utf-8");
416
+ headers.set("cache-control", "no-store");
417
+ return requested
418
+ ? new Response(messagePage("Invalid logout request", "The session was dropped, but post_logout_redirect_uri must exactly match a redirect URI or post-logout redirect URI registered by the client the request names, or by any configured client when it names none."), { status: 400, headers })
419
+ : new Response(messagePage("Signed out", "The session was dropped."), {
420
+ status: 200,
421
+ headers,
422
+ });
366
423
  }
367
424
  async function readJsonBody(request) {
368
425
  const text = new TextDecoder().decode(await readBody(request));
@@ -527,8 +584,26 @@ export async function startDevIdentityProvider(options) {
527
584
  const adminToken = options.adminToken ?? crypto.randomUUID();
528
585
  const issuer = { value: config.issuer ?? "" };
529
586
  let state = await createState(config, signingKey, issuer);
587
+ const corsOrigins = corsOriginsOf(config);
530
588
  const handler = async (request) => {
531
589
  const { pathname } = new URL(request.url);
590
+ if (!CORS_PATHS.has(pathname))
591
+ return await route(request, pathname);
592
+ const origin = request.headers.get("origin");
593
+ const allowed = origin !== null && corsOrigins.has(origin);
594
+ if (origin !== null &&
595
+ request.method === "OPTIONS" &&
596
+ request.headers.has("access-control-request-method")) {
597
+ return answerPreflight(origin, allowed);
598
+ }
599
+ const routed = await route(request, pathname);
600
+ const response = new Response(routed.body, routed);
601
+ varyOnOrigin(response.headers);
602
+ if (allowed)
603
+ response.headers.set("access-control-allow-origin", origin);
604
+ return response;
605
+ };
606
+ const route = async (request, pathname) => {
532
607
  const { method } = request;
533
608
  if (pathname.startsWith("/__admin/")) {
534
609
  const rejected = rejectUnauthorizedAdmin(request, adminToken);
@@ -573,8 +648,9 @@ export async function startDevIdentityProvider(options) {
573
648
  if (method !== "POST")
574
649
  return jsonError(405, "method must be POST");
575
650
  return await handleConsentSubmission(state, request);
651
+ case "/end_session":
576
652
  case "/logout":
577
- return handleLogout(state, config, request);
653
+ return await handleEndSession(state, config, signingKey, request);
578
654
  case "/__admin/reset":
579
655
  if (method !== "POST")
580
656
  return jsonError(405, "method must be POST");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.56.0",
3
+ "version": "0.57.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",
@@ -4,8 +4,8 @@ description: Build an OAuth2 authorization server for a Node application with @u
4
4
  license: MIT
5
5
  compatibility: Node.js 22.18 or later for the TypeScript quickstart.
6
6
  metadata:
7
- version: "0.56.0"
8
- targets: "@udibo/oauth2@0.56.0"
7
+ version: "0.57.0"
8
+ targets: "@udibo/oauth2@0.57.0"
9
9
  ---
10
10
 
11
11
  # Build authorization with @udibo/oauth2
@@ -63,12 +63,12 @@ the person's local secret storage and out of the conversation.
63
63
 
64
64
  ## Your own authorization server
65
65
 
66
- For a local sign-in, follow the complete app in the [versioned quickstart](https://github.com/udibo/oauth2/blob/0.56.0/docs/quickstart.md).
66
+ For a local sign-in, follow the complete app in the [versioned quickstart](https://github.com/udibo/oauth2/blob/0.57.0/docs/quickstart.md).
67
67
  In an existing project, keep its lockfile and package manager. Pin the package
68
68
  to the version this skill targets. For an npm project:
69
69
 
70
70
  ```sh
71
- npm install --save-exact @udibo/oauth2@0.56.0
71
+ npm install --save-exact @udibo/oauth2@0.57.0
72
72
  ```
73
73
 
74
74
  For a local provider, create the quickstart's development configuration with
@@ -105,7 +105,7 @@ rotation atomic. Wire the authorization-code grant with PKCE and the refresh
105
105
  grant the application needs. Configure the issuer and registered redirects
106
106
  from the deployment settings. Run the package's store contract tests and
107
107
  exercise sign-in, refresh and revocation before switching application traffic.
108
- [Authorization server guide](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/become-an-oauth-provider.md) · [Production deployment](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/production-deployment.md)
108
+ [Authorization server guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/become-an-oauth-provider.md) · [Production deployment](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/production-deployment.md)
109
109
 
110
110
  ## Connect a client and protect an API
111
111
 
@@ -119,7 +119,7 @@ For an API, mount the bearer middleware from
119
119
  scope required by the route. Check the verified subject's application
120
120
  permissions before returning a private record. Exercise a permitted request,
121
121
  a request without a token and a request whose token lacks the route's scope.
122
- [Protect an API](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/protect-an-api.md)
122
+ [Protect an API](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/protect-an-api.md)
123
123
 
124
124
  ## Hosted path: connect a tenant
125
125
 
@@ -128,7 +128,7 @@ application in their tenant and register the callback.
128
128
  Ask for its public issuer and client ID, and the name of the environment
129
129
  variable holding the secret. Use those settings on the server and repeat the
130
130
  client sign-in and protected API checks.
131
- [Hosted integration guide](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/use-udibo.md)
131
+ [Hosted integration guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/use-udibo.md)
132
132
 
133
133
  ## Migrating between authorization servers
134
134
 
@@ -136,4 +136,4 @@ First adopt the package against the existing issuer. Verify sign-in, sign-out,
136
136
  session continuity and one protected request on that issuer. Before switching
137
137
  issuers or moving users, present a separate plan covering account identifiers,
138
138
  credentials, registrations, cutover and rollback. Wait for approval.
139
- [Migration guide](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/migrate-from-another-provider.md)
139
+ [Migration guide](https://github.com/udibo/oauth2/blob/0.57.0/docs/guides/migrate-from-another-provider.md)