@decohere/scaffold 0.0.1-dev.18 → 0.0.1-dev.20261105.54

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 (264) hide show
  1. package/LICENSE +15 -0
  2. package/commonjs/src/add-api.action.js +37 -0
  3. package/commonjs/src/add-api.command.js +39 -0
  4. package/commonjs/src/add.command.js +22 -0
  5. package/commonjs/src/add.module.js +24 -0
  6. package/commonjs/src/auth0-configure.action.js +28 -0
  7. package/commonjs/src/auth0-configure.command.js +24 -0
  8. package/commonjs/src/auth0-login.action.js +28 -0
  9. package/commonjs/src/auth0-login.command.js +23 -0
  10. package/commonjs/src/auth0.command.js +22 -0
  11. package/commonjs/src/auth0.module.js +28 -0
  12. package/commonjs/src/cli.js +8 -0
  13. package/commonjs/src/create.command.js +22 -0
  14. package/commonjs/src/create.module.js +24 -0
  15. package/commonjs/src/domain/prompt.js +62 -0
  16. package/commonjs/src/index.js +48 -0
  17. package/commonjs/src/models/compose.model.js +258 -0
  18. package/commonjs/src/models/config-yaml.model.js +86 -0
  19. package/commonjs/src/models/const.js +30 -0
  20. package/commonjs/src/models/dev-container.model.js +172 -0
  21. package/commonjs/src/models/docker-image.model.js +277 -0
  22. package/commonjs/src/models/env-file.model.js +48 -0
  23. package/commonjs/src/models/gitignore.model.js +48 -0
  24. package/commonjs/src/models/launch-json.model.js +70 -0
  25. package/commonjs/src/models/package-json.model.js +157 -0
  26. package/commonjs/src/models/project.model.js +132 -0
  27. package/commonjs/src/models/source-file.js +4 -0
  28. package/commonjs/src/models/tsconfig.model.js +32 -0
  29. package/commonjs/src/models/vitest-config.model.js +33 -0
  30. package/commonjs/src/models/vscode-settings.model.js +29 -0
  31. package/commonjs/src/program.js +64 -0
  32. package/commonjs/src/resolve-target-dir.js +17 -0
  33. package/commonjs/src/services/scaffold.service.js +60 -0
  34. package/commonjs/src/version.js +55 -0
  35. package/commonjs/src/webapi/api-name.js +93 -0
  36. package/commonjs/src/webapi/auth0-commands.js +250 -0
  37. package/commonjs/src/webapi/authorize-scopes.js +79 -0
  38. package/commonjs/src/webapi/cli-options.js +99 -0
  39. package/commonjs/src/webapi/const.js +54 -0
  40. package/commonjs/src/webapi/create-api.js +275 -0
  41. package/commonjs/src/webapi/devcontainer/codebase-rag-mcp.js +164 -0
  42. package/commonjs/src/webapi/devcontainer/codebase-rag-mcp.ts +182 -0
  43. package/commonjs/src/webapi/devcontainer/host-scripts.js +50 -0
  44. package/commonjs/src/webapi/devcontainer/templates/codebase-rag.env.example +3 -0
  45. package/commonjs/src/webapi/devcontainer/templates/initialize.sh +169 -0
  46. package/commonjs/src/webapi/devcontainer/templates/post-create.sh +35 -0
  47. package/commonjs/src/webapi/devcontainer/templates/post-start.sh +65 -0
  48. package/commonjs/src/webapi/devcontainer/templates/tty-prompt.sh +38 -0
  49. package/commonjs/src/webapi/features/auth.feature.js +408 -0
  50. package/commonjs/src/webapi/features/auth0-cli.js +472 -0
  51. package/commonjs/src/webapi/features/biome-format.js +47 -0
  52. package/commonjs/src/webapi/features/database.feature.js +433 -0
  53. package/commonjs/src/webapi/features/finalize.feature.js +93 -0
  54. package/commonjs/src/webapi/features/postman.feature.js +322 -0
  55. package/commonjs/src/webapi/models/api-package-json.model.js +58 -0
  56. package/commonjs/src/webapi/models/auth-config.model.js +24 -0
  57. package/commonjs/src/webapi/models/controller-source-file.model.js +190 -0
  58. package/commonjs/src/webapi/models/github-ci.model.js +193 -0
  59. package/commonjs/src/webapi/models/main-source-file.model.js +165 -0
  60. package/commonjs/src/webapi/models/production-dockerfile.model.js +75 -0
  61. package/commonjs/src/webapi/models/sample-files.model.js +58 -0
  62. package/commonjs/src/webapi/models/webapi-image.model.js +25 -0
  63. package/commonjs/src/webapi/postman/hello-openapi.js +173 -0
  64. package/commonjs/src/webapi/postman/local-view.js +182 -0
  65. package/commonjs/src/webapi/postman/openapi-to-postman.js +238 -0
  66. package/commonjs/src/webapi/workspace-readme.js +109 -0
  67. package/commonjs/src/webapi.action.js +28 -0
  68. package/commonjs/src/webapi.command.js +43 -0
  69. package/es6/src/add-api.action.js +27 -0
  70. package/es6/src/add-api.command.js +29 -0
  71. package/es6/src/add.command.js +12 -0
  72. package/es6/src/add.module.js +14 -0
  73. package/es6/src/auth0-configure.action.js +18 -0
  74. package/es6/src/auth0-configure.command.js +14 -0
  75. package/es6/src/auth0-login.action.js +18 -0
  76. package/es6/src/auth0-login.command.js +13 -0
  77. package/es6/src/auth0.command.js +12 -0
  78. package/es6/src/auth0.module.js +18 -0
  79. package/es6/src/cli.js +4 -0
  80. package/es6/src/create.command.js +12 -0
  81. package/es6/src/create.module.js +14 -0
  82. package/es6/src/domain/prompt.js +41 -0
  83. package/es6/src/index.js +9 -0
  84. package/es6/src/models/compose.model.js +254 -0
  85. package/es6/src/models/config-yaml.model.js +74 -0
  86. package/es6/src/models/const.js +20 -0
  87. package/es6/src/models/dev-container.model.js +162 -0
  88. package/es6/src/models/docker-image.model.js +235 -0
  89. package/es6/src/models/env-file.model.js +44 -0
  90. package/es6/src/models/gitignore.model.js +38 -0
  91. package/es6/src/models/launch-json.model.js +60 -0
  92. package/es6/src/models/package-json.model.js +142 -0
  93. package/es6/src/models/project.model.js +117 -0
  94. package/es6/src/models/source-file.js +1 -0
  95. package/es6/src/models/tsconfig.model.js +22 -0
  96. package/es6/src/models/vitest-config.model.js +23 -0
  97. package/es6/src/models/vscode-settings.model.js +19 -0
  98. package/es6/src/program.js +50 -0
  99. package/es6/src/resolve-target-dir.js +7 -0
  100. package/es6/src/services/scaffold.service.js +50 -0
  101. package/es6/src/version.js +34 -0
  102. package/es6/src/webapi/api-name.js +57 -0
  103. package/es6/src/webapi/auth0-commands.js +185 -0
  104. package/es6/src/webapi/authorize-scopes.js +55 -0
  105. package/es6/src/webapi/cli-options.js +34 -0
  106. package/es6/src/webapi/const.js +21 -0
  107. package/es6/src/webapi/create-api.js +255 -0
  108. package/es6/src/webapi/devcontainer/codebase-rag-mcp.js +154 -0
  109. package/es6/src/webapi/devcontainer/codebase-rag-mcp.ts +182 -0
  110. package/es6/src/webapi/devcontainer/host-scripts.js +29 -0
  111. package/es6/src/webapi/devcontainer/templates/codebase-rag.env.example +3 -0
  112. package/es6/src/webapi/devcontainer/templates/initialize.sh +169 -0
  113. package/es6/src/webapi/devcontainer/templates/post-create.sh +35 -0
  114. package/es6/src/webapi/devcontainer/templates/post-start.sh +65 -0
  115. package/es6/src/webapi/devcontainer/templates/tty-prompt.sh +38 -0
  116. package/es6/src/webapi/features/auth.feature.js +357 -0
  117. package/es6/src/webapi/features/auth0-cli.js +406 -0
  118. package/es6/src/webapi/features/biome-format.js +40 -0
  119. package/es6/src/webapi/features/database.feature.js +423 -0
  120. package/es6/src/webapi/features/finalize.feature.js +83 -0
  121. package/es6/src/webapi/features/postman.feature.js +256 -0
  122. package/es6/src/webapi/models/api-package-json.model.js +53 -0
  123. package/es6/src/webapi/models/auth-config.model.js +20 -0
  124. package/es6/src/webapi/models/controller-source-file.model.js +181 -0
  125. package/{src/webapi/models/github-ci.model.ts → es6/src/webapi/models/github-ci.model.js} +27 -29
  126. package/es6/src/webapi/models/main-source-file.model.js +161 -0
  127. package/es6/src/webapi/models/production-dockerfile.model.js +66 -0
  128. package/es6/src/webapi/models/sample-files.model.js +40 -0
  129. package/es6/src/webapi/models/webapi-image.model.js +18 -0
  130. package/es6/src/webapi/postman/hello-openapi.js +166 -0
  131. package/es6/src/webapi/postman/local-view.js +167 -0
  132. package/es6/src/webapi/postman/openapi-to-postman.js +179 -0
  133. package/es6/src/webapi/workspace-readme.js +88 -0
  134. package/es6/src/webapi.action.js +18 -0
  135. package/es6/src/webapi.command.js +33 -0
  136. package/package.json +19 -9
  137. package/types/src/add-api.action.d.ts +13 -0
  138. package/types/src/add-api.command.d.ts +7 -0
  139. package/types/src/add.command.d.ts +6 -0
  140. package/types/src/add.module.d.ts +14 -0
  141. package/types/src/auth0-configure.action.d.ts +7 -0
  142. package/types/src/auth0-configure.command.d.ts +6 -0
  143. package/types/src/auth0-login.action.d.ts +4 -0
  144. package/types/src/auth0-login.command.d.ts +6 -0
  145. package/types/src/auth0.command.d.ts +6 -0
  146. package/types/src/auth0.module.d.ts +18 -0
  147. package/types/src/cli.d.ts +2 -0
  148. package/types/src/create.command.d.ts +6 -0
  149. package/types/src/create.module.d.ts +14 -0
  150. package/types/src/domain/prompt.d.ts +4 -0
  151. package/{src/index.ts → types/src/index.d.ts} +4 -0
  152. package/types/src/models/compose.model.d.ts +73 -0
  153. package/types/src/models/config-yaml.model.d.ts +27 -0
  154. package/types/src/models/const.d.ts +20 -0
  155. package/types/src/models/dev-container.model.d.ts +49 -0
  156. package/types/src/models/docker-image.model.d.ts +90 -0
  157. package/types/src/models/env-file.model.d.ts +16 -0
  158. package/types/src/models/gitignore.model.d.ts +9 -0
  159. package/types/src/models/launch-json.model.d.ts +7 -0
  160. package/types/src/models/package-json.model.d.ts +36 -0
  161. package/types/src/models/project.model.d.ts +60 -0
  162. package/{src/models/source-file.ts → types/src/models/source-file.d.ts} +4 -6
  163. package/types/src/models/tsconfig.model.d.ts +5 -0
  164. package/types/src/models/vitest-config.model.d.ts +5 -0
  165. package/types/src/models/vscode-settings.model.d.ts +7 -0
  166. package/types/src/program.d.ts +8 -0
  167. package/{src/resolve-target-dir.ts → types/src/resolve-target-dir.d.ts} +1 -4
  168. package/types/src/services/scaffold.service.d.ts +22 -0
  169. package/types/src/version.d.ts +6 -0
  170. package/types/src/webapi/api-name.d.ts +14 -0
  171. package/types/src/webapi/auth0-commands.d.ts +11 -0
  172. package/types/src/webapi/authorize-scopes.d.ts +7 -0
  173. package/types/src/webapi/cli-options.d.ts +6 -0
  174. package/{src/webapi/const.ts → types/src/webapi/const.d.ts} +9 -21
  175. package/types/src/webapi/create-api.d.ts +15 -0
  176. package/types/src/webapi/devcontainer/codebase-rag-mcp.d.ts +32 -0
  177. package/types/src/webapi/devcontainer/codebase-rag-mcp.ts +182 -0
  178. package/types/src/webapi/devcontainer/host-scripts.d.ts +7 -0
  179. package/types/src/webapi/devcontainer/templates/codebase-rag.env.example +3 -0
  180. package/types/src/webapi/devcontainer/templates/initialize.sh +169 -0
  181. package/types/src/webapi/devcontainer/templates/post-create.sh +35 -0
  182. package/types/src/webapi/devcontainer/templates/post-start.sh +65 -0
  183. package/types/src/webapi/devcontainer/templates/tty-prompt.sh +38 -0
  184. package/types/src/webapi/features/auth.feature.d.ts +10 -0
  185. package/types/src/webapi/features/auth0-cli.d.ts +84 -0
  186. package/types/src/webapi/features/biome-format.d.ts +5 -0
  187. package/types/src/webapi/features/database.feature.d.ts +7 -0
  188. package/types/src/webapi/features/finalize.feature.d.ts +2 -0
  189. package/types/src/webapi/features/postman.feature.d.ts +16 -0
  190. package/types/src/webapi/models/api-package-json.model.d.ts +18 -0
  191. package/types/src/webapi/models/auth-config.model.d.ts +26 -0
  192. package/types/src/webapi/models/controller-source-file.model.d.ts +46 -0
  193. package/types/src/webapi/models/github-ci.model.d.ts +9 -0
  194. package/types/src/webapi/models/main-source-file.model.d.ts +54 -0
  195. package/types/src/webapi/models/production-dockerfile.model.d.ts +18 -0
  196. package/types/src/webapi/models/sample-files.model.d.ts +7 -0
  197. package/types/src/webapi/models/webapi-image.model.d.ts +12 -0
  198. package/types/src/webapi/postman/hello-openapi.d.ts +19 -0
  199. package/types/src/webapi/postman/local-view.d.ts +17 -0
  200. package/types/src/webapi/postman/openapi-to-postman.d.ts +62 -0
  201. package/types/src/webapi/workspace-readme.d.ts +18 -0
  202. package/types/src/webapi.action.d.ts +14 -0
  203. package/types/src/webapi.command.d.ts +11 -0
  204. package/src/add-api.action.ts +0 -25
  205. package/src/add-api.command.ts +0 -31
  206. package/src/add.command.ts +0 -20
  207. package/src/add.module.ts +0 -11
  208. package/src/cli.ts +0 -4
  209. package/src/create.command.ts +0 -20
  210. package/src/create.module.ts +0 -11
  211. package/src/domain/prompt.ts +0 -50
  212. package/src/models/compose.model.ts +0 -205
  213. package/src/models/config-yaml.model.ts +0 -83
  214. package/src/models/const.ts +0 -20
  215. package/src/models/dev-container.model.ts +0 -136
  216. package/src/models/docker-image.model.ts +0 -343
  217. package/src/models/env-file.model.ts +0 -45
  218. package/src/models/gitignore.model.ts +0 -35
  219. package/src/models/launch-json.model.ts +0 -60
  220. package/src/models/package-json.model.ts +0 -169
  221. package/src/models/project.model.ts +0 -141
  222. package/src/models/tsconfig.model.ts +0 -29
  223. package/src/models/vitest-config.model.ts +0 -26
  224. package/src/models/vscode-settings.model.ts +0 -24
  225. package/src/program.ts +0 -63
  226. package/src/services/scaffold.service.ts +0 -89
  227. package/src/version.ts +0 -56
  228. package/src/webapi/api-name.ts +0 -73
  229. package/src/webapi/cli-options.ts +0 -56
  230. package/src/webapi/create-api.ts +0 -275
  231. package/src/webapi/devcontainer/host-scripts.ts +0 -35
  232. package/src/webapi/features/auth.feature.ts +0 -454
  233. package/src/webapi/features/auth0-cli.ts +0 -421
  234. package/src/webapi/features/biome-format.ts +0 -34
  235. package/src/webapi/features/database.feature.ts +0 -522
  236. package/src/webapi/features/finalize.feature.ts +0 -112
  237. package/src/webapi/features/postman.feature.ts +0 -287
  238. package/src/webapi/models/api-package-json.model.ts +0 -60
  239. package/src/webapi/models/auth-config.model.ts +0 -36
  240. package/src/webapi/models/controller-source-file.model.ts +0 -232
  241. package/src/webapi/models/main-source-file.model.ts +0 -208
  242. package/src/webapi/models/production-dockerfile.model.ts +0 -162
  243. package/src/webapi/models/sample-files.model.ts +0 -45
  244. package/src/webapi/models/webapi-image.model.ts +0 -21
  245. package/src/webapi/postman/hello-openapi.ts +0 -92
  246. package/src/webapi/postman/local-view.ts +0 -195
  247. package/src/webapi/postman/openapi-to-postman.ts +0 -208
  248. package/src/webapi/workspace-readme.ts +0 -192
  249. package/src/webapi.action.ts +0 -22
  250. package/src/webapi.command.ts +0 -41
  251. package/tests/auth-postman.wiring.spec.ts +0 -263
  252. package/tests/auth0-cli.spec.ts +0 -232
  253. package/tests/biome-format.spec.ts +0 -49
  254. package/tests/cli.integration.spec.ts +0 -658
  255. package/tests/compose.model.spec.ts +0 -51
  256. package/tests/container-image.model.spec.ts +0 -162
  257. package/tests/dev-container.model.spec.ts +0 -29
  258. package/tests/devcontainer-base-image.spec.ts +0 -32
  259. package/tests/hello-di-inject.scaffold.spec.ts +0 -18
  260. package/tests/hello-route.contract.spec.ts +0 -94
  261. package/tests/package-json.order.spec.ts +0 -59
  262. package/tests/postman-from-openapi.spec.ts +0 -197
  263. package/tests/seed-devcontainer-templates.ts +0 -40
  264. package/tests/webapi/devcontainer/codebase-rag-mcp.spec.ts +0 -96
