@appweaver/data 2.2.0 → 2.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appweaver/data",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Appweaver - the backend framework for AI-first development (@data)",
5
5
  "author": "Luka Matosevic",
6
6
  "license": "MIT",
@@ -51,8 +51,8 @@
51
51
  "csv-stringify": "6.8.0"
52
52
  },
53
53
  "peerDependencies": {
54
- "@appweaver/common": "^2.2.0",
55
- "@appweaver/core": "^2.2.0",
54
+ "@appweaver/common": "^2.4.0",
55
+ "@appweaver/core": "^2.4.0",
56
56
  "@prisma/client": "^7.9.0"
57
57
  },
58
58
  "devDependencies": {
@@ -64,7 +64,7 @@
64
64
  "rimraf": "6.1.3"
65
65
  },
66
66
  "scripts": {
67
- "generate": "weaver generate -t -p --no-registry --no-prune --model-pattern ./**/model.ts --types-path ./types/generated.ts --prisma-schema-path ./prisma/schema.prisma --client-path ./prisma/client",
67
+ "generate": "weaver generate --types --prisma-schema --model-pattern ./**/model.ts --types-path ./types/generated.ts --prisma-schema-path ./prisma/schema.prisma --client-dir ./prisma/client --no-registry --no-prune",
68
68
  "db:recreate": "rimraf dev.db && rimraf prisma/migrations && weaver migration new init"
69
69
  }
70
70
  }
@@ -1,4 +1,4 @@
1
- import { AuthUser, IResourceService, ResourceModel, ValidationResult } from '@appweaver/common';
1
+ import { AuthUser, Permission, IResourceService, ResourceModel, ValidationResult } from '@appweaver/common';
2
2
  /**
3
3
  * Evaluates and retrieves the resource authentication model from the available resource models.
4
4
  *
@@ -96,6 +96,45 @@ export declare function hasRoles(authUser: AuthUser, roles: Array<string> | unde
96
96
  * @return {boolean} Returns true if the user has the specified permission, otherwise false.
97
97
  */
98
98
  export declare function hasPermission(authUser: AuthUser, permission: string): boolean;
99
+ /**
100
+ * Returns the permissions of a user: the ones it is narrowed to by the scope of an API key, otherwise the ones of its
101
+ * roles, each once.
102
+ *
103
+ * @param {AuthUser} authUser - The user.
104
+ * @return {Permission[]} The permissions of the user.
105
+ */
106
+ export declare function userPermissions(authUser: AuthUser): Permission[];
107
+ /**
108
+ * Narrows the owner of an API key to the scope of the key, its roles and permissions. A key with neither acts as its
109
+ * owner. A key with a scope keeps only the roles it lists, that the owner still holds, and the permissions it lists
110
+ * among the ones of those roles (or of all the roles of the owner, when it lists no role). The scope is checked
111
+ * against the current roles of the owner on every request, so a key loses what its owner loses.
112
+ *
113
+ * @param {AuthUser} owner - The owner of the key.
114
+ * @param {Object} scope - The roles and the permissions of the key, by their ids.
115
+ * @return {AuthUser} The owner, narrowed to the scope of the key.
116
+ */
117
+ export declare function scopeAuthUser(owner: AuthUser, scope: {
118
+ roles?: {
119
+ id: unknown;
120
+ }[] | null;
121
+ permissions?: {
122
+ id: unknown;
123
+ }[] | null;
124
+ }): AuthUser;
125
+ /**
126
+ * Checks that a user grants an API key only the roles and the permissions it holds itself, by their ids in the
127
+ * relation input of the key (`[3, { id: 5 }]`).
128
+ *
129
+ * @param {AuthUser} owner - The user granting the scope, the owner of the key.
130
+ * @param {Object} scope - The `roles` and the `permissions` input of the key.
131
+ * @throws {AuthError} `AUTH_API_KEY_PERMISSION_DENIED` with the ids of the roles and the permissions the user does not
132
+ * hold.
133
+ */
134
+ export declare function checkApiKeyScope(owner: AuthUser, scope: {
135
+ roles?: unknown;
136
+ permissions?: unknown;
137
+ }): void;
99
138
  /**
100
139
  * Checks if the authenticated user has the specified permissions based on the given operator.
101
140
  *
@@ -11,6 +11,9 @@ exports.isOAuth2Enabled = isOAuth2Enabled;
11
11
  exports.hasRole = hasRole;
12
12
  exports.hasRoles = hasRoles;
13
13
  exports.hasPermission = hasPermission;
14
+ exports.userPermissions = userPermissions;
15
+ exports.scopeAuthUser = scopeAuthUser;
16
+ exports.checkApiKeyScope = checkApiKeyScope;
14
17
  exports.hasPermissions = hasPermissions;
15
18
  const node_crypto_1 = require("node:crypto");
16
19
  const common_1 = require("@appweaver/common");
@@ -224,9 +227,81 @@ function hasRoles(authUser, roles, operator = 'or') {
224
227
  * @return {boolean} Returns true if the user has the specified permission, otherwise false.
225
228
  */
