@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/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,15 @@ 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);
156
311
  }
157
312
  function normalizeName(name) {
158
313
  const trimmed = name.trim();
@@ -281,6 +436,30 @@ var Rbac = class _Rbac {
281
436
  await this.forgetCachedPermissions();
282
437
  await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
283
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
+ }
284
463
  // ---------------------------------------------------------------------- queries
285
464
  /**
286
465
  * Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
@@ -308,10 +487,10 @@ var Rbac = class _Rbac {
308
487
  const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
309
488
  if (resolved.length === 0) return [];
310
489
  const permissionIds = resolved.map((p) => p.id);
311
- const wanted = new Set(permissionIds.map(idKey));
490
+ const wanted = new Set(permissionIds.map(idKey2));
312
491
  const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
313
492
  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));
493
+ const roleIds = uniqueIds(links.filter((l) => wanted.has(idKey2(l.permissionId))).map((l) => l.roleId));
315
494
  const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
316
495
  const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
317
496
  return uniqueIds([...viaRoles, ...direct]);
@@ -330,6 +509,22 @@ var Rbac = class _Rbac {
330
509
  await this.#cache.set(key, value, this.#cacheTtl);
331
510
  return value;
332
511
  }
512
+ /**
513
+ * @internal Whether a permission with this name exists in the guard.
514
+ * With caching on, the guard's permission names are cached (cleared on every change),
515
+ * so repeated `can()` checks don't hit the database.
516
+ */
517
+ async permissionExists(name, guardName) {
518
+ if (!this.#cache) {
519
+ const [permission] = await this.adapter.findPermissions({ names: [name], guardName });
520
+ return permission !== void 0;
521
+ }
522
+ const names = await this.remember(
523
+ `rbac:permissions:${JSON.stringify([guardName])}`,
524
+ async () => (await this.adapter.findPermissions({ guardName })).map((p) => p.name)
525
+ );
526
+ return names.includes(name);
527
+ }
333
528
  // ---------------------------------------------------------------------- internal
334
529
  /** @internal Runs the `before` hook and the super-admin check. `undefined` = no decision. */
335
530
  async gate(subject, permission) {
@@ -385,7 +580,7 @@ var Rbac = class _Rbac {
385
580
  names.push(normalizeName(input));
386
581
  } else {
387
582
  if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
388
- if (input.teamId !== null && idKey(input.teamId) !== idKey(teamId)) {
583
+ if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
389
584
  throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
390
585
  }
391
586
  objects.push(input);
@@ -412,7 +607,7 @@ var Rbac = class _Rbac {
412
607
  }
413
608
  static pickRole(roles, name, teamId) {
414
609
  const candidates = roles.filter((r) => r.name === name);
415
- return candidates.find((r) => idKey(r.teamId) === idKey(teamId)) ?? candidates.find((r) => r.teamId === null);
610
+ return candidates.find((r) => idKey2(r.teamId) === idKey2(teamId)) ?? candidates.find((r) => r.teamId === null);
416
611
  }
417
612
  };
418
613
  var RoleRbac = class {
@@ -563,7 +758,7 @@ var SubjectRbac = class _SubjectRbac {
563
758
  for (const wanted of flatten(roles)) {
564
759
  const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
565
760
  if (!role) return false;
566
- matched.add(idKey(role.id));
761
+ matched.add(idKey2(role.id));
567
762
  }
568
763
  return matched.size === mine.length;
569
764
  }
@@ -688,7 +883,7 @@ var SubjectRbac = class _SubjectRbac {
688
883
  return permission.name;
689
884
  }
690
885
  const name = normalizeName(permission);
691
- if (!this.rbac.wildcard && !await this.rbac.findPermission(name, { guard: this.guardName })) {
886
+ if (!this.rbac.wildcard && !await this.rbac.permissionExists(name, this.guardName)) {
692
887
  throw new PermissionDoesNotExist(name, this.guardName);
693
888
  }
694
889
  return name;
@@ -728,7 +923,7 @@ var SubjectRbac = class _SubjectRbac {
728
923
  });
729
924
  }
730
925
  static roleMatches(role, wanted) {
731
- return typeof wanted === "string" ? role.name === wanted.trim() : idKey(role.id) === idKey(wanted.id);
926
+ return typeof wanted === "string" ? role.name === wanted.trim() : idKey2(role.id) === idKey2(wanted.id);
732
927
  }
733
928
  };
734
929
  function createRbac(options) {