@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.
@@ -0,0 +1,140 @@
1
+ // A store on the Tylix ORM, so roles live in the app's own database on any
2
+ // of its SQL drivers (SQLite, PostgreSQL, MySQL, MariaDB, CockroachDB).
3
+ //
4
+ // import { Model } from '@tylix/orm'
5
+ // const store = ormStore({ Model })
6
+ //
7
+ // Tables (created by createPermissionTables, see ./schema.js):
8
+ // permissions id, name, description, timestamps
9
+ // roles id, name, description, timestamps
10
+ // role_has_permissions id, role, permission (permission may be a pattern or !deny)
11
+ // role_inherits id, role, parent
12
+ // model_has_roles id, subject_type, subject_id, role, team, expires_at
13
+ // model_has_permissions id, subject_type, subject_id, permission, effect, team, expires_at
14
+ //
15
+ // Pivot rows refer to roles and permissions by name, not id: a grant can be
16
+ // a pattern ("posts.*") that has no row of its own, and reads need no joins.
17
+ export const DEFAULT_TABLES = Object.freeze({
18
+ permissions: 'permissions',
19
+ roles: 'roles',
20
+ roleHasPermissions: 'role_has_permissions',
21
+ roleInherits: 'role_inherits',
22
+ modelHasRoles: 'model_has_roles',
23
+ modelHasPermissions: 'model_has_permissions',
24
+ })
25
+
26
+ export function ormStore({ Model, tables = {} } = {}) {
27
+ if (typeof Model !== 'function') {
28
+ throw new TypeError('ormStore({ Model }) needs the Model class from @tylix/orm.')
29
+ }
30
+ const t = { ...DEFAULT_TABLES, ...tables }
31
+ const model = (table, fillable, timestamps) =>
32
+ class extends Model {
33
+ static table = table
34
+ static fillable = fillable
35
+ static timestamps = timestamps
36
+ }
37
+
38
+ const Permission = model(t.permissions, ['name', 'description'], true)
39
+ const Role = model(t.roles, ['name', 'description'], true)
40
+ const RolePermission = model(t.roleHasPermissions, ['role', 'permission'], false)
41
+ const RoleInherit = model(t.roleInherits, ['role', 'parent'], false)
42
+ const SubjectRole = model(t.modelHasRoles, ['subject_type', 'subject_id', 'role', 'team', 'expires_at'], false)
43
+ const SubjectPermission = model(
44
+ t.modelHasPermissions,
45
+ ['subject_type', 'subject_id', 'permission', 'effect', 'team', 'expires_at'],
46
+ false,
47
+ )
48
+
49
+ const run = (sql, params) => Model.getAdapter().run(sql, params)
50
+ const subjectWhere = (M, ref) => M.where('subject_type', ref.type).where('subject_id', String(ref.id))
51
+ const iso = (value) => (value ? new Date(value).toISOString() : null)
52
+
53
+ return {
54
+ models: { Permission, Role, RolePermission, RoleInherit, SubjectRole, SubjectPermission },
55
+
56
+ async loadCatalog() {
57
+ const [permissions, roles, grants, inherits] = await Promise.all([
58
+ Permission.query().orderBy('name').get(),
59
+ Role.query().orderBy('name').get(),
60
+ RolePermission.query().get(),
61
+ RoleInherit.query().get(),
62
+ ])
63
+ return {
64
+ permissions: permissions.map((p) => ({ name: p.name, description: p.description ?? null })),
65
+ roles: roles.map((r) => ({
66
+ name: r.name,
67
+ description: r.description ?? null,
68
+ permissions: grants.filter((g) => g.role === r.name).map((g) => g.permission),
69
+ inherits: inherits.filter((i) => i.role === r.name).map((i) => i.parent),
70
+ })),
71
+ }
72
+ },
73
+
74
+ async savePermission({ name, description = null }) {
75
+ const existing = await Permission.where('name', name).first()
76
+ if (!existing) await Permission.create({ name, description })
77
+ else if (description !== null && description !== existing.description) await Permission.update(existing.id, { description })
78
+ },
79
+
80
+ async deletePermission(name) {
81
+ await run(`DELETE FROM ${t.permissions} WHERE name = ?`, [name])
82
+ await run(`DELETE FROM ${t.roleHasPermissions} WHERE permission = ? OR permission = ?`, [name, `!${name}`])
83
+ await run(`DELETE FROM ${t.modelHasPermissions} WHERE permission = ?`, [name])
84
+ },
85
+
86
+ async saveRole({ name, description = null, permissions = [], inherits = [] }) {
87
+ const existing = await Role.where('name', name).first()
88
+ if (!existing) await Role.create({ name, description })
89
+ else if (description !== existing.description) await Role.update(existing.id, { description })
90
+ await run(`DELETE FROM ${t.roleHasPermissions} WHERE role = ?`, [name])
91
+ for (const permission of new Set(permissions)) await RolePermission.create({ role: name, permission })
92
+ await run(`DELETE FROM ${t.roleInherits} WHERE role = ?`, [name])
93
+ for (const parent of new Set(inherits)) await RoleInherit.create({ role: name, parent })
94
+ },
95
+
96
+ async deleteRole(name) {
97
+ await run(`DELETE FROM ${t.roles} WHERE name = ?`, [name])
98
+ await run(`DELETE FROM ${t.roleHasPermissions} WHERE role = ?`, [name])
99
+ await run(`DELETE FROM ${t.roleInherits} WHERE role = ? OR parent = ?`, [name, name])
100
+ await run(`DELETE FROM ${t.modelHasRoles} WHERE role = ?`, [name])
101
+ },
102
+
103
+ async getAssignments(ref) {
104
+ const [roles, permissions] = await Promise.all([subjectWhere(SubjectRole, ref).get(), subjectWhere(SubjectPermission, ref).get()])
105
+ return {
106
+ roles: roles.map((r) => ({ name: r.role, team: r.team ?? null, expiresAt: r.expires_at ?? null })),
107
+ permissions: permissions.map((p) => ({
108
+ name: p.permission,
109
+ effect: p.effect === 'deny' ? 'deny' : 'allow',
110
+ team: p.team ?? null,
111
+ expiresAt: p.expires_at ?? null,
112
+ })),
113
+ }
114
+ },
115
+
116
+ async setAssignments(ref, { roles = [], permissions = [] }) {
117
+ const id = String(ref.id)
118
+ await run(`DELETE FROM ${t.modelHasRoles} WHERE subject_type = ? AND subject_id = ?`, [ref.type, id])
119
+ for (const r of roles) {
120
+ await SubjectRole.create({ subject_type: ref.type, subject_id: id, role: r.name, team: r.team ?? null, expires_at: iso(r.expiresAt) })
121
+ }
122
+ await run(`DELETE FROM ${t.modelHasPermissions} WHERE subject_type = ? AND subject_id = ?`, [ref.type, id])
123
+ for (const p of permissions) {
124
+ await SubjectPermission.create({
125
+ subject_type: ref.type,
126
+ subject_id: id,
127
+ permission: p.name,
128
+ effect: p.effect === 'deny' ? 'deny' : 'allow',
129
+ team: p.team ?? null,
130
+ expires_at: iso(p.expiresAt),
131
+ })
132
+ }
133
+ },
134
+
135
+ async subjectsWithRole(name) {
136
+ const rows = await SubjectRole.where('role', name).get()
137
+ return rows.map((r) => ({ type: r.subject_type, id: r.subject_id, team: r.team ?? null, expiresAt: r.expires_at ?? null }))
138
+ },
139
+ }
140
+ }
@@ -0,0 +1,6 @@
1
+ import type { Ability, AccessSource, Requirement } from './client.js'
2
+ export interface Readable<T> {
3
+ subscribe(run: (value: T) => void): () => void
4
+ }
5
+ export function abilityStore(source: Readable<AccessSource> | AccessSource): Readable<Ability>
6
+ export function can(node: HTMLElement, params: [Requirement, AccessSource | Ability]): { update(params: [Requirement, AccessSource | Ability]): void }
package/src/svelte.js ADDED
@@ -0,0 +1,34 @@
1
+ // Svelte helpers. Turn a store of the signed-in user into a store of what
2
+ // they may do (works with Svelte 4 stores and Svelte 5's store contract):
3
+ //
4
+ // import { auth } from '@tylix/svelte'
5
+ // export const ability = abilityStore(auth.user)
6
+ //
7
+ // {#if $ability.can('posts.create')} <NewPostButton /> {/if}
8
+ // <button use:can={['posts.delete', $ability]}>Delete</button>
9
+ import { createAbility, check } from './client.js'
10
+
11
+ // Any store ({ subscribe }) or a plain value.
12
+ export function abilityStore(source) {
13
+ if (!source || typeof source.subscribe !== 'function') {
14
+ const fixed = createAbility(source)
15
+ return { subscribe: (run) => (run(fixed), () => {}) }
16
+ }
17
+ return {
18
+ subscribe(run) {
19
+ const unsubscribe = source.subscribe((value) => run(createAbility(value)))
20
+ return typeof unsubscribe === 'function' ? unsubscribe : () => unsubscribe?.unsubscribe?.()
21
+ },
22
+ }
23
+ }
24
+
25
+ // use:can={[requirement, abilityOrUser]}: hides the element when the
26
+ // check fails.
27
+ export function can(node, [requirement, source] = []) {
28
+ const original = node.style.display
29
+ const apply = ([req, src] = []) => {
30
+ node.style.display = check(src, req) ? original : 'none'
31
+ }
32
+ apply([requirement, source])
33
+ return { update: apply }
34
+ }
package/src/vue.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ComputedRef, MaybeRef, Plugin } from 'vue'
2
+ import type { Ability, AccessSource, Requirement } from './client.js'
3
+ export function permissionsPlugin(source: MaybeRef<AccessSource> | (() => AccessSource)): Plugin
4
+ export function useAbility(): ComputedRef<Ability>
5
+ export function useCan(requirement: MaybeRef<Requirement>): ComputedRef<boolean>
6
+ export function useHasRole(role: MaybeRef<string | string[]>): ComputedRef<boolean>
7
+ declare module 'vue' {
8
+ interface ComponentCustomProperties {
9
+ $can(requirement: Requirement): boolean
10
+ }
11
+ }
package/src/vue.js ADDED
@@ -0,0 +1,49 @@
1
+ // Vue helpers. Install the plugin with the signed-in user (a ref, a
2
+ // getter, or a reactive object carrying `access`):
3
+ //
4
+ // const { user } = useAuth()
5
+ // app.use(permissionsPlugin(() => user.value))
6
+ //
7
+ // Then in templates:
8
+ // <button v-can="'posts.create'">New post</button> hidden when not allowed
9
+ // <AdminPanel v-if="$can('role:admin')" />
10
+ // And in setup():
11
+ // const canPublish = useCan('posts.publish') a computed boolean
12
+ import { computed, inject, unref } from 'vue'
13
+ import { createAbility, check } from './client.js'
14
+
15
+ const SOURCE = Symbol.for('tylix.permissions.source')
16
+
17
+ const read = (source) => (typeof source === 'function' ? source() : unref(source))
18
+
19
+ export function permissionsPlugin(source) {
20
+ const current = () => read(source)
21
+ const apply = (el, binding) => {
22
+ const ok = check(current(), binding.value)
23
+ const show = binding.modifiers.not ? !ok : ok
24
+ if (!('tylixDisplay' in el.dataset)) el.dataset.tylixDisplay = el.style.display
25
+ el.style.display = show ? el.dataset.tylixDisplay : 'none'
26
+ }
27
+ return {
28
+ install(app) {
29
+ app.provide(SOURCE, source)
30
+ app.config.globalProperties.$can = (requirement) => check(current(), requirement)
31
+ app.directive('can', { mounted: apply, updated: apply })
32
+ },
33
+ }
34
+ }
35
+
36
+ export function useAbility() {
37
+ const source = inject(SOURCE, null)
38
+ return computed(() => createAbility(read(source)))
39
+ }
40
+
41
+ export function useCan(requirement) {
42
+ const source = inject(SOURCE, null)
43
+ return computed(() => check(read(source), unref(requirement)))
44
+ }
45
+
46
+ export function useHasRole(role) {
47
+ const ability = useAbility()
48
+ return computed(() => ability.value.hasRole(unref(role)))
49
+ }