sonamu 0.13.10 → 0.14.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 (330) hide show
  1. package/dist/api/caster.d.ts.map +1 -1
  2. package/dist/api/caster.js +2 -1
  3. package/dist/api/code-converters.d.ts +5 -1
  4. package/dist/api/code-converters.d.ts.map +1 -1
  5. package/dist/api/code-converters.js +24 -7
  6. package/dist/api/config.d.ts +7 -0
  7. package/dist/api/config.d.ts.map +1 -1
  8. package/dist/api/config.js +1 -1
  9. package/dist/api/decorators.d.ts +1 -0
  10. package/dist/api/decorators.d.ts.map +1 -1
  11. package/dist/api/decorators.js +1 -1
  12. package/dist/api/guards.d.ts +37 -0
  13. package/dist/api/guards.d.ts.map +1 -0
  14. package/dist/api/guards.js +96 -0
  15. package/dist/api/sonamu.d.ts +14 -1
  16. package/dist/api/sonamu.d.ts.map +1 -1
  17. package/dist/api/sonamu.js +121 -25
  18. package/dist/api/websocket-helpers.d.ts +6 -1
  19. package/dist/api/websocket-helpers.d.ts.map +1 -1
  20. package/dist/api/websocket-helpers.js +7 -4
  21. package/dist/auth/auth-entity-policy.d.ts +32 -0
  22. package/dist/auth/auth-entity-policy.d.ts.map +1 -0
  23. package/dist/auth/auth-entity-policy.js +44 -0
  24. package/dist/auth/auth-secret.d.ts +24 -0
  25. package/dist/auth/auth-secret.d.ts.map +1 -0
  26. package/dist/auth/auth-secret.js +46 -0
  27. package/dist/auth/base-url.d.ts +39 -0
  28. package/dist/auth/base-url.d.ts.map +1 -0
  29. package/dist/auth/base-url.js +84 -0
  30. package/dist/auth/better-auth-entities.js +20 -7
  31. package/dist/auth/better-auth-options.d.ts +15 -0
  32. package/dist/auth/better-auth-options.d.ts.map +1 -0
  33. package/dist/auth/better-auth-options.js +38 -0
  34. package/dist/auth/better-auth-request.d.ts +8 -1
  35. package/dist/auth/better-auth-request.d.ts.map +1 -1
  36. package/dist/auth/better-auth-request.js +26 -3
  37. package/dist/auth/plugins/entity-definitions/admin.d.ts.map +1 -1
  38. package/dist/auth/plugins/entity-definitions/admin.js +6 -1
  39. package/dist/auth/plugins/entity-definitions/anonymous.d.ts.map +1 -1
  40. package/dist/auth/plugins/entity-definitions/anonymous.js +2 -1
  41. package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
  42. package/dist/auth/plugins/entity-definitions/api-key.js +18 -2
  43. package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
  44. package/dist/auth/plugins/entity-definitions/audit-log.js +27 -1
  45. package/dist/auth/plugins/entity-definitions/jwt.d.ts.map +1 -1
  46. package/dist/auth/plugins/entity-definitions/jwt.js +4 -2
  47. package/dist/auth/plugins/entity-definitions/organization.d.ts.map +1 -1
  48. package/dist/auth/plugins/entity-definitions/organization.js +15 -1
  49. package/dist/auth/plugins/entity-definitions/passkey.d.ts.map +1 -1
  50. package/dist/auth/plugins/entity-definitions/passkey.js +9 -1
  51. package/dist/auth/plugins/entity-definitions/phone-number.d.ts.map +1 -1
  52. package/dist/auth/plugins/entity-definitions/phone-number.js +2 -1
  53. package/dist/auth/plugins/entity-definitions/sso.d.ts.map +1 -1
  54. package/dist/auth/plugins/entity-definitions/sso.js +7 -3
  55. package/dist/auth/plugins/entity-definitions/two-factor.d.ts.map +1 -1
  56. package/dist/auth/plugins/entity-definitions/two-factor.js +8 -3
  57. package/dist/auth/verify-email-guard.d.ts +37 -0
  58. package/dist/auth/verify-email-guard.d.ts.map +1 -0
  59. package/dist/auth/verify-email-guard.js +48 -0
  60. package/dist/bin/build-config.d.ts.map +1 -1
  61. package/dist/bin/build-config.js +6 -2
  62. package/dist/bin/typecheck-web.js +1 -1
  63. package/dist/cache/decorator.d.ts +12 -0
  64. package/dist/cache/decorator.d.ts.map +1 -1
  65. package/dist/cache/decorator.js +86 -19
  66. package/dist/cache/index.d.ts +1 -1
  67. package/dist/cache/index.d.ts.map +1 -1
  68. package/dist/cache/index.js +3 -3
  69. package/dist/cache/types.d.ts +16 -0
  70. package/dist/cache/types.d.ts.map +1 -1
  71. package/dist/cli/plugin-loader.d.ts +17 -0
  72. package/dist/cli/plugin-loader.d.ts.map +1 -0
  73. package/dist/cli/plugin-loader.js +178 -0
  74. package/dist/cli/plugin.d.ts +65 -0
  75. package/dist/cli/plugin.d.ts.map +1 -0
  76. package/dist/cli/plugin.js +7 -0
  77. package/dist/code-formatting/oxfmt.js +1 -1
  78. package/dist/code-formatting/oxlint.js +1 -1
  79. package/dist/database/db.d.ts +35 -10
  80. package/dist/database/db.d.ts.map +1 -1
  81. package/dist/database/db.js +37 -4
  82. package/dist/database/puri.d.ts +8 -0
  83. package/dist/database/puri.d.ts.map +1 -1
  84. package/dist/database/puri.js +108 -171
  85. package/dist/database/puri.types.d.ts +2 -0
  86. package/dist/database/puri.types.d.ts.map +1 -1
  87. package/dist/database/puri.types.js +1 -1
  88. package/dist/database/sql-expression-brand.d.ts +10 -0
  89. package/dist/database/sql-expression-brand.d.ts.map +1 -0
  90. package/dist/database/sql-expression-brand.js +10 -0
  91. package/dist/dict/en.d.ts +1 -0
  92. package/dist/dict/en.d.ts.map +1 -1
  93. package/dist/dict/en.js +2 -1
  94. package/dist/dict/ko.d.ts +1 -0
  95. package/dist/dict/ko.d.ts.map +1 -1
  96. package/dist/dict/ko.js +2 -1
  97. package/dist/dict/sonamu-dictionary.d.ts +23 -1
  98. package/dist/dict/sonamu-dictionary.d.ts.map +1 -1
  99. package/dist/dict/sonamu-dictionary.js +187 -32
  100. package/dist/entity/entity-codegen-safety.d.ts +105 -0
  101. package/dist/entity/entity-codegen-safety.d.ts.map +1 -0
  102. package/dist/entity/entity-codegen-safety.js +70 -0
  103. package/dist/entity/entity-manager.d.ts +32 -0
  104. package/dist/entity/entity-manager.d.ts.map +1 -1
  105. package/dist/entity/entity-manager.js +21 -2
  106. package/dist/entity/entity.d.ts +5 -2
  107. package/dist/entity/entity.d.ts.map +1 -1
  108. package/dist/entity/entity.js +19 -8
  109. package/dist/env.d.ts +19 -0
  110. package/dist/env.d.ts.map +1 -1
  111. package/dist/env.js +31 -3
  112. package/dist/filter/utils.d.ts +2 -2
  113. package/dist/filter/utils.d.ts.map +1 -1
  114. package/dist/filter/utils.js +16 -11
  115. package/dist/index.d.ts +4 -3
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +7 -6
  118. package/dist/logger/configure.d.ts.map +1 -1
  119. package/dist/logger/configure.js +10 -3
  120. package/dist/migration/code-generation.d.ts.map +1 -1
  121. package/dist/migration/code-generation.js +177 -96
  122. package/dist/migration/migrator.d.ts +16 -0
  123. package/dist/migration/migrator.d.ts.map +1 -1
  124. package/dist/migration/migrator.js +28 -3
  125. package/dist/migration/slack-confirm.d.ts +6 -2
  126. package/dist/migration/slack-confirm.d.ts.map +1 -1
  127. package/dist/migration/slack-confirm.js +11 -9
  128. package/dist/ssr/errors.d.ts +13 -0
  129. package/dist/ssr/errors.d.ts.map +1 -0
  130. package/dist/ssr/errors.js +12 -0
  131. package/dist/ssr/index.d.ts +1 -0
  132. package/dist/ssr/index.d.ts.map +1 -1
  133. package/dist/ssr/index.js +5 -2
  134. package/dist/ssr/renderer.d.ts +6 -0
  135. package/dist/ssr/renderer.d.ts.map +1 -1
  136. package/dist/ssr/renderer.js +10 -1
  137. package/dist/storage/base-file.d.ts +6 -2
  138. package/dist/storage/base-file.d.ts.map +1 -1
  139. package/dist/storage/base-file.js +10 -5
  140. package/dist/storage/buffered-file.d.ts +1 -0
  141. package/dist/storage/buffered-file.d.ts.map +1 -1
  142. package/dist/storage/buffered-file.js +5 -2
  143. package/dist/storage/index.d.ts +1 -0
  144. package/dist/storage/index.d.ts.map +1 -1
  145. package/dist/storage/index.js +4 -2
  146. package/dist/storage/upload-safety.d.ts +47 -0
  147. package/dist/storage/upload-safety.d.ts.map +1 -0
  148. package/dist/storage/upload-safety.js +112 -0
  149. package/dist/stream/ws.d.ts +6 -0
  150. package/dist/stream/ws.d.ts.map +1 -1
  151. package/dist/stream/ws.js +52 -6
  152. package/dist/syncer/api-parser.js +6 -1
  153. package/dist/syncer/code-generator.d.ts +2 -0
  154. package/dist/syncer/code-generator.d.ts.map +1 -1
  155. package/dist/syncer/code-generator.js +21 -7
  156. package/dist/template/implementations/entity.template.d.ts.map +1 -1
  157. package/dist/template/implementations/entity.template.js +40 -35
  158. package/dist/template/implementations/generated.template.d.ts +10 -0
  159. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  160. package/dist/template/implementations/generated.template.js +46 -7
  161. package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
  162. package/dist/template/implementations/generated_http.template.js +3 -1
  163. package/dist/template/implementations/init_types.template.d.ts.map +1 -1
  164. package/dist/template/implementations/init_types.template.js +3 -8
  165. package/dist/template/implementations/model.template.d.ts.map +1 -1
  166. package/dist/template/implementations/model.template.js +9 -2
  167. package/dist/template/implementations/sd.template.d.ts +0 -1
  168. package/dist/template/implementations/sd.template.d.ts.map +1 -1
  169. package/dist/template/implementations/sd.template.js +2 -5
  170. package/dist/template/implementations/view_form.template.d.ts.map +1 -1
  171. package/dist/template/implementations/view_form.template.js +8 -6
  172. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  173. package/dist/template/implementations/view_list.template.js +8 -4
  174. package/dist/testing/dev-test-routes.d.ts.map +1 -1
  175. package/dist/testing/dev-test-routes.js +7 -4
  176. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
  177. package/dist/tooling/cdd-service.js +1 -1
  178. package/dist/tooling/index.d.ts +1 -0
  179. package/dist/tooling/index.d.ts.map +1 -1
  180. package/dist/tooling/index.js +3 -1
  181. package/dist/tsdown.api.config.js +1 -1
  182. package/dist/types/types.d.ts +81 -1
  183. package/dist/types/types.d.ts.map +1 -1
  184. package/dist/types/types.js +2 -1
  185. package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
  186. package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
  187. package/dist/ui/__tests__/ui-test-helpers.js +75 -0
  188. package/dist/ui/access-guard.d.ts +42 -0
  189. package/dist/ui/access-guard.d.ts.map +1 -0
  190. package/dist/ui/access-guard.js +94 -0
  191. package/dist/ui/api.d.ts.map +1 -1
  192. package/dist/ui/api.js +40 -95
  193. package/dist/ui/dev-host-guard.d.ts +28 -0
  194. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  195. package/dist/ui/dev-host-guard.js +67 -0
  196. package/dist/ui/migrations-api.d.ts.map +1 -1
  197. package/dist/ui/migrations-api.js +72 -16
  198. package/dist/ui/open-vscode-api.d.ts +4 -0
  199. package/dist/ui/open-vscode-api.d.ts.map +1 -0
  200. package/dist/ui/open-vscode-api.js +65 -0
  201. package/dist/ui/scaffolding-api.d.ts +18 -0
  202. package/dist/ui/scaffolding-api.d.ts.map +1 -0
  203. package/dist/ui/scaffolding-api.js +111 -0
  204. package/dist/ui/ui-db-presets.d.ts +19 -0
  205. package/dist/ui/ui-db-presets.d.ts.map +1 -0
  206. package/dist/ui/ui-db-presets.js +34 -0
  207. package/dist/ui/ui-request-guard.d.ts +11 -0
  208. package/dist/ui/ui-request-guard.d.ts.map +1 -0
  209. package/dist/ui/ui-request-guard.js +38 -0
  210. package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
  211. package/dist/ui-web/index.html +2 -1
  212. package/package.json +1 -1
  213. package/src/__tests__/env.test.ts +121 -2
  214. package/src/api/__tests__/code-converters.union.test.ts +97 -0
  215. package/src/api/__tests__/guards.test.ts +233 -0
  216. package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
  217. package/src/api/__tests__/sonamu.dev-host-guard.test.ts +130 -0
  218. package/src/api/__tests__/sonamu.guards.test.ts +327 -0
  219. package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
  220. package/src/api/__tests__/websocket-helpers.test.ts +101 -0
  221. package/src/api/caster.ts +7 -0
  222. package/src/api/code-converters.ts +44 -12
  223. package/src/api/config.ts +8 -0
  224. package/src/api/decorators.ts +1 -0
  225. package/src/api/guards.ts +130 -0
  226. package/src/api/sonamu.ts +195 -39
  227. package/src/api/websocket-helpers.ts +11 -6
  228. package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
  229. package/src/auth/__tests__/auth-secret.test.ts +133 -0
  230. package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
  231. package/src/auth/__tests__/base-url.test.ts +117 -0
  232. package/src/auth/__tests__/better-auth-options.test.ts +194 -0
  233. package/src/auth/__tests__/better-auth-request.test.ts +45 -0
  234. package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
  235. package/src/auth/auth-entity-policy.ts +48 -0
  236. package/src/auth/auth-secret.ts +77 -0
  237. package/src/auth/base-url.ts +109 -0
  238. package/src/auth/better-auth-entities.ts +30 -30
  239. package/src/auth/better-auth-options.ts +39 -0
  240. package/src/auth/better-auth-request.ts +28 -1
  241. package/src/auth/plugins/entity-definitions/admin.ts +5 -0
  242. package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
  243. package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
  244. package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
  245. package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
  246. package/src/auth/plugins/entity-definitions/organization.ts +26 -6
  247. package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
  248. package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
  249. package/src/auth/plugins/entity-definitions/sso.ts +20 -15
  250. package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
  251. package/src/auth/verify-email-guard.ts +82 -0
  252. package/src/bin/__tests__/build-web-command.test.ts +24 -0
  253. package/src/bin/build-config.ts +5 -0
  254. package/src/cache/decorator.ts +116 -21
  255. package/src/cache/index.ts +6 -1
  256. package/src/cache/types.ts +18 -0
  257. package/src/cli/plugin-loader.ts +238 -0
  258. package/src/cli/plugin.ts +82 -0
  259. package/src/database/__tests__/db.test.ts +64 -1
  260. package/src/database/__tests__/puri.test.ts +56 -0
  261. package/src/database/db.ts +56 -6
  262. package/src/database/puri.ts +135 -125
  263. package/src/database/puri.types.test-d.ts +12 -0
  264. package/src/database/puri.types.ts +3 -0
  265. package/src/database/sql-expression-brand.ts +9 -0
  266. package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
  267. package/src/dict/en.ts +2 -0
  268. package/src/dict/ko.ts +2 -0
  269. package/src/dict/sonamu-dictionary.ts +298 -38
  270. package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
  271. package/src/entity/entity-codegen-safety.ts +126 -0
  272. package/src/entity/entity-manager.ts +29 -1
  273. package/src/entity/entity.ts +26 -12
  274. package/src/env.ts +52 -1
  275. package/src/filter/utils.ts +19 -7
  276. package/src/index.ts +4 -3
  277. package/src/logger/__tests__/configure.test.ts +51 -1
  278. package/src/logger/configure.ts +14 -1
  279. package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
  280. package/src/migration/__tests__/migrator.test.ts +76 -1
  281. package/src/migration/code-generation.ts +247 -117
  282. package/src/migration/migrator.ts +45 -4
  283. package/src/migration/slack-confirm.ts +19 -5
  284. package/src/ssr/__tests__/preload-guard.test.ts +274 -0
  285. package/src/ssr/errors.ts +11 -0
  286. package/src/ssr/index.ts +1 -0
  287. package/src/ssr/renderer.ts +12 -0
  288. package/src/storage/__tests__/upload-safety.test.ts +179 -0
  289. package/src/storage/base-file.ts +8 -4
  290. package/src/storage/buffered-file.ts +3 -1
  291. package/src/storage/index.ts +9 -0
  292. package/src/storage/upload-safety.ts +155 -0
  293. package/src/stream/__tests__/ws.test.ts +97 -0
  294. package/src/stream/ws.ts +67 -5
  295. package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
  296. package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
  297. package/src/syncer/api-parser.ts +12 -0
  298. package/src/syncer/code-generator.ts +34 -6
  299. package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
  300. package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
  301. package/src/template/__tests__/save-params.template.test.ts +219 -0
  302. package/src/template/implementations/entity.template.ts +53 -48
  303. package/src/template/implementations/generated.template.ts +87 -12
  304. package/src/template/implementations/generated_http.template.ts +5 -0
  305. package/src/template/implementations/init_types.template.ts +4 -22
  306. package/src/template/implementations/model.template.ts +15 -1
  307. package/src/template/implementations/sd.template.ts +4 -5
  308. package/src/template/implementations/view_form.template.ts +13 -5
  309. package/src/template/implementations/view_list.template.ts +12 -3
  310. package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
  311. package/src/testing/dev-test-routes.ts +7 -3
  312. package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
  313. package/src/tooling/index.ts +1 -0
  314. package/src/types/types.ts +22 -1
  315. package/src/ui/__tests__/access-guard.test.ts +217 -0
  316. package/src/ui/__tests__/dev-host-guard.test.ts +161 -0
  317. package/src/ui/__tests__/fixture-api.test.ts +92 -0
  318. package/src/ui/__tests__/migrations-api.test.ts +352 -0
  319. package/src/ui/__tests__/open-vscode.test.ts +151 -0
  320. package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
  321. package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
  322. package/src/ui/__tests__/ui-test-helpers.ts +71 -0
  323. package/src/ui/access-guard.ts +115 -0
  324. package/src/ui/api.ts +65 -198
  325. package/src/ui/dev-host-guard.ts +109 -0
  326. package/src/ui/migrations-api.ts +130 -24
  327. package/src/ui/open-vscode-api.ts +82 -0
  328. package/src/ui/scaffolding-api.ts +177 -0
  329. package/src/ui/ui-db-presets.ts +41 -0
  330. package/src/ui/ui-request-guard.ts +53 -0
