@apso/cli 0.48.0 → 0.49.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.
Files changed (82) 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 +49 -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/deploy/server-push.js +3 -1
  29. package/dist/lib/generators/go.d.ts +13 -1
  30. package/dist/lib/generators/go.js +144 -33
  31. package/dist/lib/generators/python.d.ts +3 -3
  32. package/dist/lib/generators/python.js +48 -24
  33. package/dist/lib/generators/typescript.d.ts +3 -5
  34. package/dist/lib/generators/typescript.js +78 -64
  35. package/dist/lib/guards.d.ts +111 -13
  36. package/dist/lib/guards.js +287 -23
  37. package/dist/lib/templates/go/handlers/handler.eta +8 -8
  38. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  39. package/dist/lib/templates/go/index-module.eta +8 -5
  40. package/dist/lib/templates/go/mcp.eta +307 -0
  41. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  42. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  43. package/dist/lib/templates/go/services/service.eta +37 -16
  44. package/dist/lib/templates/go/utils/query.eta +37 -2
  45. package/dist/lib/templates/guards/guards.module.eta +37 -29
  46. package/dist/lib/templates/guards/index.eta +4 -0
  47. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  48. package/dist/lib/templates/guards/key.guard.eta +280 -0
  49. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  50. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  51. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  52. package/dist/lib/templates/python/auth.eta +354 -95
  53. package/dist/lib/templates/python/index-module.eta +7 -7
  54. package/dist/lib/templates/python/mcp.eta +284 -0
  55. package/dist/lib/templates/python/models/model.eta +6 -5
  56. package/dist/lib/templates/python/permissions.eta +121 -0
  57. package/dist/lib/templates/python/routers/router.eta +39 -1
  58. package/dist/lib/templates/python/schemas/schema.eta +18 -5
  59. package/dist/lib/templates/python/services/service.eta +38 -15
  60. package/dist/lib/templates/python/utils/query.eta +52 -25
  61. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  62. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  63. package/dist/lib/templates/rest/service-rest.eta +3 -44
  64. package/dist/lib/types/auth.d.ts +84 -80
  65. package/dist/lib/types/auth.js +77 -60
  66. package/dist/lib/types/entity.d.ts +17 -9
  67. package/dist/lib/types/entity.js +3 -0
  68. package/dist/lib/types/index.d.ts +2 -2
  69. package/dist/lib/types/index.js +6 -5
  70. package/dist/lib/utils/crud-deps.d.ts +77 -6
  71. package/dist/lib/utils/crud-deps.js +197 -14
  72. package/dist/lib/utils/schema-convert.d.ts +20 -43
  73. package/dist/lib/utils/schema-convert.js +28 -78
  74. package/dist/lib/utils/template.d.ts +11 -0
  75. package/dist/lib/utils/template.js +36 -1
  76. package/dist/lib/verify/index.d.ts +6 -1
  77. package/dist/lib/verify/index.js +30 -13
  78. package/npm-shrinkwrap.json +2 -2
  79. package/oclif.manifest.json +36 -1
  80. package/package.json +1 -1
  81. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  82. package/dist/lib/templates/guards/auth.guard.eta +0 -233
@@ -143,20 +143,21 @@ class PythonGenerator extends base_1.BaseGenerator {
143
143
  return ".py";
144
144
  }
