@anievo-id/rbac-evolution 0.2.1 → 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,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // package.json
4
- var version = "0.2.1";
4
+ var version = "0.3.0";
5
5
 
6
6
  // src/cache.ts
7
7
  var MemoryCache = class {
@@ -120,9 +120,164 @@ function wildcardImplies(granted, required) {
120
120
  return true;
121
121
  }
122
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
+
123
278
  // src/rbac.ts
124
279
  var DAY_MS = 24 * 60 * 60 * 1e3;
125
- var idKey = (id) => id === null ? "\0null" : String(id);
280
+ var idKey2 = (id) => id === null ? "\0null" : String(id);
126
281
  function flatten(items) {
127
282
  const out = [];
128
283
  for (const item of items) {
@@ -134,7 +289,7 @@ function flatten(items) {
134
289
  function uniqueById(items) {
135
290
  const seen = /* @__PURE__ */ new Set();
136
291
  return items.filter((item) => {
137
- const k = idKey(item.id);
292
+ const k = idKey2(item.id);
138
293
  if (seen.has(k)) return false;
139
294
  seen.add(k);
140
295
  return true;
@@ -143,15 +298,15 @@ function uniqueById(items) {
143
298
  function uniqueIds(ids) {
144
299
  const seen = /* @__PURE__ */ new Set();
145
300
  return ids.filter((id) => {
146
- const k = idKey(id);
301
+ const k = idKey2(id);
147
302
  if (seen.has(k)) return false;
148
303
  seen.add(k);
149
304
  return true;
150
305
  });
151
306
  }
152
307
  function filterByIds(items, ids, keep) {
153
- const set = new Set(ids.map(idKey));
154
- 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);
155
310
  }
156
311
  function normalizeName(name) {
157
312
  const trimmed = name.trim();
@@ -280,6 +435,30 @@ var Rbac = class _Rbac {
280
435
  await this.forgetCachedPermissions();
281
436
  await this.#events.emit({ event: "role.deleted", role: resolved, teamId: resolved.teamId });
282
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
+ }
283
462
  // ---------------------------------------------------------------------- queries
284
463
  /**
285
464
  * Ids of subjects of `subjectType` that have ANY of the given roles in the given scope
@@ -307,10 +486,10 @@ var Rbac = class _Rbac {
307
486
  const resolved = await this.resolvePermissions(flatten([permissions]), guardName);
308
487
  if (resolved.length === 0) return [];
309
488
  const permissionIds = resolved.map((p) => p.id);
310
- const wanted = new Set(permissionIds.map(idKey));
489
+ const wanted = new Set(permissionIds.map(idKey2));
311
490
  const roles = await this.adapter.findRoles({ guardName, teamIds: this.visibleTeams(teamId) });
312
491
  const links = roles.length > 0 ? await this.adapter.getRolePermissionLinks(roles.map((r) => r.id)) : [];
313
- 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));
314
493
  const viaRoles = roleIds.length > 0 ? await this.adapter.getSubjectIdsWithRoles(subjectType, roleIds, teamId) : [];
315
494
  const direct = await this.adapter.getSubjectIdsWithPermissions(subjectType, permissionIds, teamId);
316
495
  return uniqueIds([...viaRoles, ...direct]);
@@ -400,7 +579,7 @@ var Rbac = class _Rbac {
400
579
  names.push(normalizeName(input));
401
580
  } else {
402
581
  if (input.guardName !== guardName) throw new GuardDoesNotMatch(input.guardName, guardName);
403
- if (input.teamId !== null && idKey(input.teamId) !== idKey(teamId)) {
582
+ if (input.teamId !== null && idKey2(input.teamId) !== idKey2(teamId)) {
404
583
  throw new RbacError("TEAM_DOES_NOT_MATCH", `Role \`${input.name}\` belongs to another team.`);
405
584
  }
406
585
  objects.push(input);
@@ -427,7 +606,7 @@ var Rbac = class _Rbac {
427
606
  }
428
607
  static pickRole(roles, name, teamId) {
429
608
  const candidates = roles.filter((r) => r.name === name);
430
- 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);
431
610
  }
432
611
  };
433
612
  var RoleRbac = class {
@@ -578,7 +757,7 @@ var SubjectRbac = class _SubjectRbac {
578
757
  for (const wanted of flatten(roles)) {
579
758
  const role = mine.find((r) => _SubjectRbac.roleMatches(r, wanted));
580
759
  if (!role) return false;
581
- matched.add(idKey(role.id));
760
+ matched.add(idKey2(role.id));
582
761
  }
583
762
  return matched.size === mine.length;
584
763
  }
@@ -743,7 +922,7 @@ var SubjectRbac = class _SubjectRbac {
743
922
  });
744
923
  }
745
924
  static roleMatches(role, wanted) {
746
- 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);
747
926
  }
748
927
  };
749
928
  function createRbac(options) {