@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
@@ -6,9 +6,10 @@
6
6
  * the CLI in a WebContainer) share these steps.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.report = exports.cliBinPath = exports.readDotEnv = exports.smokeTest = exports.entityRoute = exports.verifyMigration = exports.supportsPglite = exports.unaccepted = exports.dataLoss = exports.generateMigration = exports.buildBaseline = exports.pgliteEnv = exports.run = void 0;
9
+ exports.report = exports.cliBinPath = exports.readDotEnv = exports.smokeTest = exports.entityRoute = exports.SMOKE_KEY = exports.verifyMigration = exports.supportsPglite = exports.unaccepted = exports.dataLoss = exports.generateMigration = exports.buildBaseline = exports.pgliteEnv = exports.run = void 0;
10
10
  const tslib_1 = require("tslib");
11
11
  const child_process_1 = require("child_process");
12
+ const crypto_1 = require("crypto");
12
13
  const fs = tslib_1.__importStar(require("fs"));
13
14
  const http = tslib_1.__importStar(require("http"));
14
15
  const net = tslib_1.__importStar(require("net"));
@@ -439,14 +440,18 @@ const freePort = () => new Promise((resolve, reject) => {
439
440
  });
440
441
  s.on("error", reject);
441
442
  });
443
+ // The smoke test's own API key: the service is started with it and every
444
+ // request sends it, so the checks pass whatever the project's .env holds.
445
+ exports.SMOKE_KEY = (0, crypto_1.randomBytes)(16).toString("hex");
442
446
  const request = (method, url, body) => new Promise((resolve) => {
443
447
  const data = body === undefined ? undefined : JSON.stringify(body);
444
- const headers = data
445
- ? {
448
+ const headers = {
449
+ "x-api-key": exports.SMOKE_KEY,
450
+ ...(data && {
446
451
  "content-type": "application/json",
447
452
  "content-length": Buffer.byteLength(data),
448
- }
449
- : {};
453
+ }),
454
+ };
450
455
  http
451
456
  .request(url, { method, headers, timeout: 15000 }, (res) => {
452
457
  let text = "";
@@ -497,7 +502,8 @@ async function checkEndpoints(base, language, entities, relationships, done) {
497
502
  for (const { name } of entities) {
498
503
  done({
499
504
  name: `GET ${route(name)}`,
500
- ...expectStatus(await get(base + route(name)), 200),
505
+ // 206: a TypeScript service answers a full default page that way.
506
+ ...expectStatus(await get(base + route(name)), 200, 206),
501
507
  });
502
508
  }
503
509
  const plan = (0, crud_plan_1.planCrud)(entities, relationships);
@@ -590,9 +596,9 @@ async function serve(server, port, timeoutMs, done, check) {
590
596
  * PGlite database synced to their entities; Python and Go services run on the
591
597
  * database in DATABASE_URL.
592
598
  */
593
- async function smokeTest(projectDir, entities, relationships = {}, { skipBuild = false, timeoutMs = 60000, language = "typescript", } = {}) {
599
+ async function smokeTest(projectDir, entities, relationships = {}, { skipBuild = false, timeoutMs = 60000, language = "typescript", env: extraEnv = {}, check = (base, done) => checkEndpoints(base, language, entities, relationships, done), } = {}) {
594
600
  if (language !== "typescript")
595
- return smokeTestOnDatabaseUrl(projectDir, entities, relationships, language, timeoutMs);
601
+ return smokeTestOnDatabaseUrl(projectDir, language, timeoutMs, extraEnv, check);
596
602
  if (!supportsPglite(projectDir))
597
603
  return NO_PGLITE;
598
604
  const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "apso-pglite-"));
@@ -609,9 +615,15 @@ async function smokeTest(projectDir, entities, relationships = {}, { skipBuild =
609
615
  const port = await freePort();
610
616
  const server = (0, child_process_1.spawn)(process.execPath, ["dist/main"], {
611
617
  cwd: projectDir,
612
- env: { ...process.env, ...(0, exports.pgliteEnv)(dataDir), APP_PORT: String(port) },
618
+ env: {
619
+ ...process.env,
620
+ ...(0, exports.pgliteEnv)(dataDir),
621
+ APP_PORT: String(port),
622
+ APSO_API_KEY: exports.SMOKE_KEY,
623
+ ...extraEnv,
624
+ },
613
625
  });
614
- await serve(server, port, timeoutMs, done, (base) => checkEndpoints(base, language, entities, relationships, done));
626
+ await serve(server, port, timeoutMs, done, (base) => check(base, done));
615
627
  return { ok: steps.every((s) => s.ok), steps };
616
628
  }
617
629
  finally {
@@ -656,7 +668,7 @@ const skipped = (output) => ({
656
668
  * one in DATABASE_URL (environment first, then .env), as configured: the
657
669
  * smoke test never creates tables, and it skips when no database answers.
658
670
  */
659
- async function smokeTestOnDatabaseUrl(projectDir, entities, relationships, language, timeoutMs) {
671
+ async function smokeTestOnDatabaseUrl(projectDir, language, timeoutMs, extraEnv, check) {
660
672
  const env = { ...readDotEnv(projectDir), ...process.env };
661
673
  if (!env.DATABASE_URL)
662
674
  return skipped("No DATABASE_URL in the environment or .env, so there is no database to run the service against. Set it and rerun.");
@@ -681,7 +693,12 @@ async function smokeTestOnDatabaseUrl(projectDir, entities, relationships, langu
681
693
  return s.ok;
682
694
  };
683
695
  const port = await freePort();
684
- const serverEnv = { ...env, PORT: String(port) };
696
+ const serverEnv = {
697
+ ...env,
698
+ PORT: String(port),
699
+ APSO_API_KEY: exports.SMOKE_KEY,
700
+ ...extraEnv,
701
+ };
685
702
  const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "apso-smoke-"));
686
703
  try {
687
704
  let server;
@@ -705,7 +722,7 @@ async function smokeTestOnDatabaseUrl(projectDir, entities, relationships, langu
705
722
  String(port),
706
723
  ], { cwd: projectDir, env: serverEnv });
707
724
  }
708
- await serve(server, port, timeoutMs, done, (base) => checkEndpoints(base, language, entities, relationships, done));
725
+ await serve(server, port, timeoutMs, done, (base) => check(base, done));
709
726
  return { ok: steps.every((s) => s.ok), steps };
710
727
  }
711
728
  finally {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.47.6",
3
+ "version": "0.49.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@apso/cli",
9
- "version": "0.47.6",
9
+ "version": "0.49.0",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@apso/schema-tools": "^0.2.2",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.47.6",
2
+ "version": "0.49.0",
3
3
  "commands": {
4
4
  "config": {
5
5
  "id": "config",
@@ -1318,6 +1318,41 @@
1318
1318
  "flags": {},
1319
1319
  "args": {}
1320
1320
  },
1321
+ "test:access": {
1322
+ "id": "test:access",
1323
+ "description": "Start the service and prove the access rules on this project's own schema: who may call, tenant scope (scopeBy), permissions, API keys and MCP tools. Test sign-ins are signed by a local issuer with the claim names from the auth block; the service is pointed at it through AUTH_JWT_ISSUER and AUTH_JWKS_URI for this run only. Rows are created for two test tenants and deleted afterwards. TypeScript services run on a local PGlite database; Python and Go services run on the database in DATABASE_URL. Prints pass or fail per rule and exits 1 on any failure",
1324
+ "strict": true,
1325
+ "pluginName": "@apso/cli",
1326
+ "pluginAlias": "@apso/cli",
1327
+ "pluginType": "core",
1328
+ "aliases": [],
1329
+ "hiddenAliases": [],
1330
+ "examples": [
1331
+ "$ apso test access",
1332
+ "$ apso test access --json"
1333
+ ],
1334
+ "flags": {
1335
+ "skip-build": {
1336
+ "name": "skip-build",
1337
+ "type": "boolean",
1338
+ "description": "Use the existing dist/ build instead of building first (TypeScript)",
1339
+ "allowNo": false
1340
+ },
1341
+ "verbose": {
1342
+ "name": "verbose",
1343
+ "type": "boolean",
1344
+ "description": "Print every case, not only the failures",
1345
+ "allowNo": false
1346
+ },
1347
+ "json": {
1348
+ "name": "json",
1349
+ "type": "boolean",
1350
+ "description": "Print the result as JSON",
1351
+ "allowNo": false
1352
+ }
1353
+ },
1354
+ "args": {}
1355
+ },
1321
1356
  "test:smoke": {
1322
1357
  "id": "test:smoke",
1323
1358
  "description": "Start the service and call /health, every entity's list endpoint, and a create/read/delete of one row per entity. TypeScript services run on a local PGlite database; Python and Go services run on the database in DATABASE_URL (rows are created and deleted there, tables are not created) and the check is skipped when none answers",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apso/cli",
3
- "version": "0.47.6",
3
+ "version": "0.49.0",
4
4
  "mcpName": "io.github.apsoai/apso",
5
5
  "description": "Apso CLI",
6
6
  "author": "Apso by Mavric - @mavric",
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> []<%= it.column.arrayItemType || 'string' %> `gorm:"type:<%= it.column.arrayItemType || 'text' %>[];serializer:json<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>bool `gorm:"type:boolean<% if (!it.column.required) { %>;default:null<% } else if (it.column.default !== undefined) { %>;default:<%= it.column.default %><% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `gorm:"type:date<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `gorm:"type:decimal(<%= it.column.precision || 10 %>,<%= it.column.scale || 2 %>)<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1,2 +0,0 @@
1
- <% const enumTypeName = it.column.enumType || (it.column.pascalName + 'Enum'); %>
2
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>enums.<%= enumTypeName %> `gorm:"type:varchar(50)<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `gorm:"type:float<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>int <% if (it.column.primary) { %>`gorm:"primaryKey;autoIncrement" json:"<%= it.column.name %>"`<% } else { %>`gorm:"type:integer<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`<% } %>
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>map[string]interface{} `gorm:"type:json<% if (!it.column.required) { %>;default:null<% } %>;serializer:json" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>map[string]interface{} `gorm:"type:jsonb<% if (!it.column.required) { %>;default:null<% } %>;serializer:json" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>float64 `gorm:"type:numeric(<%= it.column.precision || 10 %>,<%= it.column.scale || 2 %>)<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `gorm:"type:varchar(<%= it.column.length || 255 %>)<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `gorm:"type:text<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `gorm:"type:timestamp<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>time.Time `gorm:"type:timestamptz<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string <% if (it.column.primary) { %>`gorm:"type:uuid;primaryKey;default:gen_random_uuid()" json:"<%= it.column.name %>"`<% } else { %>`gorm:"type:uuid<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`<% } %>
@@ -1 +0,0 @@
1
- <%= it.column.pascalName %> <% if (!it.column.required) { %>*<% } %>string `gorm:"type:varchar(<%= it.column.length || 255 %>)<% if (!it.column.required) { %>;default:null<% } %>" json:"<%= it.column.name %><% if (!it.column.required) { %>,omitempty<% } %>"`
@@ -1,145 +0,0 @@
1
- /**
2
- * AuthGuard - application API keys stored as SHA-256 hashes on <%= it.apiKey.apiKeyEntity %>
3
- *
4
- * Auto-generated by Apso CLI from .apsorc auth configuration
5
- *
6
- * This guard:
7
- * - Reads the key from the <%= it.apiKey.apiKeyHeader %> header
8
- * - Looks up the <%= it.apiKey.apiKeyEntity %> row whose <%= it.apiKey.keyField %> is the key's hex SHA-256
9
- <% if (it.apiKey.hasStatus) { %>
10
- * - Rejects keys whose status is not "active"
11
- <% } %>
12
- <% if (it.apiKey.hasExpiresAt) { %>
13
- * - Rejects keys past expiresAt
14
- <% } %>
15
- * - Attaches a normalized AuthContext to request.auth
16
- *
17
- * DO NOT EDIT - Changes will be overwritten on next scaffold
18
- */
19
- import {
20
- Injectable,
21
- CanActivate,
22
- ExecutionContext,
23
- UnauthorizedException,
24
- } from '@nestjs/common';
25
- import { Reflector } from '@nestjs/core';
26
- import { InjectRepository } from '@nestjs/typeorm';
27
- import { Repository } from 'typeorm';
28
- import { createHash } from 'crypto';
29
-
30
- import { <%= it.apiKey.apiKeyEntity %> } from '../<%= it.apiKey.apiKeyEntity %>/<%= it.apiKey.apiKeyEntity %>.entity';
31
-
32
- export const IS_PUBLIC_KEY = 'isPublic';
33
-
34
- /**
35
- * Decorator to mark a route as public (skips authentication)
36
- * Usage: @Public()
37
- */
38
- export const Public =
39
- () => (target: any, key?: string, descriptor?: PropertyDescriptor) => {
40
- Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor?.value || target);
41
- };
42
-
43
- /**
44
- * Normalized auth context attached to authenticated requests.
45
- * This is what scopeBy and RBAC consume.
46
- */
47
- export interface AuthContext {
48
- userId?: string;
49
- serviceId: string;
50
- workspaceId?: string;
51
- organizationId?: string;
52
- roles: string[];
53
- }
54
-
55
- @Injectable()
56
- export class AuthGuard implements CanActivate {
57
- constructor(
58
- private reflector: Reflector,
59
- @InjectRepository(<%= it.apiKey.apiKeyEntity %>)
60
- private apiKeyRepository: Repository<<%= it.apiKey.apiKeyEntity %>>,
61
- ) {}
62
-
63
- async canActivate(context: ExecutionContext): Promise<boolean> {
64
- const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
65
- context.getHandler(),
66
- context.getClass(),
67
- ]);
68
- if (isPublic) {
69
- return true;
70
- }
71
-
72
- // The template's health check stays public for load balancer probes.
73
- const req = context.switchToHttp().getRequest();
74
- if (req.method === 'GET' && /^\/health\/?$/.test(req.path)) {
75
- return true;
76
- }
77
-
78
- const request = context.switchToHttp().getRequest();
79
- const key = request.headers['<%= it.apiKey.apiKeyHeader %>'];
80
- if (typeof key !== 'string' || !key) {
81
- throw new UnauthorizedException('No API key provided');
82
- }
83
-
84
- const hash = createHash('sha256').update(key).digest('hex');
85
- const record: any = await this.apiKeyRepository.findOne({
86
- where: { <%= it.apiKey.keyField %>: hash } as any,
87
- });
88
- if (!record) {
89
- throw new UnauthorizedException('Invalid API key');
90
- }
91
- <% if (it.apiKey.hasStatus) { %>
92
- if (record.status !== 'active') {
93
- throw new UnauthorizedException('API key is not active');
94
- }
95
- <% } %>
96
- <% if (it.apiKey.hasExpiresAt) { %>
97
- if (record.expiresAt && new Date(record.expiresAt) <= new Date()) {
98
- throw new UnauthorizedException('API key has expired');
99
- }
100
- <% } %>
101
-
102
- const tenant =
103
- record.<%= it.apiKey.workspaceField %> != null
104
- ? String(record.<%= it.apiKey.workspaceField %>)
105
- : undefined;
106
- <% if (it.apiKey.roleField) { %>
107
- const role = record.<%= it.apiKey.roleField %>;
108
- const roles = Array.isArray(role) ? role.map(String) : role ? [String(role)] : [];
109
- <% } else { %>
110
- const roles: string[] = [];
111
- <% } %>
112
- const auth: AuthContext = {
113
- serviceId: String(record.id),
114
- workspaceId: tenant,
115
- organizationId: tenant,
116
- roles,
117
- };
118
-
119
- request.auth = auth;
120
- request.user = { id: auth.serviceId, ...auth };
121
- // Read by ScopeGuard's scope lookup.
122
- request.workspaceId = tenant;
123
- request.organizationId = tenant;
124
- return true;
125
- }
126
- }
127
-
128
- /**
129
- * Helper function to get AuthContext from request
130
- * Use this in controllers/services to access the authenticated context
131
- */
132
- export function getAuthContext(request: any): AuthContext | undefined {
133
- return request?.auth;
134
- }
135
-
136
- /**
137
- * Helper function to require AuthContext (throws if not present)
138
- */
139
- export function requireAuthContext(request: any): AuthContext {
140
- const ctx = getAuthContext(request);
141
- if (!ctx) {
142
- throw new UnauthorizedException('Authentication required');
143
- }
144
- return ctx;
145
- }
@@ -1,233 +0,0 @@
1
- /**
2
- * AuthGuard - Authentication guard for <%= it.authConfig.provider %> provider
3
- *
4
- * Auto-generated by Apso CLI from .apsorc auth configuration
5
- *
6
- * This guard:
7
- * - Validates session tokens from cookies/headers
8
- * - Loads user and organization context
9
- * - Attaches normalized AuthContext to requests
10
- *
11
- * DO NOT EDIT - Changes will be overwritten on next scaffold
12
- */
13
- import {
14
- Injectable,
15
- CanActivate,
16
- ExecutionContext,
17
- UnauthorizedException,
18
- } from '@nestjs/common';
19
- import { Reflector } from '@nestjs/core';
20
- import { InjectRepository } from '@nestjs/typeorm';
21
- import { Repository } from 'typeorm';
22
-
23
- // Entity imports (from sibling autogen folders)
24
- import { <%= it.authConfig.sessionEntity %> } from '../<%= it.authConfig.sessionEntity %>/<%= it.authConfig.sessionEntity %>.entity';
25
- import { <%= it.authConfig.userEntity %> } from '../<%= it.authConfig.userEntity %>/<%= it.authConfig.userEntity %>.entity';
26
- <% if (it.authConfig.accountUserEntity) { %>
27
- import { <%= it.authConfig.accountUserEntity %> } from '../<%= it.authConfig.accountUserEntity %>/<%= it.authConfig.accountUserEntity %>.entity';
28
- <% } %>
29
-
30
- /**
31
- * Metadata key for marking routes as public (no auth required)
32
- */
33
- export const IS_PUBLIC_KEY = 'isPublic';
34
-
35
- /**
36
- * Decorator to mark a route as public (skips authentication)
37
- * Usage: @Public()
38
- */
39
- export const Public =
40
- () => (target: any, key?: string, descriptor?: PropertyDescriptor) => {
41
- Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor?.value || target);
42
- };
43
-
44
- /**
45
- * Normalized auth context attached to authenticated requests.
46
- * This is what scopeBy and RBAC consume.
47
- */
48
- export interface AuthContext {
49
- userId?: string;
50
- email?: string;
51
- workspaceId?: string;
52
- organizationId?: string;
53
- roles: string[];
54
- user?: <%= it.authConfig.userEntity %>;
55
- session?: <%= it.authConfig.sessionEntity %>;
56
- }
57
-
58
- /**
59
- * Extended request type with auth context
60
- */
61
- export interface AuthenticatedRequest extends Request {
62
- auth: AuthContext;
63
- user: <%= it.authConfig.userEntity %>;
64
- session: <%= it.authConfig.sessionEntity %>;
65
- // Legacy compatibility aliases
66
- accountId?: string;
67
- accountRole?: string;
68
- organizationId?: string;
69
- }
70
-
71
- @Injectable()
72
- export class AuthGuard implements CanActivate {
73
- constructor(
74
- private reflector: Reflector,
75
- @InjectRepository(<%= it.authConfig.sessionEntity %>)
76
- private sessionRepository: Repository<<%= it.authConfig.sessionEntity %>>,
77
- @InjectRepository(<%= it.authConfig.userEntity %>)
78
- private userRepository: Repository<<%= it.authConfig.userEntity %>>,
79
- <% if (it.authConfig.accountUserEntity) { %>
80
- @InjectRepository(<%= it.authConfig.accountUserEntity %>)
81
- private accountUserRepository: Repository<<%= it.authConfig.accountUserEntity %>>,
82
- <% } %>
83
- ) {}
84
-
85
- async canActivate(context: ExecutionContext): Promise<boolean> {
86
- // Check if route is marked as public
87
- const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
88
- context.getHandler(),
89
- context.getClass(),
90
- ]);
91
-
92
- if (isPublic) {
93
- return true;
94
- }
95
-
96
- // The template's health check stays public for load balancer probes.
97
- const req = context.switchToHttp().getRequest();
98
- if (req.method === 'GET' && /^\/health\/?$/.test(req.path)) {
99
- return true;
100
- }
101
-
102
- const request = context.switchToHttp().getRequest();
103
- const token = this.extractToken(request);
104
-
105
- if (!token) {
106
- throw new UnauthorizedException('No session token provided');
107
- }
108
-
109
- try {
110
- // Find session by token
111
- const sessionRecord = await this.sessionRepository.findOne({
112
- where: { token },
113
- });
114
-
115
- if (!sessionRecord) {
116
- throw new UnauthorizedException('Invalid session token');
117
- }
118
-
119
- // Check if session is expired
120
- if (new Date(sessionRecord.expiresAt) < new Date()) {
121
- throw new UnauthorizedException('Session expired');
122
- }
123
-
124
- // Get user from session
125
- const user = await this.userRepository.findOne({
126
- where: { id: sessionRecord.userId },
127
- });
128
-
129
- if (!user) {
130
- throw new UnauthorizedException('User not found');
131
- }
132
-
133
- <% if (it.authConfig.accountUserEntity) { %>
134
- // Get user's organization through <%= it.authConfig.accountUserEntity %> junction
135
- const accountUser = await this.accountUserRepository.findOne({
136
- where: { userId: user.id },
137
- });
138
-
139
- if (!accountUser) {
140
- throw new UnauthorizedException('User not associated with any organization');
141
- }
142
-
143
- const organizationId = accountUser.<%= it.authConfig.organizationField %>;
144
- const role = accountUser.<%= it.authConfig.roleField %> || 'member';
145
- <% } else { %>
146
- // No account user entity configured - using user-level organization
147
- const organizationId = (user as any).<%= it.authConfig.organizationField %> || undefined;
148
- const role = (user as any).<%= it.authConfig.roleField %> || 'member';
149
- <% } %>
150
-
151
- // Build normalized AuthContext
152
- const authContext: AuthContext = {
153
- userId: user.id,
154
- email: user.email,
155
- workspaceId: organizationId,
156
- organizationId: organizationId,
157
- roles: [role],
158
- user: user,
159
- session: sessionRecord,
160
- };
161
-
162
- // Attach to request
163
- (request as any).auth = authContext;
164
- (request as any).user = user;
165
- (request as any).session = sessionRecord;
166
-
167
- // Legacy compatibility - attach directly to request root
168
- (request as any).accountId = organizationId;
169
- (request as any).accountRole = role;
170
- (request as any).organizationId = organizationId;
171
-
172
- return true;
173
- } catch (error) {
174
- if (error instanceof UnauthorizedException) {
175
- throw error;
176
- }
177
- console.error('Auth guard error:', error);
178
- throw new UnauthorizedException('Authentication failed');
179
- }
180
- }
181
-
182
- /**
183
- * Extract session token from request
184
- * Checks: Authorization header (Bearer), cookies, X-Session-Token header
185
- */
186
- private extractToken(request: any): string | undefined {
187
- // Check Authorization header first (Bearer token)
188
- const authHeader = request.headers.authorization;
189
- if (authHeader && authHeader.startsWith('Bearer ')) {
190
- return authHeader.substring(7);
191
- }
192
-
193
- // Check for session token in cookies
194
- const cookies = request.cookies || {};
195
- <% if (it.authConfig.cookiePrefix) { %>
196
- const cookieName = '<%= it.authConfig.cookiePrefix %>.session_token';
197
- const sessionToken =
198
- cookies[cookieName] ||
199
- cookies['better-auth.session_token'] ||
200
- cookies['session_token'];
201
- <% } else { %>
202
- const sessionToken =
203
- cookies['better-auth.session_token'] ||
204
- cookies['session_token'];
205
- <% } %>
206
-
207
- if (sessionToken) {
208
- return sessionToken;
209
- }
210
-
211
- // Check X-Session-Token header
212
- return request.headers['x-session-token'];
213
- }
214
- }
215
-
216
- /**
217
- * Helper function to get AuthContext from request
218
- * Use this in controllers/services to access the authenticated context
219
- */
220
- export function getAuthContext(request: any): AuthContext | undefined {
221
- return request?.auth;
222
- }
223
-
224
- /**
225
- * Helper function to require AuthContext (throws if not present)
226
- */
227
- export function requireAuthContext(request: any): AuthContext {
228
- const ctx = getAuthContext(request);
229
- if (!ctx) {
230
- throw new UnauthorizedException('Authentication required');
231
- }
232
- return ctx;
233
- }
@@ -1,4 +0,0 @@
1
- <%= it.field.name %>: Mapped[<% if (it.field.nullable !== false) { %>Optional[list]<% } else { %>list<% } %>] = mapped_column(
2
- ARRAY(<%= it.field.arrayType === 'integer' ? 'Integer' : 'String' %>),
3
- nullable=<%= it.field.nullable === false ? 'False' : 'True' %>
4
- )
@@ -1,6 +0,0 @@
1
- <%= it.field.name %>: Mapped[<% if (it.field.nullable !== false) { %>Optional[bool]<% } else { %>bool<% } %>] = mapped_column(
2
- Boolean,
3
- nullable=<%= it.field.nullable === false ? 'False' : 'True' %><% if (it.field.unique) { %>,
4
- unique=True<% } %><% if (it.field.default !== undefined && it.field.default !== null) { %>,
5
- default=<%= (it.field.default === true || it.field.default === 'true') ? 'True' : 'False' %><% } %>
6
- )
@@ -1,4 +0,0 @@
1
- <%= it.field.name %>: Mapped[<% if (it.field.nullable !== false) { %>Optional[date]<% } else { %>date<% } %>] = mapped_column(
2
- Date,
3
- nullable=<%= it.field.nullable === false ? 'False' : 'True' %>
4
- )
@@ -1,5 +0,0 @@
1
- <%= it.field.name %>: Mapped[<% if (it.field.nullable !== false) { %>Optional[datetime]<% } else { %>datetime<% } %>] = mapped_column(
2
- DateTime,
3
- nullable=<%= it.field.nullable === false ? 'False' : 'True' %><% if (it.field.default !== undefined && it.field.default !== null) { %>,
4
- default=<%= it.field.default === null ? 'None' : `"${it.field.default}"` %><% } %>
5
- )
@@ -1,4 +0,0 @@
1
- <%= it.field.name %>: Mapped[<% if (it.field.nullable !== false) { %>Optional[Decimal]<% } else { %>Decimal<% } %>] = mapped_column(
2
- Numeric(precision=<%= it.field.precision || 10 %>, scale=<%= it.field.scale || 2 %>),
3
- nullable=<%= it.field.nullable === false ? 'False' : 'True' %>
4
- )