@anievo-id/rbac-evolution 0.2.1 → 0.3.1

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/testing.cjs CHANGED
@@ -121,9 +121,164 @@ function wildcardImplies(granted, required) {
121
121
  return true;
122
122
  }
123
123
 
124
+ // src/sync.ts
125
+ var idKey = (id) => id === null ? "\0null" : String(id);
126
+ function invalid(message) {
127
+ return new RbacError("INVALID_SYNC_DEFINITION", message);
128
+ }
129
+ function cleanName(value, where) {
130
+ if (typeof value !== "string") throw invalid(`${where} must be a string, got ${typeof value}.`);
131
+ const name = value.trim();
132
+ if (name === "") throw new RbacError("INVALID_NAME", "Role and permission names must not be empty.");
133
+ return name;
134
+ }
135
+ function pushUnique(list, name) {
136
+ if (!list.includes(name)) list.push(name);
137
+ }
138
+ function normalize(rbac, definition, options) {
139
+ const list = Array.isArray(definition) ? definition : [definition];
140
+ const blocks = [];
141
+ list.forEach((raw, index) => {
142
+ const at = list.length > 1 ? `definition[${index}]` : "definition";
143
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalid(`${at} must be an object.`);
144
+ const def = raw;
145
+ const guardInput = def["guard"] ?? options.guard;
146
+ if (guardInput !== void 0 && typeof guardInput !== "string") throw invalid(`${at}.guard must be a string.`);
147
+ const guard = rbac.resolveGuard(guardInput === void 0 ? void 0 : cleanName(guardInput, `${at}.guard`));
148
+ const teamInput = def["team"] !== void 0 ? def["team"] : options.team;
149
+ if (teamInput !== void 0 && teamInput !== null && typeof teamInput !== "string" && typeof teamInput !== "number") {
150
+ throw invalid(`${at}.team must be a string, a number or null.`);
151
+ }
152
+ const team = rbac.resolveTeam(teamInput);
153
+ let block = blocks.find((b) => b.guard === guard && idKey(b.team) === idKey(team));
154
+ if (!block) {
155
+ block = { guard, team, permissions: [], roles: /* @__PURE__ */ new Map() };
156
+ blocks.push(block);
157
+ }
158
+ const permissions = def["permissions"];
159
+ if (permissions !== void 0) {
160
+ if (!Array.isArray(permissions)) throw invalid(`${at}.permissions must be an array of names.`);
161
+ for (const p of permissions) pushUnique(block.permissions, cleanName(p, `${at}.permissions[]`));
162
+ }
163
+ const roles = def["roles"];
164
+ if (roles !== void 0) {
165
+ if (typeof roles !== "object" || roles === null || Array.isArray(roles)) {
166
+ throw invalid(`${at}.roles must be an object mapping role names to permissions.`);
167
+ }
168
+ for (const [rawName, value] of Object.entries(roles)) {
169
+ if (value === void 0) continue;
170
+ const name = cleanName(rawName, `${at}.roles key`);
171
+ if (block.roles.has(name)) {
172
+ throw invalid(`Role \`${name}\` is defined twice for guard \`${guard}\`${team === null ? "" : ` (team ${String(team)})`}.`);
173
+ }
174
+ if (value === "*") {
175
+ block.roles.set(name, "*");
176
+ } else if (Array.isArray(value)) {
177
+ const names = [];
178
+ for (const p of value) pushUnique(names, cleanName(p, `${at}.roles.${name}[]`));
179
+ block.roles.set(name, names);
180
+ } else {
181
+ throw invalid(`${at}.roles.${name} must be an array of permission names or '*'.`);
182
+ }
183
+ }
184
+ }
185
+ });
186
+ return blocks;
187
+ }
188
+ async function syncDefinition(rbac, definition, options = {}) {
189
+ const blocks = normalize(rbac, definition, options);
190
+ const prune = options.prune ?? false;
191
+ const dryRun = options.dryRun ?? false;
192
+ const result = {
193
+ dryRun,
194
+ created: { permissions: [], roles: [] },
195
+ updated: { roles: [] },
196
+ deleted: { permissions: [], roles: [] }
197
+ };
198
+ const guards = [...new Set(blocks.map((b) => b.guard))];
199
+ const existingPermissions = /* @__PURE__ */ new Map();
200
+ const finalPermissions = /* @__PURE__ */ new Map();
201
+ const permissionsToDelete = [];
202
+ for (const guard of guards) {
203
+ const declared = [];
204
+ for (const block of blocks.filter((b) => b.guard === guard)) {
205
+ for (const p of block.permissions) pushUnique(declared, p);
206
+ for (const list of block.roles.values()) if (list !== "*") for (const p of list) pushUnique(declared, p);
207
+ }
208
+ if (rbac.wildcard) for (const p of declared) parseWildcardPermission(p);
209
+ const existing = await rbac.adapter.findPermissions({ guardName: guard });
210
+ existingPermissions.set(guard, existing);
211
+ const existingNames = existing.map((p) => p.name);
212
+ for (const name of declared) {
213
+ if (!existingNames.includes(name)) result.created.permissions.push({ name, guard });
214
+ }
215
+ const ownsPermissions = blocks.some((b) => b.guard === guard && b.team === null);
216
+ const stale = prune && ownsPermissions ? existing.filter((p) => !declared.includes(p.name)) : [];
217
+ permissionsToDelete.push(...stale);
218
+ for (const p of stale) result.deleted.permissions.push({ name: p.name, guard });
219
+ finalPermissions.set(guard, [
220
+ ...existingNames.filter((n) => !stale.some((p) => p.name === n)),
221
+ ...declared.filter((n) => !existingNames.includes(n))
222
+ ]);
223
+ }
224
+ const plans = [];
225
+ const rolesToDelete = [];
226
+ for (const block of blocks) {
227
+ const { guard, team } = block;
228
+ const existing = await rbac.adapter.findRoles({ guardName: guard, teamIds: [team] });
229
+ const links = existing.length > 0 ? await rbac.adapter.getRolePermissionLinks(existing.map((r) => r.id)) : [];
230
+ const permissionNames = new Map((existingPermissions.get(guard) ?? []).map((p) => [idKey(p.id), p.name]));
231
+ const namesOf = (role) => {
232
+ const names = [];
233
+ for (const link of links) {
234
+ if (idKey(link.roleId) !== idKey(role.id)) continue;
235
+ const name = permissionNames.get(idKey(link.permissionId));
236
+ if (name !== void 0) pushUnique(names, name);
237
+ }
238
+ return names;
239
+ };
240
+ for (const [name, wanted] of block.roles) {
241
+ const role = existing.find((r) => r.name === name) ?? null;
242
+ const desired = wanted === "*" ? [...finalPermissions.get(guard) ?? []] : wanted;
243
+ const plan = { name, guard, team, existing: role, desired, current: role ? namesOf(role) : [] };
244
+ plans.push(plan);
245
+ if (!role) {
246
+ result.created.roles.push({ name, guard, team, permissions: [...desired] });
247
+ continue;
248
+ }
249
+ const attached = desired.filter((p) => !plan.current.includes(p));
250
+ const detached = plan.current.filter((p) => !desired.includes(p));
251
+ if (attached.length > 0 || detached.length > 0) {
252
+ result.updated.roles.push({ name, guard, team, attached, detached });
253
+ }
254
+ }
255
+ if (prune) {
256
+ for (const role of existing) {
257
+ if (block.roles.has(role.name)) continue;
258
+ rolesToDelete.push(role);
259
+ result.deleted.roles.push({ name: role.name, guard, team, permissions: namesOf(role) });
260
+ }
261
+ }
262
+ }
263
+ if (dryRun) return result;
264
+ for (const { name, guard } of result.created.permissions) {
265
+ await rbac.createPermission(name, { guard });
266
+ }
267
+ for (const plan of plans) {
268
+ const changed = plan.existing === null || plan.desired.length !== plan.current.length || plan.desired.some((p) => !plan.current.includes(p));
269
+ if (!changed) continue;
270
+ const role = plan.existing ?? await rbac.createRole(plan.name, { guard: plan.guard, team: plan.team });
271
+ if (plan.existing === null && plan.desired.length === 0) continue;
272
+ await rbac.role(role).syncPermissions(plan.desired);
273
+ }
274
+ for (const role of rolesToDelete) await rbac.deleteRole(role);
275
+ for (const permission of permissionsToDelete) await rbac.deletePermission(permission);
276
+ return result;
277
+ }
278
+
124
279
  // src/rbac.ts