@@ -0,0 +1,82 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+ import { type BetterAuthPlugin } from "better-auth";
3
+ import { APIError, createAuthMiddleware } from "better-auth/api";
4
+ import { deleteSessionCookie } from "better-auth/cookies";
5
+
6
+ /**
7
+ * 누구나 알 수 있는 better-auth secret 값 목록입니다.
8
+ *
9
+ * 이 값으로 서명된 verify-email JWT는 외부인이 얼마든지 만들 수 있으므로 신뢰하지 않습니다.
10
+ */
11
+ export const PUBLIC_AUTH_SECRETS: ReadonlySet<string> = new Set([
12
+ // secret을 지정하지 않았을 때 better-auth가 쓰는 기본 상수(DEFAULT_SECRET)
13
+ "better-auth-secret-12345678901234567890",
14
+ // miomock·스캐폴드 예시 설정에 공개된 fallback 값
15
+ "miomock-secret-key-change-this-in-production",
16
+ ]);
17
+
18
+ /**
19
+ * secret이 비어 있거나 공개된 값인지 확인합니다.
20
+ */
21
+ export function isPublicAuthSecret(secret: string | undefined): boolean {
22
+ return !secret || PUBLIC_AUTH_SECRETS.has(secret);
23
+ }
24
+
25
+ const VERIFY_EMAIL_PATH = "/verify-email";
26
+
27
+ /**
28
+ * better-auth `/verify-email` 엔드포인트를 보호하는 Sonamu 내부 플러그인입니다.
29
+ *
30
+ * verify-email 토큰은 secret으로만 서명되는 stateless JWT이고, 이메일 변경 토큰이나
31
+ * `autoSignInAfterVerification`이 쓰이면 쿠키 없는 요청에도 토큰 주인의 세션을 새로 발급합니다.
32
+ * better-auth의 twoFactor 플러그인은 `/sign-in/*` 경로만 가로채므로 이 세션은 2FA도 거치지 않습니다.
33
+ *
34
+ * - 공개 secret으로 동작 중이면 verify-email 토큰을 모두 거부합니다.
35
+ * - 2FA가 켜진 사용자에게 verify-email이 새로 발급한 세션은 쿠키와 DB에서 즉시 폐기합니다.
36
+ * 이메일 인증·변경 자체는 그대로 반영되고, 로그인은 2FA를 거치는 일반 로그인으로 해야 합니다.
37
+ *
38
+ * Sonamu가 auth 초기화 시 자동으로 등록하므로 앱에서 직접 추가할 필요가 없습니다.
39
+ */
40
+ export const sonamuVerifyEmailGuard = () =>
41
+ ({
42
+ id: "sonamu-verify-email-guard",
43
+ hooks: {
44
+ before: [
45
+ {
46
+ matcher: (ctx) => ctx.path === VERIFY_EMAIL_PATH,
47
+ handler: createAuthMiddleware(async (ctx) => {
48
+ if (!isPublicAuthSecret(ctx.context.secret)) return;
49
+ getLogger(["sonamu", "auth"]).error(
50
+ "Rejected a /verify-email request because the auth secret is a publicly known value. Set BETTER_AUTH_SECRET to a random secret.",
51
+ );
52
+ // 이 시점에는 callbackURL의 origin 검사가 끝나지 않았으므로 리다이렉트하지 않고 바로 거부한다.
53
+ throw new APIError("UNAUTHORIZED", { code: "INVALID_TOKEN", message: "Invalid token" });
54
+ }),
55
+ },
56
+ ],
57
+ after: [
58
+ {
59
+ matcher: (ctx) => ctx.path === VERIFY_EMAIL_PATH,
60
+ handler: createAuthMiddleware(async (ctx) => {
61
+ const issued = ctx.context.newSession;
62
+ if (!issued) return;
63
+
64
+ // 요청에 실려 온 본인 세션을 재사용한 경우는 이미 2FA를 거친 로그인이므로 그대로 둔다.
65
+ const requestToken = await ctx.getSignedCookie(
66
+ ctx.context.authCookies.sessionToken.name,
67
+ ctx.context.secret,
68
+ );
69
+ if (requestToken === issued.session.token) return;
70
+
71
+ const user = await ctx.context.internalAdapter.findUserById(issued.user.id);
72
+ if (!user || !("twoFactorEnabled" in user) || user.twoFactorEnabled !== true) return;
73
+
74
+ // twoFactor 플러그인의 로그인 처리와 같이, 앞서 붙은 세션 쿠키를 지우고 세션을 폐기한다.
75
+ deleteSessionCookie(ctx, true);
76
+ await ctx.context.internalAdapter.deleteSession(issued.session.token);
77
+ ctx.context.setNewSession(null);
78
+ }),
79
+ },
80
+ ],
81
+ },
82
+ }) satisfies BetterAuthPlugin;
@@ -54,4 +54,28 @@ describe("buildWebCommand", () => {
54
54
  // 타입 오류 시 기존 dist/*를 건드리지 않도록 타입체크 명령 하나만 실행된다.
55
55
  expect(calls).toHaveLength(1);
56
56
  });
