@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/README.md CHANGED
@@ -63,6 +63,29 @@ await writer.syncPermissions(['edit articles'])
63
63
  await writer.getPermissionNames() // ['edit articles']
64
64
  ```
65
65
 
66
+ ## Seeding (`rbac.sync`)
67
+
68
+ Declare your roles & permissions once and sync them — idempotent, so it's safe to run on every deploy:
69
+
70
+ ```ts
71
+ const summary = await rbac.sync(
72
+ {
73
+ permissions: ['edit articles', 'delete articles', 'publish articles'],
74
+ roles: {
75
+ admin: '*', // every permission of the guard
76
+ writer: ['edit articles'],
77
+ },
78
+ },
79
+ { prune: false, dryRun: false },
80
+ )
81
+ // summary: { dryRun, created: { permissions, roles }, updated: { roles }, deleted: { permissions, roles } }
82
+ ```
83
+
84
+ Missing permissions & roles are created, and each role's permissions are synced to exactly the
85
+ given list. Pass an array of definitions with their own `guard` / `team` to sync several scopes;
86
+ `prune: true` deletes what's not in the definition (only in the synced scopes); `dryRun: true`
87
+ returns the plan without writing. The regular events fire.
88
+
66
89
  ## Guards
67
90
 
68
91
  Like Laravel guards — separate sets of roles/permissions (e.g. `web` and `api`):
@@ -127,4 +127,4 @@ interface RbacAdapter {
127
127
  getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
128
128
  }
129
129
 
130
- export type { DefaultRbacTypes as D, FindPermissionsQuery as F, Id as I, Many as M, Permission as P, Role as R, Subject as S, TeamId as T, RbacTypeConfig as a, RbacAdapter as b, RoleName as c, RoleInput as d, PermissionInput as e, PermissionName as f, RbacSnapshot as g, FindRolesQuery as h, RolePermissionLink as i };
130
+ export type { DefaultRbacTypes as D, FindPermissionsQuery as F, Id as I, Many as M, Permission as P, Role as R, Subject as S, TeamId as T, RbacTypeConfig as a, PermissionName as b, RoleName as c, RbacAdapter as d, RoleInput as e, PermissionInput as f, RbacSnapshot as g, FindRolesQuery as h, RolePermissionLink as i };
@@ -127,4 +127,4 @@ interface RbacAdapter {
127
127
  getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
128
128
  }
129
129
 
130
- export type { DefaultRbacTypes as D, FindPermissionsQuery as F, Id as I, Many as M, Permission as P, Role as R, Subject as S, TeamId as T, RbacTypeConfig as a, RbacAdapter as b, RoleName as c, RoleInput as d, PermissionInput as e, PermissionName as f, RbacSnapshot as g, FindRolesQuery as h, RolePermissionLink as i };
130
+ export type { DefaultRbacTypes as D, FindPermissionsQuery as F, Id as I, Many as M, Permission as P, Role as R, Subject as S, TeamId as T, RbacTypeConfig as a, PermissionName as b, RoleName as c, RbacAdapter as d, RoleInput as e, PermissionInput as f, RbacSnapshot as g, FindRolesQuery as h, RolePermissionLink as i };
@@ -115,9 +115,164 @@ var RbacEmitter = class {
115
115
  }
116
116
  };
117
117
 
118
+ // src/sync.ts
119
+ var idKey = (id) => id === null ? "\0null" : String(id);
120
+ function invalid(message) {
121
+ return new RbacError("INVALID_SYNC_DEFINITION", message);
122
+ }
123
+ function cleanName(value, where) {
124
+ if (typeof value !== "string") throw invalid(`${where} must be a string, got ${typeof value}.`);
125
+ const name = value.trim();
126
+ if (name === "") throw new RbacError("INVALID_NAME", "Role and permission names must not be empty.");
127
+ return name;
128
+ }
129
+ function pushUnique(list, name) {
130
+ if (!list.includes(name)) list.push(name);
131
+ }
132
+ function normalize(rbac, definition, options) {
133
+ const list = Array.isArray(definition) ? definition : [definition];
134
+ const blocks = [];
135
+ list.forEach((raw, index) => {
136
+ const at = list.length > 1 ? `definition[${index}]` : "definition";
137
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalid(`${at} must be an object.`);
138
+ const def = raw;
139
+ const guardInput = def["guard"] ?? options.guard;
140
+ if (guardInput !== void 0 && typeof guardInput !== "string") throw invalid(`${at}.guard must be a string.`);
141
+ const guard = rbac.resolveGuard(guardInput === void 0 ? void 0 : cleanName(guardInput, `${at}.guard`));
142
+ const teamInput = def["team"] !== void 0 ? def["team"] : options.team;
143
+ if (teamInput !== void 0 && teamInput !== null && typeof teamInput !== "string" && typeof teamInput !== "number") {
144
+ throw invalid(`${at}.team must be a string, a number or null.`);
145
+ }
146
+ const team = rbac.resolveTeam(teamInput);
147
+ let block = blocks.find((b) => b.guard === guard && idKey(b.team) === idKey(team));
148
+ if (!block) {
149
+ block = { guard, team, permissions: [], roles: /* @__PURE__ */ new Map() };
150
+ blocks.push(block);
151
+ }
152
+ const permissions = def["permissions"];
153
+ if (permissions !== void 0) {
154
+ if (!Array.isArray(permissions)) throw invalid(`${at}.permissions must be an array of names.`);
155
+ for (const p of permissions) pushUnique(block.permissions, cleanName(p, `${at}.permissions[]`));
156
+ }
157
+ const roles = def["roles"];
158
+ if (roles !== void 0) {
159
+ if (typeof roles !== "object" || roles === null || Array.isArray(roles)) {
160
+ throw invalid(`${at}.roles must be an object mapping role names to permissions.`);
161
+ }
162
+ for (const [rawName, value] of Object.entries(roles)) {
163
+ if (value === void 0) continue;
164
+ const name = cleanName(rawName, `${at}.roles key`);
165
+ if (block.roles.has(name)) {
166
+ throw invalid(`Role \`${name}\` is defined twice for guard \`${guard}\`${team === null ? "" : ` (team ${String(team)})`}.`);
167
+ }
168
+ if (value === "*") {
169
+ block.roles.set(name, "*");
170
+ } else if (Array.isArray(value)) {
171
+ const names = [];
172
+ for (const p of value) pushUnique(names, cleanName(p, `${at}.roles.${name}[]`));
173
+ block.roles.set(name, names);
174
+ } else {
175
+ throw invalid(`${at}.roles.${name} must be an array of permission names or '*'.`);
176
+ }
177
+ }
178
+ }
179
+ });
180
+ return blocks;
181
+ }
182
+ async function syncDefinition(rbac, definition, options = {}) {
183
+ const blocks = normalize(rbac, definition, options);
184
+ const prune = options.prune ?? false;
185
+ const dryRun = options.dryRun ?? false;
186
+ const result = {
187
+ dryRun,
188
+ created: { permissions: [], roles: [] },
189
+ updated: { roles: [] },
190
+ deleted: { permissions: [], roles: [] }
191
+ };
192
+ const guards = [...new Set(blocks.map((b) => b.guard))];
193
+ const existingPermissions = /* @__PURE__ */ new Map();
194
+ const finalPermissions = /* @__PURE__ */ new Map();
195
+ const permissionsToDelete = [];
196
+ for (const guard of guards) {
197
+ const declared = [];
198
+ for (const block of blocks.filter((b) => b.guard === guard)) {
199
+ for (const p of block.permissions) pushUnique(declared, p);
200
+ for (const list of block.roles.values()) if (list !== "*") for (const p of list) pushUnique(declared, p);
201
+ }
202
+ if (rbac.wildcard) for (const p of declared) parseWildcardPermission(p);
203
+ const existing = await rbac.adapter.findPermissions({ guardName: guard });
204
+ existingPermissions.set(guard, existing);
205
+ const existingNames = existing.map((p) => p.name);
206
+ for (const name of declared) {
207
+ if (!existingNames.includes(name)) result.created.permissions.push({ name, guard });
208
+ }
209
+ const ownsPermissions = blocks.some((b) => b.guard === guard && b.team === null);
210
+ const stale = prune && ownsPermissions ? existing.filter((p) => !declared.includes(p.name)) : [];
211
+ permissionsToDelete.push(...stale);
212
+ for (const p of stale) result.deleted.permissions.push({ name: p.name, guard });
213
+ finalPermissions.set(guard, [
214
+ ...existingNames.filter((n) => !stale.some((p) => p.name === n)),
215
+ ...declared.filter((n) => !existingNames.includes(n))
216
+ ]);
217
+ }
218
+ const plans = [];
219
+ const rolesToDelete = [];
220
+ for (const block of blocks) {
221
+ const { guard, team } = block;
222
+ const existing = await rbac.adapter.findRoles({ guardName: guard, teamIds: [team] });
223
+ const links = existing.length > 0 ? await rbac.adapter.getRolePermissionLinks(existing.map((r) => r.id)) : [];
224
+ const permissionNames = new Map((existingPermissions.get(guard) ?? []).map((p) => [idKey(p.id), p.name]));
225
+ const namesOf = (role) => {
226
+ const names = [];
227
+ for (const link of links) {
228
+ if (idKey(link.roleId) !== idKey(role.id)) continue;
229
+ const name = permissionNames.get(idKey(link.permissionId));
230
+ if (name !== void 0) pushUnique(names, name);
231
+ }
232
+ return names;
233
+ };
234
+ for (const [name, wanted] of block.roles) {
235
+ const role = existing.find((r) => r.name === name) ?? null;
236
+ const desired = wanted === "*" ? [...finalPermissions.get(guard) ?? []] : wanted;
237
+ const plan = { name, guard, team, existing: role, desired, current: role ? namesOf(role) : [] };
238
+ plans.push(plan);
239
+ if (!role) {
240
+ result.created.roles.push({ name, guard, team, permissions: [...desired] });
241
+ continue;
242
+ }
243
+ const attached = desired.filter((p) => !plan.current.includes(p));
244
+ const detached = plan.current.filter((p) => !desired.includes(p));
245
+ if (attached.length > 0 || detached.length > 0) {
246
+ result.updated.roles.push({ name, guard, team, attached, detached });
247
+ }
248
+ }
249
+ if (prune) {
250
+ for (const role of existing) {
251
+ if (block.roles.has(role.name)) continue;
252
+ rolesToDelete.push(role);
253
+ result.deleted.roles.push({ name: role.name, guard, team, permissions: namesOf(role) });
254
+ }
255
+ }
256
+ }
257
+ if (dryRun) return result;
258
+ for (const { name, guard } of result.created.permissions) {
259
+ await rbac.createPermission(name, { guard });
260
+ }
261
+ for (const plan of plans) {
262
+ const changed = plan.existing === null || plan.desired.length !== plan.current.length || plan.desired.some((p) => !plan.current.includes(p));
263
+ if (!changed) continue;
264
+ const role = plan.existing ?? await rbac.createRole(plan.name, { guard: plan.guard, team: plan.team });
265
+ if (plan.existing === null && plan.desired.length === 0) continue;
266
+ await rbac.role(role).syncPermissions(plan.desired);
267
+ }
268
+ for (const role of rolesToDelete) await rbac.deleteRole(role);
269
+ for (const permission of permissionsToDelete) await rbac.deletePermission(permission);
270
+ return result;
271
+ }
272
+
118
273
  // src/rbac.ts
