@apso/cli 0.47.6 → 0.49.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.
Files changed (141) hide show
  1. package/README.md +28 -1
  2. package/dist/commands/dev.d.ts +2 -0
  3. package/dist/commands/dev.js +20 -3
  4. package/dist/commands/generate.js +55 -13
  5. package/dist/commands/mcp/serve.js +24 -41
  6. package/dist/commands/schema/diff.js +3 -4
  7. package/dist/commands/schema/pull.js +13 -11
  8. package/dist/commands/schema/push.js +6 -5
  9. package/dist/commands/schema/validate.d.ts +10 -0
  10. package/dist/commands/schema/validate.js +54 -0
  11. package/dist/commands/test/access.d.ts +11 -0
  12. package/dist/commands/test/access.js +65 -0
  13. package/dist/lib/access/cases.d.ts +120 -0
  14. package/dist/lib/access/cases.js +1163 -0
  15. package/dist/lib/access/index.d.ts +4 -0
  16. package/dist/lib/access/index.js +7 -0
  17. package/dist/lib/access/report.d.ts +75 -0
  18. package/dist/lib/access/report.js +118 -0
  19. package/dist/lib/access/rules.json +207 -0
  20. package/dist/lib/access/run.d.ts +38 -0
  21. package/dist/lib/access/run.js +111 -0
  22. package/dist/lib/access/tokens.d.ts +46 -0
  23. package/dist/lib/access/tokens.js +139 -0
  24. package/dist/lib/api/services.d.ts +10 -7
  25. package/dist/lib/api/services.js +19 -32
  26. package/dist/lib/apsorc-parser.d.ts +1 -1
  27. package/dist/lib/apsorc-parser.js +2 -0
  28. package/dist/lib/ddl/change.js +2 -0
  29. package/dist/lib/ddl/index.d.ts +11 -1
  30. package/dist/lib/ddl/index.js +30 -16
  31. package/dist/lib/ddl/sync.d.ts +25 -0
  32. package/dist/lib/ddl/sync.js +78 -0
  33. package/dist/lib/deploy/server-push.js +3 -1
  34. package/dist/lib/generators/go.d.ts +25 -7
  35. package/dist/lib/generators/go.js +365 -128
  36. package/dist/lib/generators/python.d.ts +9 -3
  37. package/dist/lib/generators/python.js +282 -47
  38. package/dist/lib/generators/typescript.d.ts +3 -5
  39. package/dist/lib/generators/typescript.js +78 -64
  40. package/dist/lib/guards.d.ts +111 -13
  41. package/dist/lib/guards.js +287 -23
  42. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  43. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  44. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  45. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  46. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  47. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  48. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  49. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  50. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  51. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  52. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  53. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  54. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  55. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  56. package/dist/lib/templates/go/dto/dto.eta +17 -18
  57. package/dist/lib/templates/go/handlers/handler.eta +10 -8
  58. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  59. package/dist/lib/templates/go/index-module.eta +10 -5
  60. package/dist/lib/templates/go/mcp.eta +307 -0
  61. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  62. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  63. package/dist/lib/templates/go/models/model.eta +22 -19
  64. package/dist/lib/templates/go/models/schema.eta +72 -0
  65. package/dist/lib/templates/go/services/service.eta +84 -35
  66. package/dist/lib/templates/go/utils/query.eta +68 -7
  67. package/dist/lib/templates/guards/guards.module.eta +37 -29
  68. package/dist/lib/templates/guards/index.eta +4 -0
  69. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  70. package/dist/lib/templates/guards/key.guard.eta +280 -0
  71. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  72. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  73. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  74. package/dist/lib/templates/python/auth.eta +354 -95
  75. package/dist/lib/templates/python/index-module.eta +7 -7
  76. package/dist/lib/templates/python/mcp.eta +284 -0
  77. package/dist/lib/templates/python/models/init.eta +24 -0
  78. package/dist/lib/templates/python/models/model.eta +30 -61
  79. package/dist/lib/templates/python/permissions.eta +121 -0
  80. package/dist/lib/templates/python/routers/router.eta +39 -1
  81. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  82. package/dist/lib/templates/python/schemas/schema.eta +27 -14
  83. package/dist/lib/templates/python/services/service.eta +38 -15
  84. package/dist/lib/templates/python/utils/query.eta +52 -25
  85. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  86. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  87. package/dist/lib/templates/rest/service-rest.eta +3 -44
  88. package/dist/lib/types/auth.d.ts +84 -80
  89. package/dist/lib/types/auth.js +77 -60
  90. package/dist/lib/types/entity.d.ts +17 -9
  91. package/dist/lib/types/entity.js +3 -0
  92. package/dist/lib/types/index.d.ts +2 -2
  93. package/dist/lib/types/index.js +6 -5
  94. package/dist/lib/utils/crud-deps.d.ts +77 -6
  95. package/dist/lib/utils/crud-deps.js +197 -14
  96. package/dist/lib/utils/field.d.ts +12 -0
  97. package/dist/lib/utils/field.js +18 -2
  98. package/dist/lib/utils/schema-convert.d.ts +20 -43
  99. package/dist/lib/utils/schema-convert.js +28 -78
  100. package/dist/lib/utils/template.d.ts +11 -0
  101. package/dist/lib/utils/template.js +36 -1
  102. package/dist/lib/verify/index.d.ts +6 -1
  103. package/dist/lib/verify/index.js +30 -13
  104. package/npm-shrinkwrap.json +2 -2
  105. package/oclif.manifest.json +36 -1
  106. package/package.json +1 -1
  107. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  108. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  109. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  110. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  111. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  112. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  113. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  114. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  115. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  116. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  117. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  118. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  119. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  120. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  121. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  122. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  123. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  124. package/dist/lib/templates/guards/auth.guard.eta +0 -233
  125. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  126. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  127. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  128. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  129. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  130. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  131. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  132. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  133. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  134. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  135. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  136. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  137. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  138. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  139. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  140. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  141. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -1,6 +1,8 @@