57
+
58
+ it("NODE_ENV가 없으면 vite 빌드를 production NODE_ENV로 실행한다", async () => {
59
+ vi.stubEnv("NODE_ENV", "");
60
+ const nodeEnvs: (string | undefined)[] = [];
61
+
62
+ await buildWebCommand({
63
+ exec: async (cmd, options) => {
64
+ nodeEnvs.push(process.env.NODE_ENV);
65
+ await exec(cmd, options);
66
+ },
67
+ });
68
+
69
+ // development NODE_ENV를 물려받으면 SSR 번들이 jsxDEV를 써서 프로덕션 렌더링이 실패한다.
70
+ expect(nodeEnvs.length).toBeGreaterThan(0);
71
+ expect(nodeEnvs.every((nodeEnv) => nodeEnv === "production")).toBe(true);
72
+ });
73
+
74
+ it("명시한 NODE_ENV는 web 빌드에서도 그대로 유지한다", async () => {
75
+ vi.stubEnv("NODE_ENV", "staging");
76
+
77
+ await buildWebCommand({ exec });
78
+
79
+ expect(process.env.NODE_ENV).toBe("staging");
80
+ });
57
81
  });
@@ -7,6 +7,7 @@ import chalk from "chalk";
7
7
  import { type UserConfig } from "tsdown";
