@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
package/README.md CHANGED
@@ -54,7 +54,7 @@ Add to your MCP configuration:
54
54
  | `design_schema` | Design a database schema from application requirements |
55
55
  | `validate_schema` | Validate an `.apsorc` schema file |
56
56
  | `scaffold_api` | Generate API code from schema (TypeScript, Python, or Go) |
57
- | `setup_auth` | Configure authentication (BetterAuth, Auth0, Clerk, Cognito, API Keys) |
57
+ | `setup_auth` | Configure authentication (Better Auth, Auth0, Clerk, Cognito, any JWT issuer) |
58
58
  | `start_dev_server` | Start local dev environment via Docker Compose |
59
59
  | `deploy_api` | Deploy to the Apso platform |
60
60
 
@@ -107,6 +107,33 @@ apso dev
107
107
 
108
108
  Your API is live at `http://localhost:3000` with Swagger docs at `/api`. The generated code lives in `src/autogen/` and is standard NestJS with TypeORM -- no Apso runtime dependency.
109
109
 
110
+ ## Querying a generated API
111
+
112
+ A TypeScript service reads with the [PostgREST query syntax](https://docs.postgrest.org/en/v16/references/api/tables_views.html) and no other.
113
+
114
+ ```bash
115
+ # Filter, choose columns, embed a related row, sort and page
116
+ curl -H "x-api-key: $APSO_API_KEY" \
117
+ "http://localhost:3000/Projects?status=eq.open&select=id,title,organization(name)&order=id.desc&limit=20&offset=40"
118
+
119
+ # Any of several conditions
120
+ curl -H "x-api-key: $APSO_API_KEY" "http://localhost:3000/Projects?or=(status.eq.open,title.ilike.*urgent*)"
121
+
122
+ # Ask for the total
123
+ curl -i -H "x-api-key: $APSO_API_KEY" -H "Prefer: count=exact" "http://localhost:3000/Projects?limit=20"
124
+ # HTTP/1.1 206 Partial Content
125
+ # Content-Range: 0-19/42
126
+ ```
127
+
128
+ - A filter is `column=operator.value`. Operators: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like` and `ilike` (`*` is the wildcard), `in.(a,b)`, `is.null`, `is.not_null`, `is.true`, `is.false`. Put `not.` in front to negate.
129
+ - A list is a JSON array. The `Content-Range` response header gives the rows returned, and the total when the request sends `Prefer: count=exact`.
130
+ - With no `limit` a list returns 25 rows, the same default as Python and Go services. When more exist the status is 206 and `Content-Range` has the total. The largest `limit` is 100.
131
+ - A filter on a related row needs the relation in `select`: `select=id,tasks!inner(title)&tasks.title=eq.Ship`.
132
+ - The older nestjsx parameters (`filter`, `or` in its `field||$op||value` form, `join`, `sort`, `s`, `fields`, `page`, `per_page`, `cache`) get a 400 that names the PostgREST equivalent.
133
+ - MCP list tools take the same arguments: one per column, plus `select`, `order`, `limit`, `offset`, `or`, `and`, and `embedded` for filters on related rows.
134
+
135
+ The full list of what is supported and what is refused is in the `@apso/crud` package, in `docs/DIALECTS.md`. Python and Go services accept this syntax and, for now, the nestjsx syntax as well.
136
+
110
137
  ## Commands
111
138
 
112
139
  | Command | Subcommands | Description |
@@ -8,6 +8,8 @@ export default class Dev extends BaseCommand {
8
8
  build: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
9
  };
10
10
  private children;
11
+ /** Set on the service: the local flag and the development API key. */
12
+ private devEnv;
11
13
  private cleanup;
12
14
  run(): Promise<void>;
13
15
  /**
@@ -7,10 +7,13 @@ const fs = tslib_1.__importStar(require("fs"));
7
7
  const path = tslib_1.__importStar(require("path"));
8
8
  const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
9
9
  const base_command_1 = tslib_1.__importDefault(require("../lib/base-command"));
10
+ const template_1 = require("../lib/utils/template");
10
11
  class Dev extends base_command_1.default {
11
12
  constructor() {
12
13
  super(...arguments);
13
14
  this.children = [];
15
+ /** Set on the service: the local flag and the development API key. */
16
+ this.devEnv = {};
14
17
  this.cleanup = () => {
15
18
  for (const child of this.children) {
16
19
  child.kill("SIGTERM");
@@ -18,7 +21,18 @@ class Dev extends base_command_1.default {
18
21
  };
19
22
  }
20
23
  async run() {
24
+ var _a;
21
25
  const { flags } = await this.parse(Dev);
26
+ // Every generated service refuses requests without a key or a signed-in
27
+ // user. A project cloned from git has no .env key, so create one.
28
+ const created = process.env.APSO_API_KEY
29
+ ? undefined
30
+ : (0, template_1.ensureDevKey)(process.cwd());
31
+ if (created)
32
+ this.log(`Created a development API key in .env. Send it in the x-api-key header:\n ${created}`);
33
+ // Python and Go services do not read .env themselves.
34
+ const key = (_a = process.env.APSO_API_KEY) !== null && _a !== void 0 ? _a : this.readEnvValue("APSO_API_KEY");
35
+ this.devEnv = { APSO_LOCAL: "1", ...(key ? { APSO_API_KEY: key } : {}) };
22
36
  if (flags.docker) {
23
37
  return this.runDocker(flags);
24
38
  }
@@ -63,7 +77,7 @@ class Dev extends base_command_1.default {
63
77
  "Make sure you are in an Apso TypeScript project root.");
64
78
  }
65
79
  this.log(`Starting TypeScript dev server (npm run ${script})...`);
66
- await this.spawnAndWait("npm", ["run", script]);
80
+ await this.spawnAndWait("npm", ["run", script], this.devEnv);
67
81
  }
68
82
  /**
69
83
  * Return the first script from `candidates` that exists in the local
@@ -103,7 +117,7 @@ class Dev extends base_command_1.default {
103
117
  "0.0.0.0",
104
118
  "--port",
105
119
  this.readEnvValue("PORT") || "3000",
106
- ]);
120
+ ], this.devEnv);
107
121
  }
108
122
  /**
109
123
  * Go: if pglite, start the pglite-server sidecar first, then go run.
@@ -116,7 +130,7 @@ class Dev extends base_command_1.default {
116
130
  await this.waitForPort(5432, 10000);
117
131
  }
118
132
  this.log("Starting Go dev server...");
119
- await this.spawnAndWait("go", ["run", "cmd/main.go"]);
133
+ await this.spawnAndWait("go", ["run", "cmd/main.go"], this.devEnv);
120
134
  }
121
135
  /**
122
136
  * Fallback: run docker compose up (the old behavior).
@@ -135,8 +149,11 @@ class Dev extends base_command_1.default {
135
149
  if (flags.detach)
136
150
  args.push("-d");
137
151
  this.log(`Running: ${args.join(" ")}`);
152
+ // The templates' docker-compose.yml passes the key and the local flag on
153
+ // to the service's container.
138
154
  await this.spawnAndWait(args[0], args.slice(1), {
139
155
  AUTH_DISABLED: "true",
156
+ ...this.devEnv,
140
157
  });
141
158
  }
142
159
  // --- Helpers ---
@@ -6,12 +6,12 @@ const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
7
7
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
8
8
  const lib_1 = require("../lib");
9
- const types_1 = require("../lib/types");
10
9
  const base_command_1 = tslib_1.__importDefault(require("../lib/base-command"));
11
10
  const interactive_1 = require("../lib/utils/interactive");
12
11
  const perf_hooks_1 = require("perf_hooks");
13
12
  const file_system_1 = require("../lib/utils/file-system");
14
13
  const git_hooks_1 = require("../lib/utils/git-hooks");
14
+ const guards_1 = require("../lib/guards");
15
15
  const crud_deps_1 = require("../lib/utils/crud-deps");
16
16
  const pglite_upgrade_1 = require("../lib/utils/pglite-upgrade");
17
17
  class Generate extends base_command_1.default {
@@ -95,6 +95,8 @@ class Generate extends base_command_1.default {
95
95
  if (validationResult.warnings.length > 0) {
96
96
  console.log(`[apso] Warnings:\n${validationResult.warnings.join("\n")}`);
97
97
  }
98
+ for (const warning of (0, guards_1.tenantClaimWarnings)(entities, auth))
99
+ this.warn(warning);
98
100
  // Generate enums
99
101
  const enumFiles = await generator.generateEnums(entities, lowerCaseApiType);
100
102
  for (const file of enumFiles) {
@@ -259,34 +261,74 @@ class Generate extends base_command_1.default {
259
261
  }
260
262
  // Generated TS code imports @apso/crud*. Projects from the v1 template
261
263
  // (@nestjsx/crud) don't declare those, and every entity then fails to
262
- // compile with TS2307. Declare them so the next install picks them up.
264
+ // compile with TS2307. Older v2 projects declare a release without the
265
+ // PostgREST-only option the controllers set. Declare the packages, or
266
+ // raise their range, so the next install picks them up.
263
267
  if (language === "typescript" && generatedFileCount > 0) {
264
268
  const added = (0, crud_deps_1.ensureCrudDeps)(process.cwd());
265
269
  if (added.length > 0) {
266
- console.log(`[apso] Added ${added.join(", ")} to package.json (the generated code imports them). Run npm install before building.`);
270
+ console.log(`[apso] Set ${added.join(", ")} in package.json to the version the generated code needs. Run npm install before building.`);
267
271
  }
268
272
  // The pre-deploy checks run on PGlite; give a stock v1 config support.
269
273
  if ((0, pglite_upgrade_1.upgradeOrmConfigForPglite)(process.cwd())) {
270
274
  console.log("[apso] Updated src/orm.config.ts so `apso migrate verify` and `apso test smoke` can run on a local PGlite database. Run npm install before building.");
271
275
  }
272
276
  }
273
- // The generated auth code imports a JWT library; declare it.
274
- if (auth && (0, types_1.isJwtAuth)(auth)) {
275
- if (language === "typescript" &&
276
- (0, crud_deps_1.addMissingDeps)(process.cwd(), crud_deps_1.JOSE_DEP).length > 0)
277
- console.log("[apso] Added jose to package.json (the generated auth guard imports it). Run npm install before building.");
278
- if (language === "python" &&
279
- (0, crud_deps_1.addMissingPythonDep)(process.cwd(), crud_deps_1.PYJWT_DEP))
280
- console.log(`[apso] Added ${crud_deps_1.PYJWT_DEP} to pyproject.toml (the generated auth module imports it). Reinstall the project's dependencies.`);
281
- if (language === "go")
282
- console.log("[apso] The generated auth middleware imports github.com/golang-jwt/jwt/v5 and github.com/MicahParks/keyfunc/v3. Run go mod tidy before building.");
277
+ // Entities that opt in to MCP need the library and its endpoint.
278
+ if (language === "typescript" && entities.some((entity) => entity.mcp)) {
279
+ const wired = (0, crud_deps_1.ensureMcpWiring)(process.cwd(), rootFolder);
280
+ if (wired.length > 0)
281
+ console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). Run npm install before building.`);
283
282
  }
283
+ if ((language === "python" || language === "go") &&
284
+ !entities.some((entity) => entity.mcp)) {
285
+ const unwired = (0, crud_deps_1.removeAppMcpWiring)(process.cwd(), language);
286
+ if (unwired.length > 0)
287
+ console.log(`[apso] No entity has mcp any more: removed the /mcp endpoint from ${unwired.join(", ")}.`);
288
+ }
289
+ if ((language === "python" || language === "go") &&
290
+ entities.some((entity) => entity.mcp)) {
291
+ const wired = (0, crud_deps_1.ensureAppMcpWiring)(process.cwd(), language);
292
+ if (wired.length > 0)
293
+ console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). ${language === "python"
294
+ ? "Reinstall the project's dependencies."
295
+ : "Run go mod tidy before building; the MCP SDK needs Go 1.25."}`);
296
+ }
297
+ // Request logging: who called, the request id, and why a guard refused.
298
+ if (language === "typescript" && generatedFileCount > 0) {
299
+ const logging = (0, crud_deps_1.ensureLoggingWiring)(process.cwd(), rootFolder);
300
+ if (logging.changed.length > 0)
301
+ console.log(`[apso] Set up request logging with @apso/logging (updated ${logging.changed.join(", ")}). Run npm install before building.`);
302
+ if (logging.manual.length > 0)
303
+ console.warn(`[apso] Could not add request logging to ${logging.manual.join(", ")}. There, import { useApsoLogging } from '@apso/logging', create the app with NestFactory.create(AppModule, { bufferLogs: true }) and call useApsoLogging(app) on the next line.`);
304
+ }
305
+ // The generated auth code (the API key check in every service, and JWT
306
+ // sign-in) imports a JWT library; declare it.
307
+ if (language === "typescript" &&
308
+ (0, crud_deps_1.addMissingDeps)(process.cwd(), crud_deps_1.JOSE_DEP).length > 0)
309
+ console.log("[apso] Added jose to package.json (the generated guards import it). Run npm install before building.");
310
+ if (language === "python" &&
311
+ (0, crud_deps_1.addMissingPythonDep)(process.cwd(), crud_deps_1.PYJWT_DEP))
312
+ console.log(`[apso] Added ${crud_deps_1.PYJWT_DEP} to pyproject.toml (the generated auth module imports it). Reinstall the project's dependencies.`);
313
+ if (language === "go")
314
+ console.log("[apso] The generated auth middleware imports github.com/golang-jwt/jwt/v5 and github.com/MicahParks/keyfunc/v3. Run go mod tidy before building.");
284
315
  if (language === "python") {
285
316
  const main = path.join(process.cwd(), "app", "main.py");
286
317
  if (fs.existsSync(main) &&
287
318
  !fs.readFileSync(main, "utf8").includes("autogen_router"))
288
319
  console.warn("[apso] app/main.py does not include autogen_router, so the generated routes are not served. Add: from app.autogen import autogen_router; app.include_router(autogen_router)");
289
320
  }
