@anievo-id/rbac-evolution 0.2.0 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ // package.json
4
+ var version = "0.3.0";
5
+
3
6
  // src/cache.ts
4
7
  var MemoryCache = class {
5
8
  store = /* @__PURE__ */ new Map();
@@ -117,9 +120,164 @@ function wildcardImplies(granted, required) {
117
120
  return true;
118
121
  }
119
122
 
123
+ // src/sync.ts
124
+ var idKey = (id) => id === null ? "\0null" : String(id);
125
+ function invalid(message) {
126
+ return new RbacError("INVALID_SYNC_DEFINITION", message);
127
+ }
128
+ function cleanName(value, where) {
129
+ if (typeof value !== "string") throw invalid(`${where} must be a string, got ${typeof value}.`);
130
+ const name = value.trim();
131
+ if (name === "") throw new RbacError("INVALID_NAME", "Role and permission names must not be empty.");
132
+ return name;
133
+ }
134
+ function pushUnique(list, name) {
135
+ if (!list.includes(name)) list.push(name);
136
+ }
137
+ function normalize(rbac, definition, options) {
138
+ const list = Array.isArray(definition) ? definition : [definition];
139
+ const blocks = [];
140
+ list.forEach((raw, index) => {
141
+ const at = list.length > 1 ? `definition[${index}]` : "definition";
142
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalid(`${at} must be an object.`);
143
+ const def = raw;
144
+ const guardInput = def["guard"] ?? options.guard;
145
+ if (guardInput !== void 0 && typeof guardInput !== "string") throw invalid(`${at}.guard must be a string.`);
146
+ const guard = rbac.resolveGuard(guardInput === void 0 ? void 0 : cleanName(guardInput, `${at}.guard`));
147
+ const teamInput = def["team"] !== void 0 ? def["team"] : options.team;
148
+ if (teamInput !== void 0 && teamInput !== null && typeof teamInput !== "string" && typeof teamInput !== "number") {
149
+ throw invalid(`${at}.team must be a string, a number or null.`);
150
+ }
151
+ const team = rbac.resolveTeam(teamInput);
152
+ let block = blocks.find((b) => b.guard === guard && idKey(b.team) === idKey(team));
153
+ if (!block) {
154
+ block = { guard, team, permissions: [], roles: /* @__PURE__ */ new Map() };
155
+ blocks.push(block);
156
+ }
157
+ const permissions = def["permissions"];
158
+ if (permissions !== void 0) {
159
+ if (!Array.isArray(permissions)) throw invalid(`${at}.permissions must be an array of names.`);
160
+ for (const p of permissions) pushUnique(block.permissions, cleanName(p, `${at}.permissions[]`));
161
+ }
162
+ const roles = def["roles"];
163
+ if (roles !== void 0) {
164
+ if (typeof roles !== "object" || roles === null || Array.isArray(roles)) {
165
+ throw invalid(`${at}.roles must be an object mapping role names to permissions.`);
166
+ }
167
+ for (const [rawName, value] of Object.entries(roles)) {
168
+ if (value === void 0) continue;
169
+ const name = cleanName(rawName, `${at}.roles key`);
170
+ if (block.roles.has(name)) {
171
+ throw invalid(`Role \`${name}\` is defined twice for guard \`${guard}\`${team === null ? "" : ` (team ${String(team)})`}.`);
172
+ }
173
+ if (value === "*") {
174
+ block.roles.set(name, "*");
175
+ } else if (Array.isArray(value)) {
176
+ const names = [];
177
+ for (const p of value) pushUnique(names, cleanName(p, `${at}.roles.${name}[]`));
178
+ block.roles.set(name, names);
179
+ } else {
180
+ throw invalid(`${at}.roles.${name} must be an array of permission names or '*'.`);
181
+ }
182
+ }
183
+ }
184
+ });
185
+ return blocks;
186
+ }
187
+ async function syncDefinition(rbac, definition, options = {}) {
188
+ const blocks = normalize(rbac, definition, options);
189
+ const prune = options.prune ?? false;
190
+ const dryRun = options.dryRun ?? false;
191
+ const result = {
192
+ dryRun,
193
+ created: { permissions: [], roles: [] },
194
+ updated: { roles: [] },
195
+ deleted: { permissions: [], roles: [] }
196
+ };
197
+ const guards = [...new Set(blocks.map((b) => b.guard))];
198
+ const existingPermissions = /* @__PURE__ */ new Map();
199
+ const finalPermissions = /* @__PURE__ */ new Map();
200
+ const permissionsToDelete = [];
201
+ for (const guard of guards) {
202
+ const declared = [];
203
+ for (const block of blocks.filter((b) => b.guard === guard)) {
204
+ for (const p of block.permissions) pushUnique(declared, p);
205
+ for (const list of block.roles.values()) if (list !== "*") for (const p of list) pushUnique(declared, p);
206
+ }
207
+ if (rbac.wildcard) for (const p of declared) parseWildcardPermission(p);
208
+ const existing = await rbac.adapter.findPermissions({ guardName: guard });
209
+ existingPermissions.set(guard, existing);
210
+ const existingNames = existing.map((p) => p.name);
211
+ for (const name of declared) {
212
+ if (!existingNames.includes(name)) result.created.permissions.push({ name, guard });
213
+ }
214
+ const ownsPermissions = blocks.some((b) => b.guard === guard && b.team === null);
215
+ const stale = prune && ownsPermissions ? existing.filter((p) => !declared.includes(p.name)) : [];
216
+ permissionsToDelete.push(...stale);
217
+ for (const p of stale) result.deleted.permissions.push({ name: p.name, guard });
218
+ finalPermissions.set(guard, [
219
+ ...existingNames.filter((n) => !stale.some((p) => p.name === n)),
220
+ ...declared.filter((n) => !existingNames.includes(n))
221
+ ]);
222
+ }
223
+ const plans = [];
224
+ const rolesToDelete = [];
225
+ for (const block of blocks) {
226
+ const { guard, team } = block;
227
+ const existing = await rbac.adapter.findRoles({ guardName: guard, teamIds: [team] });
228
+ const links = existing.length > 0 ? await rbac.adapter.getRolePermissionLinks(existing.map((r) => r.id)) : [];
229
+ const permissionNames = new Map((existingPermissions.get(guard) ?? []).map((p) => [idKey(p.id), p.name]));
230
+ const namesOf = (role) => {
231
+ const names = [];
232
+ for (const link of links) {
233
+ if (idKey(link.roleId) !== idKey(role.id)) continue;
234
+ const name = permissionNames.get(idKey(link.permissionId));
235
+ if (name !== void 0) pushUnique(names, name);
236
+ }
237
+ return names;
238
+ };
239
+ for (const [name, wanted] of block.roles) {
240
+ const role = existing.find((r) => r.name === name) ?? null;
241
+ const desired = wanted === "*" ? [...finalPermissions.get(guard) ?? []] : wanted;
242
+ const plan = { name, guard, team, existing: role, desired, current: role ? namesOf(role) : [] };
243
+ plans.push(plan);
244
+ if (!role) {
245
+ result.created.roles.push({ name, guard, team, permissions: [...desired] });
246
+ continue;
247
+ }
248
+ const attached = desired.filter((p) => !plan.current.includes(p));
249
+ const detached = plan.current.filter((p) => !desired.includes(p));
250
+ if (attached.length > 0 || detached.length > 0) {
251
+ result.updated.roles.push({ name, guard, team, attached, detached });
252
+ }
253
+ }
254
+ if (prune) {
255
+ for (const role of existing) {
256
+ if (block.roles.has(role.name)) continue;
257
+ rolesToDelete.push(role);
258
+ result.deleted.roles.push({ name: role.name, guard, team, permissions: namesOf(role) });
259
+ }
260
+ }
261
+ }
262
+ if (dryRun) return result;
263
+ for (const { name, guard } of result.created.permissions) {
264
+ await rbac.createPermission(name, { guard });
265
+ }
266
+ for (const plan of plans) {
267
+ const changed = plan.existing === null || plan.desired.length !== plan.current.length || plan.desired.some((p) => !plan.current.includes(p));
268
+ if (!changed) continue;
269
+ const role = plan.existing ?? await rbac.createRole(plan.name, { guard: plan.guard, team: plan.team });
270
+ if (plan.existing === null && plan.desired.length === 0) continue;
271
+ await rbac.role(role).syncPermissions(plan.desired);
272
+ }
273
+ for (const role of rolesToDelete) await rbac.deleteRole(role);
274
+ for (const permission of permissionsToDelete) await rbac.deletePermission(permission);
275
+ return result;
276
+ }
277
+
120
278
  // src/rbac.ts
121
279
  var DAY_MS = 24 * 60 * 60 * 1e3;
122
- var idKey = (id) => id === null ? "\0null" : String(id);
280
+ var idKey2 = (id) => id === null ? "\0null" : String(id);
123
281
  function flatten(items) {
124
282
  const out = [];
125
283
  for (const item of items) {
@@ -131,7 +289,7 @@ function flatten(items) {
131
289
  function uniqueById(items) {
132
290
  const seen = /* @__PURE__ */ new Set();
133
291
  return items.filter((item) => {
134
- const k = idKey(item.id);
292
+ const k = idKey2(item.id);
135
293
  if (seen.has(k)) return false;
136
294
  seen.add(k);
137
295
  return true;
@@ -140,15 +298,15 @@ function uniqueById(items) {
140
298
  function uniqueIds(ids) {
141
299
  const seen = /* @__PURE__ */ new Set();
142
300
  return ids.filter((id) => {
143
- const k = idKey(id);
301
+ const k = idKey2(id);
144
302
  if (seen.has(k)) return false;
145
303
  seen.add(k);
146
304
  return true;
147
305
  });
148
306
  }
149
307
  function filterByIds(items, ids, keep) {
150
- const set = new Set(ids.map(idKey));
151
- return items.filter((item) => set.has(idKey(item.id)) === keep);
308
+ const set = new Set(ids.map(idKey2));
309
+ return items.filter((item) => set.has(idKey2(item.id)) === keep);
152
310
  }
153
311
  function normalizeName(name) {
154
312
  const trimmed = name.trim();
@@ -277,6 +435,30 @@ var Rbac = class _Rbac {
277
435
  await this.forgetCachedPermissions();
278
436
  await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
279
437
  }
438
+ // ------------------------------------------------------------------------- sync
439
+ /**
440
+ * Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
441
+ * permissions and roles, and syncs each role's permissions to exactly the given list.
442
+ * Idempotent — running it again changes nothing. Uses the regular engine methods, so the
443
+ * usual events fire.
444
+ *
445
+ * ```ts
446
+ * await rbac.sync({
447
+ * permissions: ['edit articles', 'delete articles'],
448
+ * roles: { admin: '*', writer: ['edit articles'] },
449
+ * })
450
+ * ```
451
+ *
452
+ * - `'*'` gives a role every permission of its guard (after the sync).
453
+ * - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
454
+ * - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
455
+ * - `dryRun: true` returns the plan without writing anything.
456
+ *
457
+ * Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
458
+ */
459
+ async sync(definition, options = {}) {
460
+ return syncDefinition(this, definition, options);
461
+ }
280
462
  // ---------------------------------------------------------------------- queries
281
463
  /**
282
464
  * Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
@@ -304,10 +486,10 @@ var Rbac = class _Rbac {
304
486
  const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
305
487
  if (resolved.length === 0) return [];
306
488
  const permissionIds = resolved.map((p) => p.id);
307
- const wanted = new Set(permissionIds.map(idKey));
489
+ const wanted = new Set(permissionIds.map(idKey2));
308
490
  const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
309
491
  const links = roles.length > 0 ? await this.adapter.getRolePermissionLinks(roles.map((r) => r.id)) : [];
310
- const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey(l.permissionId))).map((l) => l.roleId));
492
+ const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey2(l.permissionId))).map((l) => l.roleId));
311
493
  const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
312
494
  const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
313
495
  return uniqueIds([...viaRoles, ...direct]);
@@ -326,6 +508,22 @@ var Rbac = class _Rbac {
326
508
  await this.#cache.set(key2, value, this.#cacheTtl);
327
509
  return value;
328
510
  }
511
+ /**
512
+ * @internal Whether a permission with this name exists in the guard.
513
+ * With caching on, the guard's permission names are cached (cleared on every change),
514
+ * so repeated `can()` checks don't hit the database.
515
+ */
516
+ async permissionExists(name, guardName) {
517
+ if (!this.#cache) {
518
+ const [permission] = await this.adapter.findPermissions({ names: [name], guardName });
519
+ return permission !== void 0;
520
+ }
521
+ const names = await this.remember(
522
+ `rbac:permissions:${JSON.stringify([guardName])}`,
523
+ async () => (await this.adapter.findPermissions({ guardName })).map((p) => p.name)
524
+ );
525
+ return names.includes(name);
526
+ }
329
527
  // ---------------------------------------------------------------------- internal
330
528
  /** @internal Runs the `before` hook and the super-admin check. `undefined` = no decision. */
331
529
  async gate(subject, permission) {
@@ -381,7 +579,7 @@ var Rbac = class _Rbac {
381
579
  names.push(normalizeName(input));
382
580
  } else {
383
581
  if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
384
- if (input.teamId !== null && idKey(input.teamId) !== idKey(teamId)) {
582
+ if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
385
583
  throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
386
584
  }
387
585
  objects.push(input);
@@ -408,7 +606,7 @@ var Rbac = class _Rbac {
408
606
  }
409
607
  static pickRole(roles, name, teamId) {
410
608
  const candidates = roles.filter((r) => r.name === name);
411
- return candidates.find((r) => idKey(r.teamId) === idKey(teamId)) ?? candidates.find((r) => r.teamId === null);
609
+ return candidates.find((r) => idKey2(r.teamId) === idKey2(teamId)) ?? candidates.find((r) => r.teamId === null);
412
610
  }
413
611
  };
414
612
  var RoleRbac = class {
@@ -559,7 +757,7 @@ var SubjectRbac = class _SubjectRbac {
559
757
  for (const wanted of flatten(roles)) {
560
758
  const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
561
759
  if (!role) return false;
562
- matched.add(idKey(role.id));
760
+ matched.add(idKey2(role.id));
563
761
  }
564
762
  return matched.size === mine.length;
565
763
  }
@@ -684,7 +882,7 @@ var SubjectRbac = class _SubjectRbac {
684
882
  return permission.name;
685
883
  }
686
884
  const name = normalizeName(permission);
687
- if (!this.rbac.wildcard && !await this.rbac.findPermission(name, { guard: this.guardName })) {
885
+ if (!this.rbac.wildcard && !await this.rbac.permissionExists(name, this.guardName)) {
688
886
  throw new PermissionDoesNotExist(name, this.guardName);
689
887
  }
690
888
  return name;
@@ -724,7 +922,7 @@ var SubjectRbac = class _SubjectRbac {
724
922
  });
725
923
  }
726
924
  static roleMatches(role, wanted) {
727
- return typeof wanted === "string" ? role.name === wanted.trim() : idKey(role.id) === idKey(wanted.id);
925
+ return typeof wanted === "string" ? role.name === wanted.trim() : idKey2(role.id) === idKey2(wanted.id);
728
926
  }
729
927
  };
730
928
  function createRbac(options) {
@@ -845,7 +1043,7 @@ var MemoryAdapter = class _MemoryAdapter {
845
1043
  };
846
1044
 
847
1045
  // src/index.ts
848
- var VERSION = "0.1.0";
1046
+ var VERSION = version;
849
1047
 
850
1048
  exports.GuardDoesNotMatch = GuardDoesNotMatch;
851
1049
  exports.InvalidWildcardPermission = InvalidWildcardPermission;