@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/src/http.js ADDED
@@ -0,0 +1,115 @@
1
+ // HTTP guards. The (req, res, next) form works in Tylix routes, Express,
2
+ // Connect, Polka and Fastify (via middie); guardRequest() works with any
3
+ // framework built on the web Request (Hono, Next.js route handlers,
4
+ // SvelteKit, Remix, Astro, Workers).
5
+ //
6
+ // Tylix: router.post('/api/posts', permissions.middleware('posts.create'), handler)
7
+ // Express: app.delete('/posts/:id', permissions.middleware('posts.delete'), handler)
8
+ // Hono: const denied = await guardRequest(permissions, user, 'posts.create'); if (denied) return denied
9
+ //
10
+ // A requirement is one of:
11
+ // 'posts.edit' that permission
12
+ // ['posts.edit', 'posts.publish'] all of them
13
+ // { any: ['posts.edit', 'posts.own'] }
14
+ // { role: 'admin' } / { role: ['admin', 'editor'] } any of the roles
15
+ // { permission, role } both must pass
16
+ // (req) => boolean | Promise<boolean>
17
+ export const PERMISSION_MARK = Symbol.for('tylix.permission')
18
+
19
+ const list = (value) => (value === undefined || value === null ? [] : Array.isArray(value) ? value : [value])
20
+
21
+ export function describeRequirement(requirement) {
22
+ if (typeof requirement === 'string') return requirement
23
+ if (Array.isArray(requirement)) return requirement.join(' + ')
24
+ if (typeof requirement === 'function') return 'custom check'
25
+ const parts = []
26
+ if (requirement?.permission) parts.push(list(requirement.permission).join(' + '))
27
+ if (requirement?.any) parts.push(`any of ${list(requirement.any).join(', ')}`)
28
+ if (requirement?.role) parts.push(`role ${list(requirement.role).join(' | ')}`)
29
+ return parts.join(', ') || 'permission'
30
+ }
31
+
32
+ // Resolves one requirement for one subject. Exported so other adapters
33
+ // (and the Tylix page guard) share the exact semantics.
34
+ export async function satisfies(permissions, subject, requirement, { resource, team, req } = {}) {
35
+ if (!subject) return false
36
+ const opts = { team }
37
+ if (typeof requirement === 'string' || Array.isArray(requirement)) {
38
+ return permissions.can(subject, requirement, resource, opts)
39
+ }
40
+ if (typeof requirement === 'function') return Boolean(await requirement(req, { subject, permissions }))
41
+ if (!requirement || typeof requirement !== 'object') return false
42
+ if (requirement.permission && !(await permissions.can(subject, requirement.permission, resource, opts))) return false
43
+ if (requirement.all && !(await permissions.can(subject, requirement.all, resource, opts))) return false
44
+ if (requirement.any && !(await permissions.canAny(subject, requirement.any, resource, opts))) return false
45
+ if (requirement.role && !(await permissions.hasRole(subject, requirement.role, opts))) {
46
+ // A super admin passes role checks too.
47
+ const access = await permissions.access(subject, opts)
48
+ if (!access.superAdmin) return false
49
+ }
50
+ return true
51
+ }
52
+
53
+ const defaultUser = (req) => req.user ?? req.auth?.user ?? req.session?.user ?? req.locals?.user ?? null
54
+
55
+ function send(res, status, body) {
56
+ if (typeof res.status === 'function' && typeof res.json === 'function') {
57
+ const r = res.status(status)
58
+ return (r && typeof r.json === 'function' ? r : res).json(body)
59
+ }
60
+ res.statusCode = status
61
+ res.setHeader?.('Content-Type', 'application/json; charset=utf-8')
62
+ res.end(JSON.stringify(body))
63
+ }
64
+
65
+ export function middleware(permissions, requirement, options = {}) {
66
+ const {
67
+ user = defaultUser,
68
+ team = () => null,
69
+ resource,
70
+ message = 'You do not have permission to do that.',
71
+ onDenied,
72
+ } = options
73
+ const label = describeRequirement(requirement)
74
+
75
+ const fn = async (req, res, next) => {
76
+ const subject = await user(req)
77
+ if (!subject) return send(res, 401, { error: 'Not authenticated.' })
78
+ let ok
79
+ try {
80
+ ok = await satisfies(permissions, subject, requirement, {
81
+ req,
82
+ team: await team(req),
83
+ resource: resource ? await resource(req) : undefined,
84
+ })
85
+ } catch (err) {
86
+ console.error('[permissions] check failed:', err)
87
+ return send(res, 500, { error: "Couldn't check your permissions." })
88
+ }
89
+ if (!ok) {
90
+ if (onDenied) return onDenied(req, res, { requirement })
91
+ return send(res, 403, { error: message, required: label })
92
+ }
93
+ if (typeof next === 'function') return next()
94
+ }
95
+ fn[PERMISSION_MARK] = label
96
+ return fn
97
+ }
98
+
99
+ // Handler-wrapping form, like requireAuth: permissions.guard(handler, 'posts.edit')
100
+ export function guard(permissions, handler, requirement, options = {}) {
101
+ const check = middleware(permissions, requirement, options)
102
+ const wrapped = (req, res) => check(req, res, () => handler(req, res))
103
+ wrapped[PERMISSION_MARK] = check[PERMISSION_MARK]
104
+ return wrapped
105
+ }
106
+
107
+ // For web Request frameworks: returns null when allowed, or a 401/403
108
+ // Response to return as is.
109
+ export async function guardRequest(permissions, subject, requirement, { resource, team, message } = {}) {
110
+ const json = (status, body) =>
111
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } })
112
+ if (!subject) return json(401, { error: 'Not authenticated.' })
113
+ const ok = await satisfies(permissions, subject, requirement, { resource, team })
114
+ return ok ? null : json(403, { error: message ?? 'You do not have permission to do that.', required: describeRequirement(requirement) })
115
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,220 @@
1
+ import type { Access, Ability, AccessSource } from './client.js'
2
+ import type { PermissionTables } from './schema.js'
3
+
4
+ export * from './client.js'
5
+ export { DEFAULT_TABLES } from './schema.js'
6
+
7
+ /** A user row, a Tylix req.user ({ userId }), an id, or { type, id } for other subjects. */
8
+ export type Subject =
9
+ | string
10
+ | number
11
+ | { id?: unknown; userId?: unknown; sub?: unknown; type?: string; subjectType?: string; [key: string]: unknown }
12
+
13
+ export interface ScopeOptions {
14
+ /** Team or tenant. Assignments without a team apply in every team. */
15
+ team?: string | number | null
16
+ }
17
+ export interface GrantOptions extends ScopeOptions {
18
+ /** When the grant stops applying. */
19
+ expiresAt?: Date | string | number | null
20
+ }
21
+
22
+ export interface PermissionRecord {
23
+ name: string
24
+ description: string | null
25
+ }
26
+ export interface RoleRecord {
27
+ name: string
28
+ description: string | null
29
+ /** Names, patterns, and "!name" denies. */
30
+ permissions: string[]
31
+ /** Roles whose permissions this one also has. */
32
+ inherits: string[]
33
+ }
34
+ export interface Catalog {
35
+ permissions: PermissionRecord[]
36
+ roles: RoleRecord[]
37
+ }
38
+
39
+ export interface Assignment {
40
+ name: string
41
+ team: string | null
42
+ expiresAt: string | Date | null
43
+ }
44
+ export interface Assignments {
45
+ roles: Assignment[]
46
+ permissions: (Assignment & { effect: 'allow' | 'deny' })[]
47
+ }
48
+
49
+ /** Where roles live. Implement it to keep them in any database. */
50
+ export interface PermissionStore {
51
+ loadCatalog(): Promise<Catalog>
52
+ savePermission(permission: { name: string; description?: string | null }): Promise<void>
53
+ /** Also removes it from roles and subjects. */
54
+ deletePermission(name: string): Promise<void>
55
+ saveRole(role: RoleRecord): Promise<void>
56
+ /** Also removes its assignments and inherits. */
57
+ deleteRole(name: string): Promise<void>
58
+ getAssignments(subject: { type: string; id: string }): Promise<Assignments>
59
+ setAssignments(subject: { type: string; id: string }, assignments: Assignments): Promise<void>
60
+ subjectsWithRole(name: string): Promise<{ type: string; id: string; team: string | null; expiresAt: string | null }[]>
61
+ }
62
+
63
+ /** Any cache with get/set(ttlSeconds)/forget, like Tylix's `cache` or a Redis wrapper. */
64
+ export interface PermissionCache {
65
+ get(key: string): Promise<any>
66
+ set(key: string, value: any, ttlSeconds?: number | null): Promise<unknown>
67
+ forget?(key: string): Promise<unknown>
68
+ delete?(key: string): Promise<unknown>
69
+ }
70
+
71
+ export interface RuleContext<R = any, S = Subject> {
72
+ subject: S
73
+ user: S
74
+ resource: R
75
+ /** Whether stored permissions grant it. */
76
+ granted: boolean
77
+ access: Access
78
+ team: string | number | null
79
+ /** Another check for the same subject (and, by default, resource). */
80
+ can(permission: string | string[], resource?: unknown): Promise<boolean>
81
+ }
82
+ export type Rule<R = any> = (context: RuleContext<R>) => boolean | Promise<boolean>
83
+
84
+ export interface PermissionsOptions {
85
+ store?: PermissionStore
86
+ /** Role name(s) that pass every check. */
87
+ superAdmin?: string | string[] | null
88
+ /** Resource rules: decide can(user, name, resource). */
89
+ rules?: Record<string, Rule>
90
+ /** Shared cache, so every process sees changes at once. */
91
+ cache?: PermissionCache | null
92
+ /** Seconds a snapshot is cached. Default 30. */
93
+ ttl?: number
94
+ /** Subject type for plain ids and users. Default "user". */
95
+ subjectType?: string
96
+ /** Refuse to grant names that weren't created (patterns excepted). Default true. */
97
+ strict?: boolean
98
+ /** Roles every signed-in subject has without an assignment. Guests get none. */
99
+ defaultRoles?: string[]
100
+ }
101
+
102
+ export type HttpRequirement =
103
+ | string
104
+ | string[]
105
+ | { permission?: string | string[]; all?: string[]; any?: string[]; role?: string | string[] }
106
+ | ((req: any, context: { subject: Subject; permissions: Permissions }) => boolean | Promise<boolean>)
107
+
108
+ export interface MiddlewareOptions {
109
+ /** Default: req.user, req.auth.user, req.session.user or req.locals.user. */
110
+ user?: (req: any) => Subject | null | undefined | Promise<Subject | null | undefined>
111
+ team?: (req: any) => string | number | null | Promise<string | number | null>
112
+ resource?: (req: any) => unknown
113
+ message?: string
114
+ onDenied?: (req: any, res: any, info: { requirement: HttpRequirement }) => unknown
115
+ }
116
+
117
+ export interface SubjectPermissions {
118
+ assignRole(roles: string | string[], options?: GrantOptions): Promise<SubjectPermissions>
119
+ removeRole(roles: string | string[], options?: ScopeOptions): Promise<SubjectPermissions>
120
+ syncRoles(roles: string[], options?: GrantOptions): Promise<SubjectPermissions>
121
+ givePermission(permissions: string | string[], options?: GrantOptions): Promise<SubjectPermissions>
122
+ /** An explicit deny: beats any allow from a role. */
123
+ deny(permissions: string | string[], options?: GrantOptions): Promise<SubjectPermissions>
124
+ revokePermission(permissions: string | string[], options?: ScopeOptions): Promise<SubjectPermissions>
125
+ /** Replaces direct allows (denies are kept). */
126
+ syncPermissions(permissions: string[], options?: GrantOptions): Promise<SubjectPermissions>
127
+ can(permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
128
+ cannot(permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
129
+ canAny(permissions: string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
130
+ canAll(permissions: string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
131
+ hasRole(roles: string | string[], options?: ScopeOptions): Promise<boolean>
132
+ hasAnyRole(roles: string[], options?: ScopeOptions): Promise<boolean>
133
+ hasAllRoles(roles: string[], options?: ScopeOptions): Promise<boolean>
134
+ roles(options?: ScopeOptions): Promise<string[]>
135
+ permissions(options?: ScopeOptions): Promise<string[]>
136
+ access(options?: ScopeOptions): Promise<Access>
137
+ ability(options?: ScopeOptions): Promise<Ability>
138
+ assignments(): Promise<Assignments>
139
+ /** Throws ForbiddenError (status 403) when not allowed. */
140
+ authorize(permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<void>
141
+ }
142
+
143
+ export interface RolePermissions {
144
+ give(permissions: string | string[]): Promise<RolePermissions>
145
+ deny(permissions: string | string[]): Promise<RolePermissions>
146
+ revoke(permissions: string | string[]): Promise<RolePermissions>
147
+ sync(permissions: string[]): Promise<RolePermissions>
148
+ inherit(roles: string | string[]): Promise<RolePermissions>
149
+ disinherit(roles: string | string[]): Promise<RolePermissions>
150
+ get(): Promise<RoleRecord | null>
151
+ access(): Promise<Access>
152
+ subjects(): Promise<{ type: string; id: string; team: string | null; expiresAt: string | null }[]>
153
+ }
154
+
155
+ export interface SyncDefinition {
156
+ permissions?: (string | { name: string; description?: string | null })[]
157
+ roles?: Record<string, string | string[] | { permissions?: string[]; inherits?: string[]; description?: string | null }>
158
+ }
159
+
160
+ export interface Permissions {
161
+ store: PermissionStore
162
+ createPermission(name: string, options?: { description?: string | null }): Promise<PermissionRecord>
163
+ createPermissions(names: (string | { name: string; description?: string | null })[]): Promise<PermissionRecord[]>
164
+ findOrCreatePermission(name: string, options?: { description?: string | null }): Promise<PermissionRecord>
165
+ deletePermission(name: string): Promise<void>
166
+ createRole(name: string, options?: { description?: string | null; permissions?: string[]; inherits?: string[] }): Promise<RoleRecord>
167
+ findOrCreateRole(name: string, options?: { description?: string | null; permissions?: string[]; inherits?: string[] }): Promise<RoleRecord>
168
+ updateRole(name: string, options: { description?: string | null; permissions?: string[]; inherits?: string[] }): Promise<RoleRecord>
169
+ deleteRole(name: string): Promise<void>
170
+ findRole(name: string): Promise<RoleRecord | null>
171
+ roles(): Promise<RoleRecord[]>
172
+ listPermissions(): Promise<PermissionRecord[]>
173
+ catalog(): Promise<Catalog>
174
+ role(name: string): RolePermissions
175
+ for(subject: Subject, scope?: ScopeOptions): SubjectPermissions
176
+ user(subject: Subject, scope?: ScopeOptions): SubjectPermissions
177
+
178
+ access(subject: Subject | null | undefined, options?: ScopeOptions): Promise<Access>
179
+ can(subject: Subject | null | undefined, permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
180
+ cannot(subject: Subject | null | undefined, permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
181
+ canAny(subject: Subject | null | undefined, permissions: string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
182
+ canAll(subject: Subject | null | undefined, permissions: string[], resource?: unknown, options?: ScopeOptions): Promise<boolean>
183
+ hasRole(subject: Subject, roles: string | string[], options?: ScopeOptions): Promise<boolean>
184
+ hasAnyRole(subject: Subject, roles: string[], options?: ScopeOptions): Promise<boolean>
185
+ hasAllRoles(subject: Subject, roles: string[], options?: ScopeOptions): Promise<boolean>
186
+ authorize(subject: Subject | null | undefined, permission: string | string[], resource?: unknown, options?: ScopeOptions): Promise<void>
187
+ ability(subject: Subject | null | undefined, options?: ScopeOptions): Promise<Ability>
188
+ subjectsWithRole(name: string): Promise<{ type: string; id: string; team: string | null; expiresAt: string | null }[]>
189
+ rule<R = any>(name: string, rule: Rule<R>): Permissions
190
+ sync(definition: SyncDefinition, options?: { prune?: boolean }): Promise<Catalog>
191
+ flush(): Promise<void>
192
+
193
+ /** (req, res, next) middleware for Tylix routes, Express, Connect, Polka. */
194
+ middleware(requirement: HttpRequirement, options?: MiddlewareOptions): (req: any, res: any, next?: () => unknown) => Promise<unknown>
195
+ require(requirement: HttpRequirement, options?: MiddlewareOptions): (req: any, res: any, next?: () => unknown) => Promise<unknown>
196
+ /** Wraps a (req, res) handler, like requireAuth. */
197
+ guard<H extends (req: any, res: any) => unknown>(handler: H, requirement: HttpRequirement, options?: MiddlewareOptions): H
198
+ /** For web Request frameworks: null when allowed, else a 401/403 Response. */
199
+ guardRequest(subject: Subject | null | undefined, requirement: HttpRequirement, options?: { resource?: unknown; team?: string | number | null; message?: string }): Promise<Response | null>
200
+ readonly options: { superAdmin: string | string[] | null; subjectType: string; ttl: number; strict: boolean; defaultRoles: string[] }
201
+ }
202
+
203
+ export function createPermissions(options?: PermissionsOptions): Permissions
204
+ export function memoryStore(initial?: Partial<Catalog>): PermissionStore
205
+ export function ormStore(options: { Model: any; tables?: PermissionTables }): PermissionStore & { models: Record<string, any> }
206
+ export function isPattern(name: string): boolean
207
+ export function guardRequest(permissions: Permissions, subject: Subject | null | undefined, requirement: HttpRequirement, options?: { resource?: unknown; team?: string | number | null; message?: string }): Promise<Response | null>
208
+ export function satisfies(permissions: Permissions, subject: Subject | null | undefined, requirement: HttpRequirement, options?: { resource?: unknown; team?: string | number | null; req?: unknown }): Promise<boolean>
209
+ export function describeRequirement(requirement: HttpRequirement): string
210
+ export const PERMISSION_MARK: unique symbol
211
+
212
+ export class PermissionError extends Error {
213
+ code: 'ROLE_DOES_NOT_EXIST' | 'PERMISSION_DOES_NOT_EXIST' | 'ROLE_ALREADY_EXISTS' | 'ROLE_CYCLE' | 'INVALID_NAME' | 'NO_SUBJECT'
214
+ }
215
+ export class ForbiddenError extends Error {
216
+ status: 403
217
+ permission: string | string[] | null
218
+ }
219
+
220
+ export type { Access, Ability, AccessSource }
package/src/index.js ADDED
@@ -0,0 +1,20 @@
1
+ // @tylix/permissions: roles and permissions for any JavaScript app.
2
+ import { createPermissions as createEngine, PermissionError, ForbiddenError } from './engine.js'
3
+ import { middleware, guard, guardRequest, satisfies, describeRequirement, PERMISSION_MARK } from './http.js'
4
+
5
+ export { PermissionError, ForbiddenError }
6
+ export { memoryStore } from './stores/memory.js'
7
+ export { ormStore, DEFAULT_TABLES } from './stores/orm.js'
8
+ export { matches, isPattern } from './match.js'
9
+ export { can, cannot, canAny, canAll, hasRole, hasAnyRole, hasAllRoles, createAbility, check, toAccess } from './client.js'
10
+ export { guardRequest, satisfies, describeRequirement, PERMISSION_MARK }
11
+
12
+ export function createPermissions(options = {}) {
13
+ const permissions = createEngine(options)
14
+ // HTTP helpers bound to this instance.
15
+ permissions.middleware = (requirement, opts) => middleware(permissions, requirement, opts)
16
+ permissions.require = permissions.middleware
17
+ permissions.guard = (handler, requirement, opts) => guard(permissions, handler, requirement, opts)
18
+ permissions.guardRequest = (subject, requirement, opts) => guardRequest(permissions, subject, requirement, opts)
19
+ return permissions
20
+ }
package/src/match.js ADDED
@@ -0,0 +1,93 @@
1
+ // Permission names and how grants match them. Shared by the server engine
2
+ // and the browser helpers, so a check gives the same answer on both sides.
3
+ //
4
+ // A name is dot-separated segments: "posts.edit", "billing.invoices.export".
5
+ // A grant (what a role or user is given) may also use:
6
+ //
7
+ // * every permission
8
+ // posts.* everything under posts: posts.edit, posts.edit.own, ...
9
+ // posts.*.own exactly one segment in the middle: posts.edit.own
10
+ // posts.edit,delete either of the listed segments
11
+ // !posts.delete a deny, only inside role definitions (see the engine)
12
+ //
13
+ // A trailing * matches one or more segments; a * anywhere else matches
14
+ // exactly one. Matching is case-sensitive, like the names you define.
15
+
16
+ const cache = new Map()
17
+
18
+ function compile(grant) {
19
+ let compiled = cache.get(grant)
20
+ if (compiled) return compiled
21
+ const segments = grant.split('.').map((s) => (s === '*' ? '*' : s.includes(',') ? s.split(',').map((x) => x.trim()) : s))
22
+ compiled = segments
23
+ if (cache.size > 5000) cache.clear()
24
+ cache.set(grant, compiled)
25
+ return compiled
26
+ }
27
+
28
+ // True when `grant` covers the `requested` permission. A requested name
29
+ // that itself contains * is only covered by a grant at least as broad
30
+ // (a check for "posts.*" asks "may they do everything under posts?").
31
+ export function matches(grant, requested) {
32
+ if (typeof grant !== 'string' || typeof requested !== 'string') return false
33
+ if (grant === requested || grant === '*') return true
34
+ const g = compile(grant)
35
+ const r = requested.split('.')
36
+ for (let i = 0; i < g.length; i++) {
37
+ const seg = g[i]
38
+ const last = i === g.length - 1
39
+ if (seg === '*') {
40
+ if (i >= r.length) return false
41
+ if (last) return true
42
+ if (r[i] === '') return false
43
+ continue
44
+ }
45
+ if (i >= r.length) return false
46
+ if (Array.isArray(seg)) {
47
+ if (!seg.includes(r[i])) return false
48
+ } else if (seg !== r[i]) {
49
+ return false
50
+ }
51
+ }
52
+ return g.length === r.length
53
+ }
54
+
55
+ export function isPattern(name) {
56
+ return typeof name === 'string' && (name.includes('*') || name.includes(','))
57
+ }
58
+
59
+ const NAME = /^!?[A-Za-z0-9_\-:*,]+(\.[A-Za-z0-9_\-:*,]+)*$/
60
+
61
+ export function assertName(name, what = 'permission') {
62
+ if (typeof name !== 'string' || !NAME.test(name.trim())) {
63
+ throw new TypeError(
64
+ `Invalid ${what} name ${JSON.stringify(name)}. Use dot-separated words, like "posts.edit" (letters, digits, - _ : and the * wildcard).`,
65
+ )
66
+ }
67
+ return name.trim()
68
+ }
69
+
70
+ const EMPTY = Object.freeze({ roles: [], permissions: [], denied: [], superAdmin: false })
71
+
72
+ // Accepts what a check is handed: an access snapshot, a user carrying one
73
+ // as `access`, or nothing (a guest).
74
+ export function toAccess(source) {
75
+ if (!source || typeof source !== 'object') return EMPTY
76
+ const access = Array.isArray(source.permissions) || Array.isArray(source.roles) ? source : source.access
77
+ if (!access || typeof access !== 'object') return EMPTY
78
+ return {
79
+ roles: Array.isArray(access.roles) ? access.roles : [],
80
+ permissions: Array.isArray(access.permissions) ? access.permissions : [],
81
+ denied: Array.isArray(access.denied) ? access.denied : [],
82
+ superAdmin: access.superAdmin === true,
83
+ }
84
+ }
85
+
86
+ // The decision for one permission against an access snapshot: a super
87
+ // admin may do anything, a matching deny always wins over an allow.
88
+ export function allows(access, permission) {
89
+ if (access.superAdmin) return true
90
+ for (const d of access.denied) if (matches(d, permission)) return false
91
+ for (const p of access.permissions) if (matches(p, permission)) return true
92
+ return false
93
+ }
package/src/react.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { ReactNode, ReactElement } from 'react'
2
+ import type { Ability, AccessSource, Requirement } from './client.js'
3
+ export function PermissionsProvider(props: { user?: AccessSource; access?: AccessSource; children?: ReactNode }): ReactElement
4
+ export function useAbility(): Ability
5
+ export function useCan(requirement: Requirement): boolean
6
+ export function useHasRole(role: string | string[]): boolean
7
+ export function Can(props: {
8
+ permission?: string | string[]
9
+ any?: string[]
10
+ role?: string | string[]
11
+ not?: boolean
12
+ fallback?: ReactNode
13
+ children?: ReactNode
14
+ }): ReactElement
package/src/react.js ADDED
@@ -0,0 +1,45 @@
1
+ // React helpers. Give the provider the signed-in user (with its access
2
+ // snapshot) or the snapshot itself, then check anywhere below it:
3
+ //
4
+ // <PermissionsProvider user={useAuth().user}>
5
+ // <Can permission="posts.create"><NewPostButton /></Can>
6
+ // <Can role="admin" fallback={<p>Admins only.</p>}><AdminPanel /></Can>
7
+ // </PermissionsProvider>
8
+ //
9
+ // const canPublish = useCan('posts.publish')
10
+ import { createContext, createElement, Fragment, useContext, useMemo } from 'react'
11
+ import { createAbility, check, canAny } from './client.js'
12
+
13
+ const AbilityContext = createContext(createAbility(null))
14
+
15
+ export function PermissionsProvider({ user, access, children }) {
16
+ const source = access ?? user ?? null
17
+ const ability = useMemo(() => createAbility(source), [source])
18
+ return createElement(AbilityContext.Provider, { value: ability }, children)
19
+ }
20
+
21
+ export function useAbility() {
22
+ return useContext(AbilityContext)
23
+ }
24
+
25
+ // useCan('posts.edit'), useCan(['a', 'b']) for all, useCan('role:admin')
26
+ export function useCan(requirement) {
27
+ const ability = useAbility()
28
+ return check(ability, requirement)
29
+ }
30
+
31
+ export function useHasRole(role) {
32
+ return useAbility().hasRole(role)
33
+ }
34
+
35
+ // <Can permission="a"> / permission={['a','b']} (all) / any={['a','b']} /
36
+ // role="admin" or role={['admin','editor']} (any) / not (inverts).
37
+ export function Can({ permission, any, role, not = false, fallback = null, children }) {
38
+ const ability = useAbility()
39
+ let ok = true
40
+ if (permission !== undefined) ok = ok && ability.can(permission)
41
+ if (any !== undefined) ok = ok && canAny(ability, any)
42
+ if (role !== undefined) ok = ok && (ability.hasRole(role) || ability.superAdmin)
43
+ if (not) ok = !ok
44
+ return createElement(Fragment, null, ok ? children : fallback)
45
+ }
@@ -0,0 +1,12 @@
1
+ export interface PermissionTables {
2
+ permissions?: string
3
+ roles?: string
4
+ roleHasPermissions?: string
5
+ roleInherits?: string
6
+ modelHasRoles?: string
7
+ modelHasPermissions?: string
8
+ }
9
+ export const DEFAULT_TABLES: Readonly<Required<PermissionTables>>
10
+ /** Creates the six tables ormStore reads. `schema` is the Tylix migration schema. */
11
+ export function createPermissionTables(schema: unknown, tables?: PermissionTables): Promise<void>
12
+ export function dropPermissionTables(schema: unknown, tables?: PermissionTables): Promise<void>
package/src/schema.js ADDED
@@ -0,0 +1,66 @@
1
+ // The tables ormStore reads, for a Tylix migration:
2
+ //
3
+ // import { createPermissionTables, dropPermissionTables } from '@tylix/permissions/schema'
4
+ // export const up = (schema) => createPermissionTables(schema)
5
+ // export const down = (schema) => dropPermissionTables(schema)
6
+ import { DEFAULT_TABLES } from './stores/orm.js'
7
+
8
+ export { DEFAULT_TABLES }
9
+
10
+ export async function createPermissionTables(schema, tables = {}) {
11
+ const t = { ...DEFAULT_TABLES, ...tables }
12
+
13
+ await schema.createTable(t.permissions, (table) => {
14
+ table.increments('id')
15
+ table.string('name').unique()
16
+ table.string('description').nullable()
17
+ table.timestamps()
18
+ })
19
+
20
+ await schema.createTable(t.roles, (table) => {
21
+ table.increments('id')
22
+ table.string('name').unique()
23
+ table.string('description').nullable()
24
+ table.timestamps()
25
+ })
26
+
27
+ await schema.createTable(t.roleHasPermissions, (table) => {
28
+ table.increments('id')
29
+ table.string('role').index()
30
+ table.string('permission').index()
31
+ })
32
+
33
+ await schema.createTable(t.roleInherits, (table) => {
34
+ table.increments('id')
35
+ table.string('role').index()
36
+ table.string('parent').index()
37
+ })
38
+
39
+ await schema.createTable(t.modelHasRoles, (table) => {
40
+ table.increments('id')
41
+ table.string('subject_type')
42
+ table.string('subject_id')
43
+ table.string('role').index()
44
+ table.string('team').nullable()
45
+ table.datetime('expires_at').nullable()
46
+ table.index(['subject_type', 'subject_id'])
47
+ })
48
+
49
+ await schema.createTable(t.modelHasPermissions, (table) => {
50
+ table.increments('id')
51
+ table.string('subject_type')
52
+ table.string('subject_id')
53
+ table.string('permission').index()
54
+ table.string('effect').default('allow')
55
+ table.string('team').nullable()
56
+ table.datetime('expires_at').nullable()
57
+ table.index(['subject_type', 'subject_id'])
58
+ })
59
+ }
60
+
61
+ export async function dropPermissionTables(schema, tables = {}) {
62
+ const t = { ...DEFAULT_TABLES, ...tables }
63
+ for (const name of [t.modelHasPermissions, t.modelHasRoles, t.roleInherits, t.roleHasPermissions, t.roles, t.permissions]) {
64
+ await schema.dropTable(name)
65
+ }
66
+ }
@@ -0,0 +1,82 @@
1
+ // An in-memory store: tests, prototypes, and apps whose roles live in code.
2
+ // It is also the reference for the store contract: a store is any object
3
+ // with these async methods, so roles can live in Prisma, Drizzle, Mongo,
4
+ // Redis or a JSON file just as well.
5
+ //
6
+ // loadCatalog() -> { permissions: [{ name, description }],
7
+ // roles: [{ name, description, permissions: [], inherits: [] }] }
8
+ // savePermission({ name, description }) upsert
9
+ // deletePermission(name) also drops it from roles and subjects
10
+ // saveRole({ name, description, permissions, inherits }) upsert; lists replace
11
+ // deleteRole(name) also drops its assignments and inherits
12
+ // getAssignments({ type, id }) -> { roles: [{ name, team, expiresAt }],
13
+ // permissions: [{ name, effect, team, expiresAt }] }
14
+ // setAssignments({ type, id }, { roles, permissions }) replaces both lists
15
+ // subjectsWithRole(name) -> [{ type, id, team, expiresAt }]
16
+ //
17
+ // Subject ids are compared as strings, so 7 and "7" are the same user.
18
+ const clone = (value) => (value === undefined ? value : JSON.parse(JSON.stringify(value)))
19
+ const keyOf = ({ type, id }) => `${type}:${String(id)}`
20
+
21
+ export function memoryStore(initial = {}) {
22
+ const permissions = new Map()
23
+ const roles = new Map()
24
+ const subjects = new Map() // key -> { ref, roles, permissions }
25
+
26
+ for (const p of initial.permissions ?? []) permissions.set(p.name, { name: p.name, description: p.description ?? null })
27
+ for (const r of initial.roles ?? []) {
28
+ roles.set(r.name, { name: r.name, description: r.description ?? null, permissions: [...(r.permissions ?? [])], inherits: [...(r.inherits ?? [])] })
29
+ }
30
+
31
+ return {
32
+ async loadCatalog() {
33
+ return { permissions: clone([...permissions.values()]), roles: clone([...roles.values()]) }
34
+ },
35
+
36
+ async savePermission({ name, description = null }) {
37
+ const existing = permissions.get(name)
38
+ permissions.set(name, { name, description: description ?? existing?.description ?? null })
39
+ },
40
+
41
+ async deletePermission(name) {
42
+ permissions.delete(name)
43
+ for (const role of roles.values()) {
44
+ role.permissions = role.permissions.filter((p) => p !== name && p !== `!${name}`)
45
+ }
46
+ for (const entry of subjects.values()) {
47
+ entry.permissions = entry.permissions.filter((p) => p.name !== name)
48
+ }
49
+ },
50
+
51
+ async saveRole({ name, description = null, permissions: perms = [], inherits = [] }) {
52
+ roles.set(name, { name, description, permissions: [...perms], inherits: [...inherits] })
53
+ },
54
+
55
+ async deleteRole(name) {
56
+ roles.delete(name)
57
+ for (const role of roles.values()) role.inherits = role.inherits.filter((r) => r !== name)
58
+ for (const entry of subjects.values()) entry.roles = entry.roles.filter((r) => r.name !== name)
59
+ },
60
+
61
+ async getAssignments(ref) {
62
+ const entry = subjects.get(keyOf(ref))
63
+ return entry ? { roles: clone(entry.roles), permissions: clone(entry.permissions) } : { roles: [], permissions: [] }
64
+ },
65
+
66
+ async setAssignments(ref, { roles: r = [], permissions: p = [] }) {
67
+ const key = keyOf(ref)
68
+ if (r.length === 0 && p.length === 0) subjects.delete(key)
69
+ else subjects.set(key, { ref: { type: ref.type, id: String(ref.id) }, roles: clone(r), permissions: clone(p) })
70
+ },
71
+
72
+ async subjectsWithRole(name) {
73
+ const found = []
74
+ for (const entry of subjects.values()) {
75
+ for (const r of entry.roles) {
76
+ if (r.name === name) found.push({ ...entry.ref, team: r.team ?? null, expiresAt: r.expiresAt ?? null })
77
+ }
78
+ }
79
+ return found
80
+ },
81
+ }
82
+ }