321
+ if (language === "go") {
322
+ const main = path.join(process.cwd(), "cmd", "main.go");
323
+ if (fs.existsSync(main) &&
324
+ fs.readFileSync(main, "utf8").includes("AutoMigrate(models.All()"))
325
+ console.warn("[apso] cmd/main.go runs db.AutoMigrate(models.All()...) for DATABASE_SYNC. gorm can't create the enum types, constraints and names the migrations from apso migrate use, so the two databases would differ. Replace that call with: models.Migrate(db)");
326
+ }
327
+ // The marker the hosted platform reads from the pushed source: this code
328
+ // has the built-in access check.
329
+ if (guardFiles.length > 0 &&
330
+ (0, crud_deps_1.writeAccessManifest)(process.cwd(), this.config.version))
331
+ console.warn("[apso] .apso/manifest.json is git-ignored. Commit it: the Apso platform reads it from the pushed code to confirm the service checks API keys itself.");
290
332
  const totalBuildTime = perf_hooks_1.performance.now() - totalBuildStart;
291
333
  console.log(`[apso] Finished building all entities in ${totalBuildTime.toFixed(2)} ms`);
292
334
  // Best-effort: install the commit co-author hook so commits that include
@@ -14,6 +14,7 @@ const telemetry_1 = require("../../lib/telemetry/telemetry");
14
14
  const apsorc_parser_1 = require("../../lib/apsorc-parser");