125
280
  var DAY_MS = 24 * 60 * 60 * 1e3;
126
- var idKey = (id) => id === null ? "\0null" : String(id);
281
+ var idKey2 = (id) => id === null ? "\0null" : String(id);
127
282
  function flatten(items) {
128
283
  const out = [];
129
284
  for (const item of items) {
@@ -135,7 +290,7 @@ function flatten(items) {
135
290
  function uniqueById(items) {
136
291
  const seen = /* @__PURE__ */ new Set();
137
292
  return items.filter((item) => {
138
- const k = idKey(item.id);
293
+ const k = idKey2(item.id);
139
294
  if (seen.has(k)) return false;
140
295
  seen.add(k);
141
296
  return true;
@@ -144,15 +299,19 @@ function uniqueById(items) {
144
299
  function uniqueIds(ids) {
145
300
  const seen = /* @__PURE__ */ new Set();
146
301
  return ids.filter((id) => {
147
- const k = idKey(id);
302
+ const k = idKey2(id);
148
303
  if (seen.has(k)) return false;
149
304
  seen.add(k);
150
305
  return true;
151
306
  });
152
307
  }
153
308
  function filterByIds(items, ids, keep) {
154
- const set = new Set(ids.map(idKey));
155
- return items.filter((item) => set.has(idKey(item.id)) === keep);
309
+ const set = new Set(ids.map(idKey2));
310
+ return items.filter((item) => set.has(idKey2(item.id)) === keep);
311
+ }
312
+ function filterIds(ids, remove) {
313
+ const set = new Set(remove.map(idKey2));
314
+ return ids.filter((id) => !set.has(idKey2(id)));
156
315
  }
157
316
  function normalizeName(name) {
158
317
  const trimmed = name.trim();
@@ -169,6 +328,8 @@ var Rbac = class _Rbac {
169
328
  #before;
170
329
  #superAdminRoles;
171
330
  #events = new RbacEmitter();
331
+ /** Bumped on every change, so a lookup that started before the change never caches its stale result. */
332
+ #generation = 0;
172
333
  constructor(options) {
173
334
  this.adapter = options.adapter;
174
335
  this.defaultGuard = options.defaultGuard ?? "web";
@@ -281,6 +442,30 @@ var Rbac = class _Rbac {
281
442
  await this.forgetCachedPermissions();
282
443
  await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
283
444
  }
445
+ // ------------------------------------------------------------------------- sync
446
+ /**
447
+ * Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
448
+ * permissions and roles, and syncs each role's permissions to exactly the given list.
449
+ * Idempotent — running it again changes nothing. Uses the regular engine methods, so the
450
+ * usual events fire.
451
+ *
452
+ * ```ts
453
+ * await rbac.sync({
454
+ * permissions: ['edit articles', 'delete articles'],
455
+ * roles: { admin: '*', writer: ['edit articles'] },
456
+ * })
457
+ * ```
458
+ *
459
+ * - `'*'` gives a role every permission of its guard (after the sync).
460
+ * - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
461
+ * - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
462
+ * - `dryRun: true` returns the plan without writing anything.
463
+ *
464
+ * Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
465
+ */
466
+ async sync(definition, options = {}) {
467
+ return syncDefinition(this, definition, options);
468
+ }
284
469
  // ---------------------------------------------------------------------- queries
285
470
  /**
286
471
  * Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
@@ -308,10 +493,10 @@ var Rbac = class _Rbac {
308
493
  const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
309
494
  if (resolved.length === 0) return [];
310
495
  const permissionIds = resolved.map((p) => p.id);
311
- const wanted = new Set(permissionIds.map(idKey));
496
+ const wanted = new Set(permissionIds.map(idKey2));
312
497
  const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
313
498
  const links = roles.length > 0 ? await this.adapter.getRolePermissionLinks(roles.map((r) => r.id)) : [];
314
- const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey(l.permissionId))).map((l) => l.roleId));
499
+ const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey2(l.permissionId))).map((l) => l.roleId));
315
500
  const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
316
501
  const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
317
502
  return uniqueIds([...viaRoles, ...direct]);
@@ -319,6 +504,7 @@ var Rbac = class _Rbac {
319
504
  // ------------------------------------------------------------------------ cache
320
505
  /** Clears every cached role/permission lookup. Called automatically after each change. */
321
506
  async forgetCachedPermissions() {
507
+ this.#generation++;
322
508
  await this.#cache?.clear();
323
509
  }
324
510
  /** @internal */
@@ -326,8 +512,9 @@ var Rbac = class _Rbac {
326
512
  if (!this.#cache) return compute();
327
513
  const hit = await this.#cache.get(key);
328
514
  if (hit !== void 0) return hit;
515
+ const generation = this.#generation;
329
516
  const value = await compute();
330
- await this.#cache.set(key, value, this.#cacheTtl);
517
+ if (generation === this.#generation) await this.#cache.set(key, value, this.#cacheTtl);
331
518
  return value;
332
519
  }
333
520
  /**
@@ -401,7 +588,7 @@ var Rbac = class _Rbac {
401
588
  names.push(normalizeName(input));
402
589
  } else {
403
590
  if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
404
- if (input.teamId !== null && idKey(input.teamId) !== idKey(teamId)) {
591
+ if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
405
592
  throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
406
593
  }
407
594
  objects.push(input);
@@ -428,7 +615,7 @@ var Rbac = class _Rbac {
428
615
  }
429
616
  static pickRole(roles, name, teamId) {
430
617
  const candidates = roles.filter((r) => r.name === name);
431
- return candidates.find((r) => idKey(r.teamId) === idKey(teamId)) ?? candidates.find((r) => r.teamId === null);
618
+ return candidates.find((r) => idKey2(r.teamId) === idKey2(teamId)) ?? candidates.find((r) => r.teamId === null);
432
619
  }
433
620
  };
434
621
  var RoleRbac = class {
@@ -473,11 +660,12 @@ var RoleRbac = class {
473
660
  const resolved = await this.rbac.resolvePermissions(flatten(permissions), role.guardName);
474
661
  const track = this.rbac.events.has("permission.attached") || this.rbac.events.has("permission.detached");
475
662
  const current = track ? await this.getPermissions() : [];
476
- await this.rbac.adapter.detachRolePermissions(role.id);
477
- await this.rbac.adapter.attachRolePermissions(role.id, resolved.map((p) => p.id));
663
+ const newIds = resolved.map((p) => p.id);
664
+ await this.rbac.adapter.attachRolePermissions(role.id, newIds);
665
+ const staleIds = filterIds(await this.currentPermissionIds(role), newIds);
666
+ if (staleIds.length > 0) await this.rbac.adapter.detachRolePermissions(role.id, staleIds);
478
667
  await this.rbac.forgetCachedPermissions();
479
668
  if (track) {
480
- const newIds = resolved.map((p) => p.id);
481
669
  await this.emit("permission.detached", role, filterByIds(current, newIds, false));
482
670
  await this.emit("permission.attached", role, filterByIds(resolved, current.map((p) => p.id), false));
483
671
  }
@@ -547,8 +735,10 @@ var SubjectRbac = class _SubjectRbac {
547
735
  async syncRoles(...roles) {
548
736
  const resolved = await this.rbac.resolveRoles(flatten(roles), this.guardName, this.teamId);
549
737
  const current = (await this.state()).roles;
550
- await this.rbac.adapter.detachSubjectRoles(this.subject, current.map((r) => r.id), this.teamId);
551
- await this.rbac.adapter.attachSubjectRoles(this.subject, resolved.map((r) => r.id), this.teamId);
738
+ const newIds = resolved.map((r) => r.id);
739
+ await this.rbac.adapter.attachSubjectRoles(this.subject, newIds, this.teamId);
740
+ const stale = filterByIds(current, newIds, false);
741
+ if (stale.length > 0) await this.rbac.adapter.detachSubjectRoles(this.subject, stale.map((r) => r.id), this.teamId);
552
742
  await this.rbac.forgetCachedPermissions();
553
743
  await this.emitRoles("role.detached", filterByIds(current, resolved.map((r) => r.id), false));
554
744
  await this.emitRoles("role.attached", filterByIds(resolved, current.map((r) => r.id), false));
@@ -579,7 +769,7 @@ var SubjectRbac = class _SubjectRbac {
579
769
  for (const wanted of flatten(roles)) {
580
770
  const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
581
771
  if (!role) return false;
582
- matched.add(idKey(role.id));
772
+ matched.add(idKey2(role.id));
583
773
  }
584
774
  return matched.size === mine.length;
585
775
  }
@@ -608,8 +798,12 @@ var SubjectRbac = class _SubjectRbac {
608
798
  async syncPermissions(...permissions) {
609
799
  const resolved = await this.rbac.resolvePermissions(flatten(permissions), this.guardName);
610
800
  const current = (await this.state()).direct;
611
- await this.rbac.adapter.detachSubjectPermissions(this.subject, current.map((p) => p.id), this.teamId);
612
- await this.rbac.adapter.attachSubjectPermissions(this.subject, resolved.map((p) => p.id), this.teamId);
801
+ const newIds = resolved.map((p) => p.id);
802
+ await this.rbac.adapter.attachSubjectPermissions(this.subject, newIds, this.teamId);
803
+ const stale = filterByIds(current, newIds, false);
804
+ if (stale.length > 0) {
805
+ await this.rbac.adapter.detachSubjectPermissions(this.subject, stale.map((p) => p.id), this.teamId);
806
+ }
613
807
  await this.rbac.forgetCachedPermissions();
614
808
  await this.emitPermissions("permission.detached", filterByIds(current, resolved.map((p) => p.id), false));
615
809
  await this.emitPermissions("permission.attached", filterByIds(resolved, current.map((p) => p.id), false));
@@ -744,7 +938,7 @@ var SubjectRbac = class _SubjectRbac {
744
938
  });
745
939
  }
746
940
  static roleMatches(role, wanted) {
747
- return typeof wanted === "string" ? role.name === wanted.trim() : idKey(role.id) === idKey(wanted.id);
941
+ return typeof wanted === "string" ? role.name === wanted.trim() : idKey2(role.id) === idKey2(wanted.id);
748
942
  }
749
943
  };
750
944
  function createRbac(options) {