226
229
  function hasPermission(authUser, permission) {
227
- return authUser.roles
228
- .flatMap((r) => r.permissions)
229
- .some((p) => p.name === permission);
230
+ return userPermissions(authUser).some((p) => p.name === permission);
231
+ }
232
+ /**
233
+ * Returns the permissions of a user: the ones it is narrowed to by the scope of an API key, otherwise the ones of its
234
+ * roles, each once.
235
+ *
236
+ * @param {AuthUser} authUser - The user.
237
+ * @return {Permission[]} The permissions of the user.
238
+ */
239
+ function userPermissions(authUser) {
240
+ if (authUser.permissions) {
241
+ return authUser.permissions;
242
+ }
243
+ const permissions = new Map();
244
+ for (const permission of authUser.roles.flatMap((r) => r.permissions)) {
245
+ permissions.set(String(permission.id ?? permission.name), permission);
246
+ }
247
+ return [...permissions.values()];
248
+ }
249
+ /**
250
+ * Narrows the owner of an API key to the scope of the key, its roles and permissions. A key with neither acts as its
251
+ * owner. A key with a scope keeps only the roles it lists, that the owner still holds, and the permissions it lists
252
+ * among the ones of those roles (or of all the roles of the owner, when it lists no role). The scope is checked
253
+ * against the current roles of the owner on every request, so a key loses what its owner loses.
254
+ *
255
+ * @param {AuthUser} owner - The owner of the key.
256
+ * @param {Object} scope - The roles and the permissions of the key, by their ids.
257
+ * @return {AuthUser} The owner, narrowed to the scope of the key.
258
+ */
259
+ function scopeAuthUser(owner, scope) {
260
+ const roleIds = new Set((scope.roles ?? []).map(({ id }) => String(id)));
261
+ const permissionIds = new Set((scope.permissions ?? []).map(({ id }) => String(id)));
262
+ if (roleIds.size === 0 && permissionIds.size === 0) {
263
+ return owner;
264
+ }
265
+ const roles = owner.roles.filter((role) => roleIds.has(String(role.id)));
266
+ const permissions = userPermissions(roleIds.size ? { ...owner, roles } : owner).filter((permission) => permissionIds.size === 0 || permissionIds.has(String(permission.id)));
267
+ const allowed = new Set(permissions.map(({ id }) => String(id)));
268
+ return {
269
+ ...owner,
270
+ roles: roles.map((role) => ({
271
+ ...role,
272
+ permissions: role.permissions.filter(({ id }) => allowed.has(String(id)))
273
+ })),
274
+ permissions
275
+ };
276
+ }
277
+ /**
278
+ * Checks that a user grants an API key only the roles and the permissions it holds itself, by their ids in the
279
+ * relation input of the key (`[3, { id: 5 }]`).
280
+ *
281
+ * @param {AuthUser} owner - The user granting the scope, the owner of the key.
282
+ * @param {Object} scope - The `roles` and the `permissions` input of the key.
283
+ * @throws {AuthError} `AUTH_API_KEY_PERMISSION_DENIED` with the ids of the roles and the permissions the user does not
284
+ * hold.
285
+ */
286
+ function checkApiKeyScope(owner, scope) {
287
+ const ownedRoles = new Set(owner.roles.map(({ id }) => String(id)));
288
+ const ownedPermissions = new Set(userPermissions(owner).map(({ id }) => String(id)));
289
+ const roles = relationIds(scope.roles).filter((id) => !ownedRoles.has(id));
290
+ const permissions = relationIds(scope.permissions).filter((id) => !ownedPermissions.has(id));
291
+ if (roles.length || permissions.length) {
292
+ throw new common_1.AuthError(common_1.ErrorCode.AuthApiKeyPermissionDenied, 'An API key cannot be given a role or a permission its owner does not hold', { roles, permissions });
293
+ }
294
+ }
295
+ /** The ids of a relation input: an id, an `{ id }` object, or a list of either. */
296
+ function relationIds(input) {
297
+ if (input === undefined || input === null) {
298
+ return [];
299
+ }
300
+ return [input]
301
+ .flat()
302
+ .map((item) => String(typeof item === 'object' && item !== null
303
+ ? item.id
304
+ : item));
230
305
  }