1
1
  <%~ includeFile('../header.eta') %>
2
2
 
3
3
  import {
4
+ BadRequestException,
5
+ ConflictException,
4
6
  Injectable,
5
7
  CanActivate,
6
8
  ExecutionContext,
@@ -8,7 +10,7 @@ import {
8
10
  } from '@nestjs/common';
9
11
  import { Reflector } from '@nestjs/core';
10
12
  import { InjectRepository } from '@nestjs/typeorm';
11
- import { <% if (it.hasNestedFk) { %>DataSource, <% } %>Repository } from 'typeorm';
13
+ import { DataSource, Repository } from 'typeorm';
12
14
 
13
15
  <% /* Import all entities that have scoped relationships (from sibling autogen folders) */ %>
14
16
  <% it.scopedEntities.forEach((entity) => { %>
@@ -56,10 +58,6 @@ export const Public = () =>
56
58
  export interface ScopeConfig {
57
59
  /** The scope fields or paths (e.g., 'workspaceId' or 'task.workspaceId') */
58
60
  scopes: ScopeField[];
59
- /** Whether to inject scope on create */
60
- injectOnCreate: boolean;
61
- /** Which operations to enforce scope on */
62
- enforceOn: string[];
63
61
  /** Roles that can bypass scope enforcement */
64
62
  bypassRoles: string[];
65
63
  }
@@ -105,13 +103,24 @@ export const ENTITY_SCOPES: Record<string, ScopeConfig> = {
105
103
  }<%= scopeIndex < entity.scopes.length - 1 ? ',' : '' %>
106
104
  <% }) %>
107
105
  ],
108
- injectOnCreate: <%= entity.injectOnCreate %>,
109
- enforceOn: [<%~ entity.enforceOn.map(op => `'${op}'`).join(', ') %>],
110
106
  bypassRoles: [<%~ entity.bypassRoles.map(role => `'${role}'`).join(', ') %>],
111
107
  }<%= index < it.scopedEntities.length - 1 ? ',' : '' %>
112
108
  <% }) %>
113
109
  };
114
110
 
111
+ /**
112
+ * Every entity by its route, so a write body can be checked against the
113
+ * entity's relations whether or not the entity itself is scoped.
114
+ */
115
+ export const ROUTE_ENTITIES: Record<string, string> = {
116
+ <% it.routeEntities.forEach((entity) => { %>
117
+ '<%= entity.route %>': '<%= entity.name %>',
118
+ <% }) %>
119
+ };
120
+ const ENTITY_ROUTES: Record<string, string> = Object.fromEntries(
121
+ Object.entries(ROUTE_ENTITIES).map(([route, name]) => [name, route]),
122
+ );
123
+
115
124
  @Injectable()
116
125
  export class ScopeGuard implements CanActivate {
117
126
  constructor(
@@ -120,12 +129,24 @@ export class ScopeGuard implements CanActivate {
120
129
  @InjectRepository(<%= entity.name %>)
121
130
  private <%= entity.repoName %>: Repository<<%= entity.name %>>,
122
131
  <% }) %>
123
- <% if (it.hasNestedFk) { %>
124
132
  private dataSource: DataSource,
125
- <% } %>
126
133
  ) {}