8
8
 
9
9
  import { type NormalizedZodCompilerPolicy } from "../api/config";
10
+ import { ensureSonamuEnvironment } from "../env";
10
11
  import {
11
12
  execWithLinePrefix,
12
13
  printBuildSummary,
@@ -291,6 +292,8 @@ async function runBuildSteps<T>(
291
292
 
292
293
  export async function buildApiCommand(): Promise<void> {
293
294
  const apiRootPath = findApiRootPath();
295
+ // 빌드는 배포 산출물을 만드므로 NODE_ENV가 없으면 production 설정으로 빌드합니다.
296
+ ensureSonamuEnvironment(apiRootPath, "production");
294
297
  const baseConfigPath = await resolveApiBuildConfigPath(apiRootPath);
295
298
  const policy = await loadBuildCompilerPolicy(apiRootPath);
296
299
  const registryPath = path.join(apiRootPath, HTTP_VALIDATOR_REGISTRY_SOURCE_PATH);
@@ -335,6 +338,8 @@ export async function buildWebCommand({
335
338
  }: { skipIfMissing?: boolean; exec?: typeof execWithLinePrefix } = {}): Promise<void> {
336
339
  const appRootPath = findAppRootPath();
337
340
  const webPath = path.join(appRootPath, "web");
341
+ // vite 자식 프로세스가 development NODE_ENV를 물려받으면 SSR 번들이 jsxDEV를 써서 프로덕션에서 깨집니다.
342
+ ensureSonamuEnvironment(findApiRootPath(), "production");
338
343
  if (!(await exists(webPath))) {
339
344
  if (skipIfMissing) {
340
345
  console.log(chalk.gray("Web 디렉토리가 없으므로 Web 빌드를 건너뜁니다."));
@@ -1,7 +1,16 @@
1
1
  import { type BaseFrameClass } from "../api/base-frame";
2
+ import { type RuntimeContext } from "../api/context";
3
+ import { Sonamu } from "../api/sonamu";
2
4
  import { BaseModelClass } from "../database/base-model";
3
5
  import { isBooleanValue } from "../runtime-type";
4
- import { isFunctionValue, isNumberValue, isStringValue } from "../utils/runtime-value";
6
+ import {
7
+ isBigIntValue,
8
+ isFunctionValue,
9
+ isNumberValue,
10
+ isObjectValue,
11
+ isStringValue,
12
+ isSymbolValue,
13
+ } from "../utils/runtime-value";
5
14
  import { type CacheDecoratorOptions, type CacheManager } from "./types";
6
15
 
7
16
  type DecoratorTarget = { constructor: { name: string } };
@@ -28,36 +37,106 @@ export function getCacheManagerRef(): CacheManager | null {
28
37
  return cacheManagerRef;
29
38
  }
30
39
 
40
+ /**
41
+ * 캐시 키를 만들 수 없는 인자를 받았을 때 던지는 에러
42
+ */
43
+ export class CacheKeySerializationError extends TypeError {
44
+ constructor(cacheName: string, reason: string) {
45
+ super(
46
+ `@cache(${cacheName}): ${reason} 캐시 키를 만들 수 없습니다. key 옵션으로 키를 직접 지정하세요.`,
47
+ );
48
+ this.name = "CacheKeySerializationError";
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Sonamu가 API 메서드에 주입하는 Context(HTTP/WebSocket) 객체인지 판별합니다.
54
+ */
55
+ function isRuntimeContextArg<Value>(value: Value): value is Value & RuntimeContext {
56
+ if (!isObjectValue(value)) return false;
57
+ const candidate: Partial<Record<"transport" | "naiteStore", Value>> = value;
58
+ return (
59
+ (candidate.transport === "http" || candidate.transport === "ws") &&
60
+ candidate.naiteStore instanceof Map &&
61
+ "user" in value
62
+ );
63
+ }
64
+
65
+ /**
66
+ * 키에 넣을 사용자 구분자를 만듭니다.
67
+ * id를 JSON 문자열로 감싸 뒤따르는 인자 suffix와 경계가 섞이지 않게 합니다.
68
+ */
69
+ function userSegment(context: RuntimeContext): string {
70
+ const userId = context.user?.id;
71
+ return userId === undefined || userId === null ? "anon" : `user:${JSON.stringify(userId)}`;
72
+ }
73
+
74
+ /**
75
+ * 현재 요청(ALS)의 Context를 가져옵니다. 요청 밖(테스트·스크립트·워크플로)에서는 null입니다.
76
+ * Sonamu.getContext()는 테스트 환경에서 mock을 돌려주므로 ALS store를 직접 읽습니다.
77
+ */
78
+ function getRequestContext(): RuntimeContext | null {
79
+ return Sonamu.asyncLocalStorage.getStore()?.context ?? null;
80
+ }
81
+
31
82
  /**
32
83
  * 캐시 키 생성
33
84
  */
34
85
  function generateCacheKey(
86
+ cacheName: string,
35
87
  modelName: string,
36
88
  methodName: string,
37
89
  args: unknown[],
38
- keyOption?: CacheDecoratorOptions["key"],
90
+ options: Pick<CacheDecoratorOptions, "key" | "scope">,
39
91
  ): string {
40
- // 커스텀 키 함수 사용
92
+ const { key: keyOption, scope = "global" } = options;
93
+ const contextArg = args.find(isRuntimeContextArg);
94
+ const requestContext = contextArg ?? (scope === "user" ? getRequestContext() : null);
95
+ const userSuffix = scope === "user" && requestContext ? userSegment(requestContext) : "";
96
+
97
+ // 커스텀 키 함수 사용 (Context 인자는 함수가 직접 다룸)
41
98
  if (isCacheKeyFactory(keyOption)) {
42
- return keyOption(...args);
99
+ const customKey = keyOption(...args);
100
+ return userSuffix ? `${customKey}:${userSuffix}` : customKey;
43
101
  }
44
102
 
45
- // 문자열 키 + args suffix
46
- if (isStringValue(keyOption)) {
47
- const argsSuffix = serializeArgs(args);
48
- return argsSuffix ? `${keyOption}:${argsSuffix}` : keyOption;
49
- }
103
+ // Context 객체 자체는 키에서 빼고, 그 메서드는 Context 사용자 기준으로 키를 나눔
104
+ // (Context를 받는 메서드는 요청 사용자에 따라 결과가 달라질 수 있어 사용자 간 공유를 막음)
105
+ const contextSuffix = contextArg ? userSegment(contextArg) : userSuffix;
106
+ const keyArgs = args.filter((arg) => !isRuntimeContextArg(arg));
107
+
108
+ // 문자열 키 또는 자동 생성(ModelName.methodName) + args suffix
109
+ const baseKey = isStringValue(keyOption) ? keyOption : `${modelName}.${methodName}`;
110
+ const argsSuffix = serializeArgs(cacheName, keyArgs);
111
+ return [baseKey, contextSuffix, argsSuffix].filter((part) => part !== "").join(":");
112
+ }
50
113
 
51
- // 자동 생성: ModelName.methodName:serializedArgs
52
- const baseKey = `${modelName}.${methodName}`;
53
- const argsSuffix = serializeArgs(args);
54
- return argsSuffix ? `${baseKey}:${argsSuffix}` : baseKey;
114
+ /**
115
+ * JSON.stringify가 조용히 버리거나 뭉개는 값을 거부하는 replacer
116
+ */
117
+ function rejectUnserializable(cacheName: string) {
118
+ return <Value>(_key: string, value: Value): Value => {
119
+ if (isRuntimeContextArg(value)) {
120
+ throw new CacheKeySerializationError(cacheName, "인자 안에 Context 객체가 있어");
121
+ }
122
+ if (value instanceof Map || value instanceof Set) {
123
+ // JSON에서는 모두 {}가 되어 서로 다른 인자가 같은 키로 충돌함
124
+ throw new CacheKeySerializationError(cacheName, "Map/Set 인자는");
125
+ }
126
+ if (isFunctionValue(value) || isSymbolValue(value)) {
127
+ throw new CacheKeySerializationError(cacheName, "함수/심벌 인자는");
128
+ }
129
+ return value;
130
+ };
55
131
  }
56
132
 
57
133
  /**
58
134
  * 인자 직렬화
135
+ *
136
+ * 직렬화할 수 없는 인자(BigInt, 순환 참조, Map/Set, 함수 등)는 문자열로 뭉개지 않고
137
+ * CacheKeySerializationError를 던집니다.
59
138
  */
60
- function serializeArgs(args: unknown[]): string {
139
+ function serializeArgs(cacheName: string, args: unknown[]): string {
61
140
  if (args.length === 0) return "";
62
141
 
63
142
  // 단일 primitive 값
@@ -69,12 +148,17 @@ function serializeArgs(args: unknown[]): string {
69
148
  }
70
149
  }
71
150
 
151
+ if (args.some(isBigIntValue)) {
152
+ throw new CacheKeySerializationError(cacheName, "BigInt 인자는");
153
+ }
154
+
72
155
  // 복잡한 값은 JSON 직렬화
73
156
  try {
74
- return JSON.stringify(args);
75
- } catch {
76
- // 직렬화 실패 시 toString 사용
77
- return args.map((arg) => String(arg)).join(":");
157
+ return JSON.stringify(args, rejectUnserializable(cacheName));
158
+ } catch (error) {
159
+ if (error instanceof CacheKeySerializationError) throw error;
160
+ const reason = error instanceof Error ? error.message : String(error);
161
+ throw new CacheKeySerializationError(cacheName, `인자를 JSON으로 직렬화할 수 없어(${reason})`);
78
162
  }
79
163
  }
80
164
 
@@ -83,6 +167,12 @@ function serializeArgs(args: unknown[]): string {
83
167
  *
84
168
  * 메서드의 결과를 캐싱합니다.
85
169
  *
170
+ * - 자동 키·문자열 키에서 Context 인자는 키에서 빠지고, 대신 그 Context의 사용자(`user:<id>` 또는 `anon`)가 키에 들어갑니다.
171
+ * 함수 키는 Context 인자를 직접 다룹니다.
172
+ * - `scope: "user"`이면 요청 안에서 호출될 때 요청 사용자가 키에 들어갑니다. 기본값은 `"global"`입니다.
173
+ * - 직렬화할 수 없는 인자는 CacheKeySerializationError로 거부합니다.
174
+ * - 캐시 적중 시 메서드 본문을 실행하지 않으므로, 권한 검사는 캐시 밖(호출하는 메서드나 가드)에서 하세요.
175
+ *
86
176
  * @example
87
177
  * class UserModelClass extends BaseModelClass<...> {
88
178
  * @cache({ ttl: '10m', tags: ['user'] })
@@ -94,6 +184,8 @@ function serializeArgs(args: unknown[]): string {
94
184
  * }
95
185
  */
96
186
  export function cache(options: CacheDecoratorOptions = {}) {
187
+ const { key, scope, store: storeName, ...cacheOptions } = options;
188
+
97
189
  return (_target: DecoratorTarget, propertyKey: string, descriptor: PropertyDescriptor) => {
98
190
  const originalMethod = descriptor.value;
99
191
 
@@ -109,11 +201,14 @@ export function cache(options: CacheDecoratorOptions = {}) {
109
201
  const modelName = this instanceof BaseModelClass ? this.modelName : this.frameName;
110
202
  const methodName = propertyKey;
111
203
 
112
- const cacheKey = generateCacheKey(modelName, methodName, args, options.key);
113
- const store = options.store ? manager.use(options.store) : manager;
204
+ const cacheKey = generateCacheKey(`${modelName}.${methodName}`, modelName, methodName, args, {
205
+ key,
206
+ scope,
207
+ });
208
+ const store = storeName ? manager.use(storeName) : manager;
114
209
 
115
210
  return store.getOrSet({
116
- ...options,
211
+ ...cacheOptions,
117
212
  key: cacheKey,
118
213
  factory: () => originalMethod.apply(this, args),
119
214
  });
@@ -2,7 +2,12 @@
2
2
  export { createCacheManager, createTestCacheManager } from "./cache-manager";
3
3
 
4
4
  // Decorator
5
- export { cache, getCacheManagerRef, setCacheManagerRef } from "./decorator";
5
+ export {
6
+ cache,
7
+ CacheKeySerializationError,
8
+ getCacheManagerRef,
9
+ setCacheManagerRef,
10
+ } from "./decorator";
6
11
 
7
12
  // Drivers & Store builder
8
13
  export {
@@ -6,6 +6,13 @@ import { type RawCommonOptions } from "bentocache/types";
6
6
  */
7
7
  export type CacheConfig = ConstructorParameters<typeof BentoCache>[0];
8
8
 
9
+ /**
10
+ * @cache 키를 요청 사용자별로 나눌지 여부
11
+ * - "global": 인자가 같으면 모든 사용자가 같은 캐시를 공유 (기본값). 단, 자동 키·문자열 키의 Context 인자는 그 사용자로 구분
12
+ * - "user": Context 인자 또는 현재 요청(HTTP/WebSocket)의 사용자(`user:<id>` 또는 `anon`)를 키에 포함
13
+ */
14
+ export type CacheScope = "user" | "global";
15
+
9
16
  /**
10
17
  * @cache 데코레이터 옵션
11
18
  */
@@ -15,9 +22,20 @@ export type CacheDecoratorOptions = {
15
22
  * - 문자열: 고정 키 (args가 자동으로 suffix로 추가됨)
16
23
  * - 함수: 인자를 받아 키 생성
17
24
  * - 미지정: ModelName.methodName:serializedArgs 형태로 자동 생성
25
+ *
26
+ * Context 인자는 직렬화하지 않고, 그 Context의 사용자(`user:<id>` 또는 `anon`)로 바꿔 키에 넣습니다(함수 키 제외).
27
+ * 직렬화할 수 없는 인자(BigInt, 순환 참조, Map/Set, 함수 등)는 에러로 거부합니다.
18
28
  */
19
29
  key?: string | ((...args: unknown[]) => string);
20
30
 
31
+ /**
32
+ * 캐시 공유 범위 (기본값: "global")
33
+ *
34
+ * 메서드가 `Sonamu.getContext().user` 등 요청 사용자에 따라 다른 결과를 돌려준다면 "user"로 지정하세요.
35
+ * Context 인자 없이 요청 밖(테스트·스크립트·워크플로)에서 호출되면 키에 사용자 구분자가 붙지 않습니다.
36
+ */
37
+ scope?: CacheScope;
38
+
21
39
  /**
22
40
  * 사용할 스토어 이름
23
41
  * 미지정 시 default 스토어 사용
@@ -0,0 +1,238 @@
1
+ import { access } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { z } from "zod";
5
+
6
+ import { loadConfig } from "../api/config";
7
+ import { findApiRootPath } from "../utils/utils";
8
+ import { type SonamuCliPlugin } from "./plugin";
9
+
10
+ const CLI_WORD = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/;
11
+ const IDENTIFIER = /^[a-z][a-zA-Z0-9]*$/;
12
+
13
+ /** A plugin declaration that the CLI refuses, naming the plugin, the command path and the rule. */
14
+ export class SonamuCliPluginError extends Error {
15
+ readonly code = "INVALID_CLI_PLUGIN";
16
+
17
+ constructor(
18
+ readonly plugin: string,
19
+ readonly command: string | undefined,
20
+ readonly rule: string,
21
+ ) {
22
+ super(`CLI plugin "${plugin}"${command === undefined ? "" : ` command "${command}"`}: ${rule}`);
23
+ this.name = "SonamuCliPluginError";
24
+ }
25
+ }
26
+
27
+ const argumentSchema = z.object({
28
+ name: z.string().regex(IDENTIFIER, { error: "argument names must be camelCase identifiers" }),
29
+ description: z.string().optional(),
30
+ type: z
31
+ .enum(["string", "integer"], { error: "argument type must be string or integer" })
32
+ .optional(),
33
+ required: z.boolean().optional(),
34
+ variadic: z.boolean().optional(),
35
+ });
36
+
37
+ const optionSchema = z
38
+ .object({
39
+ type: z.enum(["string", "integer", "boolean"], {
40
+ error: "option type must be string, integer or boolean",
41
+ }),
42
+ description: z.string().optional(),
43
+ required: z.boolean().optional(),
44
+ multiple: z.boolean().optional(),
45
+ choices: z.array(z.string().min(1)).min(1, { error: "choices must not be empty" }).optional(),
46
+ })
47
+ .superRefine((option, context) => {
48
+ if (
49
+ option.type === "boolean" &&
50
+ (option.required !== undefined || option.multiple !== undefined)
51
+ ) {
52
+ context.addIssue({
53
+ code: "custom",
54
+ message: "required and multiple apply only to string and integer options",
55
+ });
56
+ }
57
+ if (option.type !== "string" && option.choices !== undefined) {
58
+ context.addIssue({ code: "custom", message: "choices apply only to string options" });
59
+ }
60
+ });
61
+
62
+ const argumentsSchema = z.array(argumentSchema).superRefine((declared, context) => {
63
+ const names = new Set<string>();
64
+ declared.forEach((argument, index) => {
65
+ if (names.has(argument.name)) {
66
+ context.addIssue({
67
+ code: "custom",
68
+ path: [index],
69
+ message: `argument "${argument.name}" is declared twice`,
70
+ });
71
+ }
72
+ names.add(argument.name);
73
+ if (argument.variadic === true && index < declared.length - 1) {
74
+ context.addIssue({
75
+ code: "custom",
76
+ path: [index],
77
+ message: "only the last argument may be variadic",
78
+ });
79
+ }
80
+ const followsOptional = declared
81
+ .slice(0, index)
82
+ .some((previous) => previous.required === false);
83
+ if (argument.required !== false && followsOptional) {
84
+ context.addIssue({
85
+ code: "custom",
86
+ path: [index],
87
+ message: "required arguments must come before optional ones",
88
+ });
89
+ }
90
+ });
91
+ });
92
+
93
+ const optionsSchema = z.record(z.string(), optionSchema).superRefine((declared, context) => {
94
+ for (const key of Object.keys(declared)) {
95
+ const flag = key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
96
+ if (!IDENTIFIER.test(key) || !CLI_WORD.test(flag)) {
97
+ context.addIssue({
98
+ code: "custom",
99
+ path: [key],
100
+ message: `option key "${key}" must be a camelCase identifier`,
101
+ });
102
+ }
103
+ }
104
+ });
105
+
106
+ const commandSchema = z.object({
107
+ path: z
108
+ .array(z.string().regex(CLI_WORD, { error: "path words must be lowercase CLI words" }))
109
+ .min(1, { error: "path must have at least one word" }),
110
+ description: z.string().optional(),
111
+ arguments: argumentsSchema.optional(),
112
+ options: optionsSchema.optional(),
113
+ mutation: z.object({ dryRun: z.boolean() }).optional(),
114
+ run: z.instanceof(Function, { error: "run must be a function" }),
115
+ });
116
+
117
+ const pluginSchema = z.object({
118
+ name: z.string().trim().min(1, { error: "plugin name must not be empty" }),
119
+ commands: z.array(commandSchema),
120
+ });
121
+
122
+ const cliConfigSchema = z.object({ plugins: z.array(z.unknown()).optional() }).optional();
123
+
124
+ // Lenient view of a rejected plugin, used only to name it and its command in the error.
125
+ const pluginLabelSchema = z.object({
126
+ name: z.string().min(1).optional().catch(undefined),
127
+ commands: z
128
+ .array(z.object({ path: z.array(z.string()).min(1).optional().catch(undefined) }).catch({}))
129
+ .catch([]),
130
+ });
131
+ type PluginLabels = z.infer<typeof pluginLabelSchema>;
132
+
133
+ function commandLabel(labels: PluginLabels, issuePath: readonly PropertyKey[]): string | undefined {
134
+ const commandIndex = z.number().int().safeParse(issuePath[1]);
135
+ if (issuePath[0] !== "commands" || !commandIndex.success) return undefined;
136
+ const path = labels.commands[commandIndex.data]?.path;
137
+ return path === undefined ? `commands[${commandIndex.data}]` : path.join(" ");
138
+ }
139
+
140
+ function issueRule(issue: z.core.$ZodIssue): string {
141
+ const location = issue.path.slice(2).map(String).join(".");
142
+ return location === "" || issue.path[0] !== "commands"
143
+ ? issue.message
144
+ : `${issue.message} (at ${location})`;
145
+ }
146
+
147
+ /** Validates the declarative part of `cli.plugins`; command paths must be unique and prefix-free. */
148
+ export function validateCliPlugins(plugins: readonly unknown[]): readonly SonamuCliPlugin[] {
149
+ const declared: { plugin: string; path: readonly string[] }[] = [];
150
+ plugins.forEach((plugin, index) => {
151
+ const parsed = pluginSchema.safeParse(plugin);
152
+ if (!parsed.success) {
153
+ const [issue] = parsed.error.issues;
154
+ const labels = pluginLabelSchema.catch({ commands: [] }).parse(plugin);
155
+ throw new SonamuCliPluginError(
156
+ labels.name ?? `cli.plugins[${index}]`,
157
+ commandLabel(labels, issue.path),
158
+ issueRule(issue),
159
+ );
160
+ }
161
+ for (const command of parsed.data.commands) {
162
+ const words = command.path.join(" ");
163
+ for (const other of declared) {
164
+ const otherWords = other.path.join(" ");
165
+ const shorter = Math.min(other.path.length, command.path.length);
166
+ if (other.path.slice(0, shorter).join(" ") !== command.path.slice(0, shorter).join(" ")) {
167
+ continue;
168
+ }
169
+ const rule =
170
+ otherWords === words
171
+ ? `path is already declared by plugin "${other.plugin}"`
172
+ : `path overlaps "${otherWords}" declared by plugin "${other.plugin}"; a command path must not be a prefix of another`;
173
+ throw new SonamuCliPluginError(parsed.data.name, words, rule);
174
+ }
175
+ declared.push({ plugin: parsed.data.name, path: command.path });
176
+ }
177
+ });
178
+ // SAFETY: every element passed pluginSchema above; the original objects are returned so that `run` keeps its identity.
179
+ return plugins as readonly SonamuCliPlugin[];
180
+ }
181
+
182
+ async function fileExists(filePath: string): Promise<boolean> {
183
+ try {
184
+ await access(filePath);
185
+ return true;
186
+ } catch {
187
+ return false;
188
+ }
189
+ }
190
+
191
+ function restoreProcessEnv(snapshot: NodeJS.ProcessEnv): void {
192
+ for (const key of Object.keys(process.env)) {
193
+ if (!Object.hasOwn(snapshot, key)) delete process.env[key];
194
+ }
195
+ for (const [key, value] of Object.entries(snapshot)) {
196
+ if (value !== undefined) process.env[key] = value;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Returns the validated CLI plugins of the project without initialising Sonamu.
202
+ * A directory without any sonamu.config has no plugins; a project whose config is not built fails.
203
+ */
204
+ export async function loadCliPlugins(
205
+ apiRootPath: string = findApiRootPath(),
206
+ ): Promise<readonly SonamuCliPlugin[]> {
207
+ const builtConfigPath = path.join(apiRootPath, "dist", "sonamu.config.js");
208
+ const [hasBuiltConfig, hasSourceConfig] = await Promise.all([
209
+ fileExists(builtConfigPath),
210
+ fileExists(path.join(apiRootPath, "src", "sonamu.config.ts")),
211
+ ]);
212
+ if (!hasBuiltConfig && !hasSourceConfig) return [];
213
+
214
+ // Sonamu.init snapshots process.env before its own loadConfig and derives every environment's
215
+ // DB settings from it, so the dotenv values applied here must not outlive this load.
216
+ const envBeforeLoad = { ...process.env };
217
+ let config: Awaited<ReturnType<typeof loadConfig>>;
218
+ try {
219
+ config = await loadConfig(apiRootPath);
220
+ } catch (error) {
221
+ const moduleNotFound = z.object({ code: z.literal("ERR_MODULE_NOT_FOUND") }).safeParse(error);
222
+ if (!hasBuiltConfig && moduleNotFound.success) {
223
+ throw Object.assign(
224
+ new Error(`${builtConfigPath} not found. Build the project first (sonamu build).`),
225
+ { code: "CONFIG_NOT_BUILT", cause: error },
226
+ );
227
+ }
228
+ throw error;
229
+ } finally {
230
+ restoreProcessEnv(envBeforeLoad);
231
+ }
232
+
233
+ const cli = cliConfigSchema.safeParse(config.cli);
234
+ if (!cli.success) {
235
+ throw new SonamuCliPluginError("cli.plugins", undefined, "cli.plugins must be an array");
236
+ }
237
+ return validateCliPlugins(cli.data?.plugins ?? []);
238
+ }