@r2d2bzh/moleculer-authz-helpers 0.0.1 → 1.0.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.adoc CHANGED
@@ -20,9 +20,9 @@ Currently, this library provides the following helpers:
20
20
  == `addPreflightMixin`
21
21
 
22
22
  This helper adds a service mixin used to generate preflight actions for actions exposed through rest.
23
- It takes a Moleculer service schema as a parameter and return the same service schema with the mixin added.
23
+ It takes a Moleculer service schema as a parameter and returns the same service schema with the mixin added.
24
24
 
25
- NOTE: A preflight action takes the same parameters as its action.
25
+ NOTE: A preflight action takes the same parameters as the original action.
26
26
 
27
27
  To define a preflight handler, you must add a preflight attribute to an action:
28
28
 
@@ -38,24 +38,34 @@ To define a preflight handler, you must add a preflight attribute to an action:
38
38
  handler: (ctx) => {
39
39
  // do preflight checks
40
40
  // possibly request for some authorizations through Moleculer events
41
- }
42
- }
41
+ },
42
+ },
43
+ },
44
+ 'my-other-action': {
45
+ handler: myOtherActionHandler(),
46
+ rest: {},
47
+ preflight: (ctx) => {},
43
48
  },
44
49
  },
45
50
  }
46
51
  ----
47
52
 
48
- [NOTE]
53
+ [IMPORTANT]
49
54
  ====
50
- A preflight action declaration can be skipped:
55
+ Only actions where authorization is disabled do not enforce a preflight:
51
56
 
52
57
  [source,javascript]
53
58
  ----
54
- preflight: {
55
- skip: true,
56
- },
59
+ {
60
+ 'my-action': {
61
+ handler: myActionHandler(),
62
+ rest: {
63
+ authorization: false,
64
+ },
65
+ },
66
+ }
57
67
  ----
58
- ====
68
+ ====
59
69
 
60
70
  == `isAuthorized`
61
71
 
@@ -73,6 +83,19 @@ It implements the following rules:
73
83
  * if any answer is `false`, the whole authorization process fails
74
84
  * if no answer was provided, the whole authorization process fails
75
85
 
86
+ The signature of `isAuthorized` is `(logger) => (answer) => true | false`:
87
+
88
+ . the `logger` curried argument must provide a `warn` method used to issue warnings (default: `console`)
89
+ . the `answer` curried argument is the authorization answer(s) to one or many authorization requests
90
+
91
+ `isAuthorized` will raise a warning in the following cases:
92
+
93
+ * an odd authorization answer was provided, known answers are:
94
+ ** `true`:: the request is authorized
95
+ ** `false`:: the request is denied
96
+ ** `undefined`:: the responder is not able to answer
97
+ * multiple `true` or `false` answers were provided to the same authorization request
98
+
76
99
  == `requestAuthorizations`
77
100
 
78
101
  This helper operates multiple authorization requests at once and returns a promise which result can be handled by `isAuthorized`.
package/package.json CHANGED
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "@r2d2bzh/moleculer-authz-helpers",
3
- "version": "0.0.1",
3
+ "version": "1.0.1",
4
4
  "description": "Moleculer mixin to implement preflight runner",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "scripts": {
8
- "test": "c8 ava -v"
8
+ "pretest": "npm run lint",
9
+ "test": "c8 ava -v",
10
+ "lint": "eslint ."
9
11
  },
10
12
  "keywords": [],
11
13
  "author": "",
@@ -17,6 +19,7 @@
17
19
  "@r2d2bzh/js-rules": "^0.7.1",
18
20
  "ava": "^3.15.0",
19
21
  "c8": "^7.10.0",
22
+ "eslint": "^7.32.0",
20
23
  "moleculer": "^0.14.18",
21
24
  "uuid": "^8.3.2"
22
25
  },
@@ -33,7 +36,7 @@
33
36
  ]
34
37
  },
35
38
  "engines": {
36
- "node": ">=10.0.0"
39
+ "node": ">=12.0.0"
37
40
  },