127
134
 
128
135
  async canActivate(context: ExecutionContext): Promise<boolean> {
136
+ try {
137
+ return await this.check(context);
138
+ } catch (error) {
139
+ if (error instanceof ForbiddenException) {
140
+ // The reason, for the log.
141
+ const request = context.switchToHttp().getRequest();
142
+ const denied = /tenant/.test(error.message) ? 'no tenant' : 'outside the tenant scope';
143
+ request.apso = { ...request.apso, denied };
144
+ }
145
+ throw error;
146
+ }
147
+ }
148
+
149
+ private async check(context: ExecutionContext): Promise<boolean> {
129
150
  // Check if route should skip scope check
130
151
  const skipCheck = this.reflector.getAllAndOverride<boolean>(
131
152
  SKIP_SCOPE_CHECK,
@@ -148,6 +169,11 @@ export class ScopeGuard implements CanActivate {
148
169
 
149
170
  const request = context.switchToHttp().getRequest();
150
171
 
172
+ // A service caller (valid API key) is not tenant-scoped.
173
+ if (request.auth?.serviceId) {
174
+ return true;
175
+ }
176
+
151
177
  // Get the resource path from the request
152
178
  const path = request.route?.path || request.path;
153
179
  const method = request.method;
@@ -162,8 +188,12 @@ export class ScopeGuard implements CanActivate {
162
188
 
163
189
  // Check if this is a scoped entity
164
190
  const scopeConfig = ENTITY_SCOPES[entityType];
191
+ const writes = method === 'POST' || method === 'PUT' || method === 'PATCH';
165
192
  if (!scopeConfig) {
166
- // Not a scoped entity, allow through
193
+ // Not a scoped entity; its body still must not reach a scoped row.
194
+ if (writes) {
195
+ await this.checkBody(request, entityType);
196
+ }
167
197
  return true;
168
198
  }
169
199
 
@@ -173,13 +203,14 @@ export class ScopeGuard implements CanActivate {
173
203
  return true;
174
204
  }
175
205
 
206
+ // A body must not reach another entity's rows or write over an existing row.
207
+ if (writes) {
208
+ await this.checkBody(request, entityType, scopeConfig);
209
+ }
210
+
176
211
  // Map HTTP method to operation
177
212
  const operation = this.mapMethodToOperation(method, request.params?.id);
178
213
 
179
- // Check if this operation should be enforced
180
- if (!scopeConfig.enforceOn.includes(operation)) {
181
- return true;
182
- }
183
214
  <% if (it.hasNestedFk) { %>
184
215
 
185
216
  // Nested paths (task.workspaceId): load the caller's parent ids for the
@@ -200,8 +231,8 @@ export class ScopeGuard implements CanActivate {
200
231
  }
201
232
  }
202
233
 
203
- // For POST requests, inject scope values if configured
204
- if (operation === 'create' && scopeConfig.injectOnCreate) {
234
+ // On create the scope values come from the caller, never from the body.
235
+ if (operation === 'create') {
205
236
  this.injectScopeValues(request, scopeConfig);
206
237
  }
207
238
  <% if (it.hasAuth) { %>
@@ -212,7 +243,7 @@ export class ScopeGuard implements CanActivate {
212
243
  }
213
244
  <% } %>
214
245
 
215
- // For GET (list) requests, add scope filter
246
+ // For GET (list) requests, require the caller's tenant
216
247
  if (operation === 'find') {
217
248
  this.addScopeFilter(request, scopeConfig);
218
249
  }
@@ -302,10 +333,6 @@ export class ScopeGuard implements CanActivate {
302
333
  }
303
334
 
304
335
  private injectScopeValues(request: any, scopeConfig: ScopeConfig): void {
305
- if (!request.body || typeof request.body !== 'object') {
306
- return;
307
- }
308
-
309
336
  for (const scope of scopeConfig.scopes) {
310
337
  if (scope.direct) {
311
338
  const scopeValue = this.getScopeValue(request, scope.contextKey);
@@ -314,37 +341,159 @@ export class ScopeGuard implements CanActivate {
314
341
  throw new ForbiddenException('No tenant in the auth context');
315
342
  }
316
343
  // Always the caller's tenant, never one from the body.
317
- request.body[scope.field] = scopeValue;
344
+ for (const item of this.bodyItems(request.body)) {
345
+ item[scope.field] = scopeValue;
346
+ }
318
347
  <% } else { %>
319
- if (scopeValue && !request.body[scope.field]) {
320
- request.body[scope.field] = scopeValue;
348
+ for (const item of this.bodyItems(request.body)) {
349
+ if (scopeValue && !item[scope.field]) {
350
+ item[scope.field] = scopeValue;
351
+ }
321
352
  }
322
353
  <% } %>
323
354
  }
324
355
  }
325
356
  }
326
357
 
327
- private addScopeFilter(request: any, scopeConfig: ScopeConfig): void {
328
- if (!request.query) {
329
- request.query = {};
358
+ /** The rows a write body carries: the body itself and each row of a bulk create. */
359
+ private bodyItems(body: any): any[] {
360
+ const plain = (v: any) => v !== null && typeof v === 'object' && !Array.isArray(v);
361
+ if (!plain(body)) {
362
+ return [];
330
363
  }
364
+ return [body, ...(Array.isArray(body.bulk) ? body.bulk.filter(plain) : [])];
365
+ }
331
366
 
332
- for (const scope of scopeConfig.scopes) {
333
- if (scope.direct) {
334
- const scopeValue = this.getScopeValue(request, scope.contextKey);
335
- <% if (it.hasAuth) { %>
336
- if (!scopeValue) {
337
- throw new ForbiddenException('No tenant in the auth context');
367
+ /**
368
+ * Relations and ids in a write body. TypeORM saves a relation object in
369
+ * place of the foreign key column, saves the rows listed under a to-many
370
+ * relation, and updates the row a body names by id. So before the
371
+ * checks below run:
372
+ * - the body's own id is dropped: the database assigns it on create, and
373
+ * on update the row is the one the route names. A key the client chooses
374
+ * is kept on create, and refused when a row already has it
375
+ * - a to-one relation becomes its foreign key, which is then checked like
376
+ * any other column
377
+ * - a foreign key to a tenant-scoped entity, sent as a column or as a
378
+ * relation, must name a row the caller could read (null is allowed)
379
+ * - rows of a scoped entity listed under a relation must be the caller's
380
+ * own, and only their ids are kept
381
+ * A referenced row is looked up once per request, however many rows of a
382
+ * bulk create name it.
383
+ */
384
+ private async checkBody(
385
+ request: any,
386
+ entityType: string,
387
+ scopeConfig?: ScopeConfig,
388
+ ): Promise<void> {
389
+ if (Array.isArray(request.body)) {
390
+ throw new BadRequestException('The body must be an object');
391
+ }
392
+ const name = ROUTE_ENTITIES[entityType];
393
+ if (!name) {
394
+ return;
395
+ }
396
+ const metadata = this.dataSource.getMetadata(name);
397
+ const scopeFields = (scopeConfig?.scopes ?? []).map((s) => s.fkField ?? s.field);
398
+ const denied = () => new ForbiddenException('You do not have access to this resource');
399
+ const roles: string[] = request.auth?.roles ?? request.user?.roles ?? request.roles ?? [];
400
+ // An entity whose rows the caller reads only inside its tenant.
401
+ const limited = (scope?: ScopeConfig): scope is ScopeConfig =>
402
+ Boolean(scope) && !scope!.bypassRoles.some((role) => roles.includes(role));
403
+ const lookups = new Map<string, Promise<boolean>>();
404
+ const readable = (route: string, id: unknown, scope: ScopeConfig): Promise<boolean> => {
405
+ const key = `${route}:${id}`;
406
+ if (!lookups.has(key)) lookups.set(key, this.verifyResourceAccess(route, String(id), request, scope));
407
+ return lookups.get(key)!;
408
+ };
409
+
410
+ for (const item of this.bodyItems(request.body)) {
411
+ if (scopeConfig) {
412
+ const chosen: Record<string, any> = {};
413
+ for (const column of metadata.primaryColumns) {
414
+ const sent = item[column.propertyName];
415
+ if (column.isGenerated || request.method !== 'POST') {
416
+ delete item[column.propertyName];
417
+ } else if (sent != null) {
418
+ chosen[column.propertyName] = sent;
419
+ }
338
420
  }
339
- <% } %>
340
- if (scopeValue) {
341
- // Add filter for @apso/crud
342
- request.query[`filter.${scope.field}`] = `$eq:${scopeValue}`;
421
+ // A key the client chooses: a create must not write over the row that has it.
422
+ if (Object.keys(chosen).length > 0) {
423
+ if (Object.values(chosen).some((v) => typeof v === 'object')) throw denied();
424
+ if (await this.dataSource.getRepository(name).findOne({ where: chosen })) {
425
+ throw new ConflictException('A row with this key already exists');
426
+ }
343
427
  }
344
428
  }
429
+ for (const relation of metadata.relations) {
430
+ const key = relation.propertyName;
431
+ const value = item[key];
432
+ const target = relation.inverseEntityMetadata;
433
+ const targetRoute = ENTITY_ROUTES[target.name];
434
+ const targetScope = ENTITY_SCOPES[targetRoute];
435
+ const isObject = value !== null && typeof value === 'object';
436
+
437
+ const [join] = relation.joinColumns;
438
+ if ((relation.isManyToOne || relation.isOneToOneOwner) && relation.joinColumns.length === 1) {
439
+ if (!targetScope && !scopeFields.includes(join.propertyName)) continue;
440
+ const referenced = join.referencedColumn!.propertyName;
441
+ let id: any;
442
+ if (Object.prototype.hasOwnProperty.call(item, key)) {
443
+ id = isObject ? (Array.isArray(value) ? undefined : value[referenced]) : value;
444
+ if (id !== null && typeof id === 'object') throw denied();
445
+ if (join.isVirtual) {
446
+ // No column property to move the id to: keep the id alone.
447
+ item[key] = id == null ? null : { [referenced]: id };
448
+ } else {
449
+ delete item[key];
450
+ if (id !== undefined) item[join.propertyName] = id;
451
+ }
452
+ }
453
+ // The foreign key as it will be saved. The entity's own scope fields
454
+ // are set from the caller or checked as its parent, further on.
455
+ if (!join.isVirtual) id = item[join.propertyName];
456
+ if (id == null || scopeFields.includes(join.propertyName) || !limited(targetScope)) continue;
457
+ if (typeof id === 'object' || !(await readable(targetRoute, id, targetScope))) throw denied();
458
+ continue;
459
+ }
460
+
461
+ // A to-many (or inverse one-to-one) relation: saving it writes the listed rows.
462
+ if (!Object.prototype.hasOwnProperty.call(item, key)) continue;
463
+ if (!targetScope) continue;
464
+ // A shared row cannot take over or let go of scoped rows.
465
+ if (!scopeConfig) throw denied();
466
+ const primary = target.primaryColumns[0].propertyName;
467
+ const kept: any[] = [];
468
+ for (const row of Array.isArray(value) ? value : value == null ? [] : [value]) {
469
+ const id = row !== null && typeof row === 'object' ? row[primary] : row;
470
+ if (id == null || typeof id === 'object') throw denied();
471
+ if (!(await readable(targetRoute, id, targetScope))) throw denied();
472
+ kept.push({ [primary]: id });
473
+ }
474
+ item[key] = Array.isArray(value) ? kept : kept[0] ?? null;
475
+ }
345
476
  }
346
477
  }
347
478
 
479
+ /**
480
+ * A list request needs the caller's tenant. The filter itself is the
481
+ * controller's @CrudAuth, which applies to every query dialect; nothing is
482
+ * added to the query string here.
483
+ */
484
+ private addScopeFilter(request: any, scopeConfig: ScopeConfig): void {
485
+ <% if (it.hasAuth) { %>
486
+ for (const scope of scopeConfig.scopes) {
487
+ if (scope.direct && !this.getScopeValue(request, scope.contextKey)) {
488
+ throw new ForbiddenException('No tenant in the auth context');
489
+ }
490
+ }
491
+ <% } else { %>
492
+ void request;
493
+ void scopeConfig;
494
+ <% } %>
495
+ }
496
+
348
497
  private getScopeValue(request: any, contextKey: string): string | undefined {
349
498
  // Try multiple locations for the scope value
350
499
  return (
@@ -389,10 +538,9 @@ export class ScopeGuard implements CanActivate {
389
538
  request.apsoScope = { ...request.apsoScope, [scope.fkField]: ids };
390
539
 
391
540
  if (operation === 'create' || operation === 'update') {
392
- const body = request.body && typeof request.body === 'object' ? request.body : {};
393
- const items = Array.isArray(body.bulk) ? body.bulk : [body];
394
- for (const item of items) {
395
- const fk = item?.[scope.fkField] ?? item?.[scope.field]?.[pk];
541
+ // checkBody has already turned a relation object into this foreign key.
542
+ for (const item of this.bodyItems(request.body)) {
543
+ const fk = item[scope.fkField];
396
544
  if (fk != null && !ids.some((id: any) => String(id) === String(fk))) {
397
545
  throw new ForbiddenException('You do not have access to this resource');
398
546
  }