15
15
  const lib_1 = require("../../lib");
16
16
  const runner_1 = require("../../lib/doctor/runner");
17
+ const crud_deps_1 = require("../../lib/utils/crud-deps");
17
18
  const file_system_1 = require("../../lib/utils/file-system");
18
19
  const schema_convert_1 = require("../../lib/utils/schema-convert");
19
20
  const mcp_schema_tools_1 = require("../../lib/mcp-schema-tools");
@@ -93,8 +94,6 @@ class McpServe extends base_command_1.default {
93
94
  "auth0",
94
95
  "clerk",
95
96
  "cognito",
96
- "api-key",
97
- "custom-db-session",
98
97
  "none",
99
98
  ])
100
99
  .optional()
@@ -123,7 +122,10 @@ class McpServe extends base_command_1.default {
123
122
  relationships: [],
124
123
  };
125
124
  if (auth) {
126
- schemaTemplate.auth = { provider: auth };
125
+ schemaTemplate.auth =
126
+ auth === "better-auth"
127
+ ? { provider: auth, url: "https://YOUR_APP/api/auth" }
128
+ : { provider: auth };
127
129
  }
128
130
  const instructions = [
129
131
  "# Schema Design Request",
@@ -410,6 +412,10 @@ class McpServe extends base_command_1.default {
410
412
  await (0, file_system_1.createFile)(fullPath, file.content);
411
413
  filesGenerated.push(file.path);
412
414
  }
415
+ // The access marker, as apso generate writes it: the generated
416
+ // code has the built-in access check.
417
+ if (guardFiles.length > 0)
418
+ (0, crud_deps_1.writeAccessManifest)(process.cwd(), this.config.version);
413
419
  // Generate index module
414
420
  const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { auth });