38
41
  "peerDependencies": {
39
42
  "lodash": "^4.17.21",
@@ -1,33 +1,22 @@
1
1
  import cloneDeep from 'lodash/cloneDeep.js';
2
2
  import moleculer from 'moleculer';
3
+
3
4
  const {
4
- Service,
5
5
  Errors: { MoleculerError },
6
6
  } = moleculer;
7
7
 
8
- export default (serviceSchema) => {
9
- const { actions } = serviceSchema;
10
- const actionsWithPreflight = Object.entries(actions).filter(
11
- ([, actionSpecification]) => actionSpecification?.rest && !actionSpecification?.preflight?.skip
8
+ export const unsafeAddPreflightMixin = (serviceSchema) => {
9
+ const actionsWithPreflight = Object.entries(serviceSchema.actions || {}).filter(
10
+ ([, actionSpecification]) => actionSpecification?.preflight
12
11
  );
13
12
 
14
- const missingPreflight = actionsWithPreflight
15
- .filter(([, actionSpecification]) => !actionSpecification?.preflight?.handler)
16
- .map(([actionName]) => actionName);
17
-
18
- if (missingPreflight.length) {
19
- throw new MoleculerError('missing preflight handler', 500, 'MISSING_PREFLIGHT', { missingPreflight });
20
- }
21
-
22
- const preflightActions = actionsWithPreflight.map(([actionName, { params, preflight } = {}]) => {
23
- return [
24
- `${actionName}-preflight`,
25
- {
26
- handler: preflight.handler,
27
- ...(params ? { params } : {}),
28
- },
29
- ];
30
- });
13
+ const preflightActions = actionsWithPreflight.map(([actionName, { params, preflight } = {}]) => [
14
+ `${actionName}-preflight`,
15
+ {
16
+ handler: preflight instanceof Function ? preflight : preflight.handler,
17
+ ...(params ? { params } : {}),
18
+ },
19
+ ]);
31
20
 
32
21
  const schema = cloneDeep(serviceSchema);
33
22
 
@@ -38,8 +27,20 @@ export default (serviceSchema) => {
38
27
  ...(serviceSchema.mixins || []),
39
28
  {
40
29
  actions: Object.fromEntries(preflightActions),
41
- }
30
+ },
42
31
  ];
43
32
 
44
33
  return schema;
45
34
  };
35
+
36
+ export default (serviceSchema) => {
37
+ Object.entries(serviceSchema.actions || {})
38
+ .filter(([, actionSpecification]) => actionSpecification?.rest && actionSpecification.rest?.authorization !== false)
39
+ .forEach(([actionName, actionSpecification]) => {
40
+ if (!(actionSpecification?.preflight instanceof Function || actionSpecification?.preflight?.handler)) {
41
+ throw new MoleculerError('missing preflight handler', 500, 'MISSING_PREFLIGHT', { actionName });
42
+ }
43
+ });
44
+
45
+ return unsafeAddPreflightMixin(serviceSchema);
46
+ };
@@ -1,6 +1,62 @@
1
- const ensureBoolArray = (something) =>
2
- (Array.isArray(something) ? something : [something]).flat(Infinity).filter((response) => response !== undefined);
1
+ const removeUnanswered = (authzAnswers) => authzAnswers.filter((answer) => answer !== undefined);
3
2
 
4
- const someRequestsFailed = (booleanArray) => !booleanArray.length || booleanArray.includes(false);
3
+ const reduceAnswers = (answers, reducer) =>
4
+ answers.length
5
+ ? answers.reduce(
6
+ ([authorizationStatus, authorizationsCount], answer) =>
7
+ reducer(answer, authorizationStatus, authorizationsCount),
8
+ [true, 0]
9
+ )
10
+ : [false, 0];
5
11
 
6
- export default (something) => !someRequestsFailed(ensureBoolArray(something));
12
+ const onMultipleAuthorizations =
13
+ (handle) =>
14
+ ([answersAuthorization, authorizationsCount]) => {
15
+ if (authorizationsCount > 1) {
16
+ handle(authorizationsCount);
17
+ }
18
+ return answersAuthorization;
19
+ };
20
+
21
+ const processAndCountManyAnswers = (warn) => {
22
+ const warnOnMultipleAuthorizations = onMultipleAuthorizations((authorizationsCount) =>
23
+ warn(`multiple answers to the same authorization request (${authorizationsCount})`)
24
+ );
25
+ return (answers, authorizationStatus) => {
26
+ const newRequestIsAuthorized = warnOnMultipleAuthorizations(
27
+ reduceAnswers(removeUnanswered(answers), processAndCountAnswer(warn))
28
+ );
29
+ return authorizationStatus && newRequestIsAuthorized;
30
+ };
31
+ };
32
+
33
+ const processAndCountAnswer = (warn) => {
34
+ const doAnswersAuthorize = processAndCountManyAnswers(warn);
35
+ return function (answer, authorizationStatus = true, authorizationsCount = 0) {
36
+ switch (Object.prototype.toString.call(answer)) {
37
+ case '[object Boolean]':
38
+ return [authorizationStatus && answer, authorizationsCount + 1];
39
+ case '[object Array]':
40
+ // A new array means a new authorization request with its own
41
+ // answers count that does not reflect on the current one
42
+ return [doAnswersAuthorize(answer, authorizationStatus), authorizationsCount];
43
+ case '[object Undefined]':
44
+ return [false, authorizationsCount];
45
+ default:
46
+ warn(`odd authorization answer (${answer})`);
47
+ return [false, authorizationsCount];
48
+ }
49
+ };
50
+ };
51
+
52
+ export default (logger) => {
53
+ try {
54
+ const doesAnswerAuthorizeAndWarn = processAndCountAnswer(logger.warn.bind(logger));
55
+ return function (answer) {
56
+ const [authorize] = doesAnswerAuthorizeAndWarn(answer);
57
+ return authorize;
58
+ };
59
+ } catch (e) {
60
+ throw new Error(`logger.warn must be a function`);
61
+ }
62
+ };