119
274
  var DAY_MS = 24 * 60 * 60 * 1e3;
120
- var idKey = (id) => id === null ? "\0null" : String(id);
275
+ var idKey2 = (id) => id === null ? "\0null" : String(id);
121
276
  function flatten(items) {
122
277
  const out = [];
123
278
  for (const item of items) {
@@ -129,7 +284,7 @@ function flatten(items) {
129
284
  function uniqueById(items) {
130
285
  const seen = /* @__PURE__ */ new Set();
131
286
  return items.filter((item) => {
132
- const k = idKey(item.id);
287
+ const k = idKey2(item.id);
133
288
  if (seen.has(k)) return false;
134
289
  seen.add(k);
135
290
  return true;
@@ -138,15 +293,19 @@ function uniqueById(items) {
138
293
  function uniqueIds(ids) {
139
294
  const seen = /* @__PURE__ */ new Set();
140
295
  return ids.filter((id) => {
141
- const k = idKey(id);
296
+ const k = idKey2(id);
142
297
  if (seen.has(k)) return false;
143
298
  seen.add(k);
144
299
  return true;
145
300
  });
146
301
  }
147
302
  function filterByIds(items, ids, keep) {
148
- const set = new Set(ids.map(idKey));
149
- return items.filter((item) => set.has(idKey(item.id)) === keep);
303
+ const set = new Set(ids.map(idKey2));
304
+ return items.filter((item) => set.has(idKey2(item.id)) === keep);
305
+ }
306
+ function filterIds(ids, remove) {
307
+ const set = new Set(remove.map(idKey2));
308
+ return ids.filter((id) => !set.has(idKey2(id)));
150
309
  }
151
310
  function normalizeName(name) {
152
311
  const trimmed = name.trim();
@@ -163,6 +322,8 @@ var Rbac = class _Rbac {
163
322
  #before;
164
323
  #superAdminRoles;
165
324
  #events = new RbacEmitter();
325
+ /** Bumped on every change, so a lookup that started before the change never caches its stale result. */
326
+ #generation = 0;
166
327
  constructor(options) {
167
328
  this.adapter = options.adapter;
168
329
  this.defaultGuard = options.defaultGuard ?? "web";
@@ -275,6 +436,30 @@ var Rbac = class _Rbac {
275
436
  await this.forgetCachedPermissions();
276
437
  await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
277
438
  }
439
+ // ------------------------------------------------------------------------- sync
440
+ /**
441
+ * Declaratively seeds roles & permissions (spatie's "Database Seeding"): creates missing
442
+ * permissions and roles, and syncs each role's permissions to exactly the given list.
443
+ * Idempotent — running it again changes nothing. Uses the regular engine methods, so the
444
+ * usual events fire.
445
+ *
446
+ * ```ts
447
+ * await rbac.sync({
448
+ * permissions: ['edit articles', 'delete articles'],
449
+ * roles: { admin: '*', writer: ['edit articles'] },
450
+ * })
451
+ * ```
452
+ *
453
+ * - `'*'` gives a role every permission of its guard (after the sync).
454
+ * - Pass an array of definitions (each with its own `guard` / `team`) to sync several scopes.
455
+ * - `prune: true` deletes roles & permissions of the synced scopes that aren't in the definition.
456
+ * - `dryRun: true` returns the plan without writing anything.
457
+ *
458
+ * Not atomic: adapters have no transactions, so a failure midway leaves the earlier changes.
459
+ */
460
+ async sync(definition, options = {}) {
461
+ return syncDefinition(this, definition, options);
462
+ }
278
463
  // ---------------------------------------------------------------------- queries
279
464
  /**
280
465
  * Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
@@ -302,10 +487,10 @@ var Rbac = class _Rbac {
302
487
  const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
303
488
  if (resolved.length === 0) return [];
304
489
  const permissionIds = resolved.map((p) => p.id);
305
- const wanted = new Set(permissionIds.map(idKey));
490
+ const wanted = new Set(permissionIds.map(idKey2));
306
491
  const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
307
492
  const links = roles.length > 0 ? await this.adapter.getRolePermissionLinks(roles.map((r) => r.id)) : [];
308
- const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey(l.permissionId))).map((l) => l.roleId));
493
+ const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey2(l.permissionId))).map((l) => l.roleId));
309
494
  const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
310
495
  const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
311
496
  return uniqueIds([...viaRoles, ...direct]);
@@ -313,6 +498,7 @@ var Rbac = class _Rbac {
313
498
  // ------------------------------------------------------------------------ cache
314
499
  /** Clears every cached role/permission lookup. Called automatically after each change. */
315
500
  async forgetCachedPermissions() {
501
+ this.#generation++;
316
502
  await this.#cache?.clear();
317
503
  }
318
504
  /** @internal */
@@ -320,8 +506,9 @@ var Rbac = class _Rbac {
320
506
  if (!this.#cache) return compute();
321
507
  const hit = await this.#cache.get(key);
322
508
  if (hit !== void 0) return hit;
509
+ const generation = this.#generation;
323
510
  const value = await compute();
324
- await this.#cache.set(key, value, this.#cacheTtl);
511
+ if (generation === this.#generation) await this.#cache.set(key, value, this.#cacheTtl);
325
512
  return value;
326
513
  }
327
514
  /**
@@ -395,7 +582,7 @@ var Rbac = class _Rbac {
395
582
  names.push(normalizeName(input));
396
583
  } else {
397
584
  if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
398
- if (input.teamId !== null && idKey(input.teamId) !== idKey(teamId)) {
585
+ if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
399
586
  throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
400
587
  }
401
588
  objects.push(input);
@@ -422,7 +609,7 @@ var Rbac = class _Rbac {
422
609
  }
423
610
  static pickRole(roles, name, teamId) {
424
611
  const candidates = roles.filter((r) => r.name === name);
425
- return candidates.find((r) => idKey(r.teamId) === idKey(teamId)) ?? candidates.find((r) => r.teamId === null);
612
+ return candidates.find((r) => idKey2(r.teamId) === idKey2(teamId)) ?? candidates.find((r) => r.teamId === null);
426
613
  }
427
614
  };
428
615
  var RoleRbac = class {
@@ -467,11 +654,12 @@ var RoleRbac = class {
467
654
  const resolved = await this.rbac.resolvePermissions(flatten(permissions), role.guardName);
468
655
  const track = this.rbac.events.has("permission.attached") || this.rbac.events.has("permission.detached");
469
656
  const current = track ? await this.getPermissions() : [];
470
- await this.rbac.adapter.detachRolePermissions(role.id);
471
- await this.rbac.adapter.attachRolePermissions(role.id, resolved.map((p) => p.id));
657
+ const newIds = resolved.map((p) => p.id);
658
+ await this.rbac.adapter.attachRolePermissions(role.id, newIds);
659
+ const staleIds = filterIds(await this.currentPermissionIds(role), newIds);
660
+ if (staleIds.length > 0) await this.rbac.adapter.detachRolePermissions(role.id, staleIds);
472
661
  await this.rbac.forgetCachedPermissions();
473
662
  if (track) {
474
- const newIds = resolved.map((p) => p.id);
475
663
  await this.emit("permission.detached", role, filterByIds(current, newIds, false));
476
664
  await this.emit("permission.attached", role, filterByIds(resolved, current.map((p) => p.id), false));
477
665
  }
@@ -541,8 +729,10 @@ var SubjectRbac = class _SubjectRbac {
541
729
  async syncRoles(...roles) {
542
730
  const resolved = await this.rbac.resolveRoles(flatten(roles), this.guardName, this.teamId);
543
731
  const current = (await this.state()).roles;
544
- await this.rbac.adapter.detachSubjectRoles(this.subject, current.map((r) => r.id), this.teamId);
545
- await this.rbac.adapter.attachSubjectRoles(this.subject, resolved.map((r) => r.id), this.teamId);
732
+ const newIds = resolved.map((r) => r.id);
733
+ await this.rbac.adapter.attachSubjectRoles(this.subject, newIds, this.teamId);
734
+ const stale = filterByIds(current, newIds, false);
735
+ if (stale.length > 0) await this.rbac.adapter.detachSubjectRoles(this.subject, stale.map((r) => r.id), this.teamId);
546
736
  await this.rbac.forgetCachedPermissions();
547
737
  await this.emitRoles("role.detached", filterByIds(current, resolved.map((r) => r.id), false));
548
738
  await this.emitRoles("role.attached", filterByIds(resolved, current.map((r) => r.id), false));
@@ -573,7 +763,7 @@ var SubjectRbac = class _SubjectRbac {
573
763
  for (const wanted of flatten(roles)) {
574
764
  const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
575
765
  if (!role) return false;
576
- matched.add(idKey(role.id));
766
+ matched.add(idKey2(role.id));
577
767
  }
578
768
  return matched.size === mine.length;
579
769
  }
@@ -602,8 +792,12 @@ var SubjectRbac = class _SubjectRbac {
602
792
  async syncPermissions(...permissions) {
603
793
  const resolved = await this.rbac.resolvePermissions(flatten(permissions), this.guardName);
604
794
  const current = (await this.state()).direct;
605
- await this.rbac.adapter.detachSubjectPermissions(this.subject, current.map((p) => p.id), this.teamId);
606
- await this.rbac.adapter.attachSubjectPermissions(this.subject, resolved.map((p) => p.id), this.teamId);
795
+ const newIds = resolved.map((p) => p.id);
796
+ await this.rbac.adapter.attachSubjectPermissions(this.subject, newIds, this.teamId);
797
+ const stale = filterByIds(current, newIds, false);
798
+ if (stale.length > 0) {
799
+ await this.rbac.adapter.detachSubjectPermissions(this.subject, stale.map((p) => p.id), this.teamId);
800
+ }
607
801
  await this.rbac.forgetCachedPermissions();
608
802
  await this.emitPermissions("permission.detached", filterByIds(current, resolved.map((p) => p.id), false));
609
803
  await this.emitPermissions("permission.attached", filterByIds(resolved, current.map((p) => p.id), false));
@@ -738,7 +932,7 @@ var SubjectRbac = class _SubjectRbac {
738
932
  });
739
933
  }
740
934
  static roleMatches(role, wanted) {
741
- return typeof wanted === "string" ? role.name === wanted.trim() : idKey(role.id) === idKey(wanted.id);
935
+ return typeof wanted === "string" ? role.name === wanted.trim() : idKey2(role.id) === idKey2(wanted.id);
742
936
  }
743
937
  };
744
938
  function createRbac(options) {
@@ -746,5 +940,5 @@ function createRbac(options) {
746
940
  }
747
941
 
748
942
  export { GuardDoesNotMatch, InvalidWildcardPermission, MemoryCache, PermissionAlreadyExists, PermissionDoesNotExist, Rbac, RbacError, RoleAlreadyExists, RoleDoesNotExist, RoleRbac, SubjectRbac, createRbac, parseWildcardPermission, wildcardImplies };
749
- //# sourceMappingURL=chunk-WIB3HDSP.js.map
750
- //# sourceMappingURL=chunk-WIB3HDSP.js.map
943
+ //# sourceMappingURL=chunk-DLDEHKFR.js.map
944
+ //# sourceMappingURL=chunk-DLDEHKFR.js.map