415
421
  for (const file of indexFiles) {
@@ -427,7 +433,9 @@ class McpServe extends base_command_1.default {
427
433
  content: [
428
434
  {
429
435
  type: "text",
430
- text: `Generated ${lang} REST API for ${entities.length} entities (${filesGenerated.length} files) in ${elapsed}ms.\n\nOutput: ${autogenPath}\n\nEntities: ${entities.map((e) => e.name).join(", ")}${warnings}\n\nNext steps:\n1. Run \`npm install\` to install dependencies\n2. Run \`apso dev\` to start the local development server\n3. Open http://localhost:3001/api/docs for OpenAPI documentation`,
436
+ text: `Generated ${lang} REST API for ${entities.length} entities (${filesGenerated.length} files) in ${elapsed}ms.\n\nOutput: ${autogenPath}\n\nEntities: ${entities.map((e) => e.name).join(", ")}${warnings}\n\nNext steps:\n1. Run \`npm install\` to install dependencies\n2. Run \`apso dev\` to start the local development server\n3. Open http://localhost:3001/api/docs for OpenAPI documentation${lang === "typescript"
437
+ ? "\n\nList routes take the PostgREST query syntax only: one filter per column as op.value, plus select, order, limit and offset. Example: GET /Projects?status=eq.open&select=id,title,organization(name)&order=id.desc&limit=20. A list is a JSON array; the Content-Range response header has the row range and, with the request header Prefer: count=exact, the total. The older nestjsx parameters (filter, join, sort, s, fields, page) get a 400."
438
+ : ""}`,
431
439
  },
432
440
  ],
433
441
  };
@@ -454,8 +462,6 @@ class McpServe extends base_command_1.default {
454
462
  "clerk",
455
463
  "cognito",
456
464
  "jwt",
457
- "api-key",
458
- "custom-db-session",
459
465
  ])
