@tylix/permissions 0.0.0-stage → 2.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mbiyrukzz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,310 @@
1
- # Temporary Holding Version
1
+ # @tylix/permissions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Roles and permissions for **any JavaScript app**: Express, Fastify, Hono,
4
+ Next.js, Nuxt, SvelteKit, Remix, Astro and Tylix on the server; React,
5
+ Vue, Svelte, Angular and Tylix pages in the browser. No dependencies.
6
+
7
+ It is inspired by Laravel's spatie/laravel-permission, and adds what you
8
+ otherwise build yourself:
9
+
10
+ | | spatie/laravel-permission | @tylix/permissions |
11
+ | --- | --- | --- |
12
+ | Roles, permissions, direct grants | ✔ | ✔ |
13
+ | Wildcards (`posts.*`, `posts.edit,delete`, `*`) | opt-in | built in |
14
+ | Role inheritance (`editor` inherits `writer`) | | ✔ |
15
+ | Explicit denies that beat any allow | | ✔ (`!posts.delete`, `deny()`) |
16
+ | Teams / tenants | ✔ | ✔, per assignment |
17
+ | Grants that expire | | ✔ |
18
+ | Default roles every signed-in user has | | ✔ |
19
+ | Resource rules (`can(user, 'posts.update', post)`) | via policies | ✔ |
20
+ | Same answer in the browser, synchronously | | ✔ (`user.access`) |
21
+ | Declarative, idempotent `sync()` for seeders | | ✔ |
22
+ | Storage | Eloquent | memory, Tylix ORM, or your own store |
23
+
24
+ ```sh
25
+ npm install @tylix/permissions
26
+ ```
27
+
28
+ ## Quick start
29
+
30
+ ```js
31
+ import { createPermissions } from '@tylix/permissions'
32
+
33
+ const permissions = createPermissions({ superAdmin: 'super-admin' })
34
+
35
+ await permissions.sync({
36
+ permissions: ['posts.view', 'posts.create', 'posts.update', 'posts.delete', 'users.manage'],
37
+ roles: {
38
+ writer: ['posts.view', 'posts.create'],
39
+ editor: { inherits: ['writer'], permissions: ['posts.*', '!posts.delete'] },
40
+ admin: { inherits: ['editor'], permissions: ['users.*'] },
41
+ 'super-admin': [],
42
+ },
43
+ })
44
+
45
+ await permissions.for(user).assignRole('editor')
46
+
47
+ await permissions.can(user, 'posts.update') // true (posts.*)
48
+ await permissions.can(user, 'posts.delete') // false (denied by the role)
49
+ await permissions.hasRole(user, 'writer') // true (inherited)
50
+ ```
51
+
52
+ A subject is a user row (`{ id }`), a Tylix `req.user` (`{ userId }`), a
53
+ plain id, or `{ type, id }` for things that aren't users (API clients,
54
+ devices). Ids are compared as strings.
55
+
56
+ ## Names and wildcards
57
+
58
+ Permission names are dot-separated words: `posts.edit`,
59
+ `billing.invoices.export`. Grants can use:
60
+
61
+ | Grant | Covers |
62
+ | --- | --- |
63
+ | `*` | everything |
64
+ | `posts.*` | `posts.edit`, `posts.edit.own`, ... (one or more segments) |
65
+ | `posts.*.own` | `posts.edit.own` (exactly one segment in the middle) |
66
+ | `posts.edit,delete` | `posts.edit` and `posts.delete` |
67
+ | `!posts.delete` | in a role: a deny |
68
+
69
+ A deny always wins over an allow, from any role or direct grant. Only the
70
+ super-admin role passes everything, denies included.
71
+
72
+ Concrete names must be created before they are granted, so a typo fails
73
+ loudly (`PermissionError` with `code: 'PERMISSION_DOES_NOT_EXIST'`).
74
+ Patterns never need a row. Pass `strict: false` to turn this off.
75
+
76
+ ## Roles
77
+
78
+ ```js
79
+ await permissions.createRole('support', { permissions: ['users.view'], inherits: ['writer'], description: 'Helps customers' })
80
+ await permissions.updateRole('support', { permissions: ['users.view', 'tickets.*'] })
81
+ await permissions.role('support').give('billing.view')
82
+ await permissions.role('support').deny('users.delete')
83
+ await permissions.role('support').revoke('billing.view')
84
+ await permissions.role('support').inherit('writer')
85
+ await permissions.role('support').access() // everything it allows, inherited included
86
+ await permissions.role('support').subjects() // who has it
87
+ await permissions.deleteRole('support') // also removes it from users and inheritors
88
+ await permissions.roles() // the catalog
89
+ ```
90
+
91
+ Inheritance cycles are refused (`code: 'ROLE_CYCLE'`).
92
+
93
+ ## Users (subjects)
94
+
95
+ ```js
96
+ const u = permissions.for(user)
97
+ await u.assignRole('editor')
98
+ await u.assignRole('admin', { team: 'acme' }) // only in team acme
99
+ await u.assignRole('support', { expiresAt: '2027-01-01' }) // until then
100
+ await u.removeRole('editor')
101
+ await u.syncRoles(['writer'])
102
+ await u.givePermission('billing.view')
103
+ await u.deny('posts.publish') // beats every role
104
+ await u.revokePermission('billing.view')
105
+ await u.syncPermissions(['billing.view']) // keeps denies
106
+
107
+ await u.can('posts.publish')
108
+ await u.canAny(['posts.update', 'posts.publish'])
109
+ await u.canAll(['posts.update', 'posts.publish'])
110
+ await u.hasRole(['admin', 'editor']) // any of them
111
+ await u.hasAllRoles(['admin', 'editor'])
112
+ await u.roles() // inherited included
113
+ await u.access() // the snapshot (below)
114
+ await u.authorize('posts.publish') // throws ForbiddenError (status 403)
115
+ ```
116
+
117
+ Every check takes `{ team }`. Assignments without a team apply in every
118
+ team; team assignments only in theirs. `permissions.for(user, { team: 'acme' })`
119
+ binds a team for a series of calls.
120
+
121
+ `defaultRoles: ['member']` gives every signed-in subject a role without
122
+ assigning it (guests get nothing), which is handy for "what any account may
123
+ do".
124
+
125
+ ## Resource rules
126
+
127
+ Stored permissions answer "may they edit posts?". A rule answers "may they
128
+ edit *this* post?":
129
+
130
+ ```js
131
+ const permissions = createPermissions({
132
+ rules: {
133
+ 'posts.update': ({ user, resource, granted, can }) =>
134
+ granted || resource.authorId === user.id,
135
+ },
136
+ })
137
+
138
+ await permissions.can(user, 'posts.update', post)
139
+ ```
140
+
141
+ The rule gets `granted` (what stored permissions say), the `access`
142
+ snapshot, the `team`, and `can(other)` for further checks. Without a
143
+ resource, only stored permissions count. Rules can be async, and can also
144
+ be added later with `permissions.rule(name, fn)`.
145
+
146
+ ## The browser
147
+
148
+ The server computes an **access snapshot** once and sends it with the user:
149
+
150
+ ```js
151
+ user.access = await permissions.access(user)
152
+ // { roles: ['editor', 'writer'], permissions: ['posts.*', ...], denied: ['posts.delete'], superAdmin: false }
153
+ ```
154
+
155
+ Then any code checks synchronously, with the same matching as the server:
156
+
157
+ ```js
158
+ import { can, hasRole, createAbility } from '@tylix/permissions/client'
159
+
160
+ can(user, 'posts.update') // reads user.access
161
+ hasRole(user, ['admin', 'editor'])
162
+ createAbility(user).allowed(['posts.create', 'users.manage'])
163
+ ```
164
+
165
+ Hiding a button is not security: guard the route that does the work too.
166
+
167
+ ### React
168
+
169
+ ```jsx
170
+ import { PermissionsProvider, Can, useCan } from '@tylix/permissions/react'
171
+
172
+ <PermissionsProvider user={useAuth().user}>
173
+ <Can permission="posts.create"><NewPostButton /></Can>
174
+ <Can role="admin" fallback={<p>Admins only.</p>}><AdminPanel /></Can>
175
+ <Can any={['posts.update', 'posts.publish']}>...</Can>
176
+ </PermissionsProvider>
177
+
178
+ const canPublish = useCan('posts.publish') // also 'role:admin', 'any:a|b', ['a', 'b']
179
+ ```
180
+
181
+ ### Vue
182
+
183
+ ```js
184
+ import { permissionsPlugin, useCan } from '@tylix/permissions/vue'
185
+ app.use(permissionsPlugin(() => useAuth().user.value))
186
+ ```
187
+
188
+ ```vue
189
+ <button v-can="'posts.create'">New post</button>
190
+ <AdminPanel v-if="$can('role:admin')" />
191
+ <script setup>const canPublish = useCan('posts.publish')</script>
192
+ ```
193
+
194
+ ### Svelte
195
+
196
+ ```svelte
197
+ <script>
198
+ import { auth } from '@tylix/svelte'
199
+ import { abilityStore, can } from '@tylix/permissions/svelte'
200
+ const ability = abilityStore(auth.user)
201
+ </script>
202
+
203
+ {#if $ability.can('posts.create')}<NewPostButton />{/if}
204
+ <button use:can={['posts.delete', $ability]}>Delete</button>
205
+ ```
206
+
207
+ ### Angular
208
+
209
+ ```ts
210
+ // app.config.ts
211
+ providers: [providePermissions(() => injectAuth().user)]
212
+
213
+ // a component
214
+ can = injectCan()
215
+ // @if (can('posts.create')) { <app-new-post /> }
216
+
217
+ // routes
218
+ { path: 'admin', canActivate: [permissionGuard('role:admin')], loadComponent: ... }
219
+ ```
220
+
221
+ ## HTTP
222
+
223
+ ```js
224
+ // Tylix routes, Express, Connect, Polka (req.user by default)
225
+ router.post('/api/posts', permissions.middleware('posts.create'), handler)
226
+ router.delete('/api/posts/:id', permissions.middleware({ any: ['posts.delete', 'posts.moderate'] }), handler)
227
+ router.get('/admin', permissions.middleware({ role: 'admin' }), handler)
228
+
229
+ // Wrap a handler, like requireAuth
230
+ router.put('/api/posts/:id', permissions.guard(handler, 'posts.update', {
231
+ resource: (req) => Post.find(req.params.id), // runs the posts.update rule
232
+ }))
233
+
234
+ // Hono, Next.js route handlers, SvelteKit, Workers: null when allowed
235
+ const denied = await permissions.guardRequest(user, 'posts.create')
236
+ if (denied) return denied
237
+ ```
238
+
239
+ It answers `401` without a user and `403 { error, required }` when the
240
+ check fails. Options: `user(req)`, `team(req)`, `resource(req)`,
241
+ `message`, `onDenied(req, res)`.
242
+
243
+ ## Storage
244
+
245
+ ```js
246
+ import { memoryStore, ormStore } from '@tylix/permissions'
247
+ import { Model } from '@tylix/orm'
248
+
249
+ createPermissions({ store: memoryStore() }) // the default
250
+ createPermissions({ store: ormStore({ Model }) }) // the Tylix ORM: SQLite, PostgreSQL, MySQL, MariaDB, CockroachDB
251
+ ```
252
+
253
+ The ORM store uses six tables. Create them in a migration:
254
+
255
+ ```js
256
+ import { createPermissionTables, dropPermissionTables } from '@tylix/permissions/schema'
257
+ export const up = (schema) => createPermissionTables(schema)
258
+ export const down = (schema) => dropPermissionTables(schema)
259
+ ```
260
+
261
+ Any other database works through a store: an object with `loadCatalog`,
262
+ `savePermission`, `deletePermission`, `saveRole`, `deleteRole`,
263
+ `getAssignments`, `setAssignments` and `subjectsWithRole`. See
264
+ `src/stores/memory.js` for the contract; it is about 80 lines.
265
+
266
+ ## Caching
267
+
268
+ Catalogs and snapshots are cached for `ttl` seconds (default 30) and
269
+ dropped on every change made through the instance. With several
270
+ processes, pass a shared `cache` (Tylix's `cache`, or any
271
+ `get/set(key, value, ttlSeconds)/forget` wrapper over Redis) and every
272
+ process sees a change on its next check. `permissions.flush()` drops
273
+ everything after editing the store directly.
274
+
275
+ ## In a Tylix app
276
+
277
+ ```sh
278
+ tylix make:permissions
279
+ npm install && tylix migrate && tylix db:seed
280
+ tylix permission:assign admin you@example.com
281
+ ```
282
+
283
+ That writes `app/permissions` (the instance, its rules and the starting
284
+ roles), `Role` and `Permission` models, the migration, a seeder, an admin
285
+ API, and, for `.tyx` apps, an admin page at `/admin/access` with modals to
286
+ create roles and permissions and to give users roles. Changes that would
287
+ remove your own access to that page are refused.
288
+
289
+ Then:
290
+
291
+ - `GET /api/me` (and the server-rendered session) carries `user.access`.
292
+ - `.tyx` pages check with `can("posts.create")`, `cannot(...)`,
293
+ `canAny([...])` and `hasRole("admin")` in templates, and a page's
294
+ `permissions` block is enforced: guests go to login, others see a 403.
295
+ - `tylix dev` marks guarded routes with 🔑 and the permission they need.
296
+
297
+ From the terminal:
298
+
299
+ | Command | |
300
+ | --- | --- |
301
+ | `tylix permission:create-role support users.view tickets.* --inherits writer` | a role |
302
+ | `tylix permission:create-permission invoices.export --description "..."` | permissions |
303
+ | `tylix permission:assign admin ada@example.com [--team acme] [--expires 2027-01-01]` | give a role |
304
+ | `tylix permission:revoke admin ada@example.com` | take it back |
305
+ | `tylix permission:show [user]` | the role × permission matrix, or one user's access |
306
+ | `tylix permission:sync` | apply the definition in `app/permissions` |
307
+
308
+ ## License
309
+
310
+ MIT
package/package.json CHANGED
@@ -1,6 +1,101 @@
1
1
  {
2
2
  "name": "@tylix/permissions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.1.0",
4
+ "description": "Roles and permissions for any JavaScript app: wildcards, role inheritance, denies, teams, expiring grants, resource rules, a browser snapshot, HTTP guards, and React, Vue, Svelte and Angular helpers. No dependencies.",
5
+ "license": "MIT",
6
+ "author": "Mbiyrukzz",
7
+ "type": "module",
8
+ "keywords": [
9
+ "permissions",
10
+ "roles",
11
+ "rbac",
12
+ "acl",
13
+ "authorization",
14
+ "spatie",
15
+ "react",
16
+ "vue",
17
+ "svelte",
18
+ "angular",
19
+ "tylix"
20
+ ],
21
+ "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/permissions#readme",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Mbiyrukzz/tylix.git",
25
+ "directory": "packages/permissions"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/Mbiyrukzz/tylix/issues"
29
+ },
30
+ "engines": {
31
+ "node": ">=18"
32
+ },
33
+ "main": "./src/index.js",
34
+ "types": "./src/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "types": "./src/index.d.ts",
38
+ "default": "./src/index.js"
39
+ },
40
+ "./client": {
41
+ "types": "./src/client.d.ts",
42
+ "default": "./src/client.js"
43
+ },
44
+ "./schema": {
45
+ "types": "./src/schema.d.ts",
46
+ "default": "./src/schema.js"
47
+ },
48
+ "./react": {
49
+ "types": "./src/react.d.ts",
50
+ "default": "./src/react.js"
51
+ },
52
+ "./vue": {
53
+ "types": "./src/vue.d.ts",
54
+ "default": "./src/vue.js"
55
+ },
56
+ "./svelte": {
57
+ "types": "./src/svelte.d.ts",
58
+ "default": "./src/svelte.js"
59
+ },
60
+ "./angular": {
61
+ "types": "./src/angular.d.ts",
62
+ "default": "./src/angular.js"
63
+ }
64
+ },
65
+ "sideEffects": false,
66
+ "files": [
67
+ "src",
68
+ "!**/*.test.js",
69
+ "README.md",
70
+ "LICENSE"
71
+ ],
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "scripts": {
76
+ "test": "node --test test/*.test.js"
77
+ },
78
+ "peerDependencies": {
79
+ "@angular/core": ">=17.0.0",
80
+ "react": ">=18.0.0",
81
+ "vue": ">=3.3.0",
82
+ "@angular/router": ">=17.0.0"
83
+ },
84
+ "peerDependenciesMeta": {
85
+ "@angular/core": {
86
+ "optional": true
87
+ },
88
+ "react": {
89
+ "optional": true
90
+ },
91
+ "vue": {
92
+ "optional": true
93
+ },
94
+ "@angular/router": {
95
+ "optional": true
96
+ }
97
+ },
98
+ "devDependencies": {
99
+ "@tylix/orm": "^2.1.0"
100
+ }
101
+ }
@@ -0,0 +1,8 @@
1
+ import type { InjectionToken, Provider, Signal } from '@angular/core'
2
+ import type { CanActivateFn } from '@angular/router'
3
+ import type { Ability, AccessSource, Requirement } from './client.js'
4
+ export const TYLIX_PERMISSIONS_SOURCE: InjectionToken<() => AccessSource>
5
+ export function providePermissions(factory: () => (() => AccessSource) | AccessSource): Provider
6
+ export function injectAbility(): Signal<Ability>
7
+ export function injectCan(): (requirement: Requirement) => boolean
8
+ export function permissionGuard(requirement: Requirement, options?: { redirectTo?: string }): CanActivateFn
package/src/angular.js ADDED
@@ -0,0 +1,45 @@
1
+ // Angular helpers, as signals. Provide where the signed-in user comes from:
2
+ //
3
+ // // app.config.ts
4
+ // providers: [providePermissions(() => injectAuth().user)]
5
+ //
6
+ // // a component
7
+ // can = injectCan()
8
+ // @if (can('posts.create')) { <app-new-post /> }
9
+ //
10
+ // // routes
11
+ // { path: 'admin', canActivate: [permissionGuard('role:admin')], ... }
12
+ import { InjectionToken, computed, inject } from '@angular/core'
13
+ import { Router } from '@angular/router'
14
+ import { createAbility, check } from './client.js'
15
+
16
+ // A signal (or any function) returning the user or access snapshot.
17
+ export const TYLIX_PERMISSIONS_SOURCE = new InjectionToken('TYLIX_PERMISSIONS_SOURCE')
18
+
19
+ export function providePermissions(factory) {
20
+ return { provide: TYLIX_PERMISSIONS_SOURCE, useFactory: factory }
21
+ }
22
+
23
+ function source() {
24
+ const read = inject(TYLIX_PERMISSIONS_SOURCE, { optional: true })
25
+ return typeof read === 'function' ? read : () => read ?? null
26
+ }
27
+
28
+ export function injectAbility() {
29
+ const read = source()
30
+ return computed(() => createAbility(read()))
31
+ }
32
+
33
+ // can('posts.edit'), can(['a', 'b']), can('role:admin'), can('any:a|b').
34
+ // Reads the user signal, so templates update when the session changes.
35
+ export function injectCan() {
36
+ const read = source()
37
+ return (requirement) => check(read(), requirement)
38
+ }
39
+
40
+ export function permissionGuard(requirement, { redirectTo = '/' } = {}) {
41
+ return () => {
42
+ const read = source()
43
+ return check(read(), requirement) ? true : inject(Router).parseUrl(redirectTo)
44
+ }
45
+ }
@@ -0,0 +1,42 @@
1
+ /** What a subject may do, as computed by the server. Safe to send to the browser. */
2
+ export interface Access {
3
+ /** Every role the subject has, inherited roles included. */
4
+ roles: string[]
5
+ /** Granted permission names and patterns ("posts.*"). */
6
+ permissions: string[]
7
+ /** Denied names and patterns; a deny beats any allow. */
8
+ denied: string[]
9
+ /** True for the configured super-admin role: every check passes. */
10
+ superAdmin: boolean
11
+ }
12
+
13
+ /** A snapshot, an object carrying one as `access` (a user), or nothing (a guest). */
14
+ export type AccessSource = Access | { access?: Access | null; [key: string]: unknown } | null | undefined
15
+
16
+ /** "posts.edit", ["a", "b"] (all), "role:admin|editor", "any:a|b", "all:a|b". */
17
+ export type Requirement = string | string[]
18
+
19
+ export interface Ability extends Access {
20
+ can(permission: string | string[]): boolean
21
+ cannot(permission: string | string[]): boolean
22
+ canAny(permissions: string[]): boolean
23
+ canAll(permissions: string[]): boolean
24
+ hasRole(role: string | string[]): boolean
25
+ hasAnyRole(roles: string[]): boolean
26
+ hasAllRoles(roles: string[]): boolean
27
+ /** The listed permissions this snapshot allows. */
28
+ allowed(permissions: string[]): string[]
29
+ }
30
+
31
+ export function can(source: AccessSource, permission: string | string[]): boolean
32
+ export function cannot(source: AccessSource, permission: string | string[]): boolean
33
+ export function canAny(source: AccessSource, permissions: string | string[]): boolean
34
+ export function canAll(source: AccessSource, permissions: string | string[]): boolean
35
+ export function hasRole(source: AccessSource, role: string | string[]): boolean
36
+ export function hasAnyRole(source: AccessSource, roles: string | string[]): boolean
37
+ export function hasAllRoles(source: AccessSource, roles: string | string[]): boolean
38
+ export function createAbility(source: AccessSource): Ability
39
+ export function check(source: AccessSource, requirement: Requirement): boolean
40
+ export function toAccess(source: AccessSource): Access
41
+ /** True when `grant` (which may use * and a,b) covers `requested`. */
42
+ export function matches(grant: string, requested: string): boolean
package/src/client.js ADDED
@@ -0,0 +1,92 @@
1
+ // Checks for the browser (and anywhere else a user's access snapshot is at
2
+ // hand). No server, no store, no async: the server computes a snapshot once
3
+ // (permissions.access(user)) and sends it with the user, usually as
4
+ // user.access, and these answer from it synchronously.
5
+ //
6
+ // import { can, hasRole } from '@tylix/permissions/client'
7
+ // can(user, 'posts.edit') // user.access, or a snapshot
8
+ // hasRole(user, ['admin', 'editor']) // any of them
9
+ //
10
+ // The server stays the authority: hide a button with these, but guard the
11
+ // route that does the work with permissions.require() too.
12
+ import { allows, toAccess } from './match.js'
13
+
14
+ export { matches } from './match.js'
15
+
16
+ const list = (value) => (Array.isArray(value) ? value : [value])
17
+
18
+ // can(user, 'a') -> may they do a?
19
+ // can(user, ['a', 'b']) -> may they do both?
20
+ export function can(source, permission) {
21
+ const access = toAccess(source)
22
+ const wanted = list(permission)
23
+ return wanted.length > 0 && wanted.every((p) => allows(access, p))
24
+ }
25
+
26
+ export function cannot(source, permission) {
27
+ return !can(source, permission)
28
+ }
29
+
30
+ export function canAny(source, permissions) {
31
+ const access = toAccess(source)
32
+ return list(permissions).some((p) => allows(access, p))
33
+ }
34
+
35
+ export function canAll(source, permissions) {
36
+ return can(source, permissions)
37
+ }
38
+
39
+ // hasRole(user, 'admin') or hasRole(user, ['admin', 'editor']) for any.
40
+ // Roles a role inherits count: an admin that inherits editor has editor.
41
+ export function hasRole(source, role) {
42
+ const roles = toAccess(source).roles
43
+ return list(role).some((r) => roles.includes(r))
44
+ }
45
+
46
+ export function hasAnyRole(source, roles) {
47
+ return hasRole(source, roles)
48
+ }
49
+
50
+ export function hasAllRoles(source, roles) {
51
+ const have = toAccess(source).roles
52
+ const wanted = list(roles)
53
+ return wanted.length > 0 && wanted.every((r) => have.includes(r))
54
+ }
55
+
56
+ // A bound checker over one snapshot, handy in templates:
57
+ // const ability = createAbility(user.access)
58
+ // ability.can('posts.edit')
59
+ export function createAbility(source) {
60
+ const access = toAccess(source)
61
+ return {
62
+ roles: access.roles,
63
+ permissions: access.permissions,
64
+ denied: access.denied,
65
+ superAdmin: access.superAdmin,
66
+ can: (p) => can(access, p),
67
+ cannot: (p) => !can(access, p),
68
+ canAny: (ps) => canAny(access, ps),
69
+ canAll: (ps) => canAll(access, ps),
70
+ hasRole: (r) => hasRole(access, r),
71
+ hasAnyRole: (rs) => hasAnyRole(access, rs),
72
+ hasAllRoles: (rs) => hasAllRoles(access, rs),
73
+ // Every listed permission name this snapshot allows, for menus:
74
+ // ability.allowed(['posts.create', 'users.view'])
75
+ allowed: (ps) => list(ps).filter((p) => allows(access, p)),
76
+ }
77
+ }
78
+
79
+ // Shorthand for directive-style checks: "posts.edit", "role:admin",
80
+ // "any:a|b", "all:a|b". Used by the framework bindings so a template can
81
+ // pass one string.
82
+ export function check(source, expression) {
83
+ if (Array.isArray(expression)) return can(source, expression)
84
+ const text = String(expression ?? '').trim()
85
+ if (text.startsWith('role:')) return hasRole(source, text.slice(5).split('|').map((s) => s.trim()))
86
+ if (text.startsWith('any:')) return canAny(source, text.slice(4).split('|').map((s) => s.trim()))
87
+ if (text.startsWith('all:')) return can(source, text.slice(4).split('|').map((s) => s.trim()))
88
+ return can(source, text)
89
+ }
90
+
91
+ // Re-exported so the engine and bindings share one notion of "a snapshot".
92
+ export { toAccess }