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
@@ -4,8 +4,9 @@
4
4
  <meta charset="UTF-8" />
5
5
  <link rel="icon" type="image/svg+xml" href="/sonamu-ui/setting.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <meta name="sonamu-ui-token" content="{{sonamuUIToken}}" />
7
8
  <title>{{projectName}}: Sonamu UI</title>
8
- <script type="module" crossorigin src="/sonamu-ui/assets/index-QDMyy31K.js"></script>
9
+ <script type="module" crossorigin src="/sonamu-ui/assets/index-BPqP-tug.js"></script>
9
10
  <link rel="stylesheet" crossorigin href="/sonamu-ui/assets/index-dV7akMFB.css">
10
11
  </head>
11
12
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sonamu",
3
- "version": "0.13.10",
3
+ "version": "0.14.0",
4
4
  "description": "Sonamu — TypeScript Fullstack API Framework",
5
5
  "keywords": [
6
6
  "framework",
@@ -2,9 +2,16 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
 
5
- import { afterEach, describe, expect, it } from "vitest";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
6
 
7
- import { readAllEnvironmentSnapshots, readEnvironmentSnapshot } from "../env";
7
+ import {
8
+ applyCurrentSnapshotToProcessEnv,
9
+ ensureServerEnvironment,
10
+ ensureSonamuEnvironment,
11
+ readAllEnvironmentSnapshots,
12
+ readEnvironmentSnapshot,
13
+ resolveSonamuEnvironment,
14
+ } from "../env";
8
15
 
9
16
  describe("readAllEnvironmentSnapshots", () => {
10
17
  const tempRoots: string[] = [];
@@ -125,3 +132,115 @@ describe("readAllEnvironmentSnapshots", () => {
125
132
  expect(snapshot.NODE_ENV).toBe("production");
126
133
  });
127
134
  });
135
+
136
+ describe("서버/빌드 환경 판정", () => {
137
+ const tempRoots: string[] = [];
138
+
139
+ afterEach(async () => {
140
+ await Promise.all(
141
+ tempRoots.splice(0).map((rootPath) => rm(rootPath, { recursive: true, force: true })),
142
+ );
143
+ });
144
+
145
+ async function createRoot(files: Record<string, string> = {}): Promise<string> {
146
+ const rootPath = await mkdtemp(path.join(os.tmpdir(), "sonamu-env-resolve-"));
147
+ tempRoots.push(rootPath);
148
+ await Promise.all(
149
+ Object.entries(files).map(([name, content]) => writeFile(path.join(rootPath, name), content)),
150
+ );
151
+ return rootPath;
152
+ }
153
+
154
+ it.each([undefined, ""])(
155
+ "NODE_ENV가 %j이고 dotenv에도 없으면 fallback을 쓴다",
156
+ async (nodeEnv) => {
157
+ const rootPath = await createRoot();
158
+
159
+ expect(resolveSonamuEnvironment(rootPath, "production", { NODE_ENV: nodeEnv })).toBe(
160
+ "production",
161
+ );
162
+ },
163
+ );
164
+
165
+ it("런타임 NODE_ENV가 dotenv와 fallback보다 우선한다", async () => {
166
+ const rootPath = await createRoot({ ".env": "NODE_ENV=production\n" });
167
+
168
+ expect(resolveSonamuEnvironment(rootPath, "production", { NODE_ENV: "staging" })).toBe(
169
+ "staging",
170
+ );
171
+ });
172
+
173
+ it("런타임 NODE_ENV가 없으면 .env의 NODE_ENV로 판정한다", async () => {
174
+ const rootPath = await createRoot({ ".env": "NODE_ENV=production\n" });
175
+
176
+ expect(resolveSonamuEnvironment(rootPath, "development", {})).toBe("production");
177
+ });
178
+
179
+ it(".env.local의 NODE_ENV가 .env보다 우선한다", async () => {
180
+ const rootPath = await createRoot({
181
+ ".env": "NODE_ENV=production\n",
182
+ ".env.local": "NODE_ENV=staging\n",
183
+ });
184
+
185
+ expect(resolveSonamuEnvironment(rootPath, "development", {})).toBe("staging");
186
+ });
187
+
188
+ it("dotenv의 지원하지 않는 NODE_ENV를 거부한다", async () => {
189
+ const rootPath = await createRoot({ ".env": "NODE_ENV=preview\n" });
190
+
191
+ expect(() => resolveSonamuEnvironment(rootPath, "production", {})).toThrow(
192
+ 'Invalid NODE_ENV "preview"',
193
+ );
194
+ });
195
+
196
+ it("ensureSonamuEnvironment는 판정한 환경을 env.NODE_ENV에 기록한다", async () => {
197
+ const rootPath = await createRoot();
198
+ const env: NodeJS.ProcessEnv = {};
199
+
200
+ expect(ensureSonamuEnvironment(rootPath, "production", env)).toBe("production");
201
+ expect(env.NODE_ENV).toBe("production");
202
+ });
203
+
204
+ it("빌드 산출물 서버는 NODE_ENV가 없으면 production으로 판정한다", async () => {
205
+ const rootPath = await createRoot();
206
+ const env: NodeJS.ProcessEnv = {};
207
+
208
+ expect(ensureServerEnvironment(rootPath, env)).toBe("production");
209
+ expect(env.NODE_ENV).toBe("production");
210
+ });
211
+
212
+ it.each([{ HOT: "yes" }, { VITEST: "true" }])(
213
+ "소스 실행(%j) 서버는 NODE_ENV가 없으면 development로 판정한다",
214
+ async (runtimeEnv) => {
215
+ const rootPath = await createRoot();
216
+ const env: NodeJS.ProcessEnv = { ...runtimeEnv };
217
+
218
+ expect(ensureServerEnvironment(rootPath, env)).toBe("development");
219
+ },
220
+ );
221
+
222
+ it("빌드 산출물 서버도 명시한 NODE_ENV는 그대로 쓴다", async () => {
223
+ const rootPath = await createRoot();
224
+
225
+ expect(ensureServerEnvironment(rootPath, { NODE_ENV: "development" })).toBe("development");
226
+ });
227
+
228
+ it("applyCurrentSnapshotToProcessEnv는 .env의 NODE_ENV로 환경을 고른다", async () => {
229
+ const rootPath = await createRoot({
230
+ ".env": "NODE_ENV=production\n",
231
+ ".env.production": "SONAMU_ENV_RESOLVE_PROBE=production\n",
232
+ ".env.development": "SONAMU_ENV_RESOLVE_PROBE=development\n",
233
+ });
234
+ vi.stubEnv("NODE_ENV", "");
235
+ vi.stubEnv("SONAMU_ENV_RESOLVE_PROBE", undefined);
236
+
237
+ try {
238
+ const snapshot = applyCurrentSnapshotToProcessEnv(rootPath);
239
+
240
+ expect(snapshot.SONAMU_ENV_RESOLVE_PROBE).toBe("production");
241
+ expect(process.env.NODE_ENV).toBe("production");
242
+ } finally {
243
+ vi.unstubAllEnvs();
244
+ }
245
+ });
246
+ });
@@ -0,0 +1,97 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { jit } from "zod-compiler/jit";
3
+
4
+ import { type ApiParam } from "../../types/types";
5
+ import { fastifyCaster } from "../caster";
6
+ import { getZodObjectFromApiParams } from "../code-converters";
7
+
8
+ // 감사 PoC(SON-634)의 probeUnion/probeLit 시그니처를 그대로 옮긴 파라미터 정의
9
+ const probeUnionParams: ApiParam[] = [
10
+ {
11
+ name: "order",
12
+ type: {
13
+ t: "union",
14
+ types: [
15
+ { t: "string-literal", value: "asc" },
16
+ { t: "string-literal", value: "desc" },
17
+ "null",
18
+ ],
19
+ },
20
+ optional: false,
21
+ },
22
+ { name: "name", type: { t: "union", types: ["string", "undefined"] }, optional: false },
23
+ ];
24
+
25
+ const probeLitParams: ApiParam[] = [
26
+ { name: "flag", type: "true", optional: false },
27
+ { name: "v", type: { t: "union", types: ["number", "string", "null"] }, optional: false },
28
+ ];
29
+
30
+ async function createValidators(params: ApiParam[]) {
31
+ // 명명 타입이 없는 파라미터이므로 빈 references를 명시합니다 (SON-633에서 references가 필수가 됨).
32
+ const plain = fastifyCaster(getZodObjectFromApiParams(params, {}));
33
+ const compiled = await jit(fastifyCaster(getZodObjectFromApiParams(params, {})), { eager: true });
34
+ return [
35
+ ["plain", plain],
36
+ ["jit", compiled],
37
+ ] as const;
38
+ }
39
+
40
+ describe("null·undefined·true·false가 섞인 union 파라미터 검증 (SON-634)", () => {
41
+ it("'asc' | 'desc' | null 파라미터는 객체와 union 밖 문자열을 거부한다", async () => {
42
+ for (const [mode, validator] of await createValidators(probeUnionParams)) {
43
+ expect(validator.safeParse({ order: { x: 1 }, name: "a" }).success, mode).toBe(false);
44
+ expect(
45
+ validator.safeParse({
46
+ order: { _type: "sql_expression", _sql: "1", _params: [] },
47
+ name: "a",
48
+ }).success,
49
+ mode,
50
+ ).toBe(false);
51
+ expect(validator.safeParse({ order: "zzz-not-in-union", name: "a" }).success, mode).toBe(
52
+ false,
53
+ );
54
+ expect(validator.safeParse({ order: "asc", name: "a" }).success, mode).toBe(true);
55
+ expect(validator.safeParse({ order: null, name: "a" }).success, mode).toBe(true);
56
+ }
57
+ });
58
+
59
+ it("string | undefined 파라미터는 문자열만 받고 키 누락을 허용한다", async () => {
60
+ for (const [mode, validator] of await createValidators(probeUnionParams)) {
61
+ expect(validator.safeParse({ order: "desc", name: ["a"] }).success, mode).toBe(false);
62
+ expect(validator.safeParse({ order: "desc", name: 12345 }).success, mode).toBe(false);
63
+ expect(validator.safeParse({ order: "desc", name: null }).success, mode).toBe(false);
64
+ expect(validator.safeParse({ order: "desc" }).success, mode).toBe(true);
65
+ }
66
+ });
67
+
68
+ it("true 리터럴 파라미터는 true만 받는다", async () => {
69
+ for (const [mode, validator] of await createValidators(probeLitParams)) {
70
+ expect(validator.safeParse({ flag: "anything", v: 1 }).success, mode).toBe(false);
71
+ expect(validator.safeParse({ flag: false, v: 1 }).success, mode).toBe(false);
72
+ expect(validator.safeParse({ flag: { x: 1 }, v: 1 }).success, mode).toBe(false);
73
+ expect(validator.safeParse({ flag: true, v: 1 }).success, mode).toBe(true);
74
+ }
75
+ });
76
+
77
+ it("number | string | null 파라미터는 배열과 객체를 거부한다", async () => {
78
+ for (const [mode, validator] of await createValidators(probeLitParams)) {
79
+ expect(validator.safeParse({ flag: true, v: [{ evil: true }] }).success, mode).toBe(false);
80
+ expect(validator.safeParse({ flag: true, v: { evil: true } }).success, mode).toBe(false);
81
+ expect(validator.safeParse({ flag: true, v: "1" }).success, mode).toBe(true);
82
+ expect(validator.safeParse({ flag: true, v: null }).success, mode).toBe(true);
83
+ }
84
+ });
85
+
86
+ it("GET 쿼리 문자열 'true'/'false'를 boolean 리터럴로 변환한다", async () => {
87
+ const params: ApiParam[] = [
88
+ { name: "on", type: "true", optional: false },
89
+ { name: "off", type: "false", optional: true },
90
+ ];
91
+ for (const [mode, validator] of await createValidators(params)) {
92
+ expect(validator.parse({ on: "true", off: "false" }), mode).toEqual({ on: true, off: false });
93
+ expect(validator.safeParse({ on: "false" }).success, mode).toBe(false);
94
+ expect(validator.safeParse({ on: "true", off: "true" }).success, mode).toBe(false);
95
+ }
96
+ });
97
+ });
@@ -0,0 +1,233 @@
1
+ import fastify, { type FastifyInstance } from "fastify";
2
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { z } from "zod";
4
+
5
+ import { setSDConfig } from "../../dict/sd";
6
+ import { UnauthorizedException } from "../../exceptions/so-exceptions";
7
+ import { type SonamuFastifyConfig } from "../../types/types";
8
+ import { type Context } from "../context";
9
+ import { type ExtendedApi, type GuardKey } from "../decorators";
10
+ import {
11
+ checkGuardKeys,
12
+ findApisWithUnhandledGuardKeys,
13
+ findUnguardedMutationApis,
14
+ warnUnguardedMutationApis,
15
+ } from "../guards";
16
+ import { Sonamu } from "../sonamu";
17
+
18
+ function makeApi(
19
+ methodName: string,
20
+ options: ExtendedApi["options"],
21
+ extra: Partial<ExtendedApi> = {},
22
+ ): ExtendedApi {
23
+ return {
24
+ modelName: "TagModel",
25
+ methodName,
26
+ path: `/tag/${methodName}`,
27
+ options,
28
+ typeParameters: [],
29
+ parameters: [],
30
+ returnType: "void",
31
+ ...extra,
32
+ };
33
+ }
34
+
35
+ describe("findUnguardedMutationApis", () => {
36
+ it("guards가 없는 POST API를 상태 변경 무가드 API로 보고한다", () => {
37
+ const save = makeApi("save", { httpMethod: "POST" });
38
+ expect(findUnguardedMutationApis([save])).toEqual([save]);
39
+ });
40
+
41
+ it("PUT·PATCH·DELETE도 대상이며 메서드 대소문자를 구분하지 않는다", () => {
42
+ const apis = [
43
+ makeApi("put", { httpMethod: "PUT" }),
44
+ makeApi("patch", { httpMethod: "PATCH" }),
45
+ makeApi("remove", { httpMethod: "DELETE" }),
46
+ makeApi("lower", { httpMethod: "post" }),
47
+ ];
48
+ expect(findUnguardedMutationApis(apis)).toEqual(apis);
49
+ });
50
+
51
+ it("guards를 지정했거나 guards: []로 공개를 명시한 API는 제외한다", () => {
52
+ const apis = [
53
+ makeApi("del", { httpMethod: "POST", guards: ["admin"] }),
54
+ makeApi("publicSave", { httpMethod: "POST", guards: [] }),
55
+ ];
56
+ expect(findUnguardedMutationApis(apis)).toEqual([]);
57
+ });
58
+
59
+ it("GET·HEAD·OPTIONS와 httpMethod 미지정(GET) API는 제외한다", () => {
60
+ const apis = [
61
+ makeApi("findMany", { httpMethod: "GET" }),
62
+ makeApi("head", { httpMethod: "HEAD" }),
63
+ makeApi("options", { httpMethod: "OPTIONS" }),
64
+ makeApi("defaultMethod", {}),
65
+ ];
66
+ expect(findUnguardedMutationApis(apis)).toEqual([]);
67
+ });
68
+
69
+ it("WebSocket API는 GET 업그레이드라 제외하고, @upload의 POST는 포함한다", () => {
70
+ const ws = makeApi(
71
+ "chat",
72
+ { httpMethod: "POST" },
73
+ {
74
+ websocketOptions: { outEvents: z.object({}), inEvents: z.object({}) },
75
+ },
76
+ );
77
+ const upload = makeApi(
78
+ "upload",
79
+ { httpMethod: "POST", clients: ["axios-multipart"] },
80
+ { uploadOptions: {} },
81
+ );
82
+ expect(findUnguardedMutationApis([ws, upload])).toEqual([upload]);
83
+ });
84
+ });
85
+
86
+ describe("warnUnguardedMutationApis", () => {
87
+ it("무가드 상태 변경 API가 있으면 메서드·경로·모델 메서드를 담아 한 번 경고한다", () => {
88
+ const messages: string[] = [];
89
+ const result = warnUnguardedMutationApis(
90
+ [makeApi("save", { httpMethod: "POST" }), makeApi("findMany", {})],
91
+ (message) => messages.push(message),
92
+ );
93
+
94
+ expect(result.map((api) => api.methodName)).toEqual(["save"]);
95
+ expect(messages).toHaveLength(1);
96
+ expect(messages[0]).toContain("POST /tag/save (TagModel.save)");
97
+ expect(messages[0]).toContain("guards: []");
98
+ expect(messages[0]).not.toContain("findMany");
99
+ });
100
+
101
+ it("대상이 없으면 경고하지 않는다", () => {
102
+ const messages: string[] = [];
103
+ warnUnguardedMutationApis([makeApi("del", { httpMethod: "POST", guards: ["admin"] })], (m) =>
104
+ messages.push(m),
105
+ );
106
+ expect(messages).toEqual([]);
107
+ });
108
+ });
109
+
110
+ describe("checkGuardKeys", () => {
111
+ it("guardKeys를 설정하면 목록 밖 가드 키를 쓰는 API를 나열하며 부팅을 중단한다", () => {
112
+ const apis = [
113
+ makeApi("save", { httpMethod: "POST", guards: ["user"] }),
114
+ makeApi("del", { httpMethod: "POST", guards: ["user", "admin"] }),
115
+ ];
116
+ expect(findApisWithUnhandledGuardKeys(apis, ["user"])).toEqual([
117
+ { api: apis[1], keys: ["admin"] },
118
+ ]);
119
+ expect(() => checkGuardKeys(apis, ["user"], () => {})).toThrow(
120
+ "/tag/del (TagModel.del): admin",
121
+ );
122
+ });
123
+
124
+ it("guardKeys가 모든 사용 키를 포함하면 경고 없이 통과한다", () => {
125
+ const messages: string[] = [];
126
+ checkGuardKeys(
127
+ [makeApi("del", { httpMethod: "POST", guards: ["admin"] })],
128
+ ["user", "admin"],
129
+ (m) => messages.push(m),
130
+ );
131
+ expect(messages).toEqual([]);
132
+ });
133
+
134
+ it("guardKeys가 없으면 가드를 쓰는 API가 있을 때만 경고하고 기존 동작을 유지한다", () => {
135
+ const messages: string[] = [];
136
+ checkGuardKeys([makeApi("del", { httpMethod: "POST", guards: ["admin"] })], undefined, (m) =>
137
+ messages.push(m),
138
+ );
139
+ expect(messages).toHaveLength(1);
140
+ expect(messages[0]).toContain("guardKeys is not configured");
141
+
142
+ const silent: string[] = [];
143
+ checkGuardKeys([makeApi("publicSave", { httpMethod: "POST", guards: [] })], undefined, (m) =>
144
+ silent.push(m),
145
+ );
146
+ expect(silent).toEqual([]);
147
+ });
148
+ });
149
+
150
+ describe("REST 핸들러의 가드 키 처리", () => {
151
+ const originalState = Sonamu.captureTestingSnapshot();
152
+ let app: FastifyInstance | undefined;
153
+
154
+ // Fastify inject는 첫 호출에서만 내부 모듈을 로드하므로,
155
+ // 그 비용이 첫 테스트의 시간 제한에 잡히지 않도록 미리 한 번 실행해 둔다
156
+ beforeAll(async () => {
157
+ const warmup = fastify();
158
+ await warmup.inject({ method: "GET", url: "/" });
159
+ await warmup.close();
160
+ });
161
+
162
+ beforeEach(() => {
163
+ Reflect.set(Sonamu, "httpValidators", new WeakMap());
164
+ Reflect.set(Sonamu, "pendingHttpValidators", new WeakMap());
165
+ Reflect.set(Sonamu, "aotHttpValidatorRegistry", undefined);
166
+ Reflect.set(Sonamu, "preparedApis", []);
167
+ Reflect.set(Sonamu, "configValue", {
168
+ sync: { targets: [] },
169
+ validation: { zodCompiler: false },
170
+ // 실제 createContext가 locale을 정하는 데 사용한다
171
+ i18n: { defaultLocale: "ko", supportedLocales: ["ko"] },
172
+ });
173
+ Reflect.set(Sonamu, "syncerValue", { types: {} });
174
+ vi.spyOn(Sonamu, "invokeModelMethod").mockResolvedValue("ok");
175
+ // 거부 메시지는 SD로 만들므로 i18n 설정이 필요하다
176
+ setSDConfig({ defaultLocale: "ko", supportedLocales: ["ko"] });
177
+ });
178
+
179
+ afterEach(async () => {
180
+ await app?.close();
181
+ app = undefined;
182
+ Sonamu.restoreTestingSnapshot(originalState);
183
+ vi.restoreAllMocks();
184
+ });
185
+
186
+ async function callWithGuards(
187
+ guards: GuardKey[],
188
+ guardKeys: readonly GuardKey[] | undefined,
189
+ ): Promise<{ result: Promise<unknown>; guardHandler: ReturnType<typeof vi.fn> }> {
190
+ const guardHandler = vi.fn();
191
+ const config: SonamuFastifyConfig = {
192
+ contextProvider: (defaultContext: Context) => defaultContext,
193
+ guardHandler,
194
+ guardKeys,
195
+ };
196
+ const api = makeApi("del", { httpMethod: "GET", guards });
197
+ const handler = Sonamu.createApiHandler(api, config);
198
+
199
+ // 실제 Fastify 요청·응답으로 핸들러를 호출하고, 핸들러가 돌려준 Promise를 그대로 검증한다
200
+ const results: Promise<unknown>[] = [];
201
+ app = fastify();
202
+ app.get(api.path, (request, reply) => {
203
+ const result = handler(request, reply);
204
+ results.push(result);
205
+ return result;
206
+ });
207
+ await app.inject({ method: "GET", url: api.path });
208
+ const [result] = results;
209
+ if (result === undefined) {
210
+ throw new Error("핸들러가 호출되지 않았습니다.");
211
+ }
212
+ return { result, guardHandler };
213
+ }
214
+
215
+ it("guardKeys 밖의 키는 guardHandler를 부르지 않고 401로 거부한다", async () => {
216
+ const { result, guardHandler } = await callWithGuards(["admin"], ["user"]);
217
+ await expect(result).rejects.toBeInstanceOf(UnauthorizedException);
218
+ expect(guardHandler).not.toHaveBeenCalled();
219
+ expect(Sonamu.invokeModelMethod).not.toHaveBeenCalled();
220
+ });
221
+
222
+ it("guardKeys 안의 키는 guardHandler에 위임한다", async () => {
223
+ const { result, guardHandler } = await callWithGuards(["user"], ["user"]);
224
+ await expect(result).resolves.toBe("ok");
225
+ expect(guardHandler).toHaveBeenCalledWith("user", expect.anything(), expect.anything());
226
+ });
227
+
228
+ it("guardKeys가 없으면 모든 키를 guardHandler에 위임하는 기존 동작을 유지한다", async () => {
229
+ const { result, guardHandler } = await callWithGuards(["admin"], undefined);
230
+ await expect(result).resolves.toBe("ok");
231
+ expect(guardHandler).toHaveBeenCalledWith("admin", expect.anything(), expect.anything());
232
+ });
233
+ });
@@ -0,0 +1,77 @@
1
+ import fastify, { type FastifyInstance } from "fastify";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ import { type SonamuFastifyConfig } from "../../types/types";
5
+ import { Sonamu } from "../sonamu";
6
+
7
+ const MIOMOCK_FALLBACK = "miomock-secret-key-change-this-in-production";
8
+
9
+ // secret 검사는 apiConfig를 쓰기 전에 실패해야 하므로, 핸들러가 불리면 곧바로 테스트를 실패시킨다.
10
+ const apiConfig: SonamuFastifyConfig = {
11
+ contextProvider() {
12
+ throw new Error("secret 검사 전에 contextProvider가 호출되면 안 된다");
13
+ },
14
+ guardHandler() {
15
+ throw new Error("secret 검사 전에 guardHandler가 호출되면 안 된다");
16
+ },
17
+ };
18
+
19
+ function setAuthConfig(auth: { secret?: string }): void {
20
+ Reflect.set(Sonamu, "configValue", {
21
+ sync: { targets: [] },
22
+ api: { route: { prefix: "/api" } },
23
+ server: { listen: { port: 0, host: "127.0.0.1" }, auth },
24
+ validation: { zodCompiler: false },
25
+ });
26
+ }
27
+
28
+ describe("Sonamu 서버 기동 시 better-auth secret 검사 (SON-600)", () => {
29
+ const originalState = Sonamu.captureTestingSnapshot();
30
+ const originalInitialized = Sonamu.isInitialized;
31
+ const servers: FastifyInstance[] = [];
32
+
33
+ beforeEach(() => {
34
+ Sonamu.isInitialized = true;
35
+ vi.stubEnv("BETTER_AUTH_SECRET", "");
36
+ vi.stubEnv("BETTER_AUTH_SECRETS", "");
37
+ vi.stubEnv("AUTH_SECRET", "");
38
+ });
39
+
40
+ afterEach(async () => {
41
+ await Promise.all(servers.splice(0).map(async (server) => await server.close()));
42
+ Sonamu.restoreTestingSnapshot(originalState);
43
+ Sonamu.isInitialized = originalInitialized;
44
+ vi.unstubAllEnvs();
45
+ });
46
+
47
+ it.each(["development", "staging", "production"])(
48
+ "%s에서 secret 없이 createServer를 부르면 listen 전에 실패한다",
49
+ async (environment) => {
50
+ vi.stubEnv("NODE_ENV", environment);
51
+ setAuthConfig({});
52
+
53
+ await expect(Sonamu.createServer({ doSilent: true })).rejects.toThrow(/secret is missing/);
54
+ },
55
+ );
56
+
57
+ it("공개된 예시 fallback secret으로 createServer를 부르면 실패한다", async () => {
58
+ vi.stubEnv("NODE_ENV", "production");
59
+ setAuthConfig({ secret: MIOMOCK_FALLBACK });
60
+
61
+ await expect(Sonamu.createServer({ doSilent: true })).rejects.toThrow(/publicly known/);
62
+ });
63
+
64
+ it("기존 fastify에 붙이는 withFastify도 secret이 없으면 실패한다", async () => {
65
+ vi.stubEnv("NODE_ENV", "development");
66
+ setAuthConfig({});
67
+ const server = fastify();
68
+ servers.push(server);
69
+
70
+ await expect(Sonamu.withFastify(server, apiConfig, { doSilent: true })).rejects.toThrow(
71
+ /secret is missing/,
72
+ );
73
+ // 검사가 서버를 Sonamu에 연결하거나 라우트를 등록하기 전에 실패해야 한다.
74
+ expect(Sonamu.server).not.toBe(server);
75
+ expect(server.hasRoute({ method: "GET", url: "/api/auth/*" })).toBe(false);
76
+ });
77
+ });