payload-access-plugin 0.0.0-stage → 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 +21 -0
- package/README.md +220 -2
- package/dist/access/can.d.ts +3 -0
- package/dist/access/can.js +10 -0
- package/dist/access/can.js.map +1 -0
- package/dist/access/combine.d.ts +6 -0
- package/dist/access/combine.js +23 -0
- package/dist/access/combine.js.map +1 -0
- package/dist/access/fields.d.ts +7 -0
- package/dist/access/fields.js +41 -0
- package/dist/access/fields.js.map +1 -0
- package/dist/access/load.d.ts +6 -0
- package/dist/access/load.js +22 -0
- package/dist/access/load.js.map +1 -0
- package/dist/access/manage.d.ts +9 -0
- package/dist/access/manage.js +8 -0
- package/dist/access/manage.js.map +1 -0
- package/dist/access/resolve.d.ts +22 -0
- package/dist/access/resolve.js +106 -0
- package/dist/access/resolve.js.map +1 -0
- package/dist/access/wrap.d.ts +6 -0
- package/dist/access/wrap.js +120 -0
- package/dist/access/wrap.js.map +1 -0
- package/dist/admin/AccessView.d.ts +3 -0
- package/dist/admin/AccessView.js +66 -0
- package/dist/admin/AccessView.js.map +1 -0
- package/dist/admin/Matrix.d.ts +10 -0
- package/dist/admin/Matrix.js +383 -0
- package/dist/admin/Matrix.js.map +1 -0
- package/dist/admin/MatrixCell.d.ts +17 -0
- package/dist/admin/MatrixCell.js +42 -0
- package/dist/admin/MatrixCell.js.map +1 -0
- package/dist/admin/MatrixFilters.d.ts +18 -0
- package/dist/admin/MatrixFilters.js +91 -0
- package/dist/admin/MatrixFilters.js.map +1 -0
- package/dist/admin/NavLink.d.ts +3 -0
- package/dist/admin/NavLink.js +23 -0
- package/dist/admin/NavLink.js.map +1 -0
- package/dist/admin/NavLinkClient.d.ts +9 -0
- package/dist/admin/NavLinkClient.js +36 -0
- package/dist/admin/NavLinkClient.js.map +1 -0
- package/dist/admin/NewRoleDrawer.d.ts +14 -0
- package/dist/admin/NewRoleDrawer.js +226 -0
- package/dist/admin/NewRoleDrawer.js.map +1 -0
- package/dist/admin/RoleGrid.d.ts +21 -0
- package/dist/admin/RoleGrid.js +141 -0
- package/dist/admin/RoleGrid.js.map +1 -0
- package/dist/admin/RolePermissionsField.d.ts +17 -0
- package/dist/admin/RolePermissionsField.js +96 -0
- package/dist/admin/RolePermissionsField.js.map +1 -0
- package/dist/admin/css.d.js +2 -0
- package/dist/admin/css.d.js.map +1 -0
- package/dist/admin/model.d.ts +58 -0
- package/dist/admin/model.js +166 -0
- package/dist/admin/model.js.map +1 -0
- package/dist/admin/steps/FieldsGlobalsStep.d.ts +2 -0
- package/dist/admin/steps/FieldsGlobalsStep.js +21 -0
- package/dist/admin/steps/FieldsGlobalsStep.js.map +1 -0
- package/dist/admin/steps/NameStep.d.ts +7 -0
- package/dist/admin/steps/NameStep.js +74 -0
- package/dist/admin/steps/NameStep.js.map +1 -0
- package/dist/admin/steps/PermissionsStep.d.ts +2 -0
- package/dist/admin/steps/PermissionsStep.js +21 -0
- package/dist/admin/steps/PermissionsStep.js.map +1 -0
- package/dist/admin/steps/ReviewStep.d.ts +6 -0
- package/dist/admin/steps/ReviewStep.js +85 -0
- package/dist/admin/steps/ReviewStep.js.map +1 -0
- package/dist/admin/steps/StartFromStep.d.ts +10 -0
- package/dist/admin/steps/StartFromStep.js +63 -0
- package/dist/admin/steps/StartFromStep.js.map +1 -0
- package/dist/admin/steps/types.d.ts +18 -0
- package/dist/admin/steps/types.js +3 -0
- package/dist/admin/steps/types.js.map +1 -0
- package/dist/admin/styles.module.css +289 -0
- package/dist/collections/roles.d.ts +3 -0
- package/dist/collections/roles.js +80 -0
- package/dist/collections/roles.js.map +1 -0
- package/dist/core/decide.d.ts +3 -0
- package/dist/core/decide.js +9 -0
- package/dist/core/decide.js.map +1 -0
- package/dist/core/locks.d.ts +7 -0
- package/dist/core/locks.js +57 -0
- package/dist/core/locks.js.map +1 -0
- package/dist/core/merge.d.ts +4 -0
- package/dist/core/merge.js +64 -0
- package/dist/core/merge.js.map +1 -0
- package/dist/core/types.d.ts +34 -0
- package/dist/core/types.js +4 -0
- package/dist/core/types.js.map +1 -0
- package/dist/endpoints/me.d.ts +13 -0
- package/dist/endpoints/me.js +55 -0
- package/dist/endpoints/me.js.map +1 -0
- package/dist/endpoints/schema.d.ts +14 -0
- package/dist/endpoints/schema.js +39 -0
- package/dist/endpoints/schema.js.map +1 -0
- package/dist/exports/client.d.ts +7 -0
- package/dist/exports/client.js +9 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/exports/rsc.d.ts +2 -0
- package/dist/exports/rsc.js +4 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/fields/owner.d.ts +7 -0
- package/dist/fields/owner.js +32 -0
- package/dist/fields/owner.js.map +1 -0
- package/dist/fields/userRoles.d.ts +3 -0
- package/dist/fields/userRoles.js +17 -0
- package/dist/fields/userRoles.js.map +1 -0
- package/dist/hooks/guardrails.d.ts +17 -0
- package/dist/hooks/guardrails.js +255 -0
- package/dist/hooks/guardrails.js.map +1 -0
- package/dist/i18n.d.ts +74 -0
- package/dist/i18n.js +76 -0
- package/dist/i18n.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +122 -0
- package/dist/index.js.map +1 -0
- package/dist/options.d.ts +45 -0
- package/dist/options.js +203 -0
- package/dist/options.js.map +1 -0
- package/dist/schema.d.ts +6 -0
- package/dist/schema.js +78 -0
- package/dist/schema.js.map +1 -0
- package/dist/seed.d.ts +4 -0
- package/dist/seed.js +35 -0
- package/dist/seed.js.map +1 -0
- package/dist/slug.d.ts +3 -0
- package/dist/slug.js +3 -0
- package/dist/slug.js.map +1 -0
- package/dist/types.d.ts +66 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +113 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 UPDOT
|
|
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,221 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-access-plugin
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Editable roles and an access matrix for Payload 3. Admins create roles and decide who can read, create, update, delete and publish each collection and global, and which fields are hidden or read-only, without a deploy. The app sets the guardrails in code.
|
|
4
|
+
|
|
5
|
+
- Roles are records. A user can hold several, and their permissions add up.
|
|
6
|
+
- An Access matrix screen in the admin panel, with a new-role wizard and a role edit grid.
|
|
7
|
+
- Enforcement on collections, globals and fields. The plugin can only narrow what your own access rules allow.
|
|
8
|
+
- Locks, super admins and who may manage roles are set in code.
|
|
9
|
+
- `GET /api/access-plugin/me` and `GET /api/access-plugin/schema` endpoints.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install payload-access-plugin
|
|
15
|
+
# or
|
|
16
|
+
pnpm add payload-access-plugin
|
|
17
|
+
# or
|
|
18
|
+
bun add payload-access-plugin
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Peer dependency: `payload ^3.90.0`.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { buildConfig } from 'payload'
|
|
27
|
+
import { accessPlugin } from 'payload-access-plugin'
|
|
28
|
+
|
|
29
|
+
export default buildConfig({
|
|
30
|
+
// collections: [Users, Posts, ...]
|
|
31
|
+
plugins: [
|
|
32
|
+
accessPlugin({
|
|
33
|
+
roles: { seed: [{ name: 'Admin', slug: 'admin', locked: true, permissions: {} }] },
|
|
34
|
+
superAdmin: (user) => user?.roles?.some((role) => role?.slug === 'admin') ?? false,
|
|
35
|
+
}),
|
|
36
|
+
],
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Then run `payload generate:importmap` so the admin panel finds the plugin's components. The plugin adds a `roles` collection and a `roles` field on your users collection, and an Access screen at `/admin/access`.
|
|
41
|
+
|
|
42
|
+
Create the first admin user and give them the `admin` role right away (see the first-user note under [Limitations and notes](#limitations-and-notes)).
|
|
43
|
+
|
|
44
|
+
## Options
|
|
45
|
+
|
|
46
|
+
Every option is optional. All are passed to `accessPlugin(options)`.
|
|
47
|
+
|
|
48
|
+
| Option | Type | Default | Meaning |
|
|
49
|
+
| -------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
50
|
+
| `enabled` | `boolean` | `true` | When `false`, the roles collection and the users field stay, and so do the role guardrails and the `manageRoles` gate on the roles collection. Only the collection, global and field restrictions, the Access screen and the endpoints are off. |
|
|
51
|
+
| `users` | `CollectionSlug \| CollectionSlug[]` | the admin user collection (`admin.user`) | Auth collections that get a `roles` field. Throws if a slug is not in the config. |
|
|
52
|
+
| `roles.slug` | `string` | `'roles'` | Slug of the roles collection. |
|
|
53
|
+
| `roles.overrides` | `(collection: CollectionConfig) => CollectionConfig` | none | Adjust the roles collection before it is registered. |
|
|
54
|
+
| `roles.seed` | `RoleSeed[]` | `[]` | Roles created on init when no role with that slug exists. Existing roles are never overwritten. |
|
|
55
|
+
| `govern.collections` | `true \| CollectionSlug[] \| { include?: CollectionSlug[]; exclude?: CollectionSlug[] }` | every collection except the roles collection and `payload-*` collections | Collections that appear in the matrix and are enforced. |
|
|
56
|
+
| `govern.globals` | `true \| GlobalSlug[] \| { include?: GlobalSlug[]; exclude?: GlobalSlug[] }` | every global except `payload-*` globals | Globals that appear in the matrix and are enforced. |
|
|
57
|
+
| `govern.fields` | `boolean \| Record<string, string[]>` | every named field | Field-level rows. `false` turns them off. A record lists dotted field paths per collection or global slug. |
|
|
58
|
+
| `actions` | `{ name: string; label: string; appliesTo?: string[] }[]` | `[]` | App-defined actions shown in the matrix. `appliesTo` lists governed slugs and defaults to all. Check them with `can()`. |
|
|
59
|
+
| `ownership` | `{ field: string } \| Record<CollectionSlug, string>` | none | Enables the `own` scope. One field name for every governed collection, or a field name per collection. |
|
|
60
|
+
| `superAdmin` | `(user) => boolean` | `() => false` | Users for whom this returns true bypass the matrix. They never bypass the app's own access rules. |
|
|
61
|
+
| `manageRoles` | `(user) => boolean` | the `superAdmin` function | Who may edit roles, assign them and see the matrix. |
|
|
62
|
+
| `locks` | `Lock[]` | `[]` | Code-level values the matrix shows and cannot change. Locks win over role data. |
|
|
63
|
+
| `defaultRoles` | `string[]` | `[]` | Role slugs given to a new user when none are set. |
|
|
64
|
+
| `cache.ttlSeconds` | `number` | `30` | How long role lookups stay in the process cache. |
|
|
65
|
+
| `admin.group` | `string` | none (top-level link) | Nav group for the Access link. |
|
|
66
|
+
| `admin.path` | `string` | `'/access'` | Route of the matrix screen under the admin route. |
|
|
67
|
+
| `admin.label` | `string` | the translated "Access" label | Nav link label. |
|
|
68
|
+
| `i18n` | `Partial<Translations>` | `{}` | Override any string the screens show. English is the default. |
|
|
69
|
+
|
|
70
|
+
`manageRoles` and `superAdmin` receive the user with its `roles` populated, so you can compare role slugs. Both run on every request.
|
|
71
|
+
|
|
72
|
+
`Lock` is `{ roles: '*' | string[]; target: string; action: string; value: 'allow' | 'deny' | 'own' }`. `target` is a collection or global slug, or `'*'`. Locks apply in array order and later locks override earlier ones for the same cell.
|
|
73
|
+
|
|
74
|
+
`RoleSeed` is `{ name: string; slug: string; permissions: RolePermissions; description?: string; locked?: boolean }`. `RolePermissions` is `{ collections?, globals?, fields?, custom? }`. For example:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
{
|
|
78
|
+
collections: { posts: { read: 'all', update: 'own' } },
|
|
79
|
+
globals: { settings: { read: 'all' } },
|
|
80
|
+
fields: { posts: { internalNotes: 'hidden' } },
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Scopes are `'all'`, `'own'` or `'none'`. Field rules are `'hidden'` or `'readOnly'`. Built-in actions:
|
|
85
|
+
|
|
86
|
+
- Collections: `read`, `create`, `update`, `delete`. `readVersions` when versions are on. `publish` when drafts are on.
|
|
87
|
+
- Globals: `read`, `update`. `readVersions` when versions are on. `publish` when drafts are on.
|
|
88
|
+
|
|
89
|
+
Exports: `accessPlugin`, `can(req, target, action)`, `getPermissions(req)` and the types `AccessPluginOptions`, `CustomAction`, `Lock`, `RoleSeed` and `Translations` from `payload-access-plugin`. The admin components come from `payload-access-plugin/client` and `payload-access-plugin/rsc`.
|
|
90
|
+
|
|
91
|
+
See [docs/recipes.md](docs/recipes.md) for worked examples.
|
|
92
|
+
|
|
93
|
+
## Security model
|
|
94
|
+
|
|
95
|
+
- **Final access is your rule AND the role.** For each governed collection and global, every access function is wrapped: `final = appAccess AND roleAccess`. Booleans and `Where` results combine (both wheres are joined with `and`). A role grants only what your own rules already allow, never more. Missing app access counts as Payload's default (signed in).
|
|
96
|
+
- **Roles add up.** The most permissive scope wins (`all` over `own` over `none`). A field is hidden or read-only only if every role says so.
|
|
97
|
+
- **Locks win.** A lock overrides what any role says for that cell, and the matrix shows the cell as locked.
|
|
98
|
+
- **Super admins bypass roles, not your code.** `superAdmin` skips the matrix. The app's own access functions still apply.
|
|
99
|
+
- **Permissions are never in the JWT.** They are read from the role records on each request (once per request, plus a short process cache that the roles collection invalidates on change), so a role change applies on the next request without signing out.
|
|
100
|
+
- **Guardrails** in the plugin itself:
|
|
101
|
+
- Locked roles refuse update and delete.
|
|
102
|
+
- A role's slug is fixed once created.
|
|
103
|
+
- A role that is still assigned to users cannot be deleted.
|
|
104
|
+
- A user without `manageRoles` cannot change anyone's roles, their own included.
|
|
105
|
+
- The last user holding a super-admin role cannot lose it and cannot be deleted.
|
|
106
|
+
- Bulk updates and deletes go through the same checks.
|
|
107
|
+
- A user who has `manageRoles` but is not a super admin cannot make anyone a super admin, themselves included. A roles change that newly gives a user a super-admin role is refused with a 403 ("Only a super admin can grant a super-admin role."). Calls without a signed-in user and calls with `overrideAccess` (seeds, the first user) are trusted.
|
|
108
|
+
- **A role that can update users can change their accounts.** A role granting update on a governed users collection lets its holders change those users' accounts, credentials included.
|
|
109
|
+
|
|
110
|
+
## Screens
|
|
111
|
+
|
|
112
|
+
- **Access matrix** at `/admin/access` (change it with `admin.path`). Rows are collection and action, columns are roles. Click a cell to cycle none, all and own (own only where ownership is configured). Locked cells show why they are locked. Filter by group or role, or show only differences. Changes save together after a summary of what will change.
|
|
113
|
+
- **New-role wizard.** The "+" button on the matrix opens a drawer with five steps: Name, Start from (blank, copy a role, or read-only), Permissions, Fields and globals, Review. The new role appears as a filled column.
|
|
114
|
+
- **Role edit grid.** The edit view of a role in the roles collection shows that role's permissions as a grid.
|
|
115
|
+
|
|
116
|
+
The nav link, and the schema it reads, are only for users who pass `manageRoles`. Roles keep their normal list and edit views, and the roles collection is versioned, so you can audit changes.
|
|
117
|
+
|
|
118
|
+
## Endpoints
|
|
119
|
+
|
|
120
|
+
Both are mounted under Payload's API route (`/api` by default). Neither exists when `enabled` is `false`.
|
|
121
|
+
|
|
122
|
+
### `GET /api/access-plugin/me`
|
|
123
|
+
|
|
124
|
+
The signed-in user's merged permissions, for front ends.
|
|
125
|
+
|
|
126
|
+
- `200`:
|
|
127
|
+
|
|
128
|
+
```json
|
|
129
|
+
{
|
|
130
|
+
"roles": ["editor"],
|
|
131
|
+
"superAdmin": false,
|
|
132
|
+
"collections": { "posts": { "read": "all", "update": "own", "publish": "none" } },
|
|
133
|
+
"globals": { "settings": { "read": "all", "update": "none" } },
|
|
134
|
+
"fields": { "posts": { "internalNotes": "hidden" } },
|
|
135
|
+
"custom": []
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Scopes are `all`, `own` or `none`. `fields` lists only fields with a rule and is empty for super admins. `custom` is the role's free-form custom entries.
|
|
140
|
+
|
|
141
|
+
- `401`: `{ "errors": [{ "message": "You must be signed in." }] }`
|
|
142
|
+
|
|
143
|
+
### `GET /api/access-plugin/schema`
|
|
144
|
+
|
|
145
|
+
What the matrix shows. Only for users who pass `manageRoles`.
|
|
146
|
+
|
|
147
|
+
- `200`:
|
|
148
|
+
|
|
149
|
+
```json
|
|
150
|
+
{
|
|
151
|
+
"rolesSlug": "roles",
|
|
152
|
+
"targets": {
|
|
153
|
+
"posts": {
|
|
154
|
+
"kind": "collection",
|
|
155
|
+
"label": "Posts",
|
|
156
|
+
"group": "Content",
|
|
157
|
+
"actions": [{ "name": "read", "label": "Read" }],
|
|
158
|
+
"fields": [{ "path": "title", "label": "Title" }]
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
"customActions": [{ "name": "export", "label": "Export" }],
|
|
162
|
+
"locks": [],
|
|
163
|
+
"ownership": ["posts"]
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`ownership` lists the slugs that have an owner field. `group` is present when the collection or global has an `admin.group`.
|
|
168
|
+
|
|
169
|
+
- `401`: not signed in (same body as above).
|
|
170
|
+
- `403`: `{ "errors": [{ "message": "You are not allowed to manage roles." }] }`
|
|
171
|
+
|
|
172
|
+
Payload's own `/api/access` keeps working and reflects the wrapped rules.
|
|
173
|
+
|
|
174
|
+
## Limitations and notes
|
|
175
|
+
|
|
176
|
+
- **The users collection is governed like any other.** Users without a role that grants them read and update on the users collection cannot read or edit their own account. Either exclude auth collections from `govern.collections` (for example `{ exclude: ['users'] }`) or give every role a users permission.
|
|
177
|
+
- **First-user window.** While no user exists, the first created user may be given roles, and any users collection that is publicly creatable can do the same until then. Seed a super-admin role and create the first admin immediately.
|
|
178
|
+
- **The role cache is per process.** Other instances see a role change after `cache.ttlSeconds` (default 30 seconds). The instance that saves the role sees it at once.
|
|
179
|
+
- **Concurrent demotions.** Two truly concurrent single-user demotions of the last two super admins are not prevented. Each check sees the other still holding the role.
|
|
180
|
+
- **`can()` reports the role scope only.** It does not run your collection's own access rules. Use it for custom actions and UI hints, not as the only check on a document.
|
|
181
|
+
- **Existing owner field.** If a collection already has a field named like the ownership field, the plugin does not manage it and clients can set it.
|
|
182
|
+
- **Empty roles on create.** An empty `roles` array on create counts as no roles and gets `defaultRoles`.
|
|
183
|
+
- **Nav groups.** An `admin.group` equal to an existing nav group label renders a second group with the same name.
|
|
184
|
+
|
|
185
|
+
## Payload compatibility
|
|
186
|
+
|
|
187
|
+
| payload-access-plugin | Payload | Database adapters tested |
|
|
188
|
+
| --------------------- | --------- | ------------------------- |
|
|
189
|
+
| 0.1.x | `^3.90.0` | SQLite, Postgres, MongoDB |
|
|
190
|
+
|
|
191
|
+
CI runs the integration tests on Payload 3.90.0 and 3.94.2 against all three adapters. Payload 4 is not supported yet.
|
|
192
|
+
|
|
193
|
+
Payload 3.90.0 is the minimum because earlier 3.x releases do not pass the incoming data to collection update access on bulk (where-based) updates, so the plugin could not enforce the publish permission there, and before 3.88.0 a user could sort by a field their role hides. Node `^22.23.5 || ^24.22.3 || >=26.13.1`.
|
|
194
|
+
|
|
195
|
+
## Contributing
|
|
196
|
+
|
|
197
|
+
Use [bun](https://bun.sh).
|
|
198
|
+
|
|
199
|
+
```sh
|
|
200
|
+
bun install
|
|
201
|
+
bun run dev # dev app with the plugin
|
|
202
|
+
bun run test:int # integration tests (vitest)
|
|
203
|
+
bun run test:e2e # Playwright, including axe checks
|
|
204
|
+
bun run lint
|
|
205
|
+
bun run typecheck
|
|
206
|
+
bun run build
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`TEST_DB` selects the database for the integration tests and the dev app:
|
|
210
|
+
|
|
211
|
+
- `sqlite` (default): file `dev/test.db`, recreated for every test run.
|
|
212
|
+
- `postgres`: uses `DATABASE_URL`.
|
|
213
|
+
- `mongodb`: starts an in-memory replica set.
|
|
214
|
+
|
|
215
|
+
For example, `TEST_DB=mongodb bun run test:int`. The e2e tests run with `TEST_DB=sqlite` after `bun run generate:importmap`.
|
|
216
|
+
|
|
217
|
+
Add a changeset for any user-facing change with `bun run changeset`. Releases are cut by the release workflow when the version pull request is merged.
|
|
218
|
+
|
|
219
|
+
## License
|
|
220
|
+
|
|
221
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { decide } from '../core/decide.js';
|
|
2
|
+
import { getPermissions, optionsOf } from './resolve.js';
|
|
3
|
+
/** True when the user may do the action on the target (scope `all` or `own`). */ export const can = async (req, target, action)=>{
|
|
4
|
+
const opts = optionsOf(req);
|
|
5
|
+
const resolved = await getPermissions(req, opts);
|
|
6
|
+
const kind = Object.hasOwn(opts.targets.collections, target) ? 'collection' : 'global';
|
|
7
|
+
return decide(resolved, kind, target, action) !== 'none';
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=can.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/can.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { decide } from '../core/decide.js'\nimport { getPermissions, optionsOf } from './resolve.js'\n\n/** True when the user may do the action on the target (scope `all` or `own`). */\nexport const can = async (\n req: PayloadRequest,\n target: string,\n action: string,\n): Promise<boolean> => {\n const opts = optionsOf(req)\n const resolved = await getPermissions(req, opts)\n const kind = Object.hasOwn(opts.targets.collections, target) ? 'collection' : 'global'\n return decide(resolved, kind, target, action) !== 'none'\n}\n"],"names":["decide","getPermissions","optionsOf","can","req","target","action","opts","resolved","kind","Object","hasOwn","targets","collections"],"mappings":"AAEA,SAASA,MAAM,QAAQ,oBAAmB;AAC1C,SAASC,cAAc,EAAEC,SAAS,QAAQ,eAAc;AAExD,+EAA+E,GAC/E,OAAO,MAAMC,MAAM,OACjBC,KACAC,QACAC;IAEA,MAAMC,OAAOL,UAAUE;IACvB,MAAMI,WAAW,MAAMP,eAAeG,KAAKG;IAC3C,MAAME,OAAOC,OAAOC,MAAM,CAACJ,KAAKK,OAAO,CAACC,WAAW,EAAER,UAAU,eAAe;IAC9E,OAAOL,OAAOQ,UAAUC,MAAMJ,QAAQC,YAAY;AACpD,EAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AccessResult } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* AND of the app's access result and the role result. Booleans short-circuit, `true` defers to
|
|
4
|
+
* the other side, and two `Where` results are joined with `and`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const combineAccess: (app: AccessResult, role: AccessResult) => AccessResult;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AND of the app's access result and the role result. Booleans short-circuit, `true` defers to
|
|
3
|
+
* the other side, and two `Where` results are joined with `and`.
|
|
4
|
+
*/ export const combineAccess = (app, role)=>{
|
|
5
|
+
// Any falsy result (false, null, undefined) is a refusal.
|
|
6
|
+
if (!app || !role) {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
if (app === true) {
|
|
10
|
+
return role;
|
|
11
|
+
}
|
|
12
|
+
if (role === true) {
|
|
13
|
+
return app;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
and: [
|
|
17
|
+
app,
|
|
18
|
+
role
|
|
19
|
+
]
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=combine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/combine.ts"],"sourcesContent":["import type { AccessResult } from 'payload'\n\n/**\n * AND of the app's access result and the role result. Booleans short-circuit, `true` defers to\n * the other side, and two `Where` results are joined with `and`.\n */\nexport const combineAccess = (app: AccessResult, role: AccessResult): AccessResult => {\n // Any falsy result (false, null, undefined) is a refusal.\n if (!app || !role) {\n return false\n }\n if (app === true) {\n return role\n }\n if (role === true) {\n return app\n }\n return { and: [app, role] }\n}\n"],"names":["combineAccess","app","role","and"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,gBAAgB,CAACC,KAAmBC;IAC/C,0DAA0D;IAC1D,IAAI,CAACD,OAAO,CAACC,MAAM;QACjB,OAAO;IACT;IACA,IAAID,QAAQ,MAAM;QAChB,OAAOC;IACT;IACA,IAAIA,SAAS,MAAM;QACjB,OAAOD;IACT;IACA,OAAO;QAAEE,KAAK;YAACF;YAAKC;SAAK;IAAC;AAC5B,EAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Field } from 'payload';
|
|
2
|
+
import type { NormalizedOptions } from '../options.js';
|
|
3
|
+
/**
|
|
4
|
+
* Wraps `access.read` (hidden is false) and `access.create` / `access.update` (hidden or
|
|
5
|
+
* readOnly is false) on each governed field path, each ANDed with the app's own function.
|
|
6
|
+
*/
|
|
7
|
+
export declare const wrapFields: (fields: Field[], slug: string, opts: NormalizedOptions, prefix?: string) => Field[];
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { fieldRule } from '../core/merge.js';
|
|
2
|
+
import { mapFields } from '../options.js';
|
|
3
|
+
import { getPermissions } from './resolve.js';
|
|
4
|
+
/** The app's own field access, ANDed with the role rule. No app function means allowed. */ const guard = (app, slug, path, blocks, opts)=>async (args)=>{
|
|
5
|
+
if (app && !await app(args)) {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
const resolved = await getPermissions(args.req, opts);
|
|
9
|
+
if (resolved.superAdmin) {
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
const rule = fieldRule(resolved, slug, path);
|
|
13
|
+
return !(rule && blocks(rule));
|
|
14
|
+
};
|
|
15
|
+
/** Never wrapped: the owner field and the users roles field are the plugin's own. */ const reserved = (slug, path, opts)=>Object.hasOwn(opts.ownership, slug) && opts.ownership[slug] === path || opts.usersSlugs.includes(slug) && path === 'roles';
|
|
16
|
+
/**
|
|
17
|
+
* Wraps `access.read` (hidden is false) and `access.create` / `access.update` (hidden or
|
|
18
|
+
* readOnly is false) on each governed field path, each ANDed with the app's own function.
|
|
19
|
+
*/ export const wrapFields = (fields, slug, opts, prefix = '')=>{
|
|
20
|
+
const governed = Object.hasOwn(opts.targets.fields, slug) ? opts.targets.fields[slug] : undefined;
|
|
21
|
+
if (!governed?.length) {
|
|
22
|
+
return fields;
|
|
23
|
+
}
|
|
24
|
+
return mapFields(fields, prefix, (field, path)=>{
|
|
25
|
+
if (!governed.includes(path) || reserved(slug, path, opts)) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const app = field.access ?? {};
|
|
29
|
+
return {
|
|
30
|
+
...field,
|
|
31
|
+
access: {
|
|
32
|
+
...app,
|
|
33
|
+
create: guard(app.create, slug, path, ()=>true, opts),
|
|
34
|
+
read: guard(app.read, slug, path, (rule)=>rule === 'hidden', opts),
|
|
35
|
+
update: guard(app.update, slug, path, ()=>true, opts)
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
//# sourceMappingURL=fields.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/fields.ts"],"sourcesContent":["import type { Field, FieldAccess } from 'payload'\n\nimport type { NormalizedOptions } from '../options.js'\n\nimport { fieldRule } from '../core/merge.js'\nimport { mapFields } from '../options.js'\nimport { getPermissions } from './resolve.js'\n\n/** The app's own field access, ANDed with the role rule. No app function means allowed. */\nconst guard =\n (\n app: FieldAccess | undefined,\n slug: string,\n path: string,\n blocks: (rule: 'hidden' | 'readOnly') => boolean,\n opts: NormalizedOptions,\n ): FieldAccess =>\n async (args) => {\n if (app && !(await app(args))) {\n return false\n }\n const resolved = await getPermissions(args.req, opts)\n if (resolved.superAdmin) {\n return true\n }\n const rule = fieldRule(resolved, slug, path)\n return !(rule && blocks(rule))\n }\n\n/** Never wrapped: the owner field and the users roles field are the plugin's own. */\nconst reserved = (slug: string, path: string, opts: NormalizedOptions): boolean =>\n (Object.hasOwn(opts.ownership, slug) && opts.ownership[slug] === path) ||\n (opts.usersSlugs.includes(slug) && path === 'roles')\n\n/**\n * Wraps `access.read` (hidden is false) and `access.create` / `access.update` (hidden or\n * readOnly is false) on each governed field path, each ANDed with the app's own function.\n */\nexport const wrapFields = (\n fields: Field[],\n slug: string,\n opts: NormalizedOptions,\n prefix = '',\n): Field[] => {\n const governed = Object.hasOwn(opts.targets.fields, slug) ? opts.targets.fields[slug] : undefined\n if (!governed?.length) {\n return fields\n }\n return mapFields(fields, prefix, (field, path) => {\n if (!governed.includes(path) || reserved(slug, path, opts)) {\n return\n }\n const app = (field as { access?: Record<string, FieldAccess | undefined> }).access ?? {}\n return {\n ...field,\n access: {\n ...app,\n create: guard(app.create, slug, path, () => true, opts),\n read: guard(app.read, slug, path, (rule) => rule === 'hidden', opts),\n update: guard(app.update, slug, path, () => true, opts),\n },\n } as Field\n })\n}\n"],"names":["fieldRule","mapFields","getPermissions","guard","app","slug","path","blocks","opts","args","resolved","req","superAdmin","rule","reserved","Object","hasOwn","ownership","usersSlugs","includes","wrapFields","fields","prefix","governed","targets","undefined","length","field","access","create","read","update"],"mappings":"AAIA,S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AMC,IAAI0B,IAAI,EAAEzB,MAAMC,MAAM,CAACO,OAASA,SAAS,UAAUL;gBAC/DuB,QAAQ5B,MAAMC,IAAI2B,MAAM,EAAE1B,MAAMC,MAAM,IAAM,MAAME;YACpD;QACF;IACF;AACF,EAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { NormalizedOptions } from '../options.js';
|
|
3
|
+
type Id = number | string;
|
|
4
|
+
export declare const idsOf: (value: unknown) => Id[];
|
|
5
|
+
export declare const loadRoles: (req: PayloadRequest, opts: NormalizedOptions, ids: Id[]) => Promise<(import("payload").JsonObject & import("payload").TypeWithID)[]>;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { asCollection } from '../slug.js';
|
|
2
|
+
export const idsOf = (value)=>Array.isArray(value) ? value.map((item)=>typeof item === 'object' && item !== null ? item.id : item).filter((id)=>typeof id === 'string' || typeof id === 'number') : [];
|
|
3
|
+
export const loadRoles = async (req, opts, ids)=>{
|
|
4
|
+
if (ids.length === 0) {
|
|
5
|
+
return [];
|
|
6
|
+
}
|
|
7
|
+
const { docs } = await req.payload.find({
|
|
8
|
+
collection: asCollection(opts.rolesSlug),
|
|
9
|
+
depth: 0,
|
|
10
|
+
overrideAccess: true,
|
|
11
|
+
pagination: false,
|
|
12
|
+
req,
|
|
13
|
+
where: {
|
|
14
|
+
id: {
|
|
15
|
+
in: ids
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
return docs;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=load.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/load.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { NormalizedOptions } from '../options.js'\n\nimport { asCollection } from '../slug.js'\n\ntype Id = number | string\n\nexport const idsOf = (value: unknown): Id[] =>\n Array.isArray(value)\n ? value\n .map((item) => (typeof item === 'object' && item !== null ? (item as { id: Id }).id : item))\n .filter((id): id is Id => typeof id === 'string' || typeof id === 'number')\n : []\n\nexport const loadRoles = async (req: PayloadRequest, opts: NormalizedOptions, ids: Id[]) => {\n if (ids.length === 0) {\n return []\n }\n const { docs } = await req.payload.find({\n collection: asCollection(opts.rolesSlug),\n depth: 0,\n overrideAccess: true,\n pagination: false,\n req,\n where: { id: { in: ids } },\n })\n return docs\n}\n"],"names":["asCollection","idsOf","value","Array","isArray","map","item","id","filter","loadRoles","req","opts","ids","length","docs","payload","find","collection","rolesSlug","depth","overrideAccess","pagination","where","in"],"mappings":"AAIA,SAASA,YAAY,QAAQ,aAAY;AAIzC,OAAO,MAAMC,QAAQ,CAACC,QACpBC,MAAMC,OAAO,CAACF,SACVA,MACGG,GAAG,CAAC,CAACC,OAAU,OAAOA,SAAS,YAAYA,SAAS,OAAO,AAACA,KAAoBC,EAAE,GAAGD,MACrFE,MAAM,CAAC,CAACD,KAAiB,OAAOA,OAAO,YAAY,OAAOA,OAAO,YACpE,EAAE,CAAA;AAER,OAAO,MAAME,YAAY,OAAOC,KAAqBC,MAAyBC;IAC5E,IAAIA,IAAIC,MAAM,KAAK,GAAG;QACpB,OAAO,EAAE;IACX;IACA,MAAM,EAAEC,IAAI,EAAE,GAAG,MAAMJ,IAAIK,OAAO,CAACC,IAAI,CAAC;QACtCC,YAAYjB,aAAaW,KAAKO,SAAS;QACvCC,OAAO;QACPC,gBAAgB;QAChBC,YAAY;QACZX;QACAY,OAAO;YAAEf,IAAI;gBAAEgB,IAAIX;YAAI;QAAE;IAC3B;IACA,OAAOE;AACT,EAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
import type { NormalizedOptions } from '../options.js';
|
|
3
|
+
/**
|
|
4
|
+
* Whether the signed-in user may manage roles. `manageRoles` sees the user with populated roles,
|
|
5
|
+
* so it works for apps whose users collection loads roles as ids.
|
|
6
|
+
*/
|
|
7
|
+
export declare const canManageRoles: (req: PayloadRequest, opts?: NormalizedOptions) => Promise<boolean>;
|
|
8
|
+
/** Whether the signed-in user is a super admin, evaluated on populated roles. */
|
|
9
|
+
export declare const isSuperAdmin: (req: PayloadRequest, opts?: NormalizedOptions) => Promise<boolean>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { optionsOf, populatedUser } from './resolve.js';
|
|
2
|
+
/**
|
|
3
|
+
* Whether the signed-in user may manage roles. `manageRoles` sees the user with populated roles,
|
|
4
|
+
* so it works for apps whose users collection loads roles as ids.
|
|
5
|
+
*/ export const canManageRoles = async (req, opts = optionsOf(req))=>opts.manageRoles(await populatedUser(req, opts));
|
|
6
|
+
/** Whether the signed-in user is a super admin, evaluated on populated roles. */ export const isSuperAdmin = async (req, opts = optionsOf(req))=>opts.superAdmin(await populatedUser(req, opts));
|
|
7
|
+
|
|
8
|
+
//# sourceMappingURL=manage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/manage.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport type { NormalizedOptions } from '../options.js'\n\nimport { optionsOf, populatedUser } from './resolve.js'\n\n/**\n * Whether the signed-in user may manage roles. `manageRoles` sees the user with populated roles,\n * so it works for apps whose users collection loads roles as ids.\n */\nexport const canManageRoles = async (\n req: PayloadRequest,\n opts: NormalizedOptions = optionsOf(req),\n): Promise<boolean> => opts.manageRoles(await populatedUser(req, opts))\n\n/** Whether the signed-in user is a super admin, evaluated on populated roles. */\nexport const isSuperAdmin = async (\n req: PayloadRequest,\n opts: NormalizedOptions = optionsOf(req),\n): Promise<boolean> => opts.superAdmin(await populatedUser(req, opts))\n"],"names":["optionsOf","populatedUser","canManageRoles","req","opts","manageRoles","isSuperAdmin","superAdmin"],"mappings":"AAIA,SAASA,SAAS,EAAEC,aAAa,QAAQ,eAAc;AAEvD;;;CAGC,GACD,OAAO,MAAMC,iBAAiB,OAC5BC,KACAC,OAA0BJ,UAAUG,IAAI,GACnBC,KAAKC,WAAW,CAAC,MAAMJ,cAAcE,KAAKC,OAAM;AAEvE,+EAA+E,GAC/E,OAAO,MAAME,eAAe,OAC1BH,KACAC,OAA0BJ,UAAUG,IAAI,GACnBC,KAAKG,UAAU,CAAC,MAAMN,cAAcE,KAAKC,OAAM"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, PayloadRequest } from 'payload';
|
|
2
|
+
import type { ResolvedPermissions } from '../core/types.js';
|
|
3
|
+
import type { NormalizedOptions } from '../options.js';
|
|
4
|
+
/** Drops every cached role. Called when a role changes or is deleted. */
|
|
5
|
+
export declare const clearRoleCache: () => void;
|
|
6
|
+
/** Hooks appended to the roles collection so a role change applies on the next request. */
|
|
7
|
+
export declare const roleCacheHooks: () => {
|
|
8
|
+
afterChange: CollectionAfterChangeHook;
|
|
9
|
+
afterDelete: CollectionAfterDeleteHook;
|
|
10
|
+
};
|
|
11
|
+
/** The plugin options stored on the config by the plugin. */
|
|
12
|
+
export declare const optionsOf: (req: PayloadRequest) => NormalizedOptions;
|
|
13
|
+
/**
|
|
14
|
+
* The signed-in user's merged permissions, from role documents only (never the JWT). Memoized
|
|
15
|
+
* on `req.context.accessPlugin`; role documents also sit in a short process cache.
|
|
16
|
+
*/
|
|
17
|
+
export declare const getPermissions: (req: PayloadRequest, opts?: NormalizedOptions) => Promise<ResolvedPermissions>;
|
|
18
|
+
/**
|
|
19
|
+
* The signed-in user with `roles` populated from role documents, whatever the auth depth.
|
|
20
|
+
* Null when signed out.
|
|
21
|
+
*/
|
|
22
|
+
export declare const populatedUser: (req: PayloadRequest, opts?: NormalizedOptions) => Promise<null | Record<string, unknown>>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { applyLocks } from '../core/locks.js';
|
|
2
|
+
import { mergeRoles } from '../core/merge.js';
|
|
3
|
+
import { idsOf, loadRoles } from './load.js';
|
|
4
|
+
// Bumped on every clear, so a load that started before a clear can't write its stale result.
|
|
5
|
+
let generation = 0;
|
|
6
|
+
const cache = new Map();
|
|
7
|
+
const cacheKey = (opts, id)=>`${opts.rolesSlug}:${String(id)}`;
|
|
8
|
+
/** Drops every cached role. Called when a role changes or is deleted. */ export const clearRoleCache = ()=>{
|
|
9
|
+
generation += 1;
|
|
10
|
+
cache.clear();
|
|
11
|
+
};
|
|
12
|
+
/** Hooks appended to the roles collection so a role change applies on the next request. */ export const roleCacheHooks = ()=>({
|
|
13
|
+
afterChange: ({ doc })=>{
|
|
14
|
+
clearRoleCache();
|
|
15
|
+
return doc;
|
|
16
|
+
},
|
|
17
|
+
afterDelete: ({ doc })=>{
|
|
18
|
+
clearRoleCache();
|
|
19
|
+
return doc;
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
const roleDocs = async (req, opts, ids)=>{
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const startedAt = generation;
|
|
25
|
+
const found = new Map();
|
|
26
|
+
const missing = [];
|
|
27
|
+
for (const id of ids){
|
|
28
|
+
const hit = cache.get(cacheKey(opts, id));
|
|
29
|
+
if (hit && hit.expires > now) {
|
|
30
|
+
found.set(String(id), hit.doc);
|
|
31
|
+
} else {
|
|
32
|
+
missing.push(id);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (missing.length > 0) {
|
|
36
|
+
for (const doc of (await loadRoles(req, opts, missing))){
|
|
37
|
+
found.set(String(doc.id), doc);
|
|
38
|
+
if (startedAt === generation) {
|
|
39
|
+
cache.set(cacheKey(opts, doc.id), {
|
|
40
|
+
doc,
|
|
41
|
+
expires: now + opts.cacheTtlMs
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return ids.map((id)=>found.get(String(id))).filter((doc)=>Boolean(doc));
|
|
47
|
+
};
|
|
48
|
+
const isPermissions = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
49
|
+
const nothing = ()=>({
|
|
50
|
+
custom: new Set(),
|
|
51
|
+
fields: new Map(),
|
|
52
|
+
scopes: new Map(),
|
|
53
|
+
superAdmin: false
|
|
54
|
+
});
|
|
55
|
+
const compute = async (req, opts)=>{
|
|
56
|
+
const user = req.user;
|
|
57
|
+
if (!user) {
|
|
58
|
+
return nothing();
|
|
59
|
+
}
|
|
60
|
+
const docs = await roleDocs(req, opts, idsOf(user.roles));
|
|
61
|
+
const merged = mergeRoles(docs.map((doc)=>isPermissions(doc.permissions) ? doc.permissions : {}));
|
|
62
|
+
const resolved = applyLocks(merged, docs.map((doc)=>doc.slug).filter((slug)=>typeof slug === 'string'), opts.locks, opts.targets);
|
|
63
|
+
resolved.superAdmin = opts.superAdmin({
|
|
64
|
+
...user,
|
|
65
|
+
roles: docs
|
|
66
|
+
});
|
|
67
|
+
return resolved;
|
|
68
|
+
};
|
|
69
|
+
/** The plugin options stored on the config by the plugin. */ export const optionsOf = (req)=>{
|
|
70
|
+
const stored = req.payload.config.custom?.accessPlugin;
|
|
71
|
+
if (!stored) {
|
|
72
|
+
throw new Error('payload-access-plugin: the plugin is not installed in this config.');
|
|
73
|
+
}
|
|
74
|
+
return stored;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* The signed-in user's merged permissions, from role documents only (never the JWT). Memoized
|
|
78
|
+
* on `req.context.accessPlugin`; role documents also sit in a short process cache.
|
|
79
|
+
*/ export const getPermissions = (req, opts = optionsOf(req))=>{
|
|
80
|
+
const context = req.context ??= {};
|
|
81
|
+
const userId = req.user?.id;
|
|
82
|
+
if (context.accessPlugin && context.accessPlugin.userId === userId) {
|
|
83
|
+
return context.accessPlugin.permissions;
|
|
84
|
+
}
|
|
85
|
+
const permissions = compute(req, opts);
|
|
86
|
+
context.accessPlugin = {
|
|
87
|
+
permissions,
|
|
88
|
+
userId
|
|
89
|
+
};
|
|
90
|
+
return permissions;
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* The signed-in user with `roles` populated from role documents, whatever the auth depth.
|
|
94
|
+
* Null when signed out.
|
|
95
|
+
*/ export const populatedUser = async (req, opts = optionsOf(req))=>{
|
|
96
|
+
const user = req.user;
|
|
97
|
+
if (!user) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
...user,
|
|
102
|
+
roles: await roleDocs(req, opts, idsOf(user.roles))
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
//# sourceMappingURL=resolve.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/access/resolve.ts"],"sourcesContent":["import type { CollectionAfterChangeHook, CollectionAfterDeleteHook, PayloadRequest } from 'payload'\n\nimport type { ResolvedPermissions, RolePermissions } from '../core/types.js'\nimport type { NormalizedOptions } from '../options.js'\n\nimport { applyLocks } from '../core/locks.js'\nimport { mergeRoles } from '../core/merge.js'\nimport { idsOf, loadRoles } from './load.js'\n\ntype Id = number | string\ntype RoleDoc = { id: Id; permissions?: unknown; slug?: string }\n\n// Bumped on every clear, so a load that started before a clear can't write its stale result.\nlet generation = 0\n\nconst cache = new Map<string, { doc: RoleDoc; expires: number }>()\n\nconst cacheKey = (opts: NormalizedOptions, id: Id) => `${opts.rolesSlug}:${String(id)}`\n\n/** Drops every cached role. Called when a role changes or is deleted. */\nexport const clearRoleCache = (): void => {\n generation += 1\n cache.clear()\n}\n\n/** Hooks appended to the roles collection so a role change applies on the next request. */\nexport const roleCacheHooks = (): {\n afterChange: CollectionAfterChangeHook\n afterDelete: CollectionAfterDeleteHook\n} => ({\n afterChange: ({ doc }) => {\n clearRoleCache()\n return doc\n },\n afterDelete: ({ doc }) => {\n clearRoleCache()\n return doc\n },\n})\n\nconst roleDocs = async (req: PayloadRequest, opts: NormalizedOptions, ids: Id[]) => {\n const now = Date.now()\n const startedAt = generation\n const found = new Map<string, RoleDoc>()\n const missing: Id[] = []\n for (const id of ids) {\n const hit = cache.get(cacheKey(opts, id))\n if (hit && hit.expires > now) {\n found.set(String(id), hit.doc)\n } else {\n missing.push(id)\n }\n }\n if (missing.length > 0) {\n for (const doc of (await loadRoles(req, opts, missing)) as RoleDoc[]) {\n found.set(String(doc.id), doc)\n if (startedAt === generation) {\n cache.set(cacheKey(opts, doc.id), { doc, expires: now + opts.cacheTtlMs })\n }\n }\n }\n return ids.map((id) => found.get(String(id))).filter((doc): doc is RoleDoc => Boolean(doc))\n}\n\nconst isPermissions = (value: unknown): value is RolePermissions =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst nothing = (): ResolvedPermissions => ({\n custom: new Set(),\n fields: new Map(),\n scopes: new Map(),\n superAdmin: false,\n})\n\nconst compute = async (\n req: PayloadRequest,\n opts: NormalizedOptions,\n): Promise<ResolvedPermissions> => {\n const user = req.user as ({ roles?: unknown } & Record<string, unknown>) | null\n if (!user) {\n return nothing()\n }\n const docs = await roleDocs(req, opts, idsOf(user.roles))\n const merged = mergeRoles(\n docs.map((doc) => (isPermissions(doc.permissions) ? doc.permissions : {})),\n )\n const resolved = applyLocks(\n merged,\n docs.map((doc) => doc.slug).filter((slug): slug is string => typeof slug === 'string'),\n opts.locks,\n opts.targets,\n )\n resolved.superAdmin = opts.superAdmin({ ...user, roles: docs })\n return resolved\n}\n\n/** The plugin options stored on the config by the plugin. */\nexport const optionsOf = (req: PayloadRequest): NormalizedOptions => {\n const stored = (req.payload.config.custom as { accessPlugin?: NormalizedOptions } | undefined)\n ?.accessPlugin\n if (!stored) {\n throw new Error('payload-access-plugin: the plugin is not installed in this config.')\n }\n return stored\n}\n\ntype Memo = { permissions: Promise<ResolvedPermissions>; userId: unknown }\n\n/**\n * The signed-in user's merged permissions, from role documents only (never the JWT). Memoized\n * on `req.context.accessPlugin`; role documents also sit in a short process cache.\n */\nexport const getPermissions = (\n req: PayloadRequest,\n opts: NormalizedOptions = optionsOf(req),\n): Promise<ResolvedPermissions> => {\n const context = (req.context ??= {}) as { accessPlugin?: Memo }\n const userId = req.user?.id\n if (context.accessPlugin && context.accessPlugin.userId === userId) {\n return context.accessPlugin.permissions\n }\n const permissions = compute(req, opts)\n context.accessPlugin = { permissions, userId }\n return permissions\n}\n\n/**\n * The signed-in user with `roles` populated from role documents, whatever the auth depth.\n * Null when signed out.\n */\nexport const populatedUser = async (\n req: PayloadRequest,\n opts: NormalizedOptions = optionsOf(req),\n): Promise<null | Record<string, unknown>> => {\n const user = req.user as ({ roles?: unknown } & Record<string, unknown>) | null\n if (!user) {\n return null\n }\n return { ...user, roles: await roleDocs(req, opts, idsOf(user.roles)) }\n}\n"],"names":["applyLocks","mergeRoles","idsOf","loadRoles","generation","cache","Map","cacheKey","opts","id","rolesSlug","String","clearRoleCache","clear","roleCacheHooks","afterChange","doc","afterDelete","roleDocs","req","ids","now","Date","startedAt","found","missing","hit","get","expires","set","push","length","cacheTtlMs","map","filter","Boolean","isPermissions","value","Array","isArray","nothing","custom","Set","fields","scopes","superAdmin","compute","user","docs","roles","merged","permissions","resolved","slug","locks","targets","optionsOf","stored","payload","config","accessPlugin","Error","getPermissions","context","userId","populatedUser"],"mappings":"AAKA,SAASA,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,KAAK,EAAEC,SAAS,QAAQ,YAAW;AAK5C,6FAA6F;AAC7F,IAAIC,aAAa;AAEjB,MAAMC,QAAQ,IAAIC;AAElB,MAAMC,WAAW,CAACC,MAAyBC,KAAW,GAAGD,KAAKE,SAAS,CAAC,CAAC,EAAEC,OAAOF,KAAK;AAEvF,uEAAuE,GACvE,OAAO,MAAMG,iBAAiB;IAC5BR,cAAc;IACdC,MAAMQ,KAAK;AACb,EAAC;AAED,yFAAyF,GACzF,OAAO,MAAMC,iBAAiB,IAGxB,CAAA;QACJC,aAAa,CAAC,EAAEC,GAAG,EAAE;YACnBJ;YACA,OAAOI;QACT;QACAC,aAAa,CAAC,EAAED,GAAG,EAAE;YACnBJ;YACA,OAAOI;QACT;IACF,CA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MAAM/B,SAASC,KAAKX,MAAMN,MAAM6C,KAAKE,KAAK;IAAG;AACxE,EAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CollectionConfig, GlobalConfig } from 'payload';
|
|
2
|
+
import type { NormalizedOptions } from '../options.js';
|
|
3
|
+
/** `final = appAccess AND roleAccess` on each action of a governed collection. */
|
|
4
|
+
export declare const wrapCollectionAccess: (collection: CollectionConfig, opts: NormalizedOptions) => CollectionConfig;
|
|
5
|
+
/** `final = appAccess AND roleAccess` on each action of a governed global. */
|
|
6
|
+
export declare const wrapGlobalAccess: (global: GlobalConfig, opts: NormalizedOptions) => GlobalConfig;
|