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
package/src/api/sonamu.ts CHANGED
@@ -15,11 +15,12 @@ import {
15
15
  type FastifyReply,
16
16
  type FastifyRequest,
17
17
  } from "fastify";
18
- import mime, { lookup as mimeLookup } from "mime-types";
18
+ import { lookup as mimeLookup } from "mime-types";
19
19
  import { type WebSocket } from "ws";
20
- import { type ZodObject } from "zod";
20
+ import { type ZodError, type ZodObject } from "zod";
21
21
 
22
- import { BASE_FIELD_MAPPINGS } from "../auth/better-auth-entities";
22
+ import { type AuthBaseURLResolution } from "../auth/base-url";
23
+ import { buildBetterAuthOptions } from "../auth/better-auth-options";
23
24
  import { createBetterAuthRequest } from "../auth/better-auth-request";
24
25
  import { applyCacheHeaders, CachePresets } from "../cache-control/cache-control";
25
26
  import { type CacheControlConfig, type CacheControlRequest } from "../cache-control/types";
@@ -30,12 +31,13 @@ import { DB } from "../database/db";
30
31
  import { type SonamuDBConfig } from "../database/db";
31
32
  import { SD, setSDConfig } from "../dict/sd";
32
33
  import { type LocalizedString } from "../dict/types";
33
- import { getSonamuEnvironment, readAllEnvironmentSnapshots } from "../env";
34
- import { NotFoundException } from "../exceptions/so-exceptions";
34
+ import { ensureServerEnvironment, getSonamuEnvironment, readAllEnvironmentSnapshots } from "../env";
35
+ import { NotFoundException, UnauthorizedException } from "../exceptions/so-exceptions";
35
36
  import { runtimeTypeOf } from "../runtime-type";
36
37
  import { BufferedFile } from "../storage/buffered-file";
37
38
  import { type StorageManager } from "../storage/storage-manager";
38
39
  import { type KeyGenerator } from "../storage/types";
40
+ import { resolveUploadContentType, resolveUploadExtension } from "../storage/upload-safety";
39
41
  import { UploadedFile } from "../storage/uploaded-file";
40
42
  import { createMockSSEFactory } from "../stream/sse";