@@ -1,454 +0,0 @@
1
- import { ask, pick } from "../../domain/prompt.js";
2
- import type { ConfigYaml } from "../../models/config-yaml.model.js";
3
- import { WELL_KNOWN_FILES } from "../../models/const.js";
4
- import type { EnvFile } from "../../models/env-file.model.js";
5
- import type { WorkspaceScaffold } from "../../models/project.model.js";
6
- import type { Feature } from "../../services/scaffold.service.js";
7
- import { AuthConfigModel } from "../models/auth-config.model.js";
8
- import { ControllerSourceFile } from "../models/controller-source-file.model.js";
9
- import type { MainSourceFile } from "../models/main-source-file.model.js";
10
- import * as auth0Cli from "./auth0-cli.js";
11
-
12
- export type AuthOptions = {
13
- authProvider?: "auth0" | "none";
14
- issuerBaseUrl?: string;
15
- audience?: string;
16
- databaseProvider?: "none" | "postgres/typeorm";
17
- adminUsername?: string;
18
- adminPassword?: string;
19
- };
20
-
21
- const ADMIN_ROLE = "admin";
22
-
23
- const USER_ENTITY_TS = `import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
24
- import type { Entity as IEntity } from "@decohere/codex";
25
-
26
- @Entity()
27
- export class UserEntity implements IEntity {
28
- \t@PrimaryGeneratedColumn()
29
- \tpublic id!: number;
30
-
31
- \t@Column({ unique: true })
32
- \tpublic sub!: string;
33
-
34
- \t@Column({ type: "varchar", nullable: true })
35
- \tpublic email!: string | null;
36
-
37
- \t@Column()
38
- \tpublic displayName!: string;
39
-
40
- \t/** App-owned roles. The \`admin\` role grants CASL \`manage\`/\`all\` (wildcard). */
41
- \t@Column({ type: "simple-json", default: "[]" })
42
- \tpublic roles!: string[];
43
- }
44
- `;
45
-
46
- const USER_REPOSITORY_TS = `import { injectable } from "@decohere/crucible/decorators";
47
- import { injectUnitOfWork } from "@decohere/codex";
48
- import { TypeOrmRepository, TypeOrmUnitOfWork } from "@decohere/codex-typeorm";
49
- import { UserEntity } from "../entities/user.entity.js";
50
-
51
- @injectable()
52
- export class UserEntityRepository extends TypeOrmRepository<UserEntity> {
53
- \tpublic constructor(@injectUnitOfWork() unitOfWork: TypeOrmUnitOfWork) {
54
- \t\tsuper(unitOfWork, UserEntity);
55
- \t}
56
-
57
- \tpublic findBySub(sub: string): Promise<UserEntity | null> {
58
- \t\treturn this.firstOrDefault({ where: { sub } });
59
- \t}
60
- }
61
- `;
62
-
63
- const USER_SERVICE_TS = `import { injectable } from "@decohere/crucible/decorators";
64
- import type { Principal } from "@decohere/cortex";
65
- import { UserEntity } from "../entities/user.entity.js";
66
- import { UserEntityRepository } from "../repositories/user.repository.js";
67
-
68
- function claimString(principal: Principal | undefined, key: string): string | undefined {
69
- \tconst value = principal?.[key];
70
- \treturn typeof value === "string" && value.length > 0 ? value : undefined;
71
- }
72
-
73
- @injectable()
74
- export class UserService {
75
- \tpublic constructor(private readonly users: UserEntityRepository) {}
76
-
77
- \t/**
78
- \t * Upsert a local profile keyed by JWT \`sub\`.
79
- \t * Profile fields from the token fill gaps; seeded rows keep displayName/email/roles.
80
- \t */
81
- \tpublic async ensureFromPrincipal(principal: Principal | undefined): Promise<UserEntity> {
82
- \t\tconst sub = principal?.sub;
83
- \t\tif (!sub) {
84
- \t\t\tthrow new Error("Authenticated request is missing principal.sub");
85
- \t\t}
86
-
87
- \t\tconst email =
88
- \t\t\tclaimString(principal, "email") ?? claimString(principal, "preferred_username");
89
- \t\tconst displayFromToken =
90
- \t\t\tclaimString(principal, "name") ??
91
- \t\t\tclaimString(principal, "nickname") ??
92
- \t\t\temail;
93
-
94
- \t\tconst existing = await this.users.findBySub(sub);
95
- \t\tif (existing) {
96
- \t\t\tlet dirty = false;
97
- \t\t\tif (!existing.email && email) {
98
- \t\t\t\texisting.email = email;
99
- \t\t\t\tdirty = true;
100
- \t\t\t}
101
- \t\t\tif (existing.displayName === existing.sub && displayFromToken) {
102
- \t\t\t\texisting.displayName = displayFromToken;
103
- \t\t\t\tdirty = true;
104
- \t\t\t}
105
- \t\t\treturn dirty ? this.users.save(existing) : existing;
106
- \t\t}
107
-
108
- \t\tconst created = new UserEntity();
109
- \t\tcreated.sub = sub;
110
- \t\tcreated.email = email ?? null;
111
- \t\tcreated.displayName = displayFromToken ?? sub;
112
- \t\tcreated.roles = Array.isArray(principal.roles)
113
- \t\t\t? principal.roles.filter((r): r is string => typeof r === "string")
114
- \t\t\t: [];
115
- \t\treturn this.users.save(created);
116
- \t}
117
- }
118
- `;
119
-
120
- const ABILITY_FACTORY_TS = `import type { Principal } from "@decohere/cortex";
121
- import {
122
- \tADMIN_ROLE,
123
- \tcreatePrincipalFromPayload,
124
- \tdefineAbilitiesFor as defaultDefineAbilitiesFor,
125
- } from "@decohere/cortex";
126
-
127
- /**
128
- * Customize CASL authorization here (product-specific rules).
129
- *
130
- * Default delegates to cortex: \`admin\` role → \`manage\`/\`all\`; IdP scopes
131
- * (\`action:Subject\`) → abilities. Replace the body when you need app rules
132
- * beyond that — this file is the intentional extension point, not framework
133
- * infrastructure to copy.
134
- */
135
- export function defineAbilitiesFor(principal: Principal) {
136
- \treturn defaultDefineAbilitiesFor(principal);
137
- }
138
-
139
- /**
140
- * Customize JWT → Principal mapping here (IdP-specific claims).
141
- *
142
- * Elevates \`AUTH0_ADMIN_USER_SUB\` to the admin role so the seeded admin works
143
- * before/without roles on the access token.
144
- */
145
- export function mapPrincipal(payload: Record<string, unknown>): Principal {
146
- \tconst principal = createPrincipalFromPayload(payload);
147
- \tconst sub = principal.sub;
148
- \tif (sub && sub === process.env.AUTH0_ADMIN_USER_SUB) {
149
- \t\treturn {
150
- \t\t\t...principal,
151
- \t\t\troles: [...new Set([ADMIN_ROLE, ...(principal.roles ?? [])])],
152
- \t\t};
153
- \t}
154
- \treturn principal;
155
- }
156
- `;
157
-
158
- async function getOptions(
159
- workspace: WorkspaceScaffold,
160
- cliOptions: Partial<AuthOptions>,
161
- ): Promise<Partial<AuthOptions>> {
162
- if (cliOptions.authProvider === "auth0" && !cliOptions.issuerBaseUrl) {
163
- return getAuth0Options(workspace, cliOptions);
164
- }
165
- if (cliOptions.authProvider != null) return {};
166
-
167
- const choices = [{ label: "none" as const }, { label: "auth0" as const }];
168
- const selected = await pick("\n Auth provider: ", choices, (c) => c.label);
169
- const provider = selected?.label ?? "none";
170
-
171
- if (provider !== "auth0") return { authProvider: "none" };
172
-
173
- return getAuth0Options(workspace, cliOptions);
174
- }
175
-
176
- async function getAuth0Options(
177
- workspace: WorkspaceScaffold,
178
- cliOptions: Partial<AuthOptions>,
179
- ): Promise<Partial<AuthOptions>> {
180
- if (!auth0Cli.isInstalled()) {
181
- console.error(
182
- "\n The Auth0 CLI is required for automated setup.\n" +
183
- " Install: brew install auth0/auth0-cli/auth0\n" +
184
- " Or visit: https://github.com/auth0/auth0-cli\n",
185
- );
186
- process.exit(1);
187
- }
188
-
189
- process.stdout.write("\n Checking Auth0 credentials...");
190
- let tenants = auth0Cli.listTenants();
191
- if (tenants.length === 0) {
192
- process.stdout.write(" not logged in.\n");
193
- console.log(" Logging in to Auth0 (your browser will open)...");
194
- if (!auth0Cli.login()) {
195
- console.error("\n Auth0 login failed.");
196
- process.exit(1);
197
- }
198
- tenants = auth0Cli.listTenants();
199
- }
200
-
201
- try {
202
- auth0Cli.listApis();
203
- process.stdout.write(" ok.\n");
204
- } catch (err) {
205
- if (err instanceof auth0Cli.Auth0AuthError) {
206
- process.stdout.write(" token expired.\n");
207
- console.log(" Re-authenticating (your browser will open)...");
208
- if (!auth0Cli.login()) {
209
- console.error("\n Auth0 login failed.");
210
- process.exit(1);
211
- }
212
- }
213
- }
214
-
215
- const active = tenants.find((t) => t.active) ?? tenants[0];
216
- const issuerBaseUrl = `https://${active.name}`;
217
- console.log(`\n ✓ Auth0 tenant: ${issuerBaseUrl}`);
218
-
219
- process.stdout.write("\n Fetching Auth0 APIs...");
220
- const userApis = auth0Cli.listApis().filter((a) => !a.name.includes("Management API"));
221
- process.stdout.write(` found ${userApis.length}.\n`);
222
-
223
- type ApiChoice = { label: string; existing: string | null };
224
- const projectName = workspace.name;
225
- const apiChoices: ApiChoice[] = [
226
- { label: `<new> https://api.${projectName}`, existing: null },
227
- ...userApis.map((a) => ({ label: `${a.name} — ${a.identifier}`, existing: a.identifier })),
228
- ];
229
-
230
- const apiSelected = await pick("\n Select Auth0 API: ", apiChoices, (c) => c.label);
231
-
232
- let audience: string;
233
- if (!apiSelected || apiSelected.existing === null) {
234
- const defaultId = `https://api.${projectName}`;
235
- audience = await ask(` API Identifier [${defaultId}]: `, defaultId);
236
- console.log("\n Creating Auth0 API...");
237
- audience = auth0Cli.createApi(`${projectName} API`, audience).identifier;
238
- console.log(` \u2713 API created: ${audience}`);
239
- } else {
240
- audience = apiSelected.existing;
241
- console.log(` \u2713 Selected: ${audience}`);
242
- try {
243
- auth0Cli.updateApiScopes(audience);
244
- console.log(` \u2713 API scopes ensured (${auth0Cli.HELLO_API_SCOPES.join(", ")})`);
245
- } catch {
246
- console.error(
247
- " ✗ Failed to update API scopes — add Hello scopes in the Auth0 dashboard.",
248
- );
249
- }
250
- }
251
-
252
- const withLocalUsers = cliOptions.databaseProvider === "postgres/typeorm";
253
- let adminUsername: string | undefined;
254
- let adminPassword: string | undefined;
255
- if (withLocalUsers) {
256
- adminUsername =
257
- cliOptions.adminUsername ?? (await ask("\n Admin username [admin]: ", "admin"));
258
- adminPassword = cliOptions.adminPassword;
259
- if (adminPassword == null) {
260
- adminPassword = await ask(" Admin password (leave blank to generate): ");
261
- if (!adminPassword) {
262
- adminPassword = auth0Cli.generateAdminPassword();
263
- console.log(` ✓ Generated admin password (written to .env): ${adminPassword}`);
264
- }
265
- }
266
- }
267
-
268
- return {
269
- authProvider: "auth0",
270
- issuerBaseUrl,
271
- audience,
272
- ...(withLocalUsers ? { adminUsername, adminPassword } : {}),
273
- };
274
- }
275
-
276
- function adminEmail(workspaceName: string, username: string): string {
277
- if (username.includes("@")) return username;
278
- const slug = workspaceName.toLowerCase().replace(/[^a-z0-9-]/g, "-");
279
- return `${username}@${slug}.example.com`;
280
- }
281
-
282
- function createAuth0AdminUser(
283
- workspace: WorkspaceScaffold,
284
- options: AuthOptions,
285
- authConfig: AuthConfigModel,
286
- ): void {
287
- const username = options.adminUsername ?? "admin";
288
- const password = options.adminPassword;
289
- if (!password) return;
290
-
291
- const email = adminEmail(workspace.name, username);
292
- try {
293
- const admin = auth0Cli.createAdminDatabaseUser({ email, password, username });
294
- authConfig.setAdminUser({
295
- sub: admin.user_id,
296
- email: admin.email,
297
- password: admin.password,
298
- username: admin.username,
299
- });
300
- workspace
301
- .getModel<EnvFile>(WELL_KNOWN_FILES.ENV_FILE)
302
- ?.addEntry("AUTH0_ADMIN_USER_SUB", admin.user_id)
303
- .addEntry("AUTH0_ADMIN_USER_EMAIL", admin.email)
304
- .addEntry("AUTH0_ADMIN_USER_PASSWORD", admin.password)
305
- .addEntry("AUTH0_ADMIN_USERNAME", admin.username);
306
- console.log(` ✓ Auth0 admin user ready: ${admin.email} (role: ${ADMIN_ROLE})`);
307
- console.log(` Login with EMAIL (not username): ${admin.email}`);
308
- console.log(` Password: see AUTH0_ADMIN_USER_PASSWORD in .env`);
309
- } catch (err) {
310
- console.error(
311
- ` ✗ Failed to ensure Auth0 admin user (${email}): ${err instanceof Error ? err.message : err}`,
312
- );
313
- }
314
- }
315
-
316
- function scaffoldLocalUserProfile(workspace: WorkspaceScaffold): void {
317
- for (const project of workspace.getProjects()) {
318
- project
319
- .getModel<MainSourceFile>(WELL_KNOWN_FILES.MAIN_TS)
320
- ?.addEntity({ className: "UserEntity", importPath: "./entities/user.entity.js" })
321
- .addRepository({
322
- className: "UserEntityRepository",
323
- importPath: "./repositories/user.repository.js",
324
- })
325
- .addService({
326
- className: "UserService",
327
- importPath: "./services/user.service.js",
328
- scope: "request",
329
- })
330
- .addImport("defineAbilitiesFor", "./auth/ability.factory.js")
331
- .addImport("mapPrincipal", "./auth/ability.factory.js")
332
- .setTypeOrmSeed(
333
- [
334
- "const sub = process.env.AUTH0_ADMIN_USER_SUB;",
335
- "if (!sub) return;",
336
- "const repo = dataSource.getRepository(UserEntity);",
337
- "const existing = await repo.findOne({ where: { sub } });",
338
- "if (existing) return;",
339
- "await repo.save(repo.create({",
340
- " sub,",
341
- " email: process.env.AUTH0_ADMIN_USER_EMAIL ?? null,",
342
- ' displayName: process.env.AUTH0_ADMIN_USERNAME ?? "admin",',
343
- ' roles: ["admin"],',
344
- "}));",
345
- ].join(" "),
346
- );
347
-
348
- project.addFile({
349
- files: () => [
350
- { filePath: "src/entities/user.entity.ts", content: USER_ENTITY_TS },
351
- { filePath: "src/repositories/user.repository.ts", content: USER_REPOSITORY_TS },
352
- { filePath: "src/services/user.service.ts", content: USER_SERVICE_TS },
353
- { filePath: "src/auth/ability.factory.ts", content: ABILITY_FACTORY_TS },
354
- ],
355
- });
356
- }
357
-
358
- for (const controller of workspace.getModels(ControllerSourceFile)) {
359
- controller
360
- .addImport("UserService", "../services/user.service.js")
361
- .addImport("inject", "@decohere/crucible/decorators")
362
- .addConstructorParam('@inject("UserService") private readonly users: UserService');
363
- controller.getMethod("getOne").setAsync(true).setBody([
364
- "const user = await this.users.ensureFromPrincipal(this.principalProvider.currentPrincipal);",
365
- // biome-ignore lint/suspicious/noTemplateCurlyInString: template literal in generated code
366
- "return { id, message: `Hello ${user.displayName}!`, username: user.displayName };",
367
- ]);
368
- }
369
- }
370
-
371
- function scaffold(workspace: WorkspaceScaffold, options: AuthOptions): void {
372
- if (options.authProvider !== "auth0") return;
373
-
374
- const resource = "Hello";
375
- const withLocalUsers = options.databaseProvider === "postgres/typeorm";
376
-
377
- for (const controller of workspace.getModels(ControllerSourceFile)) {
378
- controller
379
- .addDecorator(`@Authorize("read", "${resource}")`)
380
- .addCortexImport("AllowAnonymous")
381
- .addCortexImport("Authorize")
382
- .addCortexImport("IPrincipalProviderToken")
383
- .addCortexImport("IPrincipalProvider", true)
384
- .addImport("inject", "@decohere/crucible/decorators")
385
- .addConstructorParam(
386
- `@inject(IPrincipalProviderToken) private readonly principalProvider: IPrincipalProvider`,
387
- );
388
- controller.getMethod("getAll").addDecorator("@AllowAnonymous()");
389
- if (!withLocalUsers) {
390
- controller.getMethod("getOne").setBody([
391
- "const principal = this.principalProvider.currentPrincipal;",
392
- "const username =",
393
- '\t(typeof principal?.name === "string" && principal.name) ||',
394
- '\t(typeof principal?.nickname === "string" && principal.nickname) ||',
395
- '\t(typeof principal?.email === "string" && principal.email) ||',
396
- '\t(typeof principal?.preferred_username === "string" && principal.preferred_username) ||',
397
- "\tprincipal?.sub ||",
398
- '\t"unknown";',
399
- // biome-ignore lint/suspicious/noTemplateCurlyInString: template literal in generated code
400
- "return { id, message: `Hello ${username}!`, username };",
401
- ]);
402
- }
403
- controller.getMethod("create").addDecorator(`@Authorize("create", "${resource}")`);
404
- controller.getMethod("update").addDecorator(`@Authorize("update", "${resource}")`);
405
- controller.getMethod("remove").addDecorator(`@Authorize("delete", "${resource}")`);
406
- }
407
-
408
- for (const project of workspace.getProjects()) {
409
- project
410
- .getModel<MainSourceFile>(WELL_KNOWN_FILES.MAIN_TS)
411
- ?.addSideEffectImport("@decohere/cortex/auth");
412
- }
413
-
414
- if (withLocalUsers) {
415
- scaffoldLocalUserProfile(workspace);
416
- for (const project of workspace.getProjects()) {
417
- project
418
- .getModel<MainSourceFile>(WELL_KNOWN_FILES.MAIN_TS)
419
- ?.addBuilderCall(".withAuth(defineAbilitiesFor, { principalMapper: mapPrincipal })");
420
- }
421
- } else {
422
- for (const project of workspace.getProjects()) {
423
- project
424
- .getModel<MainSourceFile>(WELL_KNOWN_FILES.MAIN_TS)
425
- ?.addBuilderCall(".withAuth()");
426
- }
427
- }
428
-
429
- // biome-ignore lint/suspicious/noTemplateCurlyInString: intentional YAML env-var placeholders
430
- const issuerPlaceholder = "${AUTH0_ISSUER_BASE_URL}";
431
- // biome-ignore lint/suspicious/noTemplateCurlyInString: intentional YAML env-var placeholders
432
- const audPlaceholder = "${AUTH0_AUDIENCE}";
433
-
434
- const configSection = `auth:\n discoveryUrl: ${issuerPlaceholder}\n audience: ${audPlaceholder}\n`;
435
-
436
- workspace.getModel<ConfigYaml>(WELL_KNOWN_FILES.CONFIG_YAML)?.addSection(configSection);
437
-
438
- workspace
439
- .getModel<EnvFile>(WELL_KNOWN_FILES.ENV_FILE)
440
- ?.addEntry("AUTH0_ISSUER_BASE_URL", options.issuerBaseUrl ?? "")
441
- .addEntry("AUTH0_AUDIENCE", options.audience ?? "");
442
-
443
- const authConfig = new AuthConfigModel({
444
- issuerBaseUrl: options.issuerBaseUrl ?? "",
445
- audience: options.audience ?? "",
446
- });
447
- workspace.addModel(authConfig);
448
-
449
- if (withLocalUsers && options.adminPassword) {
450
- createAuth0AdminUser(workspace, options, authConfig);
451
- }
452
- }
453
-
454
- export const AuthFeature: Feature<AuthOptions> = { getOptions, scaffold };