@salemaljebaly/payload-plugin-rbac-ui 0.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 Salem Aljebaly
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 ADDED
@@ -0,0 +1,78 @@
1
+ # @salemaljebaly/payload-plugin-rbac-ui
2
+
3
+ Reusable RBAC permissions matrix UI for Payload CMS.
4
+
5
+ ## Features
6
+
7
+ - Adds a grouped checkbox matrix UI for role permissions in Admin.
8
+ - Validates role permissions against a strict allowed list.
9
+ - Keeps role permission UI and server-side validation in sync.
10
+ - Works by enhancing an existing roles collection.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pnpm add @salemaljebaly/payload-plugin-rbac-ui
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```ts
21
+ import { buildConfig } from 'payload'
22
+ import { rbacUIPlugin, type PermissionGroup } from '@salemaljebaly/payload-plugin-rbac-ui'
23
+
24
+ const permissionGroups: PermissionGroup[] = [
25
+ {
26
+ label: 'Posts',
27
+ permissions: [
28
+ { action: 'Create', description: 'Create posts', permission: 'Create:Post' },
29
+ { action: 'Read', description: 'Read posts', permission: 'Read:Post' },
30
+ { action: 'Update', description: 'Update posts', permission: 'Update:Post' },
31
+ { action: 'Delete', description: 'Delete posts', permission: 'Delete:Post' },
32
+ ],
33
+ },
34
+ ]
35
+
36
+ export default buildConfig({
37
+ collections: [/* users, roles, etc */],
38
+ plugins: [
39
+ rbacUIPlugin({
40
+ rolesCollectionSlug: 'roles',
41
+ permissionsFieldName: 'permissions',
42
+ permissionGroups,
43
+ }),
44
+ ],
45
+ })
46
+ ```
47
+
48
+ ## Options
49
+
50
+ - `rolesCollectionSlug`: roles collection slug. Default: `roles`
51
+ - `permissionsFieldName`: permissions field name. Default: `permissions`
52
+ - `permissionGroups`: grouped permission model used by the UI and validator.
53
+ - `rolesFieldDescription`: custom field description text.
54
+ - `ensurePermissionsField`: if `true`, inserts field when missing. Default: `true`
55
+ - `customFieldPath`: override the client component path.
56
+ - `onConfigureRolesCollection`: final roles collection mutator.
57
+
58
+ ## Best Practices
59
+
60
+ - Keep permission strings stable (`Action:Resource`).
61
+ - Use one shared permission registry for UI, role seeds, and access helpers.
62
+ - Use `overrideAccess: false` whenever you pass `user` in Local API calls.
63
+ - Keep access checks server-side; UI is only convenience.
64
+
65
+ ## Publishing / Official Discovery
66
+
67
+ To make the plugin discoverable in the Payload ecosystem:
68
+
69
+ 1. Publish to npm.
70
+ 2. Add topic `payload-plugin` to the GitHub repository.
71
+
72
+ Payload docs reference the `payload-plugin` topic for plugin discovery.
73
+
74
+ ## Development
75
+
76
+ ```bash
77
+ pnpm test
78
+ ```
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@salemaljebaly/payload-plugin-rbac-ui",
3
+ "version": "0.1.0",
4
+ "description": "Reusable RBAC permissions UI and helpers for Payload CMS",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "exports": {
10
+ ".": "./src/index.ts",
11
+ "./client": "./src/components/PermissionsMatrixField.tsx",
12
+ "./types": "./src/types.ts"
13
+ },
14
+ "files": [
15
+ "src",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "peerDependencies": {
20
+ "payload": "^3.76.1",
21
+ "react": "^19.0.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "25.2.3",
25
+ "@types/react": "19.2.14",
26
+ "@types/react-dom": "19.2.3",
27
+ "payload": "3.76.1",
28
+ "typescript": "5.9.3",
29
+ "vitest": "4.0.18"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "keywords": [
35
+ "payload",
36
+ "payloadcms",
37
+ "payload-plugin",
38
+ "rbac",
39
+ "permissions"
40
+ ],
41
+ "scripts": {
42
+ "test": "vitest run --config ./vitest.config.mts",
43
+ "typecheck": "tsc --noEmit"
44
+ }
45
+ }
@@ -0,0 +1,193 @@
1
+ 'use client'
2
+
3
+ import React, { useCallback, useMemo } from 'react'
4
+ import type { JSONFieldClientComponent } from 'payload'
5
+ import { useField } from '@payloadcms/ui'
6
+ import type { PermissionGroup } from '../types'
7
+ import { coerceStringArray } from '../lib/permissions'
8
+
9
+ type FieldAdminConfig = {
10
+ custom?: {
11
+ rbac?: {
12
+ permissionGroups?: PermissionGroup[]
13
+ }
14
+ }
15
+ }
16
+
17
+ const readPermissionGroups = (props: unknown): PermissionGroup[] => {
18
+ const typedProps = props as { field?: { admin?: FieldAdminConfig } }
19
+ const admin = typedProps.field?.admin
20
+ return admin?.custom?.rbac?.permissionGroups ?? []
21
+ }
22
+
23
+ export const PermissionsMatrixField: JSONFieldClientComponent = (props) => {
24
+ const { path } = props
25
+ const groups = readPermissionGroups(props)
26
+ const { value, setValue } = useField<unknown>({ path })
27
+
28
+ const safeValue = useMemo(() => coerceStringArray(value), [value])
29
+ const currentPermissions = useMemo(() => new Set(safeValue), [safeValue])
30
+
31
+ const handleTogglePermission = useCallback(
32
+ (permission: string) => {
33
+ const nextValue = currentPermissions.has(permission)
34
+ ? safeValue.filter((p) => p !== permission)
35
+ : [...safeValue, permission]
36
+
37
+ setValue(nextValue)
38
+ },
39
+ [currentPermissions, safeValue, setValue],
40
+ )
41
+
42
+ const handleToggleGroup = useCallback(
43
+ (group: PermissionGroup) => {
44
+ const groupPermissions = group.permissions.map((item) => item.permission)
45
+ const allSelected = groupPermissions.every((permission) => currentPermissions.has(permission))
46
+
47
+ const nextValue = allSelected
48
+ ? safeValue.filter((p) => !groupPermissions.includes(p))
49
+ : [...new Set([...safeValue, ...groupPermissions])]
50
+
51
+ setValue(nextValue)
52
+ },
53
+ [currentPermissions, safeValue, setValue],
54
+ )
55
+
56
+ return (
57
+ <div className="field-type permissions-field" style={{ marginTop: 'var(--base)' }}>
58
+ <div
59
+ style={{
60
+ marginBottom: 'var(--base)',
61
+ padding: 'var(--base)',
62
+ backgroundColor: 'var(--theme-success-50)',
63
+ border: '1px solid var(--theme-success-200)',
64
+ borderRadius: 'var(--base-radius)',
65
+ }}
66
+ >
67
+ <strong>Selected: {currentPermissions.size} permissions</strong>
68
+ </div>
69
+
70
+ {groups.map((group) => {
71
+ const groupPermissions = group.permissions.map((item) => item.permission)
72
+ const selectedCount = groupPermissions.filter((permission) => currentPermissions.has(permission)).length
73
+ const allSelected = selectedCount === groupPermissions.length
74
+ const someSelected = selectedCount > 0 && !allSelected
75
+
76
+ return (
77
+ <div
78
+ key={group.label}
79
+ style={{
80
+ marginBottom: 'calc(var(--base) * 1.5)',
81
+ border: '1px solid var(--theme-elevation-150)',
82
+ borderRadius: 'var(--base-radius)',
83
+ overflow: 'hidden',
84
+ backgroundColor: 'var(--theme-bg)',
85
+ }}
86
+ >
87
+ <div
88
+ style={{
89
+ padding: 'var(--base)',
90
+ backgroundColor: allSelected
91
+ ? 'var(--theme-success-100)'
92
+ : someSelected
93
+ ? 'var(--theme-warning-100)'
94
+ : 'var(--theme-elevation-50)',
95
+ borderBottom: '1px solid var(--theme-elevation-150)',
96
+ display: 'flex',
97
+ alignItems: 'center',
98
+ justifyContent: 'space-between',
99
+ }}
100
+ >
101
+ <div style={{ display: 'flex', alignItems: 'center', gap: 'calc(var(--base) * 0.75)' }}>
102
+ <input
103
+ type="checkbox"
104
+ checked={allSelected}
105
+ ref={(input) => {
106
+ if (input) input.indeterminate = someSelected
107
+ }}
108
+ onChange={() => handleToggleGroup(group)}
109
+ style={{ cursor: 'pointer' }}
110
+ />
111
+ <strong style={{ fontSize: '1.125rem' }}>{group.label}</strong>
112
+ {selectedCount > 0 && (
113
+ <span
114
+ style={{
115
+ fontSize: '0.875rem',
116
+ color: 'var(--theme-elevation-500)',
117
+ backgroundColor: 'var(--theme-elevation-100)',
118
+ padding: '0.125rem 0.5rem',
119
+ borderRadius: '9999px',
120
+ }}
121
+ >
122
+ {selectedCount}/{groupPermissions.length}
123
+ </span>
124
+ )}
125
+ </div>
126
+ <button
127
+ type="button"
128
+ onClick={() => handleToggleGroup(group)}
129
+ className="btn"
130
+ style={{
131
+ padding: '0.5rem 1rem',
132
+ fontSize: '0.875rem',
133
+ backgroundColor: allSelected ? 'var(--theme-error-500)' : 'var(--theme-success-500)',
134
+ color: 'white',
135
+ border: 'none',
136
+ borderRadius: 'var(--base-radius)',
137
+ cursor: 'pointer',
138
+ }}
139
+ >
140
+ {allSelected ? 'Deselect All' : 'Select All'}
141
+ </button>
142
+ </div>
143
+
144
+ <div
145
+ style={{
146
+ padding: 'var(--base)',
147
+ display: 'grid',
148
+ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
149
+ gap: 'calc(var(--base) * 0.75)',
150
+ }}
151
+ >
152
+ {group.permissions.map((item) => {
153
+ const isSelected = currentPermissions.has(item.permission)
154
+
155
+ return (
156
+ <label
157
+ key={item.permission}
158
+ style={{
159
+ display: 'flex',
160
+ alignItems: 'flex-start',
161
+ gap: '0.5rem',
162
+ padding: 'calc(var(--base) * 0.75)',
163
+ border: `2px solid ${isSelected ? 'var(--theme-success-500)' : 'var(--theme-elevation-150)'}`,
164
+ borderRadius: 'var(--base-radius)',
165
+ backgroundColor: isSelected ? 'var(--theme-success-50)' : 'var(--theme-bg)',
166
+ cursor: 'pointer',
167
+ transition: 'all 0.2s',
168
+ }}
169
+ >
170
+ <input
171
+ type="checkbox"
172
+ checked={isSelected}
173
+ onChange={() => handleTogglePermission(item.permission)}
174
+ style={{ marginTop: '0.125rem', cursor: 'pointer' }}
175
+ />
176
+ <div>
177
+ <div style={{ fontWeight: '600', fontSize: '0.875rem', marginBottom: '0.125rem' }}>
178
+ {item.action}
179
+ </div>
180
+ <div style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-600)' }}>
181
+ {item.description}
182
+ </div>
183
+ </div>
184
+ </label>
185
+ )
186
+ })}
187
+ </div>
188
+ </div>
189
+ )
190
+ })}
191
+ </div>
192
+ )
193
+ }
package/src/index.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { CollectionConfig, Config, Plugin } from 'payload'
2
+ import type { PermissionGroup, RBACUIPluginOptions } from './types'
3
+ import { flattenPermissionGroups, validatePermissionArray } from './lib/permissions'
4
+
5
+ const DEFAULT_ROLES_COLLECTION = 'roles'
6
+ const DEFAULT_PERMISSIONS_FIELD = 'permissions'
7
+ const DEFAULT_COMPONENT_PATH = '@salemaljebaly/payload-plugin-rbac-ui/client#PermissionsMatrixField'
8
+
9
+ const resolveDescription = (
10
+ description: RBACUIPluginOptions['rolesFieldDescription'],
11
+ ): string | Record<string, string> => {
12
+ if (!description) return 'Select permissions for this role'
13
+ return description
14
+ }
15
+
16
+ const configureRolesCollection = ({
17
+ collection,
18
+ options,
19
+ allowedPermissions,
20
+ }: {
21
+ collection: CollectionConfig
22
+ options: RBACUIPluginOptions
23
+ allowedPermissions: string[]
24
+ }): CollectionConfig => {
25
+ const permissionsFieldName = options.permissionsFieldName ?? DEFAULT_PERMISSIONS_FIELD
26
+ const componentPath = options.customFieldPath ?? DEFAULT_COMPONENT_PATH
27
+ const permissionGroups = options.permissionGroups
28
+ const fieldDescription = resolveDescription(options.rolesFieldDescription)
29
+
30
+ const fields = [...(collection.fields ?? [])]
31
+ const permissionsFieldIndex = fields.findIndex(
32
+ (field) => 'name' in field && field.name === permissionsFieldName,
33
+ )
34
+
35
+ const fieldPatch = {
36
+ type: 'json' as const,
37
+ name: permissionsFieldName,
38
+ admin: {
39
+ description: fieldDescription,
40
+ custom: {
41
+ rbac: {
42
+ permissionGroups,
43
+ },
44
+ },
45
+ components: {
46
+ Field: componentPath,
47
+ },
48
+ },
49
+ validate: (value: unknown) => validatePermissionArray(value, allowedPermissions),
50
+ }
51
+
52
+ if (permissionsFieldIndex === -1) {
53
+ if (options.ensurePermissionsField === false) return collection
54
+ fields.push(fieldPatch)
55
+ } else {
56
+ const existingField = fields[permissionsFieldIndex]
57
+ fields[permissionsFieldIndex] = {
58
+ ...(existingField as object),
59
+ ...fieldPatch,
60
+ admin: {
61
+ ...((existingField as { admin?: object }).admin ?? {}),
62
+ ...fieldPatch.admin,
63
+ },
64
+ }
65
+ }
66
+
67
+ const updated = {
68
+ ...collection,
69
+ fields,
70
+ }
71
+
72
+ return options.onConfigureRolesCollection ? options.onConfigureRolesCollection(updated) : updated
73
+ }
74
+
75
+ export const rbacUIPlugin = (options: RBACUIPluginOptions): Plugin => {
76
+ if (!options.permissionGroups || options.permissionGroups.length === 0) {
77
+ throw new Error('rbacUIPlugin requires at least one permission group.')
78
+ }
79
+
80
+ const rolesCollectionSlug = options.rolesCollectionSlug ?? DEFAULT_ROLES_COLLECTION
81
+ const allowedPermissions = flattenPermissionGroups(options.permissionGroups)
82
+
83
+ return (incomingConfig: Config): Config => {
84
+ const collections = incomingConfig.collections ?? []
85
+
86
+ const hasRolesCollection = collections.some((collection) => collection.slug === rolesCollectionSlug)
87
+ if (!hasRolesCollection) {
88
+ throw new Error(`rbacUIPlugin could not find roles collection: "${rolesCollectionSlug}"`)
89
+ }
90
+
91
+ return {
92
+ ...incomingConfig,
93
+ collections: collections.map((collection) => {
94
+ if (collection.slug !== rolesCollectionSlug) return collection
95
+
96
+ return configureRolesCollection({
97
+ collection,
98
+ options,
99
+ allowedPermissions,
100
+ })
101
+ }),
102
+ }
103
+ }
104
+ }
105
+
106
+ export type { PermissionGroup, PermissionItem, RBACUIPluginOptions } from './types'
107
+ export { flattenPermissionGroups, validatePermissionArray } from './lib/permissions'
@@ -0,0 +1,36 @@
1
+ import type { PermissionGroup } from '../types'
2
+
3
+ export const flattenPermissionGroups = (groups: PermissionGroup[]): string[] => {
4
+ const unique = new Set<string>()
5
+
6
+ for (const group of groups) {
7
+ for (const item of group.permissions) {
8
+ unique.add(item.permission)
9
+ }
10
+ }
11
+
12
+ return [...unique]
13
+ }
14
+
15
+ export const validatePermissionArray = (
16
+ value: unknown,
17
+ allowedPermissions: readonly string[],
18
+ ): true | string => {
19
+ if (value === null || value === undefined) return true
20
+ if (!Array.isArray(value)) return 'Permissions must be an array of strings.'
21
+
22
+ const invalid = value.filter(
23
+ (item) => typeof item !== 'string' || !allowedPermissions.includes(item),
24
+ )
25
+
26
+ if (invalid.length > 0) {
27
+ return `Invalid permissions found: ${invalid.join(', ')}`
28
+ }
29
+
30
+ return true
31
+ }
32
+
33
+ export const coerceStringArray = (value: unknown): string[] => {
34
+ if (!Array.isArray(value)) return []
35
+ return value.filter((v): v is string => typeof v === 'string')
36
+ }
package/src/types.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { CollectionConfig } from 'payload'
2
+
3
+ export type PermissionItem = {
4
+ action: string
5
+ description: string
6
+ permission: string
7
+ }
8
+
9
+ export type PermissionGroup = {
10
+ label: string
11
+ permissions: PermissionItem[]
12
+ }
13
+
14
+ export type RBACUIPluginOptions = {
15
+ rolesCollectionSlug?: string
16
+ permissionsFieldName?: string
17
+ permissionGroups: PermissionGroup[]
18
+ rolesFieldDescription?: string | Record<string, string>
19
+ ensurePermissionsField?: boolean
20
+ customFieldPath?: string
21
+ onConfigureRolesCollection?: (collection: CollectionConfig) => CollectionConfig
22
+ }