@3xweb/strapi-plugin-owner-permissions 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 3X Web
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,133 @@
1
- # Temporary Holding Version
1
+ # Owner Permissions for Strapi 5
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Limit user-generated content to its owner on the Strapi REST Content API.
4
+ Enable standard actions in **Settings → Users & Permissions → Roles**. On the
5
+ same role edit page, expand an eligible collection and click the gear next to
6
+ an action. In the **Advanced settings** pane, enable **Only own records** and
7
+ save the ownership rules. The owner field identifies the stored relationship
8
+ between each record and its owner. Enable the native action permission as well
9
+ for users with that role to use the route.
10
+
11
+ ## Installation
12
+
13
+ From your Strapi project, install the package from npm:
14
+
15
+ ```sh
16
+ npm install @3xweb/strapi-plugin-owner-permissions
17
+ ```
18
+
19
+ Enable the plugin in `config/plugins.js`:
20
+
21
+ ```js
22
+ module.exports = {
23
+ 'owner-permissions': { enabled: true },
24
+ };
25
+ ```
26
+
27
+ Ownership settings are stored in the database and edited from the Roles page.
28
+
29
+ The native role editor in Users & Permissions 5.62.0 has no injection zone. Add
30
+ the package's version-checked Vite integration in `src/admin/vite.config.js`
31
+ and rebuild the admin panel:
32
+
33
+ ```js
34
+ const { withOwnerPermissionsRoleEditor } = require('@3xweb/strapi-plugin-owner-permissions/admin-patch');
35
+
36
+ module.exports = withOwnerPermissionsRoleEditor;
37
+ ```
38
+
39
+ If you already customize the Vite config, pass your final config object to
40
+ `withOwnerPermissionsRoleEditor`. Use matching Strapi and Users & Permissions versions from **5.49.0 to <6**.
41
+ The admin integration checks the upstream Roles panel before building and
42
+ stops if its source has changed.
43
+
44
+ Rebuild the admin panel and restart Strapi:
45
+
46
+ ```sh
47
+ npm run build
48
+ npm run start
49
+ ```
50
+
51
+ ## Configure a collection
52
+
53
+ In the collection schema's `attributes`, define an ownership field. It can use
54
+ any name, such as `owner` or `author`. It must be a private, unidirectional
55
+ many-to-one relation to a Users & Permissions user.
56
+
57
+ ```json
58
+ {
59
+ "owner": {
60
+ "type": "relation",
61
+ "relation": "manyToOne",
62
+ "target": "plugin::users-permissions.user",
63
+ "private": true
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Configure a role
69
+
70
+ 1. Open **Settings → Users & Permissions → Roles** and select a role.
71
+ 2. Expand the collection in **Permissions**. Enable the native permissions for
72
+ the actions the role can execute and save them with **Save**.
73
+ 3. Click the gear beside an action. In the right-hand pane, turn on **Only own
74
+ records** and select **Save ownership rules**. Repeat for each action that
75
+ should be restricted.
76
+ 4. If the collection has one eligible owner field, the panel displays it
77
+ automatically. If there are multiple eligible fields, select the relation
78
+ that identifies the owner. All restricted actions for that role and
79
+ collection use the same field.
80
+
81
+ ![Update with Only own records enabled and owner shown as the owner field](docs/images/owner-permissions-update.jpg)
82
+
83
+ A different action in the same collection can keep native access. In this
84
+ example, **Find** is enabled for the role and **Only own records** is off.
85
+
86
+ ![Find with the native permission enabled and Only own records off](docs/images/owner-permissions-find.jpg)
87
+
88
+ Ownership is configured per role, collection, and core action. Actions with
89
+ **Only own records** enabled are limited to the caller's records. Other actions
90
+ for that role continue to follow the native permissions, so, for example, a
91
+ role can list all entries and only update its own entries. A collection with
92
+ ownership rules is available only to user roles configured for it. Collections
93
+ with no ownership rules keep their native behavior. Save the native action
94
+ permissions separately using the existing role save button.
95
+
96
+ Assign owners to existing documents through a trusted migration before enabling
97
+ the rule. Previously saved collection-wide rules are displayed and enforced
98
+ for all five core actions until changed. Removing the last rule for a collection
99
+ restores native access, including any permissions assigned to the public role.
100
+
101
+ On a protected collection, the server assigns the owner during creation and
102
+ prevents clients from setting or changing that relationship. A rule on `find`
103
+ covers both list results and pagination totals. Restricted individual actions
104
+ return 404 for records owned by someone else. Anonymous calls and API tokens
105
+ cannot access protected collections through the guarded REST API.
106
+
107
+ The ownership field must be a private, unidirectional many-to-one relationship
108
+ to Users & Permissions. The plugin rejects unsupported saved mappings at startup.
109
+ Protected collections support scalar fields and eligible ownership
110
+ relations. Only the selected owner relation is assigned on creation. Other
111
+ owner relations are managed by trusted server-side workflows. The plugin rejects populate, inbound relations to protected collections,
112
+ Draft & Publish, i18n, and GraphQL when mappings are enabled. Admin access and
113
+ internal jobs keep their existing access rules. Custom endpoints that read
114
+ directly from the database need their own explicit authorization. Rules are
115
+ keyed by core action, so custom endpoints cannot define a different rule for
116
+ another method or path using the same action.
117
+
118
+ For a fixture using the previous file-based mappings, record those rules, remove
119
+ the mapping configuration from plugins.js, and re-create the rules in the Roles
120
+ screen before making the REST API available. The plugin refuses to start with the
121
+ old configuration still present.
122
+
123
+ ## Test locally
124
+
125
+ Run `npm run test:integration` with Strapi 5, Users & Permissions and
126
+ `better-sqlite3` available. To reuse a separate dependency installation, set
127
+ `STRAPI_TEST_DEPS` to the directory containing its `node_modules`. The test
128
+ creates a temporary Strapi app and SQLite database, logs in two synthetic users
129
+ using Users & Permissions, and exercises the built-in REST endpoints on
130
+ loopback.
131
+
132
+ Both the admin bundle and the REST integration suite were verified on Strapi
133
+ and Users & Permissions **5.49.0**, **5.62.0**, and **5.64.0**, using Node.js 22.
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ // Serialized into the pinned Roles editor by the build patch. Dependencies come
4
+ // from the editor's own modules to preserve the host's React and Strapi contexts.
5
+ module.exports = function createOwnerRules(
6
+ React,
7
+ { Button, Checkbox, Flex, SingleSelect, SingleSelectOption, Typography },
8
+ { useFetchClient, useAPIErrorHandler },
9
+ { useMutation, useQuery, useQueryClient },
10
+ ) {
11
+ const h = React.createElement;
12
+
13
+ return function OwnerRules({ id, selectedAction }) {
14
+ const parts = selectedAction.split('.');
15
+ const action = parts[3];
16
+ const uid = parts[0] + '.' + parts[2];
17
+ const endpoint = '/owner-permissions/roles/' + encodeURIComponent(id);
18
+ const queryKey = ['owner-permissions', 'role', id];
19
+ const { get, put } = useFetchClient();
20
+ const { formatAPIError } = useAPIErrorHandler();
21
+ const queryClient = useQueryClient();
22
+ const [changes, setChanges] = React.useState(null);
23
+
24
+ const query = useQuery(queryKey, async () => (await get(endpoint)).data.data);
25
+ const save = useMutation(
26
+ async (mappings) => (await put(endpoint, { mappings })).data.data,
27
+ {
28
+ onSuccess(data) {
29
+ queryClient.setQueryData(queryKey, data);
30
+ setChanges(null);
31
+ },
32
+ },
33
+ );
34
+
35
+ const coreActions = ['find', 'findOne', 'create', 'update', 'delete'];
36
+ const validAction = parts.length === 4 && parts[0].startsWith('api::') &&
37
+ parts[1] === 'controllers' && coreActions.includes(action);
38
+ if (!validAction) return null;
39
+ if (query.isLoading) return h(Typography, { role: 'status' }, 'Loading ownership rules…');
40
+ if (query.isError) return h(Typography, { role: 'alert', textColor: 'danger600' }, formatAPIError(query.error));
41
+ if (!query.data.canConfigure) return null;
42
+ const content = query.data.eligible.find((item) => item.uid === uid);
43
+ if (!content) return null;
44
+
45
+ const mappings = changes ?? query.data.mappings;
46
+ const saved = mappings[uid];
47
+ const rule = typeof saved === 'string' ? { ownerField: saved, actions: coreActions } : saved;
48
+ const enabled = rule?.actions.includes(action) ?? false;
49
+
50
+ function edit(nextRule) {
51
+ save.reset();
52
+ const next = { ...mappings };
53
+ if (nextRule.actions.length) next[uid] = nextRule;
54
+ else delete next[uid];
55
+ setChanges(next);
56
+ }
57
+
58
+ function toggle(checked) {
59
+ const existing = rule?.actions ?? [];
60
+ const actions = checked === true ? [...existing, action] : existing.filter((item) => item !== action);
61
+ const onlyField = content.ownerFields.length === 1 ? content.ownerFields[0] : '';
62
+ edit({ ownerField: rule?.ownerField || onlyField, actions });
63
+ }
64
+
65
+ function renderOwnerField() {
66
+ if (!enabled) return null;
67
+ if (content.ownerFields.length === 1) {
68
+ return h(Typography, null, 'Owner field: ' + rule.ownerField + '. Strapi uses this field to identify the user who owns the record.');
69
+ }
70
+ return h(Flex, { direction: 'column', alignItems: 'stretch', gap: 2 },
71
+ h(Typography, null, 'Choose the field that links a record to its owner. This field is shared by the restricted actions for this content type.'),
72
+ h(SingleSelect, {
73
+ 'aria-label': 'Owner field',
74
+ placeholder: 'Choose an owner field',
75
+ value: rule.ownerField,
76
+ onChange: (ownerField) => edit({ ...rule, ownerField }),
77
+ disabled: save.isLoading,
78
+ }, content.ownerFields.map((field) => h(SingleSelectOption, { key: field, value: field }, field))),
79
+ );
80
+ }
81
+
82
+ const missingField = Object.values(mappings).some((item) => typeof item !== 'string' && !item.ownerField);
83
+
84
+ return h(
85
+ Flex,
86
+ { direction: 'column', alignItems: 'stretch', gap: 3, tag: 'section', 'aria-label': 'User-generated content' },
87
+ h(Typography, { tag: 'h2', variant: 'delta' }, 'User-generated content'),
88
+ h(Checkbox, {
89
+ checked: enabled,
90
+ disabled: save.isLoading,
91
+ onCheckedChange: toggle,
92
+ }, 'Only own records'),
93
+ h(Typography, null, action === 'create'
94
+ ? 'New records belong to the user who creates them. The role must also have permission to create records.'
95
+ : 'Limits this action to the user’s own records. The role must also have permission to run the action.'),
96
+ renderOwnerField(),
97
+ save.isError && h(Typography, { role: 'alert', textColor: 'danger600' }, formatAPIError(save.error)),
98
+ save.isSuccess && h(Typography, { role: 'status', textColor: 'success600' }, 'Ownership rules saved.'),
99
+ h(Button, {
100
+ type: 'button',
101
+ variant: 'secondary',
102
+ disabled: !changes || missingField,
103
+ loading: save.isLoading,
104
+ onClick: () => save.mutate(mappings),
105
+ }, 'Save ownership rules'),
106
+ );
107
+ };
108
+ };
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ const { createHash } = require('node:crypto');
4
+ const { realpathSync } = require('node:fs');
5
+ const { createRequire } = require('node:module');
6
+ const { dirname, join, resolve } = require('node:path');
7
+ const createOwnerRules = require('./OwnerRules.cjs');
8
+
9
+ const DEPENDENCY = '@strapi/plugin-users-permissions';
10
+ const MINIMUM_MINOR = 49;
11
+ const NAME = 'owner-permissions:native-role-editor';
12
+
13
+ const esmSetup = `import * as OwnerRulesReact from 'react';
14
+ import { Button, Checkbox, SingleSelect, SingleSelectOption } from '@strapi/design-system';
15
+ import { useFetchClient, useAPIErrorHandler } from '@strapi/strapi/admin';
16
+ import { useMutation, useQuery, useQueryClient } from 'react-query';
17
+ import { useMatch } from 'react-router-dom';
18
+ const OwnerPermissionsRules = (${createOwnerRules})(OwnerRulesReact, { Button, Checkbox, Flex, SingleSelect, SingleSelectOption, Typography }, { useFetchClient, useAPIErrorHandler }, { useMutation, useQuery, useQueryClient });`;
19
+
20
+ const POLICIES = [
21
+ {
22
+ path: 'dist/admin/components/Policies/index.mjs',
23
+ hash: '79885141d11b26c4b37a443c74e82dea00d9633f34c495aa084238453bdfc64f',
24
+ setup: esmSetup,
25
+ anchor: '}, key))',
26
+ insertion: ", ...(roleId ? [jsx(OwnerPermissionsRules, { id: roleId, selectedAction }, 'owner-' + roleId)] : [])]",
27
+ runtime: '',
28
+ },
29
+ {
30
+ path: 'dist/admin/components/Policies/index.js',
31
+ hash: '7c16d71d8201834c4be753232d04d4025ca21350a03f42b4625d3c185d7af21c',
32
+ setup: `const OwnerRulesReact = require('react');
33
+ const useMatch = require('react-router-dom').useMatch;
34
+ const OwnerPermissionsRules = (${createOwnerRules})(OwnerRulesReact, designSystem, require('@strapi/strapi/admin'), require('react-query'));`,
35
+ anchor: '}, key))',
36
+ insertion: ", ...(roleId ? [jsxRuntime.jsx(OwnerPermissionsRules, { id: roleId, selectedAction }, 'owner-' + roleId)] : [])]",
37
+ runtime: 'jsxRuntime.',
38
+ },
39
+ {
40
+ path: 'admin/src/components/Policies/index.jsx',
41
+ hash: 'f62fdbe2472d4587a78b19687f30e2baa3e35776f0f11da0aa625cec9e5321de',
42
+ setup: esmSetup,
43
+ anchor: ' ))}',
44
+ insertion: '\n {roleId && <OwnerPermissionsRules id={roleId} selectedAction={selectedAction} key={roleId} />}',
45
+ },
46
+ ];
47
+
48
+ function patchPolicies(code, variant) {
49
+ const hash = createHash('sha256').update(code).digest('hex');
50
+ const definition = 'const Policies =';
51
+ const map = 'children: displayedRoutes.map(';
52
+ if (
53
+ hash !== variant.hash || code.split(definition).length !== 2 ||
54
+ code.split(variant.anchor).length !== 2 ||
55
+ (variant.runtime !== undefined && code.split(map).length !== 2)
56
+ ) {
57
+ throw new Error(`[owner-permissions] Unexpected ${variant.path}. This Users & Permissions build has a different Roles panel. Review the integration before rebuilding.`);
58
+ }
59
+ const patch = code
60
+ .replace(definition, () => `${variant.setup}\n\n${definition}`)
61
+ .replace(/^( +)const \{ formatMessage \}/m, (_, indent) =>
62
+ `${indent}const roleId = useMatch('/settings/users-permissions/roles/:id')?.params.id;\n${indent}const { formatMessage }`);
63
+ if (variant.runtime === undefined) {
64
+ return patch.replace(variant.anchor, () => variant.anchor + variant.insertion);
65
+ }
66
+ return patch
67
+ .replace(
68
+ `children: selectedAction ? /*#__PURE__*/ ${variant.runtime}jsx(`,
69
+ `children: selectedAction ? /*#__PURE__*/ ${variant.runtime}jsxs(`,
70
+ )
71
+ .replace(map, 'children: [...displayedRoutes.map(')
72
+ .replace(variant.anchor, () => variant.anchor + variant.insertion);
73
+ }
74
+
75
+ function roleEditorPlugin() {
76
+ let policyPanels = new Map();
77
+ let patched = false;
78
+ return {
79
+ name: NAME,
80
+ enforce: 'pre',
81
+ configResolved(config) {
82
+ const requireFromApp = createRequire(resolve(config.root, 'package.json'));
83
+ const manifest = requireFromApp.resolve(DEPENDENCY + '/package.json');
84
+ const { version } = requireFromApp(manifest);
85
+ const stableStrapi5 = /^5\.(\d+)\.\d+$/.exec(version);
86
+ if (!stableStrapi5 || Number(stableStrapi5[1]) < MINIMUM_MINOR) {
87
+ throw new Error(`[owner-permissions] Native Role editor requires ${DEPENDENCY} >=5.${MINIMUM_MINOR}.0 <6. Installed version: ${version}.`);
88
+ }
89
+ policyPanels = new Map(POLICIES.map((variant) => [
90
+ realpathSync(join(dirname(manifest), variant.path)), variant,
91
+ ]));
92
+ },
93
+ transform(code, id) {
94
+ if (!id.split('?')[0].includes('/Policies/index.')) return null;
95
+ let filename;
96
+ try {
97
+ filename = realpathSync(id.split('?')[0]);
98
+ } catch {
99
+ return null;
100
+ }
101
+ const variant = policyPanels.get(filename);
102
+ if (!variant) return null;
103
+ const source = patchPolicies(code, variant);
104
+ patched = true;
105
+ return { code: source, map: null };
106
+ },
107
+ generateBundle() {
108
+ if (!patched) {
109
+ this.error('[owner-permissions] The native Users & Permissions Roles editor was not reached by the admin build.');
110
+ }
111
+ },
112
+ };
113
+ }
114
+
115
+ function withOwnerPermissionsRoleEditor(config) {
116
+ const exclude = config.optimizeDeps?.exclude ?? [];
117
+ return {
118
+ ...config,
119
+ optimizeDeps: {
120
+ ...config.optimizeDeps,
121
+ exclude: [...new Set([...exclude, DEPENDENCY, DEPENDENCY + '/strapi-admin'])],
122
+ },
123
+ plugins: [...(config.plugins ?? []), roleEditorPlugin()],
124
+ };
125
+ }
126
+
127
+ module.exports = { withOwnerPermissionsRoleEditor };
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
+ "version": "0.1.0",
3
+ "keywords": [
4
+ "strapi",
5
+ "strapi-plugin",
6
+ "authorization",
7
+ "ownership"
8
+ ],
9
+ "type": "commonjs",
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ "./strapi-server": "./strapi-server.js",
13
+ "./admin-patch": "./admin-patch/index.cjs"
14
+ },
15
+ "files": [
16
+ "strapi-server.js",
17
+ "admin-patch/index.cjs",
18
+ "admin-patch/OwnerRules.cjs",
19
+ "docs/images"
20
+ ],
21
+ "scripts": {
22
+ "build": "strapi-plugin build",
23
+ "watch": "strapi-plugin watch",
24
+ "watch:link": "strapi-plugin watch:link",
25
+ "verify": "strapi-plugin verify",
26
+ "test:ts:front": "tsc -p admin/tsconfig.json",
27
+ "test:ts:back": "tsc -p server/tsconfig.json",
28
+ "test:integration": "node --test test/integration.test.js",
29
+ "test:admin": "node --test admin-patch/roles-editor.test.cjs"
30
+ },
31
+ "devDependencies": {
32
+ "@strapi/design-system": "^2.2.1",
33
+ "@strapi/icons": "^2.2.1",
34
+ "@strapi/sdk-plugin": "^6.1.1",
35
+ "@strapi/strapi": "^5.49.0",
36
+ "@strapi/typescript-utils": "^5.49.0",
37
+ "@types/react": "^18.3.31",
38
+ "@types/react-dom": "^18.3.7",
39
+ "prettier": "^3.9.1",
40
+ "react": "^18.3.1",
41
+ "react-dom": "^18.3.1",
42
+ "react-intl": "^6.8.9",
43
+ "react-router-dom": "^6.30.4",
44
+ "styled-components": "^6.4.3",
45
+ "typescript": "^5.9.3"
46
+ },
47
+ "peerDependencies": {
48
+ "@strapi/design-system": "^2.2.1",
49
+ "@strapi/icons": "^2.2.1",
50
+ "@strapi/plugin-users-permissions": "^5.49.0",
51
+ "@strapi/sdk-plugin": "^6.1.1",
52
+ "@strapi/strapi": "^5.49.0",
53
+ "react": "^18.3.1",
54
+ "react-dom": "^18.3.1",
55
+ "react-intl": "^6.8.9",
56
+ "react-router-dom": "^6.30.4",
57
+ "styled-components": "^6.4.3"
58
+ },
59
+ "strapi": {
60
+ "kind": "plugin",
61
+ "name": "owner-permissions",
62
+ "displayName": "Owner Permissions",
63
+ "description": "Automatically adds owner-based permissions to Strapi content types, allowing authenticated users to access only records they own."
64
+ },
2
65
  "name": "@3xweb/strapi-plugin-owner-permissions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
66
+ "description": "Automatically adds owner-based permissions to Strapi content types, allowing authenticated users to access only records they own.",
67
+ "license": "MIT",
68
+ "repository": {
69
+ "type": "git",
70
+ "url": "git+ssh://git@github.com/3xweb/strapi-plugin-owner-permissions.git"
71
+ },
72
+ "bugs": {
73
+ "url": "https://github.com/3xweb/strapi-plugin-owner-permissions/issues"
74
+ },
75
+ "homepage": "https://github.com/3xweb/strapi-plugin-owner-permissions#readme",
76
+ "author": "Douglas Everbero <douglas@3xweb.site>",
77
+ "publishConfig": {
78
+ "access": "public"
79
+ }
80
+ }
@@ -0,0 +1,260 @@
1
+ 'use strict';
2
+
3
+ const USER = 'plugin::users-permissions.user';
4
+ const ROLE = 'plugin::users-permissions.role';
5
+ const MAPPING = 'plugin::owner-permissions.role-mapping';
6
+ const ROLE_READ = 'plugin::users-permissions.roles.read';
7
+ const ROLE_UPDATE = 'plugin::users-permissions.roles.update';
8
+ const REQUEST_RULES = Symbol('owner-permissions.rules');
9
+ const ACTIONS = new Map([
10
+ ['findMany', 'find'],
11
+ ['count', 'find'],
12
+ ['findOne', 'findOne'],
13
+ ['create', 'create'],
14
+ ['update', 'update'],
15
+ ['delete', 'delete'],
16
+ ]);
17
+ const CORE_ACTIONS = [...new Set(ACTIONS.values())];
18
+ function isOwnerField(attribute) {
19
+ return attribute?.type === 'relation' && attribute.relation === 'manyToOne' &&
20
+ attribute.target === USER && !attribute.inversedBy && !attribute.mappedBy &&
21
+ attribute.private === true;
22
+ }
23
+
24
+ function discoverEligible(strapi) {
25
+ if (strapi.plugins.graphql) return [];
26
+
27
+ // Populated data can be loaded without invoking the target model's middleware.
28
+ const blockedTargets = new Set();
29
+ const schemas = { ...strapi.contentTypes, ...strapi.components };
30
+ for (const [uid, schema] of Object.entries(schemas)) {
31
+ for (const [field, attribute] of Object.entries(schema.attributes)) {
32
+ if (field === 'localizations' && uid === attribute.target) continue;
33
+ if (attribute.type === 'relation' && attribute.target) blockedTargets.add(attribute.target);
34
+ }
35
+ }
36
+
37
+ const models = [];
38
+ for (const [uid, schema] of Object.entries(strapi.contentTypes)) {
39
+ if (!uid.startsWith('api::') || schema.kind !== 'collectionType' ||
40
+ schema.options?.draftAndPublish || schema.pluginOptions?.i18n?.localized ||
41
+ blockedTargets.has(uid)) continue;
42
+
43
+ const fields = Object.entries(schema.attributes).filter(
44
+ ([field]) => !['createdBy', 'updatedBy', 'localizations'].includes(field),
45
+ );
46
+ const relations = fields.filter(
47
+ ([, attribute]) => ['relation', 'media', 'component', 'dynamiczone'].includes(attribute.type),
48
+ );
49
+ if (!relations.length || relations.some(([, attribute]) => !isOwnerField(attribute))) continue;
50
+
51
+ models.push({ uid, label: schema.info.displayName, ownerFields: relations.map(([field]) => field) });
52
+ }
53
+ return models;
54
+ }
55
+
56
+ function normalizeMapping(mapping) {
57
+ return typeof mapping === 'string'
58
+ ? { ownerField: mapping, actions: CORE_ACTIONS }
59
+ : mapping;
60
+ }
61
+
62
+ function serializeMappings(mappings) {
63
+ return Object.fromEntries(
64
+ Object.entries(mappings).map(([uid, mapping]) => [uid, normalizeMapping(mapping)]),
65
+ );
66
+ }
67
+
68
+ function firstInvalidMapping(mappings, eligible) {
69
+ return Object.entries(mappings).find(
70
+ ([uid, mapping]) => {
71
+ const rule = normalizeMapping(mapping);
72
+ return !rule || !Array.isArray(rule.actions) || rule.actions.length === 0 ||
73
+ new Set(rule.actions).size !== rule.actions.length ||
74
+ rule.actions.some((action) => !CORE_ACTIONS.includes(action)) ||
75
+ !eligible.some((model) => model.uid === uid && model.ownerFields.includes(rule.ownerField));
76
+ },
77
+ );
78
+ }
79
+
80
+ function roleRoutes() {
81
+ return [
82
+ { method: 'GET', handler: 'roles.find', action: ROLE_READ },
83
+ { method: 'PUT', handler: 'roles.update', action: ROLE_UPDATE },
84
+ ].map(({ method, handler, action }) => ({
85
+ method,
86
+ path: '/roles/:id',
87
+ handler,
88
+ config: {
89
+ policies: [{ name: 'admin::hasPermissions', config: { actions: [action] } }],
90
+ },
91
+ }));
92
+ }
93
+
94
+ function roleController({ strapi }) {
95
+ const query = (uid) => strapi.db.query(uid);
96
+ const getRole = async (ctx) => {
97
+ const id = Number(ctx.params.id);
98
+ if (!/^\d+$/.test(ctx.params.id) || !Number.isSafeInteger(id) || id < 1) {
99
+ ctx.throw(400, 'Invalid role ID');
100
+ }
101
+ const role = await query(ROLE).findOne({ where: { id }, select: ['id', 'type'] });
102
+ if (!role) ctx.throw(404, 'Role not found');
103
+ return role;
104
+ };
105
+ const getSettings = async (role) => query(MAPPING).findOne({ where: { roleId: role.id } });
106
+ const canConfigure = (ctx, role) =>
107
+ role.type !== 'public' && Boolean(ctx.state.userAbility?.can(ROLE_UPDATE));
108
+
109
+ return {
110
+ async find(ctx) {
111
+ const role = await getRole(ctx);
112
+ const settings = await getSettings(role);
113
+ ctx.body = {
114
+ data: {
115
+ eligible: discoverEligible(strapi),
116
+ mappings: serializeMappings(settings?.mappings ?? {}),
117
+ canConfigure: canConfigure(ctx, role),
118
+ },
119
+ };
120
+ },
121
+ async update(ctx) {
122
+ const role = await getRole(ctx);
123
+ if (!canConfigure(ctx, role)) ctx.throw(403, 'This role cannot use ownership rules');
124
+ const input = ctx.request.body?.mappings;
125
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
126
+ ctx.throw(400, 'mappings must be an object keyed by content type UID');
127
+ }
128
+
129
+ const eligible = discoverEligible(strapi);
130
+ const mappings = serializeMappings(input);
131
+ const invalid = firstInvalidMapping(mappings, eligible);
132
+ if (invalid) ctx.throw(400, `Unsupported ownership mapping: ${invalid[0]}`);
133
+
134
+ const settings = await getSettings(role);
135
+ if (settings) {
136
+ await query(MAPPING).update({ where: { id: settings.id }, data: { mappings } });
137
+ } else {
138
+ await query(MAPPING).create({ data: { roleId: role.id, mappings } });
139
+ }
140
+ ctx.body = { data: { eligible, mappings, canConfigure: true } };
141
+ },
142
+ };
143
+ }
144
+
145
+ function ownerFilter(field, userId) {
146
+ return { [field]: { id: { $eq: userId } } };
147
+ }
148
+
149
+ function addOwnerFilter(params, filter) {
150
+ params.filters = params.filters ? { $and: [params.filters, filter] } : filter;
151
+ }
152
+
153
+ function installOwnership(strapi) {
154
+ strapi.documents.use(async (context, next) => {
155
+ const { uid, action, params } = context;
156
+ const ctx = strapi.requestContext.get();
157
+ if (!uid.startsWith('api::') || ctx?.state.route?.info?.type !== 'content-api') {
158
+ return next();
159
+ }
160
+ ctx.state[REQUEST_RULES] ??= strapi.db.query(MAPPING).findMany({
161
+ select: ['roleId', 'mappings'],
162
+ });
163
+ const rules = (await ctx.state[REQUEST_RULES]).filter(({ mappings }) => Object.hasOwn(mappings, uid));
164
+ if (!rules.length) return next();
165
+
166
+ const auth = ctx.state.auth;
167
+ const user = auth?.strategy?.name === 'users-permissions' ? auth.credentials : null;
168
+ const rule = rules.find(({ roleId }) => roleId === user?.role?.id);
169
+ if (!user?.id || !user.documentId || !rule) {
170
+ ctx.throw(403, 'An authorized user account is required for this content');
171
+ }
172
+ const { ownerField, actions } = normalizeMapping(rule.mappings[uid]);
173
+
174
+ const coreAction = ACTIONS.get(action);
175
+ if (!coreAction) {
176
+ ctx.throw(403, 'This document action is disabled');
177
+ }
178
+ if (params.populate !== undefined || ctx.query.populate !== undefined) {
179
+ ctx.throw(400, 'Populating protected content is unsupported');
180
+ }
181
+
182
+ if (actions.includes(coreAction)) {
183
+ const filter = ownerFilter(ownerField, user.id);
184
+ if (['find', 'findOne', 'delete'].includes(coreAction)) {
185
+ addOwnerFilter(params, filter);
186
+ }
187
+ if (['findOne', 'update', 'delete'].includes(coreAction)) {
188
+ if (typeof params.documentId !== 'string' || !params.documentId.trim()) {
189
+ ctx.throw(400, 'A documentId is required');
190
+ }
191
+ // update() does not propagate filters to its primary lookup in Strapi 5.
192
+ // The owner relation is immutable for client writes.
193
+ const record = await strapi.db.query(uid).findOne({
194
+ select: ['id'],
195
+ where: { documentId: params.documentId, ...filter },
196
+ });
197
+ if (!record) ctx.throw(404, 'Document not found');
198
+ }
199
+ }
200
+
201
+ if (coreAction === 'create' || coreAction === 'update') {
202
+ const input = ctx.request.body?.data;
203
+ const ownerFields = Object.entries(strapi.contentTypes[uid].attributes)
204
+ .filter(([, attribute]) => isOwnerField(attribute))
205
+ .map(([field]) => field);
206
+ if (ownerFields.some((field) =>
207
+ (input && Object.hasOwn(input, field)) || (params.data && Object.hasOwn(params.data, field))
208
+ )) {
209
+ ctx.throw(400, 'The owner relation is assigned by the server');
210
+ }
211
+ if (coreAction === 'create') {
212
+ params.data = { ...params.data, [ownerField]: user.documentId };
213
+ }
214
+ }
215
+ return next();
216
+ });
217
+ }
218
+
219
+ module.exports = {
220
+ config: {
221
+ default: {},
222
+ validator(config) {
223
+ if (Object.hasOwn(config, 'mappings')) {
224
+ throw new Error('Migrate file-based mappings to Roles settings before removing the old rule. See the README.');
225
+ }
226
+ },
227
+ },
228
+ contentTypes: {
229
+ 'role-mapping': {
230
+ schema: {
231
+ kind: 'collectionType',
232
+ collectionName: 'owner_permissions_role_mappings',
233
+ info: {
234
+ singularName: 'role-mapping',
235
+ pluralName: 'role-mappings',
236
+ displayName: 'Ownership rules by role',
237
+ },
238
+ options: { draftAndPublish: false },
239
+ pluginOptions: {
240
+ 'content-manager': { visible: false },
241
+ 'content-type-builder': { visible: false },
242
+ },
243
+ attributes: {
244
+ roleId: { type: 'integer', required: true, unique: true, private: true },
245
+ mappings: { type: 'json', required: true, private: true },
246
+ },
247
+ },
248
+ },
249
+ },
250
+ controllers: { roles: roleController },
251
+ routes: { admin: { type: 'admin', routes: roleRoutes() } },
252
+ async bootstrap({ strapi }) {
253
+ const eligible = discoverEligible(strapi);
254
+ for (const { mappings } of await strapi.db.query(MAPPING).findMany()) {
255
+ const invalid = firstInvalidMapping(mappings, eligible);
256
+ if (invalid) throw new Error(`[owner-permissions] persisted mapping no longer supported: ${invalid[0]}`);
257
+ }
258
+ installOwnership(strapi);
259
+ },
260
+ };