@strapi/permissions 4.12.0 → 4.12.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/permissions",
3
- "version": "4.12.0",
3
+ "version": "4.12.2",
4
4
  "description": "Strapi's permission layer.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,21 +19,34 @@
19
19
  "url": "https://strapi.io"
20
20
  }
21
21
  ],
22
- "main": "./lib/index.js",
22
+ "files": [
23
+ "./dist"
24
+ ],
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
23
27
  "scripts": {
28
+ "build": "run -T tsc",
29
+ "build:ts": "run build",
30
+ "watch": "run -T tsc -w --preserveWatchOutput",
31
+ "clean": "run -T rimraf ./dist",
32
+ "prepublishOnly": "yarn clean && yarn build",
24
33
  "test:unit": "run -T jest",
25
34
  "test:unit:watch": "run -T jest --watch",
26
35
  "lint": "run -T eslint ."
27
36
  },
28
37
  "dependencies": {
29
38
  "@casl/ability": "5.4.4",
30
- "@strapi/utils": "4.12.0",
39
+ "@strapi/utils": "4.12.2",
31
40
  "lodash": "4.17.21",
32
41
  "sift": "16.0.1"
33
42
  },
43
+ "devDependencies": {
44
+ "eslint-config-custom": "4.12.2",
45
+ "tsconfig": "4.12.2"
46
+ },
34
47
  "engines": {
35
- "node": ">=14.19.1 <=18.x.x",
48
+ "node": ">=16.0.0 <=20.x.x",
36
49
  "npm": ">=6.0.0"
37
50
  },
