@3xweb/strapi-plugin-owner-permissions 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,21 @@
1
1
  # Owner Permissions for Strapi 5
2
2
 
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.
3
+ Owner Permissions limits access to user-generated content on the Strapi REST
4
+ Content API. The plugin can identify the owner in two ways:
5
+
6
+ - **Direct ownership** (`ownerPath: 'owner'`). A record links directly to
7
+ the user who owns it.
8
+ - **Ownership through a parent** (`ownerPath: 'parent.owner'`). A child
9
+ record links to a parent record. The plugin follows that link and uses
10
+ the parent's owner to decide who can access the child.
11
+
12
+ Configure the ownership path in the backend for each collection. Then open
13
+ **Settings → Users & Permissions → Roles** and enable the native permission
14
+ for the action. On the same page, click the gear next to that action, enable
15
+ **Only own records** in **Advanced settings**, and save the ownership rules.
16
+ The backend also defines which related details the API may return with
17
+ `populate`, such as a parent's list of child records. See
18
+ [Opt-in collection profiles](#opt-in-collection-profiles) for a complete example.
10
19
 
11
20
  ## Installation
12
21
 
@@ -136,6 +145,50 @@ the mapping configuration from plugins.js, and re-create the rules in the Roles
136
145
  screen before making the REST API available. The plugin refuses to start with the
137
146
  old configuration still present.
138
147
 
148
+ ### Opt-in collection profiles
149
+
150
+ Applications with a fixed REST relation graph can configure a collection
151
+ profile under `config.collections`:
152
+
153
+ ```ts
154
+ 'owner-permissions': {
155
+ enabled: true,
156
+ config: {
157
+ collections: {
158
+ 'api::parent.parent': {
159
+ ownerPath: 'owner',
160
+ populate: { children: true },
161
+ },
162
+ 'api::child.child': {
163
+ ownerPath: 'parent.owner',
164
+ populate: { parent: true },
165
+ },
166
+ },
167
+ },
168
+ },
169
+ ```
170
+
171
+ An opted-in collection denies Content API document operations until a role rule
172
+ explicitly grants the requested action. Provision those role rules before
173
+ making the collection available. The native Users & Permissions route grant
174
+ also remains required. A derived path uses one to-one or many-to-one parent
175
+ relation to another opted-in collection with a direct owner. Supply the parent
176
+ `documentId` as a string when creating a child. Client updates cannot move a
177
+ child to another parent or mutate the inverse relation from the parent.
178
+
179
+ The caller can populate the listed paths explicitly. Wildcards, nested filters
180
+ and sorts, and client filters and sorts on relations are rejected. Filter by
181
+ scalar fields such as `documentId`; the server applies ownership before
182
+ retrieval and pagination. The reciprocal edge of the derived parent may be
183
+ listed for population if Strapi's inverse relationship matches.
184
+
185
+ Other inbound schema relations are rejected during startup. A private reverse
186
+ relation on the Users & Permissions user is allowed when the application
187
+ blocks its exposure and mutation on the source User API. Keep custom API routes
188
+ that bypass the Document Service scoped to the caller and prevent them from
189
+ changing protected relationships. The application must preserve owner and
190
+ parent relationships while a Content API operation is in progress.
191
+
139
192
  ## Test locally
140
193
 
141
194
  Run `npm run test:integration` with Strapi 5, Users & Permissions and
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.1",
2
+ "version": "0.2.1",
3
3
  "keywords": [
4
4
  "strapi",
5
5
  "strapi-plugin",
@@ -29,7 +29,7 @@
29
29
  "verify": "strapi-plugin verify",
30
30
  "test:ts:front": "tsc -p admin/tsconfig.json",
31
31
  "test:ts:back": "tsc -p server/tsconfig.json",
32
- "test:integration": "node --test test/integration.test.js",
32
+ "test:integration": "node --test test/*.test.js",
33
33
  "test:admin": "node --test admin-patch/roles-editor.test.cjs"
34
34
  },
35
35
  "devDependencies": {
package/strapi-server.js CHANGED
@@ -8,6 +8,7 @@ const ROLE_UPDATE = 'plugin::users-permissions.roles.update';
8
8
  const REQUEST_RULES = Symbol('owner-permissions.rules');
9
9
  const ACTIONS = new Map([
10
10
  ['findMany', 'find'],
11
+ ['findFirst', 'find'],
11
12
  ['count', 'find'],
12
13
  ['findOne', 'findOne'],
13
14
  ['create', 'create'],
@@ -21,6 +22,102 @@ function isOwnerField(attribute) {
21
22
  attribute.private === true;
22
23
  }
23
24
 
25
+ function profileFor(strapi, uid) {
26
+ const profiles = strapi.config.get('plugin::owner-permissions.collections', {});
27
+ return Object.hasOwn(profiles, uid) ? profiles[uid] : undefined;
28
+ }
29
+
30
+ function requireProfile(condition, uid, message) {
31
+ if (!condition) throw new Error(`[owner-permissions] ${uid}: ${message}`);
32
+ }
33
+
34
+ function supportsProfile(uid, schema) {
35
+ return uid.startsWith('api::') && schema?.kind === 'collectionType' &&
36
+ !schema.options?.draftAndPublish && !schema.pluginOptions?.i18n?.localized;
37
+ }
38
+
39
+ function ownerFieldsFor(strapi, uid, profile) {
40
+ const path = profile.ownerPath.split('.');
41
+ const [field, owner] = path;
42
+ const relation = strapi.contentTypes[uid]?.attributes[field];
43
+ const isToOne = relation?.type === 'relation' &&
44
+ ['manyToOne', 'oneToOne'].includes(relation.relation);
45
+ requireProfile(isToOne, uid, 'ownerPath must traverse a to-one relation');
46
+ if (path.length === 1) {
47
+ requireProfile(relation.target === USER && !relation.mappedBy, uid,
48
+ 'direct ownerPath must be a writable relation to Users & Permissions');
49
+ } else {
50
+ requireProfile(path.length === 2 && !relation.mappedBy &&
51
+ profileFor(strapi, relation.target)?.ownerPath === owner &&
52
+ strapi.contentTypes[relation.target]?.attributes[owner]?.target === USER,
53
+ uid, 'derived ownerPath must reference an opted-in parent with a direct owner');
54
+ }
55
+ return path;
56
+ }
57
+
58
+ function sharedOwnerEdge(strapi, uid, field, attribute) {
59
+ const source = profileFor(strapi, uid);
60
+ const target = profileFor(strapi, attribute.target);
61
+ if (!source || !target) return false;
62
+ if (source.ownerPath === `${field}.${target.ownerPath}`) return true;
63
+ const inverse = attribute.mappedBy;
64
+ return Boolean(inverse && target.ownerPath === `${inverse}.${source.ownerPath}` &&
65
+ strapi.contentTypes[attribute.target]?.attributes[inverse]?.target === uid &&
66
+ strapi.contentTypes[attribute.target]?.attributes[inverse]?.inversedBy === field);
67
+ }
68
+
69
+ function isRecord(value) {
70
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
71
+ }
72
+
73
+ function validateProfiles(strapi) {
74
+ const profiles = strapi.config.get('plugin::owner-permissions.collections', {});
75
+ requireProfile(isRecord(profiles), 'collections', 'must be an object keyed by UID');
76
+ requireProfile(!strapi.plugins.graphql || !Object.keys(profiles).length,
77
+ 'collections', 'GraphQL is unsupported');
78
+ const schemas = { ...strapi.contentTypes, ...strapi.components };
79
+ for (const [uid, profile] of Object.entries(profiles)) {
80
+ requireProfile(supportsProfile(uid, schemas[uid]) && isRecord(profile) &&
81
+ typeof profile.ownerPath === 'string' && isRecord(profile.populate ?? {}),
82
+ uid, 'invalid collection profile');
83
+ ownerFieldsFor(strapi, uid, profile);
84
+ }
85
+
86
+ function validatePopulate(uid, tree) {
87
+ for (const [field, children] of Object.entries(tree)) {
88
+ const attribute = schemas[uid]?.attributes[field];
89
+ requireProfile(attribute && !attribute.private &&
90
+ ['relation', 'component', 'media'].includes(attribute.type) &&
91
+ (children === true || isRecord(children)), uid, `invalid populate field: ${field}`);
92
+ if (attribute.type === 'relation') {
93
+ requireProfile(attribute.target !== USER && (!profiles[attribute.target] ||
94
+ sharedOwnerEdge(strapi, uid, field, attribute)), uid, `unsafe populate relation: ${field}`);
95
+ }
96
+ if (children !== true) {
97
+ requireProfile(attribute.type !== 'media', uid, `nested media populate is unsupported: ${field}`);
98
+ validatePopulate(attribute.component ?? attribute.target, children);
99
+ }
100
+ }
101
+ }
102
+
103
+ for (const [uid, profile] of Object.entries(profiles)) {
104
+ validatePopulate(uid, profile.populate ?? {});
105
+ }
106
+ for (const [uid, schema] of Object.entries(schemas)) {
107
+ for (const [field, attribute] of Object.entries(schema.attributes)) {
108
+ if (attribute.type !== 'relation' || !profiles[attribute.target]) continue;
109
+ if (field === 'localizations' && attribute.target === uid) continue;
110
+ const targetOwner = profiles[attribute.target].ownerPath;
111
+ const privateUserInverse = uid === USER && attribute.private === true &&
112
+ attribute.mappedBy === targetOwner &&
113
+ schemas[attribute.target].attributes[targetOwner]?.inversedBy === field;
114
+ requireProfile(sharedOwnerEdge(strapi, uid, field, attribute) ||
115
+ privateUserInverse, uid,
116
+ `uncontrolled inbound relation to ${attribute.target}: ${field}`);
117
+ }
118
+ }
119
+ }
120
+
24
121
  function discoverEligible(strapi) {
25
122
  if (strapi.plugins.graphql) return [];
26
123
 
@@ -36,9 +133,13 @@ function discoverEligible(strapi) {
36
133
 
37
134
  const models = [];
38
135
  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;
136
+ if (!supportsProfile(uid, schema)) continue;
137
+ const profile = profileFor(strapi, uid);
138
+ if (profile) {
139
+ models.push({ uid, label: schema.info.displayName, ownerFields: [profile.ownerPath] });
140
+ continue;
141
+ }
142
+ if (blockedTargets.has(uid)) continue;
42
143
 
43
144
  const fields = Object.entries(schema.attributes).filter(
44
145
  ([field]) => !['createdBy', 'updatedBy', 'localizations'].includes(field),
@@ -142,14 +243,135 @@ function roleController({ strapi }) {
142
243
  };
143
244
  }
144
245
 
145
- function ownerFilter(field, userId) {
146
- return { [field]: { id: { $eq: userId } } };
246
+ function ownerFilter(path, userId) {
247
+ return path.split('.').reduceRight((filter, field) => ({ [field]: filter }), {
248
+ id: { $eq: userId },
249
+ });
147
250
  }
148
251
 
149
252
  function addOwnerFilter(params, filter) {
150
253
  params.filters = params.filters ? { $and: [params.filters, filter] } : filter;
151
254
  }
152
255
 
256
+ function validateProfileQuery(ctx, strapi, uid, profile, roleMappings, query = {}) {
257
+ const schemas = { ...strapi.contentTypes, ...strapi.components };
258
+ function assertScalar(model, field) {
259
+ if (['id', 'documentId', 'createdAt', 'updatedAt', 'publishedAt', 'locale'].includes(field)) {
260
+ return;
261
+ }
262
+ const attribute = schemas[model]?.attributes[field];
263
+ if (!attribute || attribute.private ||
264
+ ['relation', 'component', 'media', 'dynamiczone', 'password', 'json'].includes(attribute.type)) {
265
+ ctx.throw(400, `Unsupported query field: ${field}`);
266
+ }
267
+ }
268
+
269
+ function validateFilters(filters) {
270
+ if (!isRecord(filters)) ctx.throw(400, 'Invalid ownership filters');
271
+ for (const [field, value] of Object.entries(filters)) {
272
+ if (['$and', '$or'].includes(field)) {
273
+ if (!Array.isArray(value)) ctx.throw(400, 'Invalid logical filter');
274
+ value.forEach(validateFilters);
275
+ } else if (field === '$not') {
276
+ validateFilters(value);
277
+ } else {
278
+ assertScalar(uid, field);
279
+ }
280
+ }
281
+ }
282
+
283
+ function validateSort(sort) {
284
+ if (typeof sort === 'string') {
285
+ sort.split(',').forEach((clause) => assertScalar(uid, clause.split(':')[0]));
286
+ } else if (Array.isArray(sort)) {
287
+ sort.forEach(validateSort);
288
+ } else if (isRecord(sort)) {
289
+ for (const [field, direction] of Object.entries(sort)) {
290
+ assertScalar(uid, field);
291
+ if (typeof direction !== 'string') ctx.throw(400, 'Invalid sort');
292
+ }
293
+ } else {
294
+ ctx.throw(400, 'Invalid sort');
295
+ }
296
+ }
297
+
298
+ function ensurePopulateField(model, allowed, field) {
299
+ if (typeof field !== 'string' || !Object.hasOwn(allowed, field)) {
300
+ ctx.throw(400, 'Use explicitly permitted populate fields');
301
+ }
302
+ const attribute = schemas[model]?.attributes[field];
303
+ if (attribute.type === 'relation' && profileFor(strapi, attribute.target) &&
304
+ !normalizeMapping(roleMappings[attribute.target])?.actions.includes('find')) {
305
+ ctx.throw(403, 'Access to the requested relation is disabled');
306
+ }
307
+ return attribute;
308
+ }
309
+
310
+ function validatePopulate(model, allowed, requested) {
311
+ if (typeof requested === 'string') {
312
+ requested = requested.split(',');
313
+ }
314
+ if (Array.isArray(requested)) {
315
+ requested.forEach((field) => ensurePopulateField(model, allowed, field));
316
+ return;
317
+ }
318
+ if (!isRecord(requested)) ctx.throw(400, 'Use explicitly permitted populate fields');
319
+ for (const [field, options] of Object.entries(requested)) {
320
+ if (options === false || options === 'false') continue;
321
+ const attribute = ensurePopulateField(model, allowed, field);
322
+ if (options === true || options === 'true') continue;
323
+ if (!isRecord(options) || Object.keys(options).some((key) => key !== 'populate' && key !== 'fields')) {
324
+ ctx.throw(400, 'Unsupported populate options');
325
+ }
326
+ const target = attribute.type === 'media' ? 'plugin::upload.file' :
327
+ attribute.component ?? attribute.target;
328
+ if (options.fields !== undefined) {
329
+ const fields = typeof options.fields === 'string' ? options.fields.split(',') : options.fields;
330
+ if (!Array.isArray(fields)) ctx.throw(400, 'Invalid selected fields');
331
+ fields.forEach((entry) => assertScalar(target, entry));
332
+ }
333
+ if (options.populate !== undefined) {
334
+ validatePopulate(target, allowed[field] === true ? {} : allowed[field], options.populate);
335
+ }
336
+ }
337
+ }
338
+
339
+ if (query.filters !== undefined) validateFilters(query.filters);
340
+ if (query.sort !== undefined) validateSort(query.sort);
341
+ if (query.populate !== undefined) validatePopulate(uid, profile.populate ?? {}, query.populate);
342
+ }
343
+
344
+ async function guardProfileWrite(ctx, strapi, uid, action, params, user, profile) {
345
+ const [field, parentOwner] = profile.ownerPath.split('.');
346
+ const input = ctx.request.body?.data;
347
+ const attributes = strapi.contentTypes[uid].attributes;
348
+ for (const [name, attribute] of Object.entries(attributes)) {
349
+ if (attribute.type !== 'relation' || (!profileFor(strapi, attribute.target) &&
350
+ attribute.target !== USER)) continue;
351
+ if (name === field && parentOwner && action === 'create') continue;
352
+ if ((input && Object.hasOwn(input, name)) || (params.data && Object.hasOwn(params.data, name))) {
353
+ ctx.throw(400, 'Protected relationships cannot be written directly');
354
+ }
355
+ }
356
+ if (action !== 'create') return;
357
+
358
+ if (!parentOwner) {
359
+ params.data = { ...params.data, [field]: user.id };
360
+ return;
361
+ }
362
+
363
+ const documentId = params.data?.[field];
364
+ if (typeof documentId !== 'string' || !documentId.trim()) {
365
+ ctx.throw(400, 'The parent documentId is required');
366
+ }
367
+ const parent = await strapi.db.query(attributes[field].target).findOne({
368
+ select: ['id'],
369
+ where: { documentId, ...ownerFilter(parentOwner, user.id) },
370
+ });
371
+ if (!parent) ctx.throw(404, 'Document not found');
372
+ params.data = { ...params.data, [field]: parent.id };
373
+ }
374
+
153
375
  function installOwnership(strapi) {
154
376
  strapi.documents.use(async (context, next) => {
155
377
  const { uid, action, params } = context;
@@ -161,7 +383,8 @@ function installOwnership(strapi) {
161
383
  select: ['roleId', 'mappings'],
162
384
  });
163
385
  const rules = (await ctx.state[REQUEST_RULES]).filter(({ mappings }) => Object.hasOwn(mappings, uid));
164
- if (!rules.length) return next();
386
+ const profile = profileFor(strapi, uid);
387
+ if (!profile && !rules.length) return next();
165
388
 
166
389
  const auth = ctx.state.auth;
167
390
  const user = auth?.strategy?.name === 'users-permissions' ? auth.credentials : null;
@@ -175,7 +398,11 @@ function installOwnership(strapi) {
175
398
  if (!coreAction) {
176
399
  ctx.throw(403, 'This document action is disabled');
177
400
  }
178
- if (params.populate !== undefined || ctx.query.populate !== undefined) {
401
+ if (profile) {
402
+ if (!actions.includes(coreAction)) ctx.throw(403, 'This document action is disabled');
403
+ validateProfileQuery(ctx, strapi, uid, profile, rule.mappings, ctx.query);
404
+ validateProfileQuery(ctx, strapi, uid, profile, rule.mappings, params);
405
+ } else if (params.populate !== undefined || ctx.query.populate !== undefined) {
179
406
  ctx.throw(400, 'Populating protected content is unsupported');
180
407
  }
181
408
 
@@ -198,7 +425,9 @@ function installOwnership(strapi) {
198
425
  }
199
426
  }
200
427
 
201
- if (coreAction === 'create' || coreAction === 'update') {
428
+ if (profile && (coreAction === 'create' || coreAction === 'update')) {
429
+ await guardProfileWrite(ctx, strapi, uid, coreAction, params, user, profile);
430
+ } else if (coreAction === 'create' || coreAction === 'update') {
202
431
  const input = ctx.request.body?.data;
203
432
  const ownerFields = Object.entries(strapi.contentTypes[uid].attributes)
204
433
  .filter(([, attribute]) => isOwnerField(attribute))
@@ -250,6 +479,7 @@ module.exports = {
250
479
  controllers: { roles: roleController },
251
480
  routes: { admin: { type: 'admin', routes: roleRoutes() } },
252
481
  async bootstrap({ strapi }) {
482
+ validateProfiles(strapi);
253
483
  const eligible = discoverEligible(strapi);
254
484
  for (const { mappings } of await strapi.db.query(MAPPING).findMany()) {
255
485
  const invalid = firstInvalidMapping(mappings, eligible);