@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
@@ -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>;