38
- "gitHead": "7f8109a1a736c1d997fbb445469b3b59550c7aeb"
51
+ "gitHead": "b5a0cb4020ee9b170243e458decd5b1babf474e3"
39
52
  }
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- node_modules/
2
- .eslintrc.js
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- extends: ['custom/back'],
4
- };
package/index.d.ts DELETED
@@ -1,54 +0,0 @@
1
- import { hooks, providerFactory } from '@strapi/utils';
2
-
3
- interface Permission {
4
- action: string;
5
- subject?: string | object | null;
6
- properties?: object;
7
- conditions?: string[];
8
- }
9
-
10
- type Provider = ReturnType<typeof providerFactory>;
11
-
12
- interface BaseAction {
13
- actionId: string;
14
- }
15
-
16
- interface BaseCondition {
17
- name: string;
18
- handler(...params: unknown[]): boolean | object;
19
- }
20
-
21
- interface ActionProvider<T extends Action = Action> extends Provider {}
22
- interface ConditionProvider<T extends Condition = Condition> extends Provider {}
23
-
24
- interface PermissionEngineHooks {
25
- 'before-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
26
- 'format.permission': ReturnType<typeof hooks.createAsyncSeriesWaterfallHook>;
27
- 'after-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
28
- 'before-evaluate.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
29
- 'before-register.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
30
- }
31
-
32
- type PermissionEngineHookName = keyof PermissionEngineHooks;
33
-
34
- interface PermissionEngine {
35
- hooks: object;
36
-
37
- on(hook: PermissionEngineHookName, handler: Function): PermissionEngine;
38
- generateAbility(permissions: Permission[], options?: object): Ability;
39
- createRegisterFunction(can: Function, options: object): Function;
40
- }
41
-
42
- interface BaseAbility {
43
- can: Function;
44
- }
45
-
46
- interface AbilityBuilder {
47
- can(permission: Permission): void | Promise<void>;
48
- build(): BaseAbility | Promise<BaseAbility>;
49
- }
50
-
51
- interface PermissionEngineParams {
52
- providers: { action: ActionProvider; condition: ConditionProvider };
53
- abilityBuilderFactory(): AbilityBuilder;
54
- }
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- const permission = require('./permission');
4
-
5
- module.exports = {
6
- permission,
7
- };
@@ -1,68 +0,0 @@
1
- 'use strict';
2
-
3
- const _ = require('lodash/fp');
4
-
5
- const PERMISSION_FIELDS = ['action', 'subject', 'properties', 'conditions'];
6
-
7
- const sanitizePermissionFields = _.pick(PERMISSION_FIELDS);
8
-
9
- /**
10
- * @typedef {import("../../..").Permission} Permission
11
- */
12
-
13
- /**
14
- * Creates a permission with default values for optional properties
15
- *
16
- * @return {Pick<Permission, 'conditions' | 'properties' | 'subject'>}
17
- */
18
- const getDefaultPermission = () => ({
19
- conditions: [],
20
- properties: {},
21
- subject: null,
22
- });
23
-
24
- /**
25
- * Create a new permission based on given attributes
26
- *
27
- * @param {object} attributes
28
- *
29
- * @return {Permission}
30
- */
31
- const create = _.pipe(_.pick(PERMISSION_FIELDS), _.merge(getDefaultPermission()));
32
-
33
- /**
34
- * Add a condition to a permission
35
- *
36
- * @param {string} condition The condition to add
37
- * @param {Permission} permission The permission on which we want to add the condition
38
- *
39
- * @return {Permission}
40
- */
41
- const addCondition = _.curry((condition, permission) => {
42
- const { conditions } = permission;
43
-
44
- const newConditions = Array.isArray(conditions)
45
- ? _.uniq(conditions.concat(condition))
46
- : [condition];
47
-
48
- return _.set('conditions', newConditions, permission);
49
- });
50
-
51
- /**
52
- * Gets a property or a part of a property from a permission.
53
- *
54
- * @function
55
- *
56
- * @param {string} property - The property to get
57
- * @param {Permission} permission - The permission on which we want to access the property
58
- *
59
- * @return {Permission}
60
- */
61
- const getProperty = _.curry((property, permission) => _.get(`properties.${property}`, permission));
62
-
63
- module.exports = {
64
- create,
65
- sanitizePermissionFields,
66
- addCondition,
67
- getProperty,
68
- };
@@ -1,57 +0,0 @@
1
- 'use strict';
2
-
3
- const sift = require('sift');
4
- const { AbilityBuilder, Ability } = require('@casl/ability');
5
- const { pick, isNil, isObject } = require('lodash/fp');
6
-
7
- const allowedOperations = [
8
- '$or',
9
- '$and',
10
- '$eq',
11
- '$ne',
12
- '$in',
13
- '$nin',
14
- '$lt',
15
- '$lte',
16
- '$gt',
17
- '$gte',
18
- '$exists',
19
- '$elemMatch',
20
- ];
21
-
22
- const operations = pick(allowedOperations, sift);
23
-
24
- const conditionsMatcher = (conditions) => {
25
- return sift.createQueryTester(conditions, { operations });
26
- };
27
-
28
- /**
29
- * Casl Ability Builder.
30
- */
31
- const caslAbilityBuilder = () => {
32
- const { can, build, ...rest } = new AbilityBuilder(Ability);
33
-
34
- return {
35
- can(permission) {
36
- const { action, subject, properties = {}, condition } = permission;
37
- const { fields } = properties;
38
-
39
- return can(
40
- action,
41
- isNil(subject) ? 'all' : subject,
42
- fields,
43
- isObject(condition) ? condition : undefined
44
- );
45
- },
46
-
47
- build() {
48
- return build({ conditionsMatcher });
49
- },
50
-
51
- ...rest,
52
- };
53
- };
54
-
55
- module.exports = {
56
- caslAbilityBuilder,
57
- };
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- const { caslAbilityBuilder } = require('./casl-ability');
4
-
5
- module.exports = {
6
- caslAbilityBuilder,
7
- };
@@ -1,97 +0,0 @@
1
- 'use strict';
2
-
3
- const { cloneDeep, has } = require('lodash/fp');
4
- const { hooks } = require('@strapi/utils');
5
-
6
- const domain = require('../domain');
7
-
8
- /**
9
- * Create a hook map used by the permission Engine
10
- *
11
- * @return {import('../..').PermissionEngineHooks}
12
- */
13
- const createEngineHooks = () => ({
14
- 'before-format::validate.permission': hooks.createAsyncBailHook(),
15
- 'format.permission': hooks.createAsyncSeriesWaterfallHook(),
16
- 'after-format::validate.permission': hooks.createAsyncBailHook(),
17
- 'before-evaluate.permission': hooks.createAsyncSeriesHook(),
18
- 'before-register.permission': hooks.createAsyncSeriesHook(),
19
- });
20
-
21
- /**
22
- * Create a context from a domain {@link Permission} used by the validate hooks
23
- * @param {Permission} permission
24
- * @return {{ readonly permission: Permission }}
25
- */
26
- const createValidateContext = (permission) => ({
27
- get permission() {
28
- return cloneDeep(permission);
29
- },
30
- });
31
-
32
- /**
33
- * Create a context from a domain {@link Permission} used by the before valuate hook
34
- * @param {Permission} permission
35
- * @return {{readonly permission: Permission, addCondition(string): this}}
36
- */
37
- const createBeforeEvaluateContext = (permission) => ({
38
- get permission() {
39
- return cloneDeep(permission);
40
- },
41
-
42
- addCondition(condition) {
43
- Object.assign(permission, domain.permission.addCondition(condition, permission));
44
-
45
- return this;
46
- },
47
- });
48
-
49
- /**
50
- * Create a context from a casl Permission & some options
51
- * @param caslPermission
52
- * @param {object} options
53
- * @param {Permission} options.permission
54
- * @param {object} options.user
55
- */
56
- const createWillRegisterContext = ({ permission, options }) => ({
57
- ...options,
58
-
59
- get permission() {
60
- return cloneDeep(permission);
61
- },
62
-
63
- condition: {
64
- and(rawConditionObject) {
65
- if (!permission.condition) {
66
- Object.assign(permission, { condition: { $and: [] } });
67
- }
68
-
69
- permission.condition.$and.push(rawConditionObject);
70
-
71
- return this;
72
- },
73
-
74
- or(rawConditionObject) {
75
- if (!permission.condition) {
76
- Object.assign(permission, { condition: { $and: [] } });
77
- }
78
-
79
- const orClause = permission.condition.$and.find(has('$or'));
80
-
81
- if (orClause) {
82
- orClause.$or.push(rawConditionObject);
83
- } else {
84
- permission.condition.$and.push({ $or: [rawConditionObject] });
85
- }
86
-
87
- return this;
88
- },
89
- },
90
- });
91
-
92
- module.exports = {
93
- createEngineHooks,
94
- createValidateContext,
95
- createBeforeEvaluateContext,
96
- createWillRegisterContext,
97
- };
@@ -1,209 +0,0 @@
1
- 'use strict';
2
-
3
- const _ = require('lodash/fp');
4
-
5
- const abilities = require('./abilities');
6
-
7
- const {
8
- createEngineHooks,
9
- createWillRegisterContext,
10
- createBeforeEvaluateContext,
11
- createValidateContext,
12
- } = require('./hooks');
13
-
14
- /**
15
- * @typedef {import("../..").PermissionEngine} PermissionEngine
16
- * @typedef {import("../..").ActionProvider} ActionProvider
17
- * @typedef {import("../..").ConditionProvider} ConditionProvider
18
- * @typedef {import("../..").PermissionEngineParams} PermissionEngineParams
19
- * @typedef {import("../..").Permission} Permission
20
- */
21
-
22
- /**
23
- * Create a default state object for the engine
24
- */
25
- const createEngineState = () => {
26
- const hooks = createEngineHooks();
27
-
28
- return { hooks };
29
- };
30
-
31
- module.exports = {
32
- abilities,
33
-
34
- /**
35
- * Create a new instance of a permission engine
36
- *
37
- * @param {PermissionEngineParams} params
38
- *
39
- * @return {PermissionEngine}
40
- */
41
- new(params) {
42
- const { providers, abilityBuilderFactory = abilities.caslAbilityBuilder } = params;
43
-
44
- const state = createEngineState();
45
-
46
- const runValidationHook = async (hook, context) => state.hooks[hook].call(context);
47
-
48
- /**
49
- * Evaluate a permission using local and registered behaviors (using hooks).
50
- * Validate, format (add condition, etc...), evaluate (evaluate conditions) and register a permission
51
- *
52
- * @param {object} params
53
- * @param {object} params.options
54
- * @param {Function} params.register
55
- * @param {Permission} params.permission
56
- */
57
- const evaluate = async (params) => {
58
- const { options, register } = params;
59
-
60
- const preFormatValidation = await runValidationHook(
61
- 'before-format::validate.permission',
62
- createBeforeEvaluateContext(params.permission)
63
- );
64
-
65
- if (preFormatValidation === false) {
66
- return;
67
- }
68
-
69
- const permission = await state.hooks['format.permission'].call(params.permission);
70
-
71
- const afterFormatValidation = await runValidationHook(
72
- 'after-format::validate.permission',
73
- createValidateContext(permission)
74
- );
75
-
76
- if (afterFormatValidation === false) {
77
- return;
78
- }
79
-
80
- await state.hooks['before-evaluate.permission'].call(createBeforeEvaluateContext(permission));
81
-
82
- const { action, subject, properties, conditions = [] } = permission;
83
-
84
- if (conditions.length === 0) {
85
- return register({ action, subject, properties });
86
- }
87
-
88
- const resolveConditions = _.map(providers.condition.get);
89
-
90
- const removeInvalidConditions = _.filter((condition) => _.isFunction(condition.handler));
91
-
92
- const evaluateConditions = (conditions) => {
93
- return Promise.all(
94
- conditions.map(async (condition) => ({
95
- condition,
96
- result: await condition.handler(
97
- _.merge(options, { permission: _.cloneDeep(permission) })
98
- ),
99
- }))
100
- );
101
- };
102
-
103
- const removeInvalidResults = _.filter(
104
- ({ result }) => _.isBoolean(result) || _.isObject(result)
105
- );
106
-
107
- const evaluatedConditions = await Promise.resolve(conditions)
108
- .then(resolveConditions)
109
- .then(removeInvalidConditions)
110
- .then(evaluateConditions)
111
- .then(removeInvalidResults);
112
-
113
- const resultPropEq = _.propEq('result');
114
- const pickResults = _.map(_.prop('result'));
115
-
116
- if (evaluatedConditions.every(resultPropEq(false))) {
117
- return;
118
- }
119
-
120
- if (_.isEmpty(evaluatedConditions) || evaluatedConditions.some(resultPropEq(true))) {
121
- return register({ action, subject, properties });
122
- }
123
-
124
- const results = pickResults(evaluatedConditions).filter(_.isObject);
125
-
126
- if (_.isEmpty(results)) {
127
- return register({ action, subject, properties });
128
- }
129
-
130
- return register({
131
- action,
132
- subject,
133
- properties,
134
- condition: { $and: [{ $or: results }] },
135
- });
136
- };
137
-
138
- return {
139
- get hooks() {
140
- return state.hooks;
141
- },
142
-
143
- /**
144
- * Create a register function that wraps a `can` function
145
- * used to register a permission in the ability builder
146
- *
147
- * @param {Function} can
148
- * @param {object} options
149
- *
150
- * @return {Function}
151
- */
152
- createRegisterFunction(can, options) {
153
- return async (permission) => {
154
- const hookContext = createWillRegisterContext({ options, permission });
155
-
156
- await state.hooks['before-register.permission'].call(hookContext);
157
-
158
- return can(permission);
159
- };
160
- },
161
-
162
- /**
163
- * Register a new handler for a given hook
164
- *
165
- * @param {string} hook
166
- * @param {Function} handler
167
- *
168
- * @return {this}
169
- */
170
- on(hook, handler) {
171
- const validHooks = Object.keys(state.hooks);
172
- const isValidHook = validHooks.includes(hook);
173
-
174
- if (!isValidHook) {
175
- throw new Error(
176
- `Invalid hook supplied when trying to register an handler to the permission engine. Got "${hook}" but expected one of ${validHooks.join(
177
- ', '
178
- )}`
179
- );
180
- }
181
-
182
- state.hooks[hook].register(handler);
183
-
184
- return this;
185
- },
186
-
187
- /**
188
- * Generate an ability based on the instance's
189
- * ability builder and the given permissions
190
- *
191
- * @param {Permission[]} permissions
192
- * @param {object} [options]
193
- *
194
- * @return {object}
195
- */
196
- async generateAbility(permissions, options = {}) {
197
- const { can, build } = abilityBuilderFactory();
198
-
199
- for (const permission of permissions) {
200
- const register = this.createRegisterFunction(can, options);
201
-
202
- await evaluate({ permission, options, register });
203
- }
204
-
205
- return build();
206
- },
207
- };
208
- },
209
- };
package/lib/index.js DELETED
@@ -1,9 +0,0 @@
1
- 'use strict';
2
-
3
- const domain = require('./domain');
4
- const engine = require('./engine');
5
-
6
- module.exports = {
7
- domain,
8
- engine,
9
- };