@udibo/oauth2 0.55.3 → 0.56.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.
@@ -80,6 +80,14 @@ export interface TenantContractFixture {
80
80
  * returns its id.
81
81
  */
82
82
  addRole(permissions: string[]): Promise<string>;
83
+ /**
84
+ * Removes a permission key from the tenant's registry, as an administrator
85
+ * deleting it does: every role keeps carrying the key, but no role confers
86
+ * it or is listed for it any more. The suite deregisters only keys it
87
+ * named for this purpose. Leave it out and the checks that need it are
88
+ * skipped.
89
+ */
90
+ deregisterPermission?(key: string): Promise<void>;
83
91
  /**
84
92
  * Grants `permissions` on one instance of a resource type to a person, or
85
93
  * to every member of an organization. Registers the type if it is new.
@@ -680,6 +680,117 @@ export function runTenantContractTests(options) {
680
680
  const reply = await call(null, "GET", "/api/organizations");
681
681
  expect(reply.status).toStrictEqual(401);
682
682
  });
683
+ describe("member-roles narrowed to a product's permission keys", () => {
684
+ const run = crypto.randomUUID().slice(0, 8);
685
+ const projectsRead = `contract-projects-${run}:read`;
686
+ const projectsWrite = `contract-projects-${run}:write`;
687
+ const reportsEdit = `contract-reports-${run}:edit`;
688
+ const archiveRead = `contract-archive-${run}:read`;
689
+ const archiveWrite = `contract-archive-${run}:write`;
690
+ const roles = {
691
+ projectLead: "",
692
+ reportEditor: "",
693
+ portalOwner: "",
694
+ archivist: "",
695
+ };
696
+ beforeAll(async () => {
697
+ roles.projectLead = await tenant.addRole([
698
+ projectsRead,
699
+ projectsWrite,
700
+ ]);
701
+ roles.reportEditor = await tenant.addRole([reportsEdit]);
702
+ roles.portalOwner = await tenant.addRole([projectsRead, reportsEdit]);
703
+ roles.archivist = await tenant.addRole([archiveRead, archiveWrite]);
704
+ });
705
+ function memberRoles(query, accessToken = seats.admin.token) {
706
+ return call(accessToken, "GET", `/api/organizations/${organization.id}/member-roles${query}`);
707
+ }
708
+ const naming = (keys) => `?${new URLSearchParams(keys.map((key) => ["permission", key]))}`;
709
+ async function offered(query) {
710
+ const reply = await memberRoles(query);
711
+ expect(reply.status, JSON.stringify(reply.body)).toStrictEqual(200);
712
+ for (const slug of ["owner", "admin", "member"]) {
713
+ const tier = reply.body.find((entry) => entry.slug === slug);
714
+ assert(tier, `the built-in ${slug} tier is listed for ${query}`);
715
+ expect("id" in tier).toBeFalsy();
716
+ }
717
+ const ours = new Set(Object.values(roles));
718
+ return reply.body
719
+ .flatMap((entry) => (entry.id === undefined ? [] : [entry.id]))
720
+ .filter((id) => ours.has(id))
721
+ .sort();
722
+ }
723
+ const sorted = (...ids) => [...ids].sort();
724
+ const emptyKeyRefusal = {
725
+ permission: "Name a permission key in every permission parameter",
726
+ };
727
+ const tooManyKeysRefusal = {
728
+ permission: "Name at most 500 permission keys, as many as a tenant may register",
729
+ };
730
+ function refusal(reply) {
731
+ expect(reply.status, JSON.stringify(reply.body)).toStrictEqual(400);
732
+ const { fieldErrors } = reply.body;
733
+ return fieldErrors ?? {};
734
+ }
735
+ it("lists every tenant-wide role when no permission key is named", async () => {
736
+ expect(await offered("")).toStrictEqual(sorted(...Object.values(roles)));
737
+ });
738
+ it("offers each product on a shared tenant only the roles conferring one of its keys, and a mixed role to both", async () => {
739
+ expect(await offered(naming([projectsRead, projectsWrite]))).toStrictEqual(sorted(roles.projectLead, roles.portalOwner));
740
+ expect(await offered(naming([projectsWrite]))).toStrictEqual([
741
+ roles.projectLead,
742
+ ]);
743
+ expect(await offered(naming([reportsEdit]))).toStrictEqual(sorted(roles.reportEditor, roles.portalOwner));
744
+ });
745
+ it("matches nothing for a key nobody registered or a comma-joined value, without refusing the read", async () => {
746
+ expect(await offered(naming([`contract-unknown-${run}:read`]))).toStrictEqual([]);
747
+ expect(await offered(naming([`${projectsRead},${reportsEdit}`]))).toStrictEqual([]);
748
+ });
749
+ it("stops matching a role on a key the tenant deregistered, while its live keys still match it", async ({ skip, }) => {
750
+ if (!tenant.deregisterPermission) {
751
+ skip("the fixture cannot deregister a permission key");
752
+ return;
753
+ }
754
+ expect(await offered(naming([archiveRead]))).toStrictEqual([
755
+ roles.archivist,
756
+ ]);
757
+ await tenant.deregisterPermission(archiveRead);
758
+ expect(await offered(naming([archiveRead]))).toStrictEqual([]);
759
+ expect(await offered(naming([archiveWrite]))).toStrictEqual([
760
+ roles.archivist,
761
+ ]);
762
+ expect(await offered(""), "the unfiltered list still names the role").toContain(roles.archivist);
763
+ });
764
+ it("refuses an empty key, bare or beside a named one, rather than reading it as no filter", async () => {
765
+ for (const query of [
766
+ "?permission=",
767
+ "?permission",
768
+ `?permission=${encodeURIComponent(projectsRead)}&permission=`,
769
+ ]) {
770
+ expect(refusal(await memberRoles(query)), query).toStrictEqual(emptyKeyRefusal);
771
+ }
772
+ });
773
+ it("refuses more keys than a tenant may register, and accepts exactly that many", async () => {
774
+ const keys = Array.from({ length: 501 }, (_, index) => `k${index}`);
775
+ expect(refusal(await memberRoles(naming(keys)))).toStrictEqual(tooManyKeysRefusal);
776
+ expect(refusal(await memberRoles(naming(["", ...keys.slice(1)]))), "the key count is checked before an empty key").toStrictEqual(tooManyKeysRefusal);
777
+ expect(await offered(naming(keys.slice(0, 500)))).toStrictEqual([]);
778
+ });
779
+ it("refuses a plain member with the same 404 before looking at the keys", async () => {
780
+ const unfiltered = await memberRoles("", seats.member.token);
781
+ expect(unfiltered.status).toStrictEqual(404);
782
+ const tooMany = Array.from({ length: 501 }, (_, index) => `k${index}`);
783
+ for (const query of [
784
+ naming([projectsRead]),
785
+ "?permission=",
786
+ naming(tooMany),
787
+ ]) {
788
+ const refused = await memberRoles(query, seats.member.token);
789
+ expect(refused.status, query).toStrictEqual(404);
790
+ expect(refused.body, query).toStrictEqual(unfiltered.body);
791
+ }
792
+ });
793
+ });
683
794
  describe("application roles a manager grants a member", () => {
684
795
  const APP_PERMISSION = "contract:app";
685
796
  let roleId;
@@ -266,9 +266,19 @@ export interface FakeTenant {
266
266
  * offer it, `member-roles` lists it, and an organization's manager may grant
267
267
  * it to a member. Returns its id. Defining a slug again changes its name
268
268
  * and permissions and keeps its id. Throws on a built-in slug, on an id
269
- * another role holds, and on a new id for a slug already defined.
269
+ * another role holds, on a new id for a slug already defined, and on a key
270
+ * {@linkcode deregisterPermission} removed.
270
271
  */
271
272
  defineOrganizationRole(role: FakeTenantOrganizationRole): string;
273
+ /**
274
+ * Removes a permission key from the tenant's registry, as an administrator
275
+ * deleting it does. Every role, person, membership and grant naming the key
276
+ * keeps it but confers it no more, and `member-roles` no longer lists a role
277
+ * for it under `?permission=`. The other keys a role carries still count.
278
+ * Re-registering a key is not modelled: the removal lasts for the fake's
279
+ * life, so name a key you deregister nowhere afterwards.
280
+ */
281
+ deregisterPermission(key: string): void;
272
282
  /** Registers a resource type, so `/api/check` accepts it. */
273
283
  registerResourceType(type: string): void;
274
284
  /**
@@ -16,6 +16,7 @@ const PATHS = {
16
16
  jwks: "/api/oauth2/jwks",
17
17
  };
18
18
  const MAX_PERMISSIONS = 50;
19
+ const MAX_REGISTERED_PERMISSIONS = 500;
19
20
  const MAX_BATCH_IDS = 100;
20
21
  const DEFAULT_PAGE_SIZE = 20;
21
22
  const MAX_PAGE_SIZE = 100;
@@ -302,6 +303,7 @@ export async function createFakeTenant(options) {
302
303
  const userMetadata = new Map();
303
304
  const organizations = new Map();
304
305
  const definedRoles = new Map();
306
+ const deregisteredPermissions = new Set();
305
307
  const appRoles = [];
306
308
  const invitations = new Map();
307
309
  const resourceTypes = new Set();
@@ -325,6 +327,7 @@ export async function createFakeTenant(options) {
325
327
  const definedRoleById = (roleId) => [...definedRoles.values()].find((role) => role.id === roleId);
326
328
  const appRolesHeld = (organizationId, userId) => appRoles.filter((assignment) => assignment.organizationId === organizationId &&
327
329
  assignment.userId === userId);
330
+ const registered = (key) => !deregisteredPermissions.has(key);
328
331
  const appRolePermissions = (organizationId, userId) => appRolesHeld(organizationId, userId).flatMap((assignment) => definedRoleById(assignment.roleId)?.permissions ?? []);
329
332
  const permissionsIn = (userId, organizationId) => new Set([
330
333
  ...(users.get(userId)?.permissions ?? []),
@@ -335,7 +338,7 @@ export async function createFakeTenant(options) {
335
338
  ...appRolePermissions(organizationId, userId),
336
339
  ]
337
340
  : []),
338
- ]);
341
+ ].filter(registered));
339
342
  const organizationClaims = (userId, organizationId) => {
340
343
  if (!organizationId || !isMember(organizationId, userId))
341
344
  return {};
@@ -465,7 +468,7 @@ export async function createFakeTenant(options) {
465
468
  ? grant.subject.id === userId
466
469
  : isMember(grant.subject.id, userId);
467
470
  if (admits)
468
- grant.permissions.forEach((p) => held.add(p));
471
+ grant.permissions.filter(registered).forEach((p) => held.add(p));
469
472
  }
470
473
  return held;
471
474
  };
@@ -999,11 +1002,25 @@ export async function createFakeTenant(options) {
999
1002
  };
1000
1003
  }), request));
1001
1004
  });
1002
- const listMemberRoles = organizationApi((caller, _request, [id]) => {
1005
+ const listMemberRoles = organizationApi((caller, request, [id]) => {
1003
1006
  const organization = managedOrganization(caller, id);
1004
1007
  if (organization instanceof Response)
1005
1008
  return organization;
1006
- return Response.json(roleVocabulary());
1009
+ const query = new URL(request.url).searchParams;
1010
+ if (!query.has("permission"))
1011
+ return Response.json(roleVocabulary());
1012
+ const keys = query.getAll("permission");
1013
+ if (keys.length > MAX_REGISTERED_PERMISSIONS) {
1014
+ return invalid("permission", `Name at most ${MAX_REGISTERED_PERMISSIONS} permission keys, as many as a tenant may register`);
1015
+ }
1016
+ if (keys.includes("")) {
1017
+ return invalid("permission", "Name a permission key in every permission parameter");
1018
+ }
1019
+ const named = new Set(keys.filter(registered));
1020
+ const matching = new Set([...definedRoles.values()]
1021
+ .filter((role) => role.permissions.some((key) => named.has(key)))
1022
+ .map((role) => role.id));
1023
+ return Response.json(roleVocabulary().filter((role) => role.id === undefined || matching.has(role.id)));
1007
1024
  });
1008
1025
  const revokeMembership = organizationApi((caller, _request, [id, userId, role]) => {
1009
1026
  const organization = managedOrganization(caller, id);
@@ -1033,7 +1050,7 @@ export async function createFakeTenant(options) {
1033
1050
  organizationId: null,
1034
1051
  slug: role.slug,
1035
1052
  name: role.name,
1036
- permissions: [...role.permissions],
1053
+ permissions: role.permissions.filter(registered),
1037
1054
  });
1038
1055
  const listMemberAppRoles = organizationApi((caller, _request, [id, userId]) => {
1039
1056
  const organization = managedOrganization(caller, id);
@@ -1640,6 +1657,10 @@ export async function createFakeTenant(options) {
1640
1657
  if (holder && holder.slug !== slug) {
1641
1658
  throw new Error(`Role id "${roleId}" belongs to "${holder.slug}"`);
1642
1659
  }
1660
+ const unregistered = permissions?.find((key) => !registered(key));
1661
+ if (unregistered !== undefined) {
1662
+ throw new Error(`Permission "${unregistered}" is not registered`);
1663
+ }
1643
1664
  definedRoles.set(slug, {
1644
1665
  id: roleId,
1645
1666
  slug,
@@ -1648,6 +1669,9 @@ export async function createFakeTenant(options) {
1648
1669
  });
1649
1670
  return roleId;
1650
1671
  },
1672
+ deregisterPermission: (key) => {
1673
+ deregisteredPermissions.add(key);
1674
+ },
1651
1675
  registerResourceType: (type) => {
1652
1676
  resourceTypes.add(type);
1653
1677
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@udibo/oauth2",
3
- "version": "0.55.3",
3
+ "version": "0.56.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.55.3"
8
- targets: "@udibo/oauth2@0.55.3"
7
+ version: "0.56.0"
8
+ targets: "@udibo/oauth2@0.56.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.55.3/docs/quickstart.md).
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).
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.55.3
71
+ npm install --save-exact @udibo/oauth2@0.56.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.55.3/docs/guides/become-an-oauth-provider.md) · [Production deployment](https://github.com/udibo/oauth2/blob/0.55.3/docs/guides/production-deployment.md)
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)
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.55.3/docs/guides/protect-an-api.md)
122
+ [Protect an API](https://github.com/udibo/oauth2/blob/0.56.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.55.3/docs/guides/use-udibo.md)
131
+ [Hosted integration guide](https://github.com/udibo/oauth2/blob/0.56.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.55.3/docs/guides/migrate-from-another-provider.md)
139
+ [Migration guide](https://github.com/udibo/oauth2/blob/0.56.0/docs/guides/migrate-from-another-provider.md)