@tylix/permissions 0.0.0-stage → 2.1.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/LICENSE +21 -0
- package/README.md +309 -2
- package/package.json +99 -4
- package/src/angular.d.ts +8 -0
- package/src/angular.js +45 -0
- package/src/client.d.ts +42 -0
- package/src/client.js +92 -0
- package/src/engine.js +609 -0
- package/src/http.js +115 -0
- package/src/index.d.ts +220 -0
- package/src/index.js +20 -0
- package/src/match.js +93 -0
- package/src/react.d.ts +14 -0
- package/src/react.js +45 -0
- package/src/schema.d.ts +12 -0
- package/src/schema.js +66 -0
- package/src/stores/memory.js +82 -0
- package/src/stores/orm.js +140 -0
- package/src/svelte.d.ts +6 -0
- package/src/svelte.js +34 -0
- package/src/vue.d.ts +11 -0
- package/src/vue.js +49 -0
package/src/engine.js
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
// Roles and permissions for any JavaScript app. Inspired by Laravel's
|
|
2
|
+
// spatie/laravel-permission, plus what it leaves to you:
|
|
3
|
+
//
|
|
4
|
+
// - wildcards built in ("posts.*", "posts.edit,delete", "*")
|
|
5
|
+
// - role inheritance (editor inherits writer)
|
|
6
|
+
// - explicit denies that beat any allow ("!posts.delete" in a role, or
|
|
7
|
+
// permissions.for(user).deny("posts.delete"))
|
|
8
|
+
// - teams / tenants on every assignment, and assignments that expire
|
|
9
|
+
// - rules for resource checks: can(user, "posts.update", post)
|
|
10
|
+
// - one serializable snapshot (access) the browser checks synchronously
|
|
11
|
+
// - a declarative sync() for seeders and config, idempotent
|
|
12
|
+
// - storage you choose (memory, the Tylix ORM, or your own store)
|
|
13
|
+
//
|
|
14
|
+
// const permissions = createPermissions({ store: ormStore({ Model }), superAdmin: 'super-admin' })
|
|
15
|
+
// await permissions.createRole('editor', { permissions: ['posts.*'] })
|
|
16
|
+
// await permissions.for(user).assignRole('editor')
|
|
17
|
+
// await permissions.can(user, 'posts.publish') // true
|
|
18
|
+
import { allows, assertName, isPattern, toAccess } from './match.js'
|
|
19
|
+
import { memoryStore } from './stores/memory.js'
|
|
20
|
+
import { createAbility } from './client.js'
|
|
21
|
+
|
|
22
|
+
export class PermissionError extends Error {
|
|
23
|
+
constructor(message, code) {
|
|
24
|
+
super(message)
|
|
25
|
+
this.name = 'PermissionError'
|
|
26
|
+
this.code = code
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Thrown by authorize(); carries a 403 for HTTP layers.
|
|
31
|
+
export class ForbiddenError extends Error {
|
|
32
|
+
constructor(message = 'You do not have permission to do that.', permission = null) {
|
|
33
|
+
super(message)
|
|
34
|
+
this.name = 'ForbiddenError'
|
|
35
|
+
this.status = 403
|
|
36
|
+
this.permission = permission
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const list = (value) => (value === undefined || value === null ? [] : Array.isArray(value) ? value.flat() : [value])
|
|
41
|
+
const uniq = (items) => [...new Set(items)]
|
|
42
|
+
|
|
43
|
+
function expired(entry, now) {
|
|
44
|
+
if (!entry.expiresAt) return false
|
|
45
|
+
const at = new Date(entry.expiresAt).getTime()
|
|
46
|
+
return Number.isFinite(at) && at <= now
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// What a check is handed as "the user": an id, a user row, a Tylix
|
|
50
|
+
// req.user ({ userId }), or { type, id } for things that aren't users
|
|
51
|
+
// (API clients, teams, devices).
|
|
52
|
+
function makeRef(subject, defaultType) {
|
|
53
|
+
if (subject === null || subject === undefined) return null
|
|
54
|
+
if (typeof subject === 'string' || typeof subject === 'number' || typeof subject === 'bigint') {
|
|
55
|
+
return { type: defaultType, id: String(subject) }
|
|
56
|
+
}
|
|
57
|
+
if (typeof subject === 'object') {
|
|
58
|
+
const id = subject.id ?? subject.userId ?? subject.sub ?? subject._id
|
|
59
|
+
if (id === undefined || id === null) return null
|
|
60
|
+
return { type: subject.subjectType ?? subject.type ?? defaultType, id: String(id) }
|
|
61
|
+
}
|
|
62
|
+
return null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function makeCache({ cache, ttl }) {
|
|
66
|
+
// Shared cache (Tylix's cache, Redis, ...): get(key), set(key, value,
|
|
67
|
+
// ttlSeconds), forget(key) or delete(key). Changes are seen by every
|
|
68
|
+
// process at once through a version key.
|
|
69
|
+
if (cache) {
|
|
70
|
+
const forget = (cache.forget ?? cache.delete)?.bind(cache)
|
|
71
|
+
const VERSION = 'tylix-permissions:version'
|
|
72
|
+
let current = 'v0'
|
|
73
|
+
const version = async () => {
|
|
74
|
+
current = (await cache.get(VERSION)) ?? 'v0'
|
|
75
|
+
return current
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
// Every read checks the version first, so a change made by another
|
|
79
|
+
// process is seen on the next check.
|
|
80
|
+
async get(key) {
|
|
81
|
+
return cache.get(`tylix-permissions:${await version()}:${key}`)
|
|
82
|
+
},
|
|
83
|
+
async set(key, value) {
|
|
84
|
+
await cache.set(`tylix-permissions:${current}:${key}`, value, ttl)
|
|
85
|
+
},
|
|
86
|
+
async bump() {
|
|
87
|
+
if (forget) await forget(`tylix-permissions:${current}:catalog`)
|
|
88
|
+
current = `v${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
|
|
89
|
+
await cache.set(VERSION, current, null)
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// In-process: entries live `ttl` seconds, so in a multi-process deploy
|
|
94
|
+
// another worker's change is seen within that window. Pass a shared
|
|
95
|
+
// cache to make it immediate.
|
|
96
|
+
const entries = new Map()
|
|
97
|
+
return {
|
|
98
|
+
async get(key) {
|
|
99
|
+
const hit = entries.get(key)
|
|
100
|
+
if (!hit) return undefined
|
|
101
|
+
if (hit.until < Date.now()) {
|
|
102
|
+
entries.delete(key)
|
|
103
|
+
return undefined
|
|
104
|
+
}
|
|
105
|
+
return hit.value
|
|
106
|
+
},
|
|
107
|
+
async set(key, value) {
|
|
108
|
+
if (ttl > 0) entries.set(key, { value, until: Date.now() + ttl * 1000 })
|
|
109
|
+
},
|
|
110
|
+
async bump() {
|
|
111
|
+
entries.clear()
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function createPermissions(options = {}) {
|
|
117
|
+
const {
|
|
118
|
+
store = memoryStore(),
|
|
119
|
+
superAdmin = null,
|
|
120
|
+
rules = {},
|
|
121
|
+
cache: sharedCache = null,
|
|
122
|
+
ttl = 30,
|
|
123
|
+
subjectType = 'user',
|
|
124
|
+
// Concrete names must exist before they're granted (catches typos);
|
|
125
|
+
// patterns ("posts.*") never need a row.
|
|
126
|
+
strict = true,
|
|
127
|
+
// Roles every signed-in subject has without an assignment, e.g. a
|
|
128
|
+
// "member" role with what any account may do. Guests get none.
|
|
129
|
+
defaultRoles = [],
|
|
130
|
+
} = options
|
|
131
|
+
|
|
132
|
+
const cache = makeCache({ cache: sharedCache, ttl })
|
|
133
|
+
const ruleMap = new Map(Object.entries(rules))
|
|
134
|
+
|
|
135
|
+
const ref = (subject) => {
|
|
136
|
+
const r = makeRef(subject, subjectType)
|
|
137
|
+
if (!r) throw new PermissionError('A subject needs an id: pass a user, { id }, { userId } or an id.', 'NO_SUBJECT')
|
|
138
|
+
return r
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── Catalog ────────────────────────────────────────────────────────
|
|
142
|
+
|
|
143
|
+
async function catalog() {
|
|
144
|
+
const hit = await cache.get('catalog')
|
|
145
|
+
if (hit) return hit
|
|
146
|
+
const raw = await store.loadCatalog()
|
|
147
|
+
const value = {
|
|
148
|
+
permissions: raw.permissions.map((p) => ({ name: p.name, description: p.description ?? null })),
|
|
149
|
+
roles: raw.roles.map((r) => ({
|
|
150
|
+
name: r.name,
|
|
151
|
+
description: r.description ?? null,
|
|
152
|
+
permissions: uniq(r.permissions ?? []),
|
|
153
|
+
inherits: uniq(r.inherits ?? []),
|
|
154
|
+
})),
|
|
155
|
+
}
|
|
156
|
+
await cache.set('catalog', value)
|
|
157
|
+
return value
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function changed() {
|
|
161
|
+
await cache.bump()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function findRole(name) {
|
|
165
|
+
return (await catalog()).roles.find((r) => r.name === name) ?? null
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function requireRole(name) {
|
|
169
|
+
const role = await findRole(name)
|
|
170
|
+
if (!role) throw new PermissionError(`There is no role named "${name}". Create it first: permissions.createRole("${name}").`, 'ROLE_DOES_NOT_EXIST')
|
|
171
|
+
return role
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function checkGrantable(names) {
|
|
175
|
+
if (!strict) return
|
|
176
|
+
const known = new Set((await catalog()).permissions.map((p) => p.name))
|
|
177
|
+
for (const raw of names) {
|
|
178
|
+
const name = raw.startsWith('!') ? raw.slice(1) : raw
|
|
179
|
+
if (!isPattern(name) && !known.has(name)) {
|
|
180
|
+
throw new PermissionError(
|
|
181
|
+
`There is no permission named "${name}". Create it first: permissions.createPermission("${name}").`,
|
|
182
|
+
'PERMISSION_DOES_NOT_EXIST',
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Role names a set of roles expands to, through inheritance. Cycles are
|
|
189
|
+
// harmless: each role is visited once.
|
|
190
|
+
function expandRoles(names, roles) {
|
|
191
|
+
const byName = new Map(roles.map((r) => [r.name, r]))
|
|
192
|
+
const seen = new Set()
|
|
193
|
+
const stack = [...names]
|
|
194
|
+
while (stack.length) {
|
|
195
|
+
const name = stack.pop()
|
|
196
|
+
if (seen.has(name) || !byName.has(name)) continue
|
|
197
|
+
seen.add(name)
|
|
198
|
+
stack.push(...byName.get(name).inherits)
|
|
199
|
+
}
|
|
200
|
+
return [...seen]
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function createPermission(name, { description = null } = {}) {
|
|
204
|
+
const clean = assertName(name)
|
|
205
|
+
if (clean.startsWith('!')) throw new PermissionError('A permission name cannot start with "!"; that marks a deny inside a role.', 'INVALID_NAME')
|
|
206
|
+
await store.savePermission({ name: clean, description })
|
|
207
|
+
await changed()
|
|
208
|
+
return { name: clean, description }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function createPermissionsBulk(names) {
|
|
212
|
+
const out = []
|
|
213
|
+
for (const entry of list(names)) {
|
|
214
|
+
const { name, description } = typeof entry === 'string' ? { name: entry } : entry
|
|
215
|
+
out.push(await createPermission(name, { description }))
|
|
216
|
+
}
|
|
217
|
+
return out
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function deletePermission(name) {
|
|
221
|
+
await store.deletePermission(name)
|
|
222
|
+
await changed()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function saveRole(name, { description, permissions, inherits }, { create }) {
|
|
226
|
+
const clean = assertName(name, 'role')
|
|
227
|
+
const existing = await findRole(clean)
|
|
228
|
+
if (create && existing) throw new PermissionError(`A role named "${clean}" already exists.`, 'ROLE_ALREADY_EXISTS')
|
|
229
|
+
if (!create && !existing) await requireRole(clean)
|
|
230
|
+
const perms = permissions === undefined ? existing?.permissions ?? [] : uniq(list(permissions).map((p) => assertName(p)))
|
|
231
|
+
const parents = inherits === undefined ? existing?.inherits ?? [] : uniq(list(inherits).map((r) => assertName(r, 'role')))
|
|
232
|
+
await checkGrantable(perms)
|
|
233
|
+
const cat = await catalog()
|
|
234
|
+
for (const parent of parents) {
|
|
235
|
+
if (parent === clean) throw new PermissionError(`Role "${clean}" cannot inherit itself.`, 'ROLE_CYCLE')
|
|
236
|
+
if (!cat.roles.some((r) => r.name === parent)) await requireRole(parent)
|
|
237
|
+
if (expandRoles([parent], cat.roles).includes(clean)) {
|
|
238
|
+
throw new PermissionError(`Role "${clean}" cannot inherit "${parent}": "${parent}" already inherits "${clean}".`, 'ROLE_CYCLE')
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const role = {
|
|
242
|
+
name: clean,
|
|
243
|
+
description: description === undefined ? existing?.description ?? null : description,
|
|
244
|
+
permissions: perms,
|
|
245
|
+
inherits: parents,
|
|
246
|
+
}
|
|
247
|
+
await store.saveRole(role)
|
|
248
|
+
await changed()
|
|
249
|
+
return role
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ── Subjects (users, API clients, ...) ─────────────────────────────
|
|
253
|
+
|
|
254
|
+
function activeFor(entries, team, now) {
|
|
255
|
+
return entries.filter((e) => !expired(e, now) && (e.team == null || (team != null && String(e.team) === String(team))))
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function access(subject, { team = null } = {}) {
|
|
259
|
+
const r = makeRef(subject, subjectType)
|
|
260
|
+
if (!r) return { roles: [], permissions: [], denied: [], superAdmin: false }
|
|
261
|
+
const key = `access:${r.type}:${r.id}:${team ?? ''}`
|
|
262
|
+
const hit = await cache.get(key)
|
|
263
|
+
if (hit) return hit
|
|
264
|
+
|
|
265
|
+
const now = Date.now()
|
|
266
|
+
const [cat, assigned] = await Promise.all([catalog(), store.getAssignments(r)])
|
|
267
|
+
const roleNames = expandRoles(
|
|
268
|
+
[...list(defaultRoles), ...activeFor(assigned.roles, team, now).map((x) => x.name)],
|
|
269
|
+
cat.roles,
|
|
270
|
+
).sort()
|
|
271
|
+
const allowed = []
|
|
272
|
+
const denied = []
|
|
273
|
+
for (const name of roleNames) {
|
|
274
|
+
const role = cat.roles.find((x) => x.name === name)
|
|
275
|
+
for (const p of role.permissions) (p.startsWith('!') ? denied : allowed).push(p.replace(/^!/, ''))
|
|
276
|
+
}
|
|
277
|
+
for (const p of activeFor(assigned.permissions, team, now)) (p.effect === 'deny' ? denied : allowed).push(p.name)
|
|
278
|
+
|
|
279
|
+
const snapshot = {
|
|
280
|
+
roles: roleNames,
|
|
281
|
+
permissions: uniq(allowed).sort(),
|
|
282
|
+
denied: uniq(denied).sort(),
|
|
283
|
+
superAdmin: superAdmin != null && list(superAdmin).some((s) => roleNames.includes(s)),
|
|
284
|
+
}
|
|
285
|
+
// A snapshot with a pending expiry is only cached until then.
|
|
286
|
+
const expiries = [...assigned.roles, ...assigned.permissions]
|
|
287
|
+
.map((e) => (e.expiresAt ? new Date(e.expiresAt).getTime() : Infinity))
|
|
288
|
+
.filter((at) => at > now)
|
|
289
|
+
if (!expiries.some((at) => at - now < ttl * 1000)) await cache.set(key, snapshot)
|
|
290
|
+
return snapshot
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async function update(subject, change) {
|
|
294
|
+
const r = ref(subject)
|
|
295
|
+
const current = await store.getAssignments(r)
|
|
296
|
+
const next = change({ roles: current.roles, permissions: current.permissions })
|
|
297
|
+
await store.setAssignments(r, next)
|
|
298
|
+
await changed()
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const sameScope = (a, team) => String(a.team ?? '') === String(team ?? '')
|
|
302
|
+
|
|
303
|
+
async function can(subject, permission, resource, opts) {
|
|
304
|
+
;[resource, opts] = splitArgs(resource, opts)
|
|
305
|
+
const team = opts.team ?? null
|
|
306
|
+
const snapshot = await access(subject, { team })
|
|
307
|
+
const names = list(permission)
|
|
308
|
+
if (names.length === 0) return false
|
|
309
|
+
for (const name of names) {
|
|
310
|
+
if (snapshot.superAdmin) continue
|
|
311
|
+
const granted = allows(snapshot, name)
|
|
312
|
+
const rule = ruleMap.get(name)
|
|
313
|
+
if (rule && resource !== undefined) {
|
|
314
|
+
const ok = await rule({
|
|
315
|
+
subject,
|
|
316
|
+
user: subject,
|
|
317
|
+
resource,
|
|
318
|
+
granted,
|
|
319
|
+
access: snapshot,
|
|
320
|
+
team,
|
|
321
|
+
can: (other, res = resource) => can(subject, other, res, { team }),
|
|
322
|
+
})
|
|
323
|
+
if (!ok) return false
|
|
324
|
+
} else if (!granted) {
|
|
325
|
+
return false
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return true
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// can(user, perm, { team }) with no resource: a plain object whose only
|
|
332
|
+
// key is team is read as the options.
|
|
333
|
+
function splitArgs(resource, opts) {
|
|
334
|
+
if (opts === undefined && resource && typeof resource === 'object' && !Array.isArray(resource)) {
|
|
335
|
+
const keys = Object.keys(resource)
|
|
336
|
+
if (keys.length === 1 && keys[0] === 'team') return [undefined, resource]
|
|
337
|
+
}
|
|
338
|
+
return [resource, opts ?? {}]
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function subjectApi(subject, { team: boundTeam = null } = {}) {
|
|
342
|
+
const scope = (opts) => ({ team: opts?.team ?? boundTeam })
|
|
343
|
+
const api = {
|
|
344
|
+
async assignRole(roles, opts = {}) {
|
|
345
|
+
const names = list(roles)
|
|
346
|
+
for (const name of names) await requireRole(name)
|
|
347
|
+
const { team } = scope(opts)
|
|
348
|
+
await update(subject, ({ roles: current, permissions }) => ({
|
|
349
|
+
roles: [
|
|
350
|
+
...current.filter((x) => !(names.includes(x.name) && sameScope(x, team))),
|
|
351
|
+
...names.map((name) => ({ name, team, expiresAt: opts.expiresAt ?? null })),
|
|
352
|
+
],
|
|
353
|
+
permissions,
|
|
354
|
+
}))
|
|
355
|
+
return api
|
|
356
|
+
},
|
|
357
|
+
async removeRole(roles, opts = {}) {
|
|
358
|
+
const names = list(roles)
|
|
359
|
+
const { team } = scope(opts)
|
|
360
|
+
await update(subject, ({ roles: current, permissions }) => ({
|
|
361
|
+
roles: current.filter((x) => !(names.includes(x.name) && sameScope(x, team))),
|
|
362
|
+
permissions,
|
|
363
|
+
}))
|
|
364
|
+
return api
|
|
365
|
+
},
|
|
366
|
+
async syncRoles(roles, opts = {}) {
|
|
367
|
+
const names = uniq(list(roles))
|
|
368
|
+
for (const name of names) await requireRole(name)
|
|
369
|
+
const { team } = scope(opts)
|
|
370
|
+
await update(subject, ({ roles: current, permissions }) => ({
|
|
371
|
+
roles: [...current.filter((x) => !sameScope(x, team)), ...names.map((name) => ({ name, team, expiresAt: opts.expiresAt ?? null }))],
|
|
372
|
+
permissions,
|
|
373
|
+
}))
|
|
374
|
+
return api
|
|
375
|
+
},
|
|
376
|
+
async givePermission(perms, opts = {}) {
|
|
377
|
+
return setDirect(list(perms), 'allow', opts)
|
|
378
|
+
},
|
|
379
|
+
async deny(perms, opts = {}) {
|
|
380
|
+
return setDirect(list(perms), 'deny', opts)
|
|
381
|
+
},
|
|
382
|
+
async revokePermission(perms, opts = {}) {
|
|
383
|
+
const names = list(perms)
|
|
384
|
+
const { team } = scope(opts)
|
|
385
|
+
await update(subject, ({ roles, permissions }) => ({
|
|
386
|
+
roles,
|
|
387
|
+
permissions: permissions.filter((x) => !(names.includes(x.name) && sameScope(x, team))),
|
|
388
|
+
}))
|
|
389
|
+
return api
|
|
390
|
+
},
|
|
391
|
+
async syncPermissions(perms, opts = {}) {
|
|
392
|
+
const names = uniq(list(perms).map((p) => assertName(p)))
|
|
393
|
+
await checkGrantable(names)
|
|
394
|
+
const { team } = scope(opts)
|
|
395
|
+
await update(subject, ({ roles, permissions }) => ({
|
|
396
|
+
roles,
|
|
397
|
+
permissions: [
|
|
398
|
+
...permissions.filter((x) => !sameScope(x, team) || x.effect === 'deny'),
|
|
399
|
+
...names.map((name) => ({ name, effect: 'allow', team, expiresAt: opts.expiresAt ?? null })),
|
|
400
|
+
],
|
|
401
|
+
}))
|
|
402
|
+
return api
|
|
403
|
+
},
|
|
404
|
+
can: (permission, resource, opts) => {
|
|
405
|
+
;[resource, opts] = splitArgs(resource, opts)
|
|
406
|
+
return can(subject, permission, resource, scope(opts))
|
|
407
|
+
},
|
|
408
|
+
cannot: async (permission, resource, opts) => !(await api.can(permission, resource, opts)),
|
|
409
|
+
canAny: async (perms, resource, opts) => {
|
|
410
|
+
for (const p of list(perms)) if (await api.can(p, resource, opts)) return true
|
|
411
|
+
return false
|
|
412
|
+
},
|
|
413
|
+
canAll: (perms, resource, opts) => api.can(list(perms), resource, opts),
|
|
414
|
+
hasRole: async (roles, opts) => {
|
|
415
|
+
const have = (await access(subject, scope(opts))).roles
|
|
416
|
+
return list(roles).some((r) => have.includes(r))
|
|
417
|
+
},
|
|
418
|
+
hasAnyRole: (roles, opts) => api.hasRole(roles, opts),
|
|
419
|
+
hasAllRoles: async (roles, opts) => {
|
|
420
|
+
const have = (await access(subject, scope(opts))).roles
|
|
421
|
+
const wanted = list(roles)
|
|
422
|
+
return wanted.length > 0 && wanted.every((r) => have.includes(r))
|
|
423
|
+
},
|
|
424
|
+
roles: async (opts) => (await access(subject, scope(opts))).roles,
|
|
425
|
+
permissions: async (opts) => (await access(subject, scope(opts))).permissions,
|
|
426
|
+
access: (opts) => access(subject, scope(opts)),
|
|
427
|
+
ability: async (opts) => createAbility(await access(subject, scope(opts))),
|
|
428
|
+
// What is stored for this subject, before inheritance and expiry.
|
|
429
|
+
assignments: () => store.getAssignments(ref(subject)),
|
|
430
|
+
authorize: async (permission, resource, opts) => {
|
|
431
|
+
if (!(await api.can(permission, resource, opts))) throw new ForbiddenError(undefined, permission)
|
|
432
|
+
},
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function setDirect(perms, effect, opts) {
|
|
436
|
+
const names = perms.map((p) => assertName(p))
|
|
437
|
+
await checkGrantable(names)
|
|
438
|
+
const { team } = scope(opts)
|
|
439
|
+
await update(subject, ({ roles, permissions }) => ({
|
|
440
|
+
roles,
|
|
441
|
+
permissions: [
|
|
442
|
+
...permissions.filter((x) => !(names.includes(x.name) && sameScope(x, team))),
|
|
443
|
+
...names.map((name) => ({ name, effect, team, expiresAt: opts.expiresAt ?? null })),
|
|
444
|
+
],
|
|
445
|
+
}))
|
|
446
|
+
return api
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return api
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// ── Declarative sync ───────────────────────────────────────────────
|
|
453
|
+
//
|
|
454
|
+
// await permissions.sync({
|
|
455
|
+
// permissions: ['posts.view', 'posts.create', { name: 'users.manage', description: '...' }],
|
|
456
|
+
// roles: {
|
|
457
|
+
// writer: ['posts.view', 'posts.create'],
|
|
458
|
+
// editor: { inherits: ['writer'], permissions: ['posts.*'] },
|
|
459
|
+
// admin: ['*'],
|
|
460
|
+
// },
|
|
461
|
+
// }, { prune: false })
|
|
462
|
+
//
|
|
463
|
+
// Creates what is missing and updates what changed. With prune: true it
|
|
464
|
+
// also deletes roles and permissions the definition no longer lists.
|
|
465
|
+
async function sync(definition = {}, { prune = false } = {}) {
|
|
466
|
+
const wantedPerms = list(definition.permissions).map((p) => (typeof p === 'string' ? { name: p } : p))
|
|
467
|
+
const cat = await catalog()
|
|
468
|
+
const known = new Map(cat.permissions.map((p) => [p.name, p]))
|
|
469
|
+
for (const p of wantedPerms) {
|
|
470
|
+
const existing = known.get(p.name)
|
|
471
|
+
if (!existing || (p.description !== undefined && p.description !== existing.description)) {
|
|
472
|
+
await createPermission(p.name, { description: p.description ?? existing?.description ?? null })
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
const roles = Object.entries(definition.roles ?? {}).map(([name, spec]) =>
|
|
476
|
+
Array.isArray(spec) || typeof spec === 'string' ? { name, permissions: list(spec) } : { name, ...spec },
|
|
477
|
+
)
|
|
478
|
+
// Roles first without parents, so inheritance can point at any of them.
|
|
479
|
+
for (const role of roles) {
|
|
480
|
+
if (!(await findRole(role.name))) await saveRole(role.name, { description: role.description ?? null, permissions: [], inherits: [] }, { create: true })
|
|
481
|
+
}
|
|
482
|
+
for (const role of roles) {
|
|
483
|
+
await saveRole(role.name, { description: role.description, permissions: role.permissions ?? [], inherits: role.inherits ?? [] }, { create: false })
|
|
484
|
+
}
|
|
485
|
+
if (prune) {
|
|
486
|
+
const keepRoles = new Set(roles.map((r) => r.name))
|
|
487
|
+
const keepPerms = new Set(wantedPerms.map((p) => p.name))
|
|
488
|
+
for (const r of (await catalog()).roles) if (!keepRoles.has(r.name)) await store.deleteRole(r.name)
|
|
489
|
+
for (const p of (await catalog()).permissions) if (!keepPerms.has(p.name)) await store.deletePermission(p.name)
|
|
490
|
+
await changed()
|
|
491
|
+
}
|
|
492
|
+
return catalog()
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const permissions = {
|
|
496
|
+
store,
|
|
497
|
+
|
|
498
|
+
// Catalog
|
|
499
|
+
createPermission,
|
|
500
|
+
createPermissions: createPermissionsBulk,
|
|
501
|
+
findOrCreatePermission: async (name, opts = {}) => {
|
|
502
|
+
const found = (await catalog()).permissions.find((p) => p.name === name)
|
|
503
|
+
return found ?? createPermission(name, opts)
|
|
504
|
+
},
|
|
505
|
+
deletePermission,
|
|
506
|
+
createRole: (name, opts = {}) => saveRole(name, opts, { create: true }),
|
|
507
|
+
findOrCreateRole: async (name, opts = {}) => (await findRole(name)) ?? saveRole(name, opts, { create: true }),
|
|
508
|
+
updateRole: (name, opts = {}) => saveRole(name, opts, { create: false }),
|
|
509
|
+
deleteRole: async (name) => {
|
|
510
|
+
await store.deleteRole(name)
|
|
511
|
+
await changed()
|
|
512
|
+
},
|
|
513
|
+
findRole,
|
|
514
|
+
roles: async () => (await catalog()).roles,
|
|
515
|
+
listPermissions: async () => (await catalog()).permissions,
|
|
516
|
+
catalog,
|
|
517
|
+
|
|
518
|
+
// Role-side grants: permissions.role('editor').give('posts.publish')
|
|
519
|
+
role(name) {
|
|
520
|
+
const api = {
|
|
521
|
+
give: async (perms) => {
|
|
522
|
+
const role = await requireRole(name)
|
|
523
|
+
await saveRole(name, { permissions: [...role.permissions, ...list(perms)] }, { create: false })
|
|
524
|
+
return api
|
|
525
|
+
},
|
|
526
|
+
deny: async (perms) => {
|
|
527
|
+
const role = await requireRole(name)
|
|
528
|
+
await saveRole(name, { permissions: [...role.permissions, ...list(perms).map((p) => `!${p.replace(/^!/, '')}`)] }, { create: false })
|
|
529
|
+
return api
|
|
530
|
+
},
|
|
531
|
+
revoke: async (perms) => {
|
|
532
|
+
const role = await requireRole(name)
|
|
533
|
+
const drop = new Set(list(perms).flatMap((p) => [p, `!${p}`]))
|
|
534
|
+
await saveRole(name, { permissions: role.permissions.filter((p) => !drop.has(p)) }, { create: false })
|
|
535
|
+
return api
|
|
536
|
+
},
|
|
537
|
+
sync: async (perms) => {
|
|
538
|
+
await saveRole(name, { permissions: list(perms) }, { create: false })
|
|
539
|
+
return api
|
|
540
|
+
},
|
|
541
|
+
inherit: async (parents) => {
|
|
542
|
+
const role = await requireRole(name)
|
|
543
|
+
await saveRole(name, { inherits: [...role.inherits, ...list(parents)] }, { create: false })
|
|
544
|
+
return api
|
|
545
|
+
},
|
|
546
|
+
disinherit: async (parents) => {
|
|
547
|
+
const role = await requireRole(name)
|
|
548
|
+
const drop = new Set(list(parents))
|
|
549
|
+
await saveRole(name, { inherits: role.inherits.filter((p) => !drop.has(p)) }, { create: false })
|
|
550
|
+
return api
|
|
551
|
+
},
|
|
552
|
+
get: () => findRole(name),
|
|
553
|
+
// Everything the role allows, inherited included.
|
|
554
|
+
access: async () => {
|
|
555
|
+
const cat = await catalog()
|
|
556
|
+
const names = expandRoles([name], cat.roles)
|
|
557
|
+
const allowed = []
|
|
558
|
+
const denied = []
|
|
559
|
+
for (const n of names) {
|
|
560
|
+
for (const p of cat.roles.find((r) => r.name === n).permissions) (p.startsWith('!') ? denied : allowed).push(p.replace(/^!/, ''))
|
|
561
|
+
}
|
|
562
|
+
return { roles: names.sort(), permissions: uniq(allowed).sort(), denied: uniq(denied).sort(), superAdmin: list(superAdmin).some((s) => names.includes(s)) }
|
|
563
|
+
},
|
|
564
|
+
subjects: () => store.subjectsWithRole(name),
|
|
565
|
+
}
|
|
566
|
+
return api
|
|
567
|
+
},
|
|
568
|
+
|
|
569
|
+
// Subject-side: permissions.for(user).assignRole('editor')
|
|
570
|
+
for: subjectApi,
|
|
571
|
+
user: subjectApi,
|
|
572
|
+
|
|
573
|
+
// Checks
|
|
574
|
+
access,
|
|
575
|
+
can,
|
|
576
|
+
cannot: async (subject, permission, resource, opts) => !(await can(subject, permission, resource, opts)),
|
|
577
|
+
canAny: async (subject, perms, resource, opts) => {
|
|
578
|
+
for (const p of list(perms)) if (await can(subject, p, resource, opts)) return true
|
|
579
|
+
return false
|
|
580
|
+
},
|
|
581
|
+
canAll: (subject, perms, resource, opts) => can(subject, list(perms), resource, opts),
|
|
582
|
+
hasRole: (subject, roles, opts) => subjectApi(subject).hasRole(roles, opts),
|
|
583
|
+
hasAnyRole: (subject, roles, opts) => subjectApi(subject).hasAnyRole(roles, opts),
|
|
584
|
+
hasAllRoles: (subject, roles, opts) => subjectApi(subject).hasAllRoles(roles, opts),
|
|
585
|
+
authorize: async (subject, permission, resource, opts) => {
|
|
586
|
+
if (!(await can(subject, permission, resource, opts))) throw new ForbiddenError(undefined, permission)
|
|
587
|
+
},
|
|
588
|
+
ability: async (subject, opts) => createAbility(await access(subject, opts)),
|
|
589
|
+
|
|
590
|
+
// Who has a role (direct assignments; inherited roles aren't listed).
|
|
591
|
+
subjectsWithRole: (name) => store.subjectsWithRole(name),
|
|
592
|
+
|
|
593
|
+
// Resource rules: permissions.rule('posts.update', ({ user, resource, granted }) => ...)
|
|
594
|
+
rule(name, fn) {
|
|
595
|
+
ruleMap.set(name, fn)
|
|
596
|
+
return permissions
|
|
597
|
+
},
|
|
598
|
+
|
|
599
|
+
sync,
|
|
600
|
+
// Drops every cached catalog and snapshot (after editing the store
|
|
601
|
+
// directly, for example).
|
|
602
|
+
flush: changed,
|
|
603
|
+
options: { superAdmin, subjectType, ttl, strict, defaultRoles: list(defaultRoles) },
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
return permissions
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
export { toAccess }
|