145
145
  validateConfig(config) {
146
- var _a;
146
+ var _a, _b;
147
147
  const errors = [];
148
148
  const warnings = [];
149
149
  // Validate that entities are provided
150
150
  if (!config.entities || config.entities.length === 0) {
151
151
  errors.push("No entities defined in configuration");
152
152
  }
153
+ errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
153
154
  // Validate each entity
154
155
  for (const entity of config.entities) {
155
156
  if (!entity.name) {
156
157
  errors.push("Entity missing required 'name' property");
157
158
  }
158
159
  // Validate field types
159
- for (const field of (_a = entity.fields) !== null && _a !== void 0 ? _a : []) {
160
+ for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
160
161
  if (!field.name) {
161
162
  errors.push(`Entity '${entity.name}' has a field without a name`);
162
163
  }
@@ -295,6 +296,8 @@ class PythonGenerator extends base_1.BaseGenerator {
295
296
  pluralEntityName,
296
297
  primaryKeyType,
297
298
  associations: [...new Set(relationshipsForTemplate)],
299
+ // Operations exposed as MCP tools, and the names the tools get.
300
+ ...(0, guards_1.mcpToolNames)(entity, options.auth),
298
301
  };
299
302
  const content = await this.renderTemplate("./routers/router", data);
300
303
  return [
@@ -305,6 +308,7 @@ class PythonGenerator extends base_1.BaseGenerator {
305
308
  ];
306
309
  }
307
310
  async generateService(options) {
311
+ var _a;
308
312
  const { entity, relationships } = options;
309
313
  const { name: entityName } = entity;
310
314
  const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
@@ -316,6 +320,10 @@ class PythonGenerator extends base_1.BaseGenerator {
316
320
  primaryKeyType,
317
321
  associations: [...new Set(relationshipsForTemplate)],
318
322
  scope: (0, guards_1.entityScope)(entity, Boolean(options.auth)),
323
+ // Foreign keys a write must check: those onto tenant-scoped entities.
324
+ references: Object.entries((0, guards_1.scopedReferences)(entity, relationshipsForTemplate
325
+ .filter((a) => a.type === "ManyToOne" || (a.type === "OneToOne" && a.joinTable))
326
+ .map((a) => [a.camelCasedId, a.name]), (0, guards_1.relationScopes)(options.allEntities, (_a = options.relationshipMap) !== null && _a !== void 0 ? _a : this.config.relationshipMap, Boolean(options.auth)))).map(([field, target]) => ({ field, target })),
319
327
  };
320
328
  const content = await this.renderTemplate("./services/service", data);
321
329
  return [
@@ -368,7 +376,12 @@ class PythonGenerator extends base_1.BaseGenerator {
368
376
  createdAt,
369
377
  updatedAt,
370
378
  columns,
371
- associations: relationshipsTemplate,
379
+ // Auth entities are for service callers only, so no other entity's
380
+ // response carries one.
381
+ associations: relationshipsTemplate.map((r) => ({
382
+ ...r,
383
+ hidden: (0, guards_1.hidesRelation)(entityName, r.name, allEntities, options.auth),
384
+ })),
372
385
  apiType: apiType !== null && apiType !== void 0 ? apiType : "rest",
373
386
  importEnums: (0, field_1.typeExistsInEntity)(entity, "enum") !== -1,
374
387
  };
@@ -451,10 +464,10 @@ ${downStatements || " pass"}
451
464
  },
452
465
  ];
453
466
  }
454
- async generateIndexModule(entities, _apiType, opts) {
467
+ async generateIndexModule(entities, _apiType, _opts) {
455
468
  const content = await this.renderTemplate("./index-module", {
456
469
  entities,
457
- hasAuth: Boolean(opts === null || opts === void 0 ? void 0 : opts.auth),
470
+ permissions: (0, guards_1.hasPermissions)(entities),
458
471
  });
459
472
  return [
460
473
  {
@@ -537,28 +550,39 @@ ${downStatements || " pass"}
537
550
  },
538
551
  ];
539
552
  }
540
- async generateGuards(entities, auth) {
541
- if (!auth)
542
- return [];
543
- const nested = (0, guards_1.nestedScopeEntities)(entities);
553
+ async generateGuards(entities, auth, relationshipMap) {
554
+ var _a, _b;
555
+ if (relationshipMap === void 0) { relationshipMap = (_a = this.config.relationshipMap) !== null && _a !== void 0 ? _a : {}; }
556
+ const mcp = entities.some((e) => (0, guards_1.mcpToolNames)(e, auth).mcp.length > 0);
557
+ // Fails on a grants entity that would be an escalation path.
558
+ const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
559
+ if (permissions && !auth)
560
+ throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
561
+ const nested = auth ? (0, guards_1.nestedScopeEntities)(entities) : [];
544
562
  if (nested.length > 0)
545
- console.warn(`[apso] Nested scopeBy paths are enforced in TypeScript services only; ${nested.join(", ")} will not be filtered by those paths in this Python service`);
546
- let data;
547
- if ((0, types_1.isJwtAuth)(auth)) {
548
- data = { jwt: (0, types_1.resolveJwtAuth)(auth) };
549
- }
550
- else if ((0, types_1.isApiKeyAuth)(auth)) {
551
- const apiKey = (0, guards_1.apiKeyTemplateData)((0, types_1.resolveApiKeyAuth)(auth), entities);
552
- data = {
553
- apiKey: { ...apiKey, pyModule: apiKey.apiKeyEntity.toLowerCase() },
554
- };
555
- }
556
- else {
557
- throw new Error(`auth.provider "${auth.provider}" is generated for TypeScript services only. For Python, use "jwt" (Better Auth issues JWTs with its JWT plugin) or "api-key".`);
558
- }
559
- return [
563
+ throw new Error(`${nested.join(", ")}: a scopeBy path through a parent (for example "project.organizationId") is enforced in TypeScript services only for now. In Python, put the tenant field on the entity and scope by it, or generate with --language typescript.`);
564
+ // The API key check is part of every service; auth adds user sign-in.
565
+ // One entry per trusted issuer; undefined when there is no sign-in.
566
+ const jwt = (0, types_1.resolveJwtProviders)(auth);
567
+ const data = {
568
+ jwt: jwt.length > 0 ? jwt : undefined,
569
+ mcp,
570
+ // Routes only a service caller reaches (sessions, accounts, ...).
571
+ authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
572
+ relationScopes: (_b = (0, guards_1.relationScopes)(entities, relationshipMap, Boolean(auth))) !== null && _b !== void 0 ? _b : {},
573
+ };
574
+ const files = [
560
575
  { path: "auth.py", content: await this.renderTemplate("./auth", data) },
561
576
  ];
577
+ if (permissions)
578
+ files.push({
579
+ path: "permissions.py",
580
+ content: await this.renderTemplate("./permissions", { permissions }),
581
+ });
582
+ // The /mcp endpoint; app/main.py mounts it (see ensurePythonMcpWiring).
583
+ if (mcp)
584
+ files.push({ path: "mcp.py", content: await this.renderTemplate("./mcp", {}) });
585
+ return files;
562
586
  }
563
587
  async generateQueryUtils(_entities, _apiType) {
564
588
  const queryContent = await this.renderTemplate("./utils/query", {});
@@ -16,7 +16,7 @@ export declare class TypeScriptGenerator extends BaseGenerator {
16
16
  generateModule(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
17
17
  generateMigration(_options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
18
18
  generateEnums(entities: Entity[], apiType: string): Promise<GeneratedFile[]>;
19
- generateIndexModule(entities: Entity[], apiType: string, opts?: {
19
+ generateIndexModule(entities: Entity[], apiType: string, _opts?: {
20
20
  emitEvents?: boolean;
21
21
  auth?: AuthConfig;
22
22
  }): Promise<GeneratedFile[]>;
@@ -41,8 +41,6 @@ export declare class TypeScriptGenerator extends BaseGenerator {
41
41
  generateDomainEvents(entities: Entity[], _apiType?: string, opts?: {
42
42
  emitEvents?: boolean;
43
43
  }): Promise<GeneratedFile[]>;
44
- /**
45
- * Normalizes auth config by applying defaults for DB session providers
46
- */
47
- private normalizeAuthConfig;
44
+ /** True when requests can load a relation that is tenant-scoped or limited by role. */
45
+ private hasRelationAccess;
48
46
  }
@@ -40,20 +40,21 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
40
40
  return ".ts";
41
41
  }
42
42
  validateConfig(config) {
43
- var _a;
43
+ var _a, _b;
44
44
  const errors = [];
45
45
  const warnings = [];
46
46
  // Validate that entities are provided
47
47
  if (!config.entities || config.entities.length === 0) {
48
48
  errors.push("No entities defined in configuration");
49
49
  }
50
+ errors.push(...(0, guards_1.removedScopeOptionErrors)((_a = config.entities) !== null && _a !== void 0 ? _a : []));
50
51
  // Validate each entity
51
52
  for (const entity of config.entities) {
52
53
  if (!entity.name) {
53
54
  errors.push("Entity missing required 'name' property");
54
55
  }
55
56
  // Validate field types
56
- for (const field of (_a = entity.fields) !== null && _a !== void 0 ? _a : []) {
57
+ for (const field of (_b = entity.fields) !== null && _b !== void 0 ? _b : []) {
57
58
  if (!field.name) {
58
59
  errors.push(`Entity '${entity.name}' has a field without a name`);
59
60
  }
@@ -66,6 +67,11 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
66
67
  if (config.apiType && !["rest", "graphql"].includes(config.apiType)) {
67
68
  errors.push(`Invalid API type: '${config.apiType}'. Must be 'rest' or 'graphql'`);
68
69
  }
70
+ // The GraphQL templates are incomplete, and no access guard runs on
71
+ // GraphQL resolvers, so a GraphQL service would answer without credentials.
72
+ if (config.apiType === "graphql") {
73
+ errors.push('apiType "Graphql" cannot be generated for TypeScript: the built-in API key and sign-in checks cover REST routes only, so a GraphQL service would answer requests with no credentials. Set "apiType": "Rest" in .apsorc.');
74
+ }
69
75
  return this.createValidationResult(errors, warnings);
70
76
  }
71
77
  async generateEntity(options) {
@@ -122,14 +128,22 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
122
128
  var _a;
123
129
  const { entity, relationships, relationshipMap, auth } = options;
124
130
  const { name: entityName } = entity;
125
- const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships);
131
+ // Auth entities are for service callers only, so no other entity's
132
+ // controller joins onto them.
133
+ const authEntities = new Set((0, guards_1.authEntityNames)(options.allEntities, auth));
134
+ const joinable = (r) => authEntities.has(entityName) || !authEntities.has(r.name);
135
+ const relationshipsForTemplate = (0, relationships_1.getRelationshipForTemplate)(entityName, relationships === null || relationships === void 0 ? void 0 : relationships.filter((r) => joinable(r)));
136
+ const joinMap = Object.fromEntries(Object.entries(relationshipMap !== null && relationshipMap !== void 0 ? relationshipMap : {}).map(([name, list]) => [
137
+ name,
138
+ list.filter((r) => joinable(r)),
139
+ ]));
126
140
  // Handle nested relationships for joins
127
141
  const tmpDir = os.tmpdir();
128
142
  const nestedJoinsFile = path.join(tmpDir, `apso-nested-joins-${entityName}-${Date.now()}.eta`);
129
143
  const nestedJoinsStream = fs.createWriteStream(nestedJoinsFile, {
130
144
  encoding: "utf8",
131
145
  });
132
- await (0, parse_1.streamNestedRelationships)(entityName, relationshipMap, nestedJoinsStream);
146
+ await (0, parse_1.streamNestedRelationships)(entityName, joinMap, nestedJoinsStream);
133
147
  nestedJoinsStream.end();
134
148
  await new Promise((resolve) => {
135
149
  nestedJoinsStream.on("finish", () => resolve());
@@ -142,18 +156,14 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
142
156
  ? (0, guards_1.getScopedEntities)([entity], relationshipMap)[0]
143
157
  : undefined;
144
158
  const scopes = (_a = scoped === null || scoped === void 0 ? void 0 : scoped.scopes) !== null && _a !== void 0 ? _a : [];
145
- // Only emitted when scopeOptions differ from the defaults, so services
146
- // without them keep the same generated controller.
147
- const scopeOptions = scoped &&
148
- (scoped.bypassRoles.length > 0 ||
149
- !scoped.injectOnCreate ||
150
- ["find", "get", "create", "update", "delete"].some((op) => !scoped.enforceOn.includes(op)))
151
- ? {
152
- enforceOn: scoped.enforceOn,
153
- bypassRoles: scoped.bypassRoles,
154
- injectOnCreate: scoped.injectOnCreate,
155
- }
156
- : undefined;
159
+ // Which requests the tenant filter covers; a service caller (API key)
160
+ // always skips it.
161
+ const scopeOptions = scoped && {
162
+ bypassRoles: scoped.bypassRoles,
163
+ };
164
+ const mcp = (0, guards_1.mcpOperations)(entity);
165
+ if (mcp.length > 0 && !auth)
166
+ throw new Error(`${entityName}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
157
167
  const data = {
158
168
  svcName,
159
169
  ctrlName,
@@ -169,6 +179,12 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
169
179
  crudAuth: scopes.filter((s) => s.direct),
170
180
  crudAuthNested: scopes.filter((s) => s.fkField),
171
181
  scopeOptions,
182
+ // Every controller checks which relations a request may load.
183
+ relationAccess: this.hasRelationAccess(options.allEntities, relationshipMap, auth),
184
+ // Operations exposed as MCP tools, and the names the tools get.
185
+ mcp,
186
+ mcpName: (0, casing_1.snakeCase)(entityName),
187
+ mcpPluralName: (0, casing_1.snakeCase)(pluralEntityName),
172
188
  };
173
189
  const controllerContent = await this.renderTemplate("./rest/controller-rest", data);
174
190
  const specContent = await this.renderTemplate("./rest/controller-rest-spec", data);
@@ -341,13 +357,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
341
357
  },
342
358
  ];
343
359
  }
344
- async generateIndexModule(entities, apiType, opts) {
345
- // generateGuards emits GuardsModule whenever auth or scopeBy is configured;
346
- // listing it here is what turns its global guards on.
347
- const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, {
348
- entities,
349
- hasGuards: Boolean(opts === null || opts === void 0 ? void 0 : opts.auth) || (0, guards_1.hasScopedEntities)(entities),
350
- });
360
+ async generateIndexModule(entities, apiType, _opts) {
361
+ // Listing GuardsModule is what turns the global guards on; every service
362
+ // has at least the API key check.
363
+ const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities });
351
364
  return [
352
365
  {
353
366
  path: "index.ts",
@@ -357,51 +370,61 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
357
370
  }
358
371
  async generateGuards(entities, auth, relationshipMap) {
359
372
  const hasScopes = (0, guards_1.hasScopedEntities)(entities);
360
- const normalizedAuth = this.normalizeAuthConfig(auth);
361
- const jwt = auth && (0, auth_1.isJwtAuth)(auth) ? (0, auth_1.resolveJwtAuth)(auth) : undefined;
362
- const apiKey = auth && (0, auth_1.isApiKeyAuth)(auth)
363
- ? (0, guards_1.apiKeyTemplateData)((0, auth_1.resolveApiKeyAuth)(auth), entities)
364
- : undefined;
365
- const hasAuth = Boolean(normalizedAuth || jwt || apiKey);
366
- if (!hasScopes && !hasAuth) {
367
- return [];
373
+ // One entry per trusted issuer; undefined when there is no sign-in.
374
+ const jwtProviders = (0, auth_1.resolveJwtProviders)(auth);
375
+ const jwt = jwtProviders.length > 0 ? jwtProviders : undefined;
376
+ const hasAuth = Boolean(jwt);
377
+ // Roles come from the caller's identity; without auth there are none, and
378
+ // a permissions block that is silently not enforced is worse than an error.
379
+ const permissions = (0, guards_1.getPermissionConfig)(entities, relationshipMap, auth);
380
+ if (permissions && !hasAuth) {
381
+ throw new Error("permissions in .apsorc need an auth block: roles come from the signed-in caller");
368
382
  }
369
383
  const scopedEntities = (0, guards_1.getScopedEntities)(entities, relationshipMap);
370
384
  const files = [];
371
- const authEntities = normalizedAuth
372
- ? [
373
- normalizedAuth.sessionEntity,
374
- normalizedAuth.userEntity,
375
- ...(normalizedAuth.accountUserEntity
376
- ? [normalizedAuth.accountUserEntity]
377
- : []),
378
- ]
379
- : apiKey
380
- ? [apiKey.apiKeyEntity]
381
- : [];
382
385
  const templateData = {
383
386
  scopedEntities,
387
+ // Every entity by route: the scope guard checks relations in write bodies.
388
+ routeEntities: entities.map((e) => ({ route: (0, guards_1.toRouteName)(e.name), name: e.name })),
384
389
  // Nested paths are only enforced on list and create with a caller's tenant.
385
390
  hasNestedFk: hasAuth && scopedEntities.some((e) => e.scopes.some((s) => s.fkField)),
386
- authConfig: normalizedAuth,
387
391
  hasAuth,
388
- authProvider: auth === null || auth === void 0 ? void 0 : auth.provider,
389
- authEntities,
392
+ authProvider: (0, auth_1.authProviders)(auth).map((a) => a.provider).join(", "),
393
+ // Routes only a service caller reaches (sessions, accounts, ...).
394
+ authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
390
395
  jwt,
391
- apiKey,
396
+ permissions,
397
+ // OAuth sign-in for MCP clients: tokens come from the listed issuers.
398
+ mcpAuth: hasAuth && entities.some((e) => (0, guards_1.mcpOperations)(e).length > 0),
392
399
  };
400
+ // The API key check is part of every service.
401
+ files.push({
402
+ path: "guards/key.guard.ts",
403
+ content: await this.renderTemplate("./guards/key.guard.eta", templateData),
404
+ });
393
405
  // Generate auth.guard.ts if auth is configured
394
406
  if (hasAuth) {
395
- const authGuardContent = await this.renderTemplate(jwt
396
- ? "./guards/jwt-auth.guard.eta"
397
- : apiKey
398
- ? "./guards/api-key-auth.guard.eta"
399
- : "./guards/auth.guard.eta", templateData);
407
+ const authGuardContent = await this.renderTemplate("./guards/jwt-auth.guard.eta", templateData);
400
408
  files.push({
401
409
  path: "guards/auth.guard.ts",
402
410
  content: authGuardContent,
403
411
  });
404
412
  }
413
+ if (this.hasRelationAccess(entities, relationshipMap, auth)) {
414
+ files.push({
415
+ path: "guards/relations.interceptor.ts",
416
+ content: await this.renderTemplate("./guards/relations.interceptor.eta", {
417
+ permissions: Boolean(permissions),
418
+ relationScopes: (0, guards_1.relationScopes)(entities, relationshipMap, hasAuth),
419
+ }),
420
+ });
421
+ }
422
+ if (permissions) {
423
+ files.push({
424
+ path: "guards/permission.guard.ts",
425
+ content: await this.renderTemplate("./guards/permission.guard.eta", templateData),
426
+ });
427
+ }
405
428
  // Generate scope.guard.ts if there are scoped entities
406
429
  if (hasScopes) {
407
430
  const scopeGuardContent = await this.renderTemplate("./guards/scope.guard.eta", templateData);
@@ -458,19 +481,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
458
481
  },
459
482
  ];
460
483
  }
461
- /**
462
- * Normalizes auth config by applying defaults for DB session providers
463
- */
464
- normalizeAuthConfig(auth) {
465
- if (!auth)
466
- return undefined;
467
- if ((0, auth_1.isDbSessionAuth)(auth)) {
468
- return {
469
- ...auth_1.DB_SESSION_AUTH_DEFAULTS,
470
- ...auth,
471
- };
472
- }
473
- return undefined;
484
+ /** True when requests can load a relation that is tenant-scoped or limited by role. */
485
+ hasRelationAccess(entities, relationshipMap, auth) {
486
+ return Boolean(auth &&
487
+ ((0, guards_1.hasPermissions)(entities) || (0, guards_1.relationScopes)(entities, relationshipMap, true)));
474
488
  }
475
489
  }
476
490
  exports.TypeScriptGenerator = TypeScriptGenerator;
@@ -1,4 +1,4 @@
1
- import { Entity, RelationshipMap, ResolvedApiKeyAuth } from "./types";
1
+ import { AuthConfig, Entity, PermissionOperation, RelationshipMap } from "./types";
2
2
  /**
3
3
  * Represents a scope field configuration for template rendering
4
4
  */
@@ -24,10 +24,14 @@ export interface ScopedEntityConfig {
24
24
  routeName: string;
25
25
  repoName: string;
26
26
  scopes: ScopeFieldConfig[];
27
- injectOnCreate: boolean;
28
- enforceOn: string[];
29
27
  bypassRoles: string[];
30
28
  }
29
+ /**
30
+ * One error per removed scopeOptions key an entity still sets. `apso generate`
31
+ * and `apso schema validate` both refuse it.
32
+ */
33
+ export declare function removedScopeOptionErrors(entities: Entity[]): string[];
34
+ export declare function toRouteName(entityName: string): string;
31
35
  /**
32
36
  * Extracts scoped entity configurations from all entities. Pass the
33
37
  * relationship map to resolve nested paths to their foreign keys.
@@ -37,16 +41,65 @@ export declare function getScopedEntities(entities: Entity[], relationshipMap?:
37
41
  * Checks if any entities have scopeBy configured.
38
42
  */
39
43
  export declare function hasScopedEntities(entities: Entity[]): boolean;
40
- /** API key settings plus what the key entity offers, as the guard templates use them. */
41
- export interface ApiKeyTemplateData extends ResolvedApiKeyAuth {
42
- hasStatus: boolean;
43
- hasExpiresAt: boolean;
44
+ /**
45
+ * Operations an entity exposes as MCP tools, from its `mcp` setting.
46
+ * Empty when the entity has not opted in.
47
+ */
48
+ export declare function mcpOperations(entity: Entity): PermissionOperation[];
49
+ /**
50
+ * The entities that store Better Auth's own rows when the better-auth
51
+ * provider is listed: the auth block's session, user and membership
52
+ * (accountUserEntity) entities, and Better Auth's other tables (account,
53
+ * verification, the organization plugin's member and invitation, the JWT
54
+ * plugin's jwks, the OAuth provider's tables). Only a service caller (API
55
+ * key) reaches them: the key guard refuses a signed-in user on their routes,
56
+ * no other entity's controller joins onto them, and they cannot be MCP tools.
57
+ */
58
+ export declare function authEntityNames(entities: Entity[], auth?: AuthConfig): string[];
59
+ /**
60
+ * True for a relation that a response must not carry: one from another entity
61
+ * onto an auth entity. Auth entities keep the relations between themselves.
62
+ */
63
+ export declare function hidesRelation(entityName: string, relatedName: string, entities: Entity[], auth?: AuthConfig): boolean;
64
+ /** The auth entities' route names (sessions), for the key guard. */
65
+ export declare const authEntityRoutes: (entities: Entity[], auth?: AuthConfig) => string[];
66
+ /**
67
+ * An entity's MCP operations and the names its tools get, the same in every
68
+ * language: list_line_items, get_line_item, create_line_item and so on.
69
+ */
70
+ export declare function mcpToolNames(entity: Entity, auth?: AuthConfig): {
71
+ mcp: ("create" | "update" | "delete" | "read")[];
72
+ mcpName: string;
73
+ mcpPluralName: string;
74
+ };
75
+ export declare function hasPermissions(entities: Entity[]): boolean;
76
+ /** One guarded operation: its permission name and the roles that have it by default. */
77
+ export interface PermissionRule {
78
+ permission: string;
79
+ roles: string[];
80
+ }
81
+ /** What the permission guard template needs. */
82
+ export interface PermissionConfig {
83
+ /** Guarded operations by route name (projects). */
84
+ routes: Record<string, Partial<Record<PermissionOperation, PermissionRule>>>;
85
+ /**
86
+ * Read rules a `?join` must satisfy, by relation name (singular and plural).
87
+ * A name shared by relations to different entities must satisfy all of them.
88
+ */
89
+ joins: Record<string, PermissionRule[]>;
90
+ /** The entity whose rows grant permissions to roles at runtime, if declared. */
91
+ grants?: {
92
+ entity: string;
93
+ tenantField?: string;
94
+ };
44
95
  }
45
96
  /**
46
- * Check the API key entity exists and has the hash field, and note whether it
47
- * has `status` and `expiresAt`, which the guard then enforces.
97
+ * Validates every entity's permissions and resolves them to permission names
98
+ * ("invoice:delete") by route and by join name, so a role that cannot read
99
+ * Task cannot read it through /projects?join=tasks either. Undefined when no
100
+ * entity has permissions.
48
101
  */
49
- export declare function apiKeyTemplateData(apiKey: ResolvedApiKeyAuth, entities: Entity[]): ApiKeyTemplateData;
102
+ export declare function getPermissionConfig(entities: Entity[], relationshipMap?: RelationshipMap, auth?: AuthConfig): PermissionConfig | undefined;
50
103
  /** A direct scopeBy field and the auth context value that fills it. */
51
104
  export interface DirectScopeField {
52
105
  field: string;
@@ -56,9 +109,7 @@ export interface DirectScopeField {
56
109
  /** What Go and Python services need to scope one entity. */
57
110
  export interface EntityScopeData {
58
111
  fields: DirectScopeField[];
59
- enforceOn: string[];
60
112
  bypassRoles: string[];
61
- injectOnCreate: boolean;
62
113
  }
63
114
  /**
64
115
  * The direct scopeBy fields of an entity, for services that filter in their
@@ -67,5 +118,52 @@ export interface EntityScopeData {
67
118
  * included; see hasNestedScopes.
68
119
  */
69
120
  export declare function entityScope(entity: Entity, hasAuth: boolean): EntityScopeData | undefined;
70
- /** Entities whose scopeBy uses a nested path, which Go and Python do not enforce. */
121
+ /** One entity in the relation table every generated service checks. */
122
+ export interface RelationScope {
123
+ /** Set when the entity's reads are tenant-scoped: the roles that skip its scope. */
124
+ bypassRoles?: string[];
125
+ /**
126
+ * Set with bypassRoles: the entity's own scopeBy fields and the caller
127
+ * value each must equal (userId, email, or any other name for the tenant).
128
+ * Rows loaded through a relation are limited by these, so a row that points
129
+ * at another tenant's row does not carry it into a response.
130
+ */
131
+ scope?: Record<string, string>;
132
+ /**
133
+ * Each relation a request can load, by the name requests use: the entity it
134
+ * loads, and whether a caller limited to its tenant on this entity stays in
135
+ * that tenant on the related rows (the target is scoped by the same keys).
136
+ */
137
+ relations: Record<string, [entity: string, sameTenant: boolean]>;
138
+ }
139
+ /**
140
+ * The relation table for the one rule on loading relations (R7): the tenant
141
+ * filter limits only the entity a request starts from, so a user caller may
142
+ * load a relation onto a tenant-scoped entity only when
143
+ * - the caller holds a role that skips that entity's scope, or
144
+ * - the caller is limited to its tenant on the entity the relation starts
145
+ * from, and the target is scoped by the same keys (Project.tasks).
146
+ * Any other load is refused, for every query syntax and at every depth. The
147
+ * rows of an allowed same-key relation are still limited to the caller's
148
+ * tenant by the target's own scope fields (`scope`), so the rule does not rely
149
+ * on every stored foreign key pointing inside the tenant. A service caller is
150
+ * not limited. Each language walks this table at run time.
151
+ *
152
+ * Undefined without auth or when no entity is scoped.
153
+ */
154
+ export declare function relationScopes(entities: Entity[], relationshipMap: RelationshipMap | undefined, hasAuth: boolean): Record<string, RelationScope> | undefined;
155
+ /** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
71
156
  export declare function nestedScopeEntities(entities: Entity[]): string[];
157
+ /**
158
+ * One warning per provider that maps no tenant claim while entities are
159
+ * tenant-scoped: its users would get 403 on every one of those entities.
160
+ */
161
+ export declare function tenantClaimWarnings(entities: Entity[], auth?: AuthConfig): string[];
162
+ /**
163
+ * The foreign keys of an entity that point at a tenant-scoped entity, as
164
+ * field -> that entity, from [field, entity] pairs in the generator's own
165
+ * naming. On a write a user caller may only name rows it could read there
166
+ * (R8). The entity's own scopeBy fields are left out: a write sets those from
167
+ * the caller.
168
+ */
169
+ export declare function scopedReferences(entity: Entity, foreignKeys: [field: string, target: string][], scopes: Record<string, RelationScope> | undefined): Record<string, string>;