@aeriajs/security 0.0.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,19 @@
1
+ Copyright 2023 João Santos (joaosan177@gmail.com)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the “Software”), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # `@aeriajs/security`
2
+
3
+ ## Introduction
4
+
5
+ This package implements common security checks.
6
+ The checks can be used separatelly, or through a function called `useSecurity()`. This function returns an object with two functions:
7
+
8
+ - `beforeRead()`: checks to be made before reading data
9
+ - `beforeWrite()`: checks to be made before writing data
10
+
11
+ ## References
12
+
13
+ - `checkOwnershipRead()` and `checkOwnershipWrite()`: [CWE-284: Improper Access Control](https://cwe.mitre.org/data/definitions/284.html), [CWE-639: Authorization Bypass Through User-Controlled Key](https://cwe.mitre.org/data/definitions/639.html)
14
+ - `checkImmutability()`: [CWE-471: Modification of Assumed-Immutable Data (MAID)](https://cwe.mitre.org/data/definitions/471.html )
15
+ - `checkPagination()`: [CWE-770: Allocation of Resources Without Limits or Throttling](https://cwe.mitre.org/data/definitions/770.html)
16
+ - `rateLimiting()`: [CWE-799: Improper Control of Interaction Frequency](https://cwe.mitre.org/data/definitions/799.html)
17
+
@@ -0,0 +1,2 @@
1
+ import type { SecurityPolicy } from '@aeriajs/types';
2
+ export declare const defineSecurityPolicy: <const TSecurityPolicy extends SecurityPolicy>(policy: TSecurityPolicy) => TSecurityPolicy;
package/dist/define.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineSecurityPolicy = void 0;
4
+ const defineSecurityPolicy = (policy) => {
5
+ return policy;
6
+ };
7
+ exports.defineSecurityPolicy = defineSecurityPolicy;
@@ -0,0 +1,3 @@
1
+ export var defineSecurityPolicy = function(policy) {
2
+ return policy;
3
+ };
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@aeriajs/types';
2
+ import type { SecurityCheckProps, SecurityCheckReadPayload, SecurityCheckWritePayload } from './types.js';
3
+ import { ACErrors } from '@aeriajs/types';
4
+ export declare const checkImmutability: (props: SecurityCheckProps<SecurityCheckReadPayload | SecurityCheckWritePayload>, context: Context) => Promise<import("@aeriajs/types").Right<SecurityCheckReadPayload | SecurityCheckWritePayload> | import("@aeriajs/types").Left<ACErrors.ImmutabilityParentNotFound> | import("@aeriajs/types").Left<ACErrors.ImmutabilityIncorrectChild> | import("@aeriajs/types").Left<ACErrors.ImmutabilityTargetImmutable>>;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkImmutability = void 0;
4
+ const types_1 = require("@aeriajs/types");
5
+ const common_1 = require("@aeriajs/common");
6
+ const internalCheckImmutability = async (props, context) => {
7
+ const { propertyName = '', parentId, childId, payload, } = props;
8
+ const { description } = context;
9
+ const source = 'what' in payload
10
+ ? payload.what
11
+ : payload.filters;
12
+ const property = description.properties[propertyName];
13
+ if (!property) {
14
+ return (0, common_1.right)(props.payload);
15
+ }
16
+ const immutable = parentId && (description.immutable === true
17
+ || (Array.isArray(description.immutable) && description.immutable.includes(propertyName)));
18
+ const currentDocument = await context.collection.model.findOne({
19
+ _id: new types_1.ObjectId(parentId),
20
+ });
21
+ if (!currentDocument) {
22
+ return (0, common_1.left)(types_1.ACErrors.ImmutabilityParentNotFound);
23
+ }
24
+ if (childId) {
25
+ if ((Array.isArray(currentDocument[propertyName]) && !currentDocument[propertyName].some((child) => child.toString() === childId))
26
+ || (!Array.isArray(currentDocument[propertyName]) && currentDocument[propertyName] && currentDocument[propertyName] !== childId.toString())) {
27
+ return (0, common_1.left)(types_1.ACErrors.ImmutabilityIncorrectChild);
28
+ }
29
+ }
30
+ const fulfilled = currentDocument[propertyName]
31
+ && (typeof currentDocument[propertyName] === 'object' && !Object.keys(currentDocument[propertyName]).length);
32
+ if (immutable
33
+ && fulfilled
34
+ && (property.inline || (currentDocument[propertyName]).toString() !== source[propertyName])) {
35
+ return (0, common_1.left)(types_1.ACErrors.ImmutabilityTargetImmutable);
36
+ }
37
+ return (0, common_1.right)(props.payload);
38
+ };
39
+ const checkImmutability = async (props, context) => {
40
+ if (!props.parentId) {
41
+ return (0, common_1.right)(props.payload);
42
+ }
43
+ for (const propertyName of Object.keys(props.payload)) {
44
+ const result = await internalCheckImmutability({
45
+ ...props,
46
+ propertyName,
47
+ }, context);
48
+ if ((0, common_1.isLeft)(result)) {
49
+ return result;
50
+ }
51
+ }
52
+ return internalCheckImmutability(props, context);
53
+ };
54
+ exports.checkImmutability = checkImmutability;
@@ -0,0 +1,325 @@
1
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
+ try {
3
+ var info = gen[key](arg);
4
+ var value = info.value;
5
+ } catch (error) {
6
+ reject(error);
7
+ return;
8
+ }
9
+ if (info.done) {
10
+ resolve(value);
11
+ } else {
12
+ Promise.resolve(value).then(_next, _throw);
13
+ }
14
+ }
15
+ function _async_to_generator(fn) {
16
+ return function() {
17
+ var self = this, args = arguments;
18
+ return new Promise(function(resolve, reject) {
19
+ var gen = fn.apply(self, args);
20
+ function _next(value) {
21
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
+ }
23
+ function _throw(err) {
24
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
+ }
26
+ _next(undefined);
27
+ });
28
+ };
29
+ }
30
+ function _define_property(obj, key, value) {
31
+ if (key in obj) {
32
+ Object.defineProperty(obj, key, {
33
+ value: value,
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true
37
+ });
38
+ } else {
39
+ obj[key] = value;
40
+ }
41
+ return obj;
42
+ }
43
+ function _object_spread(target) {
44
+ for(var i = 1; i < arguments.length; i++){
45
+ var source = arguments[i] != null ? arguments[i] : {};
46
+ var ownKeys = Object.keys(source);
47
+ if (typeof Object.getOwnPropertySymbols === "function") {
48
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
49
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
50
+ }));
51
+ }
52
+ ownKeys.forEach(function(key) {
53
+ _define_property(target, key, source[key]);
54
+ });
55
+ }
56
+ return target;
57
+ }
58
+ function ownKeys(object, enumerableOnly) {
59
+ var keys = Object.keys(object);
60
+ if (Object.getOwnPropertySymbols) {
61
+ var symbols = Object.getOwnPropertySymbols(object);
62
+ if (enumerableOnly) {
63
+ symbols = symbols.filter(function(sym) {
64
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
65
+ });
66
+ }
67
+ keys.push.apply(keys, symbols);
68
+ }
69
+ return keys;
70
+ }
71
+ function _object_spread_props(target, source) {
72
+ source = source != null ? source : {};
73
+ if (Object.getOwnPropertyDescriptors) {
74
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
75
+ } else {
76
+ ownKeys(Object(source)).forEach(function(key) {
77
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
78
+ });
79
+ }
80
+ return target;
81
+ }
82
+ function _ts_generator(thisArg, body) {
83
+ var f, y, t, g, _ = {
84
+ label: 0,
85
+ sent: function() {
86
+ if (t[0] & 1) throw t[1];
87
+ return t[1];
88
+ },
89
+ trys: [],
90
+ ops: []
91
+ };
92
+ return g = {
93
+ next: verb(0),
94
+ "throw": verb(1),
95
+ "return": verb(2)
96
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
97
+ return this;
98
+ }), g;
99
+ function verb(n) {
100
+ return function(v) {
101
+ return step([
102
+ n,
103
+ v
104
+ ]);
105
+ };
106
+ }
107
+ function step(op) {
108
+ if (f) throw new TypeError("Generator is already executing.");
109
+ while(_)try {
110
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
111
+ if (y = 0, t) op = [
112
+ op[0] & 2,
113
+ t.value
114
+ ];
115
+ switch(op[0]){
116
+ case 0:
117
+ case 1:
118
+ t = op;
119
+ break;
120
+ case 4:
121
+ _.label++;
122
+ return {
123
+ value: op[1],
124
+ done: false
125
+ };
126
+ case 5:
127
+ _.label++;
128
+ y = op[1];
129
+ op = [
130
+ 0
131
+ ];
132
+ continue;
133
+ case 7:
134
+ op = _.ops.pop();
135
+ _.trys.pop();
136
+ continue;
137
+ default:
138
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
139
+ _ = 0;
140
+ continue;
141
+ }
142
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
143
+ _.label = op[1];
144
+ break;
145
+ }
146
+ if (op[0] === 6 && _.label < t[1]) {
147
+ _.label = t[1];
148
+ t = op;
149
+ break;
150
+ }
151
+ if (t && _.label < t[2]) {
152
+ _.label = t[2];
153
+ _.ops.push(op);
154
+ break;
155
+ }
156
+ if (t[2]) _.ops.pop();
157
+ _.trys.pop();
158
+ continue;
159
+ }
160
+ op = body.call(thisArg, _);
161
+ } catch (e) {
162
+ op = [
163
+ 6,
164
+ e
165
+ ];
166
+ y = 0;
167
+ } finally{
168
+ f = t = 0;
169
+ }
170
+ if (op[0] & 5) throw op[1];
171
+ return {
172
+ value: op[0] ? op[1] : void 0,
173
+ done: true
174
+ };
175
+ }
176
+ }
177
+ import { ACErrors, ObjectId } from "@aeriajs/types";
178
+ import { left, right, isLeft } from "@aeriajs/common";
179
+ var internalCheckImmutability = function() {
180
+ var _ref = _async_to_generator(function(props, context) {
181
+ var _props_propertyName, propertyName, parentId, childId, payload, description, source, property, immutable, currentDocument, fulfilled;
182
+ return _ts_generator(this, function(_state) {
183
+ switch(_state.label){
184
+ case 0:
185
+ _props_propertyName = props.propertyName, propertyName = _props_propertyName === void 0 ? "" : _props_propertyName, parentId = props.parentId, childId = props.childId, payload = props.payload;
186
+ description = context.description;
187
+ source = "what" in payload ? payload.what : payload.filters;
188
+ property = description.properties[propertyName];
189
+ if (!property) {
190
+ return [
191
+ 2,
192
+ right(props.payload)
193
+ ];
194
+ }
195
+ immutable = parentId && (description.immutable === true || Array.isArray(description.immutable) && description.immutable.includes(propertyName));
196
+ return [
197
+ 4,
198
+ context.collection.model.findOne({
199
+ _id: new ObjectId(parentId)
200
+ })
201
+ ];
202
+ case 1:
203
+ currentDocument = _state.sent();
204
+ if (!currentDocument) {
205
+ return [
206
+ 2,
207
+ left(ACErrors.ImmutabilityParentNotFound)
208
+ ];
209
+ }
210
+ if (childId) {
211
+ if (Array.isArray(currentDocument[propertyName]) && !currentDocument[propertyName].some(function(child) {
212
+ return child.toString() === childId;
213
+ }) || !Array.isArray(currentDocument[propertyName]) && currentDocument[propertyName] && currentDocument[propertyName] !== childId.toString()) {
214
+ return [
215
+ 2,
216
+ left(ACErrors.ImmutabilityIncorrectChild)
217
+ ];
218
+ }
219
+ }
220
+ fulfilled = currentDocument[propertyName] && typeof currentDocument[propertyName] === "object" && !Object.keys(currentDocument[propertyName]).length;
221
+ if (immutable && fulfilled && (property.inline || currentDocument[propertyName].toString() !== source[propertyName])) {
222
+ return [
223
+ 2,
224
+ left(ACErrors.ImmutabilityTargetImmutable)
225
+ ];
226
+ }
227
+ return [
228
+ 2,
229
+ right(props.payload)
230
+ ];
231
+ }
232
+ });
233
+ });
234
+ return function internalCheckImmutability(props, context) {
235
+ return _ref.apply(this, arguments);
236
+ };
237
+ }();
238
+ export var checkImmutability = function() {
239
+ var _ref = _async_to_generator(function(props, context) {
240
+ var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, propertyName, result, err;
241
+ return _ts_generator(this, function(_state) {
242
+ switch(_state.label){
243
+ case 0:
244
+ if (!props.parentId) {
245
+ return [
246
+ 2,
247
+ right(props.payload)
248
+ ];
249
+ }
250
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
251
+ _state.label = 1;
252
+ case 1:
253
+ _state.trys.push([
254
+ 1,
255
+ 6,
256
+ 7,
257
+ 8
258
+ ]);
259
+ _iterator = Object.keys(props.payload)[Symbol.iterator]();
260
+ _state.label = 2;
261
+ case 2:
262
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
263
+ 3,
264
+ 5
265
+ ];
266
+ propertyName = _step.value;
267
+ return [
268
+ 4,
269
+ internalCheckImmutability(_object_spread_props(_object_spread({}, props), {
270
+ propertyName: propertyName
271
+ }), context)
272
+ ];
273
+ case 3:
274
+ result = _state.sent();
275
+ if (isLeft(result)) {
276
+ return [
277
+ 2,
278
+ result
279
+ ];
280
+ }
281
+ _state.label = 4;
282
+ case 4:
283
+ _iteratorNormalCompletion = true;
284
+ return [
285
+ 3,
286
+ 2
287
+ ];
288
+ case 5:
289
+ return [
290
+ 3,
291
+ 8
292
+ ];
293
+ case 6:
294
+ err = _state.sent();
295
+ _didIteratorError = true;
296
+ _iteratorError = err;
297
+ return [
298
+ 3,
299
+ 8
300
+ ];
301
+ case 7:
302
+ try {
303
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
304
+ _iterator.return();
305
+ }
306
+ } finally{
307
+ if (_didIteratorError) {
308
+ throw _iteratorError;
309
+ }
310
+ }
311
+ return [
312
+ 7
313
+ ];
314
+ case 8:
315
+ return [
316
+ 2,
317
+ internalCheckImmutability(props, context)
318
+ ];
319
+ }
320
+ });
321
+ });
322
+ return function checkImmutability(props, context) {
323
+ return _ref.apply(this, arguments);
324
+ };
325
+ }();
@@ -0,0 +1,6 @@
1
+ export * from './define.js';
2
+ export * from './immutability.js';
3
+ export * from './ownership.js';
4
+ export * from './pagination.js';
5
+ export * from './rateLimiting.js';
6
+ export * from './use.js';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./define.js"), exports);
18
+ __exportStar(require("./immutability.js"), exports);
19
+ __exportStar(require("./ownership.js"), exports);
20
+ __exportStar(require("./pagination.js"), exports);
21
+ __exportStar(require("./rateLimiting.js"), exports);
22
+ __exportStar(require("./use.js"), exports);
package/dist/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./define.mjs";
2
+ export * from "./immutability.mjs";
3
+ export * from "./ownership.mjs";
4
+ export * from "./pagination.mjs";
5
+ export * from "./rateLimiting.mjs";
6
+ export * from "./use.mjs";
@@ -0,0 +1,5 @@
1
+ import type { Context, InsertPayload } from '@aeriajs/types';
2
+ import type { SecurityCheckProps, SecurityCheckReadPayload } from './types.js';
3
+ import { ACErrors } from '@aeriajs/types';
4
+ export declare const checkOwnershipRead: (props: SecurityCheckProps<SecurityCheckReadPayload>, context: Context) => Promise<import("@aeriajs/types").Right<SecurityCheckReadPayload>>;
5
+ export declare const checkOwnershipWrite: (props: SecurityCheckProps<InsertPayload<any>>, context: Context) => Promise<import("@aeriajs/types").Right<InsertPayload<any>> | import("@aeriajs/types").Left<ACErrors.OwnershipError>>;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkOwnershipWrite = exports.checkOwnershipRead = void 0;
4
+ const types_1 = require("@aeriajs/types");
5
+ const common_1 = require("@aeriajs/common");
6
+ const checkOwnershipRead = async (props, context) => {
7
+ const { token, description } = context;
8
+ const payload = Object.assign({}, props.payload);
9
+ if (token.authenticated && description.owned) {
10
+ if (!token.roles.includes('root')) {
11
+ payload.filters.owner = token.sub;
12
+ }
13
+ }
14
+ return (0, common_1.right)(payload);
15
+ };
16
+ exports.checkOwnershipRead = checkOwnershipRead;
17
+ const checkOwnershipWrite = async (props, context) => {
18
+ const { token, description } = context;
19
+ const { parentId } = props;
20
+ const payload = Object.assign({}, props.payload);
21
+ if (token.authenticated && description.owned) {
22
+ if (!payload.what._id || description.owned === 'always') {
23
+ payload.what.owner = token.sub;
24
+ }
25
+ else {
26
+ return (0, common_1.right)(payload);
27
+ }
28
+ }
29
+ if ((!payload.what.owner && !parentId) && context.description.owned) {
30
+ return (0, common_1.left)(types_1.ACErrors.OwnershipError);
31
+ }
32
+ return (0, common_1.right)(payload);
33
+ };
34
+ exports.checkOwnershipWrite = checkOwnershipWrite;