41
43
  import {
@@ -64,7 +66,7 @@ import {
64
66
  isStringValue,
65
67
  isSymbolValue,
66
68
  } from "../utils/runtime-value";
67
- import { convertFastifyHeadersToStandard, merge } from "../utils/utils";
69
+ import { convertFastifyHeadersToStandard } from "../utils/utils";
68
70
  import {
69
71
  normalizeZodCompilerPolicy,
70
72
  type SonamuConfig,
@@ -72,11 +74,13 @@ import {
72
74
  type SonamuTaskOptions,
73
75
  } from "./config";
74
76
  import { type Context, type RuntimeContext, type WebSocketContext } from "./context";
75
- import { type ExtendedApi } from "./decorators";
77
+ import { type ExtendedApi, type UploadDecoratorOptions } from "./decorators";
78
+ import { assertGuardKeyHandled, checkGuardKeys, warnUnguardedMutationApis } from "./guards";
76
79
  import {
77
80
  assertHttpValidatorRegistry,
78
81
  createHttpValidator,
79
82
  getHttpValidatorRouteKey,
83
+ type HttpRequestParameters,
80
84
  type HttpValidator,
81
85
  type HttpValidatorRegistry,
82
86
  } from "./http-validator";
@@ -132,6 +136,40 @@ function toApiArgumentMap<Value extends object>(value: Value): Map<string, ApiAr
132
136
  return new Map(Object.entries(value).map(([key, item]) => [key, toApiArgument(item)]));
133
137
  }
134
138
 
139
+ /**
140
+ * Zod 검증 오류를 HTTP 400 응답에 쓰는 메시지로 바꿉니다.
141
+ * HTTP 요청과 SSR preload가 같은 메시지를 내도록 두 경로가 함께 사용합니다.
142
+ */
143
+ async function humanizeZodErrorMessage(e: ZodError): Promise<LocalizedString> {
144
+ const { humanizeZodError } = await import("../utils/zod-error");
145
+ const messages = humanizeZodError(e)
146
+ .map((issue) => issue.message)
147
+ .join(" ");
148
+ return /* SAFETY: API 데코레이터와 Zod 검증기 등록 계약이 이 값의 타입을 보장한다. */ messages as LocalizedString;
149
+ }
150
+
151
+ type UploadLimits = NonNullable<UploadDecoratorOptions["limits"]>;
152
+
153
+ /**
154
+ * `@upload` 데코레이터의 limits를 `request.parts()` 옵션으로 바꿉니다.
155
+ *
156
+ * `@fastify/multipart`는 플러그인 옵션과 요청 옵션을 deepmerge로 병합하는데, 값이 undefined인 키도
157
+ * 그대로 덮어씁니다. `{ limits: undefined }`를 넘기면 전역 multipart limits(fileSize, parts 등)가
158
+ * 통째로 사라져 busboy가 모든 한도를 Infinity로 취급합니다. 그래서 정의된 항목만 남기고,
159
+ * 남은 항목이 없으면 옵션 자체를 생략해 전역 한도를 그대로 적용합니다.
160
+ */
161
+ function toMultipartPartsOptions(
162
+ limits: UploadDecoratorOptions["limits"],
163
+ ): { limits: UploadLimits } | undefined {
164
+ if (limits === undefined) {
165
+ return undefined;
166
+ }
167
+ const definedLimits: UploadLimits = Object.fromEntries(
168
+ Object.entries(limits).filter(([, value]) => value !== undefined),
169
+ );
170
+ return Object.keys(definedLimits).length > 0 ? { limits: definedLimits } : undefined;
171
+ }
172
+
135
173
  function createUnavailableSSE<T extends ZodObject>(_events: T): never {
136
174
  throw new Error(
137
175
  "createSSE is not available in websocket context. Define websocketContextProvider if your context setup depends on SSE helpers.",
@@ -294,6 +332,8 @@ class SonamuClass {
294
332
  }
295
333
  return this.authValue;
296
334
  }
335
+ // init에서 better-auth에 주입한 baseURL과 그 출처 (Host 헤더로 baseURL을 정하지 않기 위해 보관)
336
+ private authBaseURLResolution: AuthBaseURLResolution | null = null;
297
337
 
298
338
  private devVitestManagerValue: DevVitestManager | null = null;
299
339
  get devVitestManager(): DevVitestManager | null {
@@ -423,16 +463,34 @@ class SonamuClass {
423
463
  // BetterAuth 초기화
424
464
  const authConfig = this.config.server.auth;
425
465
  if (authConfig) {
426
- // 사용자 설정과 기본값을 merge
427
- const mergedFieldMappings = merge(BASE_FIELD_MAPPINGS, authConfig);
466
+ // 사용자 설정과 기본값을 merge하고 additionalFields의 클라이언트 입력을 기본 차단
467
+ const mergedFieldMappings = buildBetterAuthOptions(authConfig);
428
468
 
429
469
  // better-auth 인스턴스 생성
430
470
  const { betterAuth } = await import("better-auth");
431
471
  const { sonamuKnexAdapter } = await import("../auth/knex-adapter");
472
+ const { sonamuVerifyEmailGuard } = await import("../auth/verify-email-guard");
473
+ const { resolveAuthBaseURL } = await import("../auth/base-url");
474
+ const { isLocal } = await import("../utils/controller");
475
+
476
+ // baseURL이 없으면 better-auth가 Host 헤더로 리셋·인증 링크를 만들므로 설정값으로 고정한다.
477
+ // 원격 환경에서 정할 수 없으면(source: "none") CLI는 그대로 두고 서버 기동만 거부한다.
478
+ const baseURLResolution = resolveAuthBaseURL(this.config.server, { local: isLocal() });
479
+ this.authBaseURLResolution = baseURLResolution;
480
+ if (baseURLResolution.source === "listen" && !doSilent) {
481
+ console.warn(
482
+ chalk.yellow(
483
+ `⚠ auth.baseURL is not set. Using ${String(baseURLResolution.baseURL)} for auth links. Set auth.baseURL, BETTER_AUTH_URL, or server.baseUrl before deploying.`,
484
+ ),
485
+ );
486
+ }
432
487
 
433
488
  const authOptions: BetterAuthOptions = {
434
489
  database: sonamuKnexAdapter(),
435
490
  ...mergedFieldMappings,
491
+ baseURL: baseURLResolution.baseURL,
492
+ // verify-email 가드는 다른 플러그인 훅보다 먼저 실행되도록 맨 앞에 둔다. (SON-601)
493
+ plugins: [sonamuVerifyEmailGuard(), ...(mergedFieldMappings.plugins ?? [])],
436
494
  };
437
495
  this.authValue = betterAuth(authOptions);
438
496
  }
@@ -473,12 +531,22 @@ class SonamuClass {
473
531
  private initElapsed = 0;
474
532
  private configElapsed = 0;
475
533
 
534
+ /**
535
+ * Fastify 서버를 만들어 라우트를 등록하고 기동합니다.
536
+ * 초기화 전이면 `resolveSonamuEnvironment` 규칙으로 NODE_ENV를 정하며,
537
+ * `HOT=yes`(sonamu dev)·`VITEST=true`가 아니면 기본값은 production입니다.
538
+ */
476
539
  async createServer(initOptions?: { enableSync?: boolean; doSilent?: boolean }) {
477
540
  if (!this.isInitialized) {
541
+ // 설정을 읽기 전에 서버 환경을 확정해야 dist 서버가 NODE_ENV 없이 개발 도구 라우트를 열지 않습니다.
542
+ const { findApiRootPath } = await import("../utils/utils");
543
+ ensureServerEnvironment(findApiRootPath());
478
544
  await this.init(initOptions?.doSilent, initOptions?.enableSync);
479
545
  }
480
546
 
481
547
  const options = this.config.server;
548
+ // 공개된 secret으로 서명하면 세션·토큰을 위조할 수 있으므로 라우트 등록·listen 전에 거부한다.
549
+ await this.assertAuthSecretForServing();
482
550
  const { default: fastify } = await import("fastify");
483
551
  const { getLogTapeFastifyLogger } = await import("@logtape/fastify");
484
552
  // Fastify 5는 logger 옵션에 설정 객체만 받고, 로거 인스턴스는 loggerInstance로 넘겨야 한다
@@ -533,10 +601,18 @@ class SonamuClass {
533
601
  await this.init(options?.doSilent, options?.enableSync);
534
602
  }
535
603
 
604
+ await this.assertAuthSecretForServing();
536
605
  this.server = server;
537
606
  this.websocketRuntime ??= new WebSocketRuntime(this.config.server.websocket);
538
607
  await this.refreshHttpValidators();
539
608
 
609
+ // guardKeys를 설정했다면 목록 밖 가드 키를 쓰는 API가 있을 때 부팅을 중단한다
610
+ checkGuardKeys(this.syncer.apis, config.guardKeys, options?.doSilent ? () => {} : undefined);
611
+ // guards 미지정 상태 변경 API는 비인증으로 호출되므로 부팅 시 목록을 경고로 알린다
612
+ if (!options?.doSilent) {
613
+ warnUnguardedMutationApis(this.syncer.apis);
614
+ }
615
+
540
616
  // timezone 설정
541
617
  const timezone = this.config.api.timezone;
542
618
  if (timezone) {
@@ -587,6 +663,20 @@ class SonamuClass {
587
663
  // Sonamu UI API (로컬 환경에서만)
588
664
  const { isLocal } = await import("../utils/controller");
589
665
  if (isLocal()) {
666
+ // DNS rebinding으로 공격자 도메인이 개발 서버를 가리켜도 UI·dev 라우트에 닿지 못하도록 Host를 검사합니다.
667
+ // 보호할 라우트를 등록하기 전에 훅을 걸어야 합니다.
668
+ const { getConfiguredDevHostnames, registerDevHostGuard } =
669
+ await import("../ui/dev-host-guard");
670
+ registerDevHostGuard(server, {
671
+ configuredHostnames: getConfiguredDevHostnames(this.config.server),
672
+ protectedPrefixes: [
673
+ "/sonamu-ui",
674
+ ...(this.config.test?.devRunner?.enabled
675
+ ? [this.config.test.devRunner.routePrefix ?? "/__test__"]
676
+ : []),
677
+ ],
678
+ });
679
+
590
680
  const { sonamuUIApiPlugin } = await import("../ui/api");
591
681
  server.register(sonamuUIApiPlugin);
592
682
  }
@@ -1071,7 +1161,7 @@ class SonamuClass {
1071
1161
 
1072
1162
  return this.asyncLocalStorage.run({ context }, async () => {
1073
1163
  // guards 처리
1074
- runGuards({
1164
+ await runGuards({
1075
1165
  guards: api.options.guards,
1076
1166
  config,
1077
1167
  request,
@@ -1090,9 +1180,7 @@ class SonamuClass {
1090
1180
  try {
1091
1181
  const body = request[which] ?? {};
1092
1182
  if (api.uploadOptions) {
1093
- const parts = request.parts({
1094
- limits: api.uploadOptions.limits,
1095
- });
1183
+ const parts = request.parts(toMultipartPartsOptions(api.uploadOptions.limits));
1096
1184
 
1097
1185
  // FormData의 field들을 임시로 저장
1098
1186
  const fields: Record<string, string> = {};
@@ -1128,7 +1216,7 @@ class SonamuClass {
1128
1216
  });
1129
1217
 
1130
1218
  await disk.putStream(key, part.file, {
1131
- contentType: part.mimetype,
1219
+ contentType: resolveUploadContentType(part.mimetype),
1132
1220
  });
1133
1221
 
1134
1222
  const url = await disk.getUrl(key);
@@ -1161,17 +1249,10 @@ class SonamuClass {
1161
1249
  } catch (e) {
1162
1250
  const { ZodError } = await import("zod");
1163
1251
  if (e instanceof ZodError) {
1164
- const { humanizeZodError } = await import("../utils/zod-error");
1165
- const messages = humanizeZodError(e)
1166
- .map((issue) => issue.message)
1167
- .join(" ");
1168
1252
  const { BadRequestException } = await import("../exceptions/so-exceptions");
1169
- throw new BadRequestException(
1170
- /* SAFETY: API 데코레이터와 Zod 검증기 등록 계약이 이 값의 타입을 보장한다. */ messages as LocalizedString,
1171
- {
1172
- zodError: e,
1173
- },
1174
- );
1253
+ throw new BadRequestException(await humanizeZodErrorMessage(e), {
1254
+ zodError: e,
1255
+ });
1175
1256
  } else {
1176
1257
  throw e;
1177
1258
  }
@@ -1436,7 +1517,7 @@ class SonamuClass {
1436
1517
  wsContext = await this.createWebSocketContext(config, request, scopedWs);
1437
1518
 
1438
1519
  await this.asyncLocalStorage.run({ context: wsContext }, async () => {
1439
- runGuards({
1520
+ await runGuards({
1440
1521
  guards: api.options.guards,
1441
1522
  config,
1442
1523
  request,
@@ -1766,7 +1847,9 @@ class SonamuClass {
1766
1847
 
1767
1848
  /**
1768
1849
  * SSR용 API 호출 (HTTP 오버헤드 없이 직접 호출)
1769
- * createApiHandler의 로직을 재사용하되, request 파싱 대신 params 직접 사용
1850
+ * createApiHandler와 같은 guards와 HTTP 검증기를 거친 뒤, request 파싱 대신 preload params를 사용합니다.
1851
+ * guard가 거부하면 그 예외를 그대로 던지고, params가 검증기를 통과하지 못하면
1852
+ * SSRPreloadValidationException(400)을 던집니다.
1770
1853
  */
1771
1854
  async invokeApiForSSR(
1772
1855
  api: ExtendedApi,
@@ -1775,18 +1858,56 @@ class SonamuClass {
1775
1858
  request: FastifyRequest,
1776
1859
  reply: FastifyReply,
1777
1860
  ): Promise<ApiMethodResult> {
1861
+ // HTTP 경로와 같은 검증기(캐시·AOT·JIT 정책 포함)를 사용한다
1862
+ const preparedValidator = this.getOrCreateHttpValidator(
1863
+ api,
1864
+ defaultSonamuHttpValidatorDependencies,
1865
+ );
1866
+ const validator =
1867
+ preparedValidator instanceof Promise ? await preparedValidator : preparedValidator;
1778
1868
  // Context 생성 (기존 메소드 재사용)
1779
1869
  const context = await this.createContext(config, request, reply);
1780
1870
 
1781
1871
  return this.asyncLocalStorage.run({ context }, async () => {
1782
- // args 생성: Context 파라미터는 주입, 나머지는 params에서 가져오기
1872
+ // SSR 응답에 보호된 데이터가 실리지 않도록 HTTP 호출과 같은 guards를 먼저 실행한다.
1873
+ // guardHandler가 Promise를 돌려주는 경우에도 거부가 무시되지 않도록 await한다.
1874
+ await runGuards({
1875
+ guards: api.options.guards,
1876
+ config,
1877
+ request,
1878
+ api,
1879
+ });
1880
+
1881
+ // preload는 Context를 뺀 위치 인수를 넘기므로, HTTP 요청과 같은 이름 맵으로 바꿔 검증한다
1783
1882
  const { ApiParamType } = await import("../types/types");
1883
+ const namedParams: HttpRequestParameters = {};
1784
1884
  let paramsIndex = 0;
1885
+ for (const param of api.parameters) {
1886
+ if (!ApiParamType.isContext(param.type)) {
1887
+ namedParams[param.name] = params[paramsIndex++];
1888
+ }
1889
+ }
1890
+
1891
+ let parsedParams: Map<string, ApiArgument>;
1892
+ try {
1893
+ parsedParams = toApiArgumentMap(validator.parse(namedParams));
1894
+ } catch (e) {
1895
+ const { ZodError } = await import("zod");
1896
+ if (e instanceof ZodError) {
1897
+ const { SSRPreloadValidationException } = await import("../ssr/errors");
1898
+ throw new SSRPreloadValidationException(await humanizeZodErrorMessage(e), {
1899
+ zodError: e,
1900
+ });
1901
+ }
1902
+ throw e;
1903
+ }
1904
+
1905
+ // args 생성: Context 파라미터는 주입, 나머지는 검증된 값 사용
1785
1906
  const args = api.parameters.map((param) => {
1786
1907
  if (ApiParamType.isContext(param.type)) {
1787
1908
  return context;
1788
1909
  }
1789
- return params[paramsIndex++];
1910
+ return parsedParams.get(param.name);
1790
1911
  });
1791
1912
 
1792
1913
  // 모델 메서드 호출 (기존 메서드 재사용)
@@ -2076,11 +2197,7 @@ class SonamuClass {
2076
2197
  const resolvedPluginOptions = resolveWebSocketPluginOptions({
2077
2198
  rawPluginOption: pluginOption,
2078
2199
  });
2079
- if (resolvedPluginOptions) {
2080
- await server.register(websocketPlugin, resolvedPluginOptions);
2081
- } else {
2082
- await server.register(websocketPlugin);
2083
- }
2200
+ await server.register(websocketPlugin, resolvedPluginOptions);
2084
2201
 
2085
2202
  this.websocketPluginServers.add(server);
2086
2203
  this.warnOnPotentialWebSocketTimeoutConflicts(server);
@@ -2115,6 +2232,20 @@ class SonamuClass {
2115
2232
  }
2116
2233
  }
2117
2234
 
2235
+ /**
2236
+ * auth를 쓰는 서버를 띄우기 전에 better-auth secret이 없거나 공개된 값이면 기동을 거부합니다(test 환경 제외).
2237
+ * CLI 도구(sync·migrate 등)도 init()을 부르지만 요청을 받지 않으므로 init()이 아니라 서버 경계에서 확인합니다.
2238
+ */
2239
+ private async assertAuthSecretForServing(): Promise<void> {
2240
+ const authConfig = this.config.server.auth;
2241
+ if (!authConfig) {
2242
+ return;
2243
+ }
2244
+
2245
+ const { assertAuthSecretConfigured } = await import("../auth/auth-secret");
2246
+ assertAuthSecretConfigured(authConfig);
2247
+ }
2248
+
2118
2249
  /**
2119
2250
  * better-auth 라우트를 등록합니다.
2120
2251
  * /api/auth/* 경로로 인증 API가 자동 등록됩니다.
@@ -2125,6 +2256,13 @@ class SonamuClass {
2125
2256
  ) {
2126
2257
  if (!options) return;
2127
2258
 
2259
+ const baseURLResolution = this.authBaseURLResolution;
2260
+ if (!baseURLResolution || baseURLResolution.source === "none") {
2261
+ throw new Error(
2262
+ "auth.baseURL is required outside development/test. Set server.auth.baseURL, the BETTER_AUTH_URL environment variable, or an absolute http(s) server.baseUrl so auth links are not built from the request Host header.",
2263
+ );
2264
+ }
2265
+ const { requestBaseURL } = baseURLResolution;
2128
2266
  const basePath = options.basePath ?? "/api/auth";
2129
2267
 
2130
2268
  // better-auth 라우트 등록
@@ -2133,7 +2271,11 @@ class SonamuClass {
2133
2271
  url: `${basePath}/*`,
2134
2272
  handler: async (request, reply) => {
2135
2273
  const response = await this.auth.handler(
2136
- createBetterAuthRequest(request, options.advanced?.ipAddress?.ipAddressHeaders),
2274
+ createBetterAuthRequest(
2275
+ request,
2276
+ options.advanced?.ipAddress?.ipAddressHeaders,
2277
+ requestBaseURL,
2278
+ ),
2137
2279
  );
2138
2280
 
2139
2281
  reply.status(response.status);
@@ -2313,9 +2455,10 @@ export const Sonamu = new SonamuClass();
2313
2455
 
2314
2456
  /**
2315
2457
  * stream 모드에서 키 생성 함수가 지정되지 않았을 때 사용하는 기본 함수입니다.
2458
+ * 확장자는 클라이언트 MIME 을 믿지 않고 허용 목록 안에서만 고르며, 그 밖이면 `bin` 입니다.
2316
2459
  */
2317
2460
  function defaultKeyGenerator(file: { filename: string; mimetype: string }): string {
2318
- const ext = mime.extension(file.mimetype) || "bin";
2461
+ const ext = resolveUploadExtension(file.mimetype) || "bin";
2319
2462
  const timestamp = Date.now();
2320
2463
  const random = Math.random().toString(36).slice(2, 8);
2321
2464
  return `uploads/${timestamp}-${random}.${ext}`;
@@ -2331,19 +2474,32 @@ function isLocalHost(host: string): boolean {
2331
2474
  return LOCAL_HOSTS.has(host) || host.endsWith(".local");
2332
2475
  }
2333
2476
 
2477
+ /**
2478
+ * API에 선언된 guard를 순서대로 실행합니다.
2479
+ *
2480
+ * async guardHandler의 Promise를 기다리고, 예외는 그대로 전파합니다.
2481
+ * guardHandler가 `false`를 반환하면 UnauthorizedException으로 요청을 거부합니다.
2482
+ * 호출부는 반드시 await해야 하며, 그렇지 않으면 거부가 무시되고 unhandledRejection이 발생합니다.
2483
+ */
2334
2484
  // `.every()`가 첫 guard 이후 순회를 멈추는 문제가 있어 `for...of`로 모든 guard를 순서대로 실행하도록 고정함
2335
- function runGuards({
2485
+ async function runGuards({
2336
2486
  guards,
2337
2487
  config,
2338
2488
  request,
2339
2489
  api,
2340
2490
  }: {
2341
2491
  guards: ExtendedApi["options"]["guards"] | undefined;
2342
- config: Pick<SonamuFastifyConfig, "guardHandler">;
2492
+ config: Pick<SonamuFastifyConfig, "guardHandler" | "guardKeys">;
2343
2493
  request: FastifyRequest;
2344
2494
  api: ExtendedApi;
2345
- }): void {
2495
+ }): Promise<void> {
2346
2496
  for (const guard of guards ?? []) {
2347
- config.guardHandler(guard, request, api);
2497
+ // guardKeys 밖의 키는 guardHandler가 처리하지 않는 키이므로 호출 없이 거부한다
2498
+ assertGuardKeyHandled(guard, config.guardKeys);
2499
+ const result = await config.guardHandler(guard, request, api);
2500
+ // 문서가 안내하는 "false 반환 시 차단" 계약을 지킨다. undefined/true는 통과로 본다
2501
+ if (result === false) {
2502
+ throw new UnauthorizedException(SD("error.unauthorized"));
2503
+ }
2348
2504
  }
2349
2505
  }
@@ -31,12 +31,18 @@ export function resolveIntegratedViteHmrOptions({
31
31
  return Number.isFinite(parsedPort) && parsedPort > 0 ? { port: parsedPort } : { port: 24678 };
32
32
  }
33
33
 
34
- // @fastify/websocket transport option은 server.plugins.ws에 명시된 값만 사용함.
34
+ /**
35
+ * 인바운드 WebSocket 프레임 1개의 기본 최대 크기(바이트).
36
+ * ws 기본값(100MiB)이면 프레임 하나로 이벤트 루프가 멈추거나 힙이 고갈되므로, 넘는 프레임은 ws가 1009로 닫게 한다.
37
+ */
38
+ export const DEFAULT_WEBSOCKET_MAX_PAYLOAD_BYTES = 64 * 1024;
39
+
40
+ // @fastify/websocket transport option은 server.plugins.ws에 명시된 값을 쓰고, maxPayload만 안전한 기본값을 채움.
35
41
  export function resolveWebSocketPluginOptions({
36
42
  rawPluginOption,
37
43
  }: {
38
44
  rawPluginOption: boolean | WebsocketPluginOptions | undefined;
39
- }): WebsocketPluginOptions | undefined {
45
+ }): WebsocketPluginOptions {
40
46
  const pluginOptions = rawPluginOption && rawPluginOption !== true ? { ...rawPluginOption } : {};
41
47
  const serverOptions: NonNullable<WebsocketPluginOptions["options"]> = isPlainObject(
42
48
  pluginOptions.options,
@@ -44,11 +50,10 @@ export function resolveWebSocketPluginOptions({
44
50
  ? { ...pluginOptions.options }
45
51
  : {};
46
52
 
47
- if (Object.keys(serverOptions).length > 0) {
48
- pluginOptions.options = serverOptions;
49
- }
53
+ serverOptions.maxPayload ??= DEFAULT_WEBSOCKET_MAX_PAYLOAD_BYTES;
54
+ pluginOptions.options = serverOptions;
50
55
 
51
- return Object.keys(pluginOptions).length > 0 ? pluginOptions : undefined;
56
+ return pluginOptions;
52
57
  }
53
58
 
54
59
  // handshake/auth/validation 실패를 generic 1011로 뭉개지 않고 1008(policy violation)로 매핑해,
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { getSubsetFields, normalizeSubsetField } from "../../types/types";
4
+ import {
5
+ BETTER_AUTH_SECRET_FIELDS,
6
+ findBetterAuthCredentialEntity,
7
+ getAllBetterAuthEntityDefinitions,
8
+ } from "../auth-entity-policy";
9
+
10
+ describe("better-auth 자격 증명 엔티티 정책", () => {
11
+ const definitions = getAllBetterAuthEntityDefinitions();
12
+
13
+ it("비밀 필드 목록의 엔티티와 필드는 모두 실제 better-auth 정의에 존재한다", () => {
14
+ for (const [entityId, fields] of Object.entries(BETTER_AUTH_SECRET_FIELDS)) {
15
+ const definition = definitions.find((entity) => entity.id === entityId);
16
+ expect(definition, entityId).toBeDefined();
17
+ const propNames = definition?.props?.map((prop) => prop.name) ?? [];
18
+ for (const field of fields) {
19
+ expect(propNames, `${entityId}.${field}`).toContain(field);
20
+ }
21
+ }
22
+ });
23
+
24
+ it("기본 subset에는 비밀 필드가 들어가지 않는다", () => {
25
+ const leaked = definitions.flatMap((definition) => {
26
+ const secretFields: readonly string[] =
27
+ Object.entries(BETTER_AUTH_SECRET_FIELDS).find(([id]) => id === definition.id)?.[1] ?? [];
28
+ return Object.entries(definition.subsets ?? {}).flatMap(([subsetKey, subsetDef]) =>
29
+ getSubsetFields(subsetDef)
30
+ .map(normalizeSubsetField)
31
+ .filter((field) => secretFields.includes(field))
32
+ .map((field) => `${definition.id}.${subsetKey}.${field}`),
33
+ );
34
+ });
35
+ expect(leaked).toEqual([]);
36
+ });
37
+
38
+ it.each([
39
+ ["Session", "sessions"],
40
+ ["Account", "accounts"],
41
+ ["Verification", "verifications"],
42
+ ["TwoFactor", "two_factors"],
43
+ ["Passkey", "passkeys"],
44
+ ["Jwks", "jwks"],
45
+ ["ApiKey", "api_keys"],
46
+ ["SsoProvider", "sso_providers"],
47
+ ])("%s(%s)는 자격 증명 엔티티로 판단한다", (id, table) => {
48
+ expect(findBetterAuthCredentialEntity({ id, table })?.id).toBe(id);
49
+ });
50
+
51
+ it.each([
52
+ ["User", "users"],
53
+ ["Organization", "organizations"],
54
+ ["AuditEvent", "audit_events"],
55
+ ["Session", "conference_sessions"],
56
+ ])("%s(%s)는 자격 증명 엔티티로 판단하지 않는다", (id, table) => {
57
+ expect(findBetterAuthCredentialEntity({ id, table })).toBeUndefined();
58
+ });
59
+ });
@@ -0,0 +1,133 @@
1
+ import { describe, expect, test } from "vitest";
2
+
3
+ import {
4
+ assertAuthSecretConfigured,
5
+ KNOWN_PUBLIC_AUTH_SECRETS,
6
+ resolveAuthSecretCandidates,
7
+ } from "../auth-secret";
8
+
9
+ const STRONG_SECRET = "Yq3vN8kP2xR7tL0wZ5mB9cH4jF6sD1gA";
10
+ const MIOMOCK_FALLBACK = "miomock-secret-key-change-this-in-production";
11
+ const BETTER_AUTH_DEFAULT = "better-auth-secret-12345678901234567890";
12
+
13
+ describe("assertAuthSecretConfigured — secret 누락·공개값 기동 거부 (SON-600)", () => {
14
+ test.each(["development", "staging", "production"] as const)(
15
+ "%s에서 secret이 없으면 오류를 던진다",
16
+ (environment) => {
17
+ expect(() => assertAuthSecretConfigured({}, {}, environment)).toThrow(/secret is missing/);
18
+ },
19
+ );
20
+
21
+ test("NODE_ENV가 없으면 development로 보고 secret 누락을 거부한다", () => {
22
+ expect(() => assertAuthSecretConfigured({}, {})).toThrow(/NODE_ENV=development/);
23
+ });
24
+
25
+ test("공백뿐인 secret은 없는 것으로 본다", () => {
26
+ expect(() =>
27
+ assertAuthSecretConfigured({ secret: " " }, { BETTER_AUTH_SECRET: " " }, "production"),
28
+ ).toThrow(/secret is missing/);
29
+ });
30
+
31
+ test.each([MIOMOCK_FALLBACK, BETTER_AUTH_DEFAULT, "better-auth-secret-123456789"])(
32
+ "공개된 secret(%s)은 설정·환경변수 어느 쪽이든 거부한다",
33
+ (publicSecret) => {
34
+ expect(() => assertAuthSecretConfigured({ secret: publicSecret }, {}, "staging")).toThrow(
35
+ /publicly known/,
36
+ );
37
+ expect(() =>
38
+ assertAuthSecretConfigured({}, { BETTER_AUTH_SECRET: publicSecret }, "development"),
39
+ ).toThrow(/publicly known/);
40
+ expect(() =>
41
+ assertAuthSecretConfigured({}, { AUTH_SECRET: ` ${publicSecret} ` }, "production"),
42
+ ).toThrow(/publicly known/);
43
+ },
44
+ );
45
+
46
+ test("오류 메시지에 secret 값을 넣지 않는다", () => {
47
+ expect(() =>
48
+ assertAuthSecretConfigured({ secret: MIOMOCK_FALLBACK }, {}, "production"),
49
+ ).toThrow(expect.objectContaining({ message: expect.not.stringContaining(MIOMOCK_FALLBACK) }));
50
+ });
51
+
52
+ test("교체용 secrets 목록에 공개값이 하나라도 있으면 거부한다", () => {
53
+ expect(() =>
54
+ assertAuthSecretConfigured(
55
+ {
56
+ secrets: [
57
+ { version: 2, value: STRONG_SECRET },
58
+ { version: 1, value: MIOMOCK_FALLBACK },
59
+ ],
60
+ },
61
+ {},
62
+ "production",
63
+ ),
64
+ ).toThrow(/publicly known/);
65
+ expect(() =>
66
+ assertAuthSecretConfigured(
67
+ {},
68
+ { BETTER_AUTH_SECRETS: `2:${STRONG_SECRET}, 1:${MIOMOCK_FALLBACK}` },
69
+ "production",
70
+ ),
71
+ ).toThrow(/publicly known/);
72
+ });
73
+
74
+ test("secrets 목록이 있어도 함께 남는 legacy secret이 공개값이면 거부한다", () => {
75
+ expect(() =>
76
+ assertAuthSecretConfigured(
77
+ { secrets: [{ version: 1, value: STRONG_SECRET }] },
78
+ { BETTER_AUTH_SECRET: MIOMOCK_FALLBACK },
79
+ "production",
80
+ ),
81
+ ).toThrow(/publicly known/);
82
+ });
83
+
84
+ test("임의의 secret이 있으면 모든 환경에서 통과한다", () => {
85
+ for (const environment of ["development", "staging", "production"] as const) {
86
+ expect(() =>
87
+ assertAuthSecretConfigured({ secret: STRONG_SECRET }, {}, environment),
88
+ ).not.toThrow();
89
+ expect(() =>
90
+ assertAuthSecretConfigured({}, { BETTER_AUTH_SECRET: STRONG_SECRET }, environment),
91
+ ).not.toThrow();
92
+ expect(() =>
93
+ assertAuthSecretConfigured({}, { BETTER_AUTH_SECRETS: `1:${STRONG_SECRET}` }, environment),
94
+ ).not.toThrow();
95
+ }
96
+ });
97
+
98
+ test("test 환경은 secret이 없거나 공개값이어도 검사하지 않는다", () => {
99
+ expect(() => assertAuthSecretConfigured({}, {}, "test")).not.toThrow();
100
+ expect(() =>
101
+ assertAuthSecretConfigured({ secret: MIOMOCK_FALLBACK }, {}, "test"),
102
+ ).not.toThrow();
103
+ });
104
+ });
105
+
106
+ describe("resolveAuthSecretCandidates — better-auth와 같은 secret 해석 (SON-600)", () => {
107
+ test("설정의 secret이 환경변수보다 우선한다", () => {
108
+ expect(
109
+ resolveAuthSecretCandidates({ secret: STRONG_SECRET }, { BETTER_AUTH_SECRET: "env-secret" }),
110
+ ).toEqual([STRONG_SECRET]);
111
+ });
112
+
113
+ test("BETTER_AUTH_SECRET이 없으면 AUTH_SECRET을 쓴다", () => {
114
+ expect(resolveAuthSecretCandidates({}, { AUTH_SECRET: STRONG_SECRET })).toEqual([
115
+ STRONG_SECRET,
116
+ ]);
117
+ });
118
+
119
+ test("설정의 secrets가 BETTER_AUTH_SECRETS보다 우선한다", () => {
120
+ expect(
121
+ resolveAuthSecretCandidates(
122
+ { secrets: [{ version: 1, value: STRONG_SECRET }] },
123
+ { BETTER_AUTH_SECRETS: `1:${MIOMOCK_FALLBACK}` },
124
+ ),
125
+ ).toEqual([STRONG_SECRET]);
126
+ });
127
+
128
+ test("공개 secret 목록에 예시 fallback과 better-auth 기본값이 들어 있다", () => {
129
+ expect(KNOWN_PUBLIC_AUTH_SECRETS).toEqual(
130
+ expect.arrayContaining([MIOMOCK_FALLBACK, BETTER_AUTH_DEFAULT]),
131
+ );
132
+ });
133
+ });