231
306
  /**
232
307
  * Checks if the authenticated user has the specified permissions based on the given operator.
@@ -53,6 +53,29 @@ exports.default = shouldCreateModel
53
53
  output: {
54
54
  type: 'none'
55
55
  }
56
+ },
57
+ // The scope of the key, a subset of the ones of its owner, the full access of the owner when empty
58
+ roles: {
59
+ model: 'Role',
60
+ type: 'manyToMany',
61
+ required: false,
62
+ input: {
63
+ type: 'all'
64
+ },
65
+ output: {
66
+ type: 'always'
67
+ }
68
+ },
69
+ permissions: {
70
+ model: 'Permission',
71
+ type: 'manyToMany',
72
+ required: false,
73
+ input: {
74
+ type: 'all'
75
+ },
76
+ output: {
77
+ type: 'always'
78
+ }
56
79
  }
57
80
  }
58
81
  }
@@ -1,3 +1,3 @@
1
1
  import { ApiKey } from '../../../types/generated';
2
- declare const _default: import("@appweaver/common").Ctor<import("../../..").ResourceService<ApiKey, ApiKey, ApiKey, any, import("@appweaver/common").QueryFilter<ApiKey>, ApiKey>> | undefined;
2
+ declare const _default: import("@appweaver/common").Ctor<import("../../..").ResourceService<ApiKey, ApiKey, ApiKey, Partial<ApiKey>, import("@appweaver/common").QueryFilter<ApiKey>, ApiKey>> | undefined;
3
3
  export default _default;
@@ -9,6 +9,7 @@ exports.default = auth_config_1.apiKeyConfig.ENABLED
9
9
  ? (0, create_service_1.createService)({
10
10
  modelName: 'ApiKey',
11
11
  beforeCreate: (data) => {
12
+ checkScope(data);
12
13
  data.key = (0, common_1.randomString)(64, { special: false });
13
14
  data.keyHash = (0, common_1.makeHash)(data.key);
14
15
  // Add relation to the current user when creating a new API Key
@@ -25,6 +26,9 @@ exports.default = auth_config_1.apiKeyConfig.ENABLED
25
26
  }
26
27
  }
27
28
  },
29
+ beforeUpdate: (_id, data) => {
30
+ checkScope(data);
31
+ },
28
32
  afterCreate: async (data) => {
29
33
  const service = (0, core_1.injectService)('ApiKey');
30
34
  await service.update(data.id, { key: `...${data.key.slice(-6)}` });
@@ -32,3 +36,13 @@ exports.default = auth_config_1.apiKeyConfig.ENABLED
32
36
  }
33
37
  })
34
38
  : undefined;
39
+ /**
40
+ * Checks that the current user, the owner of the key, gives it only roles and permissions it holds. The scope is also
41
+ * narrowed to the ones the owner still holds on every request, so a service call without a user is not checked.
42
+ */
43
+ function checkScope(data) {
44
+ const owner = (0, core_1.currentAuthUser)();
45
+ if (owner) {
46
+ (0, helper_1.checkApiKeyScope)(owner, data);
47
+ }
48
+ }