460
466
  .optional()
461
467
  .describe("Authentication provider (default: better-auth)"),
@@ -463,7 +469,17 @@ class McpServe extends base_command_1.default {
463
469
  const authProvider = provider || "better-auth";
464
470
  const authConfigs = {
465
471
  "better-auth": {
466
- auth: { provider: "better-auth" },
472
+ // The service verifies the JWTs Better Auth issues (JWT plugin); it does not look sessions up.
473
+ auth: {
474
+ provider: "better-auth",
475
+ // Better Auth's base URL. Keys are read from <url>/jwks.
476
+ url: "https://YOUR_APP/api/auth",
477
+ // The names your definePayload puts in the token.
478
+ claims: {
479
+ workspaceId: "activeOrganizationId",
480
+ roles: "roles",
481
+ },
482
+ },
467
483
  entities: [
468
484
  {
469
485
  name: "User",
@@ -585,46 +601,13 @@ class McpServe extends base_command_1.default {
585
601
  entities: [],
586
602
  relationships: [],
587
603
  },
588
- "api-key": {
589
- auth: {
590
- provider: "api-key",
591
- apiKeyHeader: "x-api-key",
592
- apiKeyEntity: "ApiKey",
593
- },
594
- entities: [
595
- {
596
- name: "ApiKey",
597
- created_at: true,
598
- updated_at: true,
599
- scopeBy: "organizationId",
600
- fields: [
601
- { name: "name", type: "text", length: 100 },
602
- { name: "keyHash", type: "text", length: 255 },
603
- { name: "prefix", type: "text", length: 10 },
604
- { name: "scopes", type: "json-plain", nullable: true },
605
- { name: "expiresAt", type: "date", nullable: true },
606
- { name: "lastUsedAt", type: "date", nullable: true },
607
- { name: "status", type: "enum", values: ["active", "revoked"], default: "active" },
608
- ],
609
- },
610
- ],
611
- relationships: [
612
- { from: "Organization", to: "ApiKey", type: "OneToMany" },
613
- { from: "ApiKey", to: "Organization", type: "ManyToOne" },
614
- ],
615
- },
616
- "custom-db-session": {
617
- auth: { provider: "custom-db-session" },
618
- entities: [],
619
- relationships: [],
620
- },
621
604
  };
622
605
  const config = authConfigs[authProvider] || authConfigs["better-auth"];
623
606
  return {
624
607
  content: [
625
608
  {
626
609
  type: "text",
627
- text: `# Auth Setup: ${authProvider}\n\nMerge the following into your .apsorc file:\n\n\`\`\`json\n${JSON.stringify(config, null, 2)}\n\`\`\`\n\nAfter updating .apsorc:\n1. Run \`apso generate\` (or use the scaffold_api tool) to regenerate code\n2. Run \`npm install\` if new dependencies are needed\n3. Run \`apso dev\` to start the server and create auth tables\n\n${authProvider === "better-auth" ? "**Important:** BetterAuth stores passwords in the `account` table (not User). The `providerId` field must be set to \"credential\" for email/password login to work. Use `@apso/better-auth-adapter@latest` in your frontend." : authProvider === "api-key" ? "Store each key's hex SHA-256 in ApiKey.keyHash, never the key itself; callers send the key in the x-api-key header." : "Replace the issuer, audience and claim names with your " + authProvider + " tenant's values. The service checks each token's signature against the issuer's JWKS. See https://docs.apso.ai/develop/auth/byoa."}`,
610
+ text: `# Auth Setup: ${authProvider}\n\nMerge the following into your .apsorc file:\n\n\`\`\`json\n${JSON.stringify(config, null, 2)}\n\`\`\`\n\nAfter updating .apsorc:\n1. Run \`apso generate\` (or use the scaffold_api tool) to regenerate code\n2. Run \`npm install\` if new dependencies are needed\n3. Run \`apso dev\` to start the server and create auth tables\n\n${authProvider === "better-auth" ? "**How sign-in works:** the service verifies JWTs from Better Auth; a session cookie or session token gets 401. In your Better Auth config add the `jwt()` plugin, and add the tenant and roles to the token with its `definePayload` option, for example `{ email: user.email, activeOrganizationId: session.activeOrganizationId, roles: [memberRole] }`. The front end gets the token from `GET /api/auth/token` (`authClient.token()` with the `jwtClient` plugin) and sends it as `Authorization: Bearer <token>`. Set `url` to your Better Auth base URL.\n\n**The tables below are for the server only:** `@apso/better-auth-adapter` stores Better Auth's rows through this API with an API key (`x-api-key`). A signed-in user gets 403 on their routes. BetterAuth stores passwords in the `account` table (not User); the `providerId` field must be set to \"credential\" for email/password login to work." : "Replace the issuer, audience and claim names with your " + authProvider + " tenant's values. The service checks each token's signature against the issuer's JWKS. See https://docs.apso.ai/develop/auth/byoa."}`,
628
611
  },
629
612
  ],
630
613
  };
@@ -5,7 +5,6 @@ const base_command_1 = tslib_1.__importDefault(require("../../lib/base-command")
5
5
  const config_1 = require("../../lib/config");
6
6
  const services_1 = require("../../lib/api/services");
7
7
  const apsorc_parser_1 = require("../../lib/apsorc-parser");
8
- const schema_convert_1 = require("../../lib/utils/schema-convert");
9
8
  // Inline ANSI color helpers (no dependency needed)
10
9
  const useColor = () => !config_1.globalConfig.read().noColor;
11
10
  const green = (s) => useColor() ? `\u001B[32m${s}\u001B[0m` : s;
@@ -23,15 +22,15 @@ class SchemaDiff extends base_command_1.default {
23
22
  this.error("Project not linked. Run 'apso link' first.");
24
23
  }
25
24
  // Parse local schema
26
- let parsed;
25
+ let localSchema;
27
26
  try {
28
- parsed = (0, apsorc_parser_1.parseApsorc)();
27
+ (0, apsorc_parser_1.parseApsorc)();
28
+ localSchema = (0, apsorc_parser_1.readApsorcFile)().apsorc;
29
29
  }
30
30
  catch (error) {
31
31
  const msg = error instanceof Error ? error.message : String(error);
32
32
  this.error(`Failed to parse .apsorc: ${msg}`);
33
33
  }
34
- const localSchema = (0, schema_convert_1.apsorcToServiceSchema)(parsed);
35
34
  // Get diff from platform
36
35
  const diff = await services_1.schemaApi.diff(link.workspaceSlug, link.serviceSlug, localSchema);
37
36
  if (!diff.hasChanges) {
@@ -11,6 +11,7 @@ const apsorc_parser_1 = require("../../lib/apsorc-parser");
11
11
  const schema_convert_1 = require("../../lib/utils/schema-convert");
12
12
  class SchemaPull extends base_command_1.default {
13
13
  async run() {
14
+ var _a, _b;
14
15
  const { flags } = await this.parse(SchemaPull);
15
16
  // Auth guard
16
17
  if (!config_1.credentials.isValid()) {
@@ -21,19 +22,21 @@ class SchemaPull extends base_command_1.default {
21
22
  if (!link) {
22
23
  this.error("Project not linked. Run 'apso link' first.");
23
24
  }
24
- // Fetch remote schema
25
- const remoteSchema = await services_1.schemaApi.get(link.workspaceSlug, link.serviceSlug);
26
- // Convert to .apsorc format
27
- const apsorcData = (0, schema_convert_1.serviceSchemaToApsorc)(remoteSchema);
25
+ // The platform stores the .apsorc whole, so it is written back as it is.
26
+ const apsorcData = await services_1.schemaApi.get(link.workspaceSlug, link.serviceSlug);
27
+ if (!apsorcData) {
28
+ this.error("This service has no schema on the platform yet. Run 'apso schema push' first.");
29
+ }
28
30
  // Find local .apsorc path
29
31
  const configPath = (0, apsorc_parser_1.findConfigPath)();
30
32
  if (!configPath) {
31
33
  this.error("No .apsorc file found. Run 'apso init' first.");
32
34
  }
33
35
  // Show what will change
34
- const entityNames = apsorcData.entities.map((e) => e.name).join(", ");
35
- this.log(`Remote schema: ${apsorcData.entities.length} entities (${entityNames})`);
36
- this.log(`Relationships: ${apsorcData.relationships.length}`);
36
+ const entities = (_a = apsorcData.entities) !== null && _a !== void 0 ? _a : [];
37
+ const entityNames = entities.map((e) => e.name).join(", ");
38
+ this.log(`Remote schema: ${entities.length} entities (${entityNames})`);
39
+ this.log(`Relationships: ${((_b = apsorcData.relationships) !== null && _b !== void 0 ? _b : []).length}`);
37
40
  this.log(`Target file: ${configPath}`);
38
41
  // Confirm
39
42
  if (!flags.yes) {
@@ -56,12 +59,11 @@ class SchemaPull extends base_command_1.default {
56
59
  // Write updated .apsorc
57
60
  fs.writeFileSync(configPath, JSON.stringify(apsorcData, null, 2), "utf-8");
58
61
  // Update sync metadata
59
- const remoteHash = (0, schema_convert_1.computeSchemaHash)(remoteSchema.entities);
60
- const localHash = (0, schema_convert_1.computeSchemaHash)(apsorcData);
62
+ const hash = (0, schema_convert_1.computeSchemaHash)(apsorcData);
61
63
  config_1.projectLink.updateSyncMetadata({
62
64
  lastSyncedAt: new Date().toISOString(),
63
- localSchemaHash: localHash,
64
- remoteSchemaHash: remoteHash,
65
+ localSchemaHash: hash,
66
+ remoteSchemaHash: hash,
65
67
  });
66
68
  this.log("Schema pulled successfully.");
67
69
  }
@@ -20,16 +20,17 @@ class SchemaPush extends base_command_1.default {
20
20
  if (!link) {
21
21
  this.error("Project not linked. Run 'apso link' first.");
22
22
  }
23
- // Parse local schema
24
- let parsed;
23
+ // Check the schema parses, then push the file as it is: the platform
24
+ // stores the .apsorc whole, so nothing in it is lost on the way.
25
+ let localSchema;
25
26
  try {
26
- parsed = (0, apsorc_parser_1.parseApsorc)();
27
+ (0, apsorc_parser_1.parseApsorc)();
28
+ localSchema = (0, apsorc_parser_1.readApsorcFile)().apsorc;
27
29
  }
28
30
  catch (error) {
29
31
  const msg = error instanceof Error ? error.message : String(error);
30
32
  this.error(`Failed to parse .apsorc: ${msg}`);
31
33
  }
32
- const localSchema = (0, schema_convert_1.apsorcToServiceSchema)(parsed);
33
34
  // Check diff first
34
35
  const diff = await services_1.schemaApi.diff(link.workspaceSlug, link.serviceSlug, localSchema);
35
36
  if (!diff.hasChanges) {
@@ -73,7 +74,7 @@ class SchemaPush extends base_command_1.default {
73
74
  const updatedSchema = await services_1.schemaApi.update(link.workspaceSlug, link.serviceSlug, localSchema);
74
75
  // Update sync metadata
75
76
  const localHash = (0, schema_convert_1.computeSchemaHash)(localSchema);
76
- const remoteHash = (0, schema_convert_1.computeSchemaHash)(updatedSchema.entities);
77
+ const remoteHash = (0, schema_convert_1.computeSchemaHash)(updatedSchema !== null && updatedSchema !== void 0 ? updatedSchema : localSchema);
77
78
  config_1.projectLink.updateSyncMetadata({
78
79
  lastSyncedAt: new Date().toISOString(),
79
80
  localSchemaHash: localHash,
@@ -1,4 +1,14 @@
1
1
  import BaseCommand from "../../lib/base-command";
2
+ import { ParsedApsorc } from "../../lib/apsorc-parser";
3
+ /**
4
+ * What `apso generate` would stop on: its configuration checks and the auth,
5
+ * permissions and mcp rules. It runs the generator's own checks
6
+ * and writes nothing, so the two cannot disagree.
7
+ *
8
+ * @param {ParsedApsorc} parsed - The parsed .apsorc.
9
+ * @returns {Promise<string[]>} One message per problem; empty when there are none.
10
+ */
11
+ export declare function accessRuleErrors(parsed: Pick<ParsedApsorc, "rootFolder" | "apiType" | "entities" | "relationshipMap" | "auth" | "language">): Promise<string[]>;
2
12
  export default class SchemaValidate extends BaseCommand {
3
13
  static description: string;
4
14
  static examples: string[];
@@ -1,13 +1,63 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.accessRuleErrors = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  const core_1 = require("@oclif/core");
5
6
  const base_command_1 = tslib_1.__importDefault(require("../../lib/base-command"));
7
+ const guards_1 = require("../../lib/guards");
6
8
  const config_1 = require("../../lib/config");
7
9
  const services_1 = require("../../lib/api/services");
8
10
  const schema_tools_1 = require("@apso/schema-tools");
9
11
  const apsorc_parser_1 = require("../../lib/apsorc-parser");
12
+ const generators_1 = require("../../lib/generators");
10
13
  const schema_convert_1 = require("../../lib/utils/schema-convert");
14
+ /**
15
+ * What `apso generate` would stop on: its configuration checks and the auth,
16
+ * permissions and mcp rules. It runs the generator's own checks
17
+ * and writes nothing, so the two cannot disagree.
18
+ *
19
+ * @param {ParsedApsorc} parsed - The parsed .apsorc.
20
+ * @returns {Promise<string[]>} One message per problem; empty when there are none.
21
+ */
22
+ async function accessRuleErrors(parsed) {
23
+ var _a;
24
+ const { entities, relationshipMap, auth } = parsed;
25
+ const config = {
26
+ language: (_a = parsed.language) !== null && _a !== void 0 ? _a : "typescript",
27
+ rootFolder: parsed.rootFolder,
28
+ apiType: parsed.apiType.toLowerCase(),
29
+ entities,
30
+ relationshipMap,
31
+ auth,
32
+ };
33
+ const generator = (0, generators_1.createGenerator)(config);
34
+ // What generate checks before it writes anything (for example a GraphQL API type).
35
+ const errors = [...generator.validateConfig(config).errors];
36
+ const attempt = async (run) => {
37
+ try {
38
+ await run();
39
+ }
40
+ catch (error) {
41
+ errors.push(error instanceof Error ? error.message : String(error));
42
+ }
43
+ };
44
+ // auth and permissions for every language; mcp for Python and Go.
45
+ await attempt(() => generator.generateGuards(entities, auth, relationshipMap));
46
+ // mcp in TypeScript is checked where the controller is generated.
47
+ if (config.language === "typescript")
48
+ for (const entity of entities)
49
+ // eslint-disable-next-line no-await-in-loop -- one message per entity, in order
50
+ await attempt(() => generator.generateController({
51
+ entity,
52
+ relationships: relationshipMap[entity.name] || [],
53
+ allEntities: entities,
54
+ apiType: config.apiType,
55
+ relationshipMap,
56
+ auth,
57
+ }));
58
+ return [...new Set(errors)];
59
+ }
60
+ exports.accessRuleErrors = accessRuleErrors;
11
61
  class SchemaValidate extends base_command_1.default {
12
62
  async run() {
13
63
  var _a;
@@ -40,6 +90,8 @@ class SchemaValidate extends base_command_1.default {
40
90
  const msg = error instanceof Error ? error.message : String(error);
41
91
  this.error(`Failed to parse .apsorc: ${msg}`);
42
92
  }
93
+ for (const warning of (0, guards_1.tenantClaimWarnings)(parsed.entities, parsed.auth))
94
+ this.warn(warning);
43
95
  // Convert to platform schema format
44
96
  const schema = (0, schema_convert_1.apsorcToServiceSchema)(parsed);
45
97
  // Count stats
@@ -65,6 +117,8 @@ class SchemaValidate extends base_command_1.default {
65
117
  }
66
118
  }
67
119
  }
120
+ // The rules apso generate enforces for auth, permissions and mcp
121
+ errors.push(...(await accessRuleErrors(parsed)));
68
122
  // Server validation if linked and not --local
69
123
  const isLinked = config_1.projectLink.exists();
70
124
  const isAuthenticated = config_1.credentials.isValid();
@@ -0,0 +1,11 @@
1
+ import BaseCommand from "../../lib/base-command";
2
+ export default class TestAccess extends BaseCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ "skip-build": import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
+ verbose: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
+ json: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
+ };
10
+ run(): Promise<void>;
11
+ }