sonamu 0.13.11 → 0.14.1

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 (327) 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 +20 -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 +127 -26
  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/code-generator.d.ts +2 -0
  153. package/dist/syncer/code-generator.d.ts.map +1 -1
  154. package/dist/syncer/code-generator.js +21 -7
  155. package/dist/template/implementations/entity.template.d.ts.map +1 -1
  156. package/dist/template/implementations/entity.template.js +40 -35
  157. package/dist/template/implementations/generated.template.d.ts +10 -0
  158. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  159. package/dist/template/implementations/generated.template.js +46 -7
  160. package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
  161. package/dist/template/implementations/generated_http.template.js +3 -1
  162. package/dist/template/implementations/init_types.template.d.ts.map +1 -1
  163. package/dist/template/implementations/init_types.template.js +3 -8
  164. package/dist/template/implementations/model.template.d.ts.map +1 -1
  165. package/dist/template/implementations/model.template.js +9 -2
  166. package/dist/template/implementations/sd.template.d.ts +0 -1
  167. package/dist/template/implementations/sd.template.d.ts.map +1 -1
  168. package/dist/template/implementations/sd.template.js +2 -5
  169. package/dist/template/implementations/view_form.template.d.ts.map +1 -1
  170. package/dist/template/implementations/view_form.template.js +8 -6
  171. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  172. package/dist/template/implementations/view_list.template.js +8 -4
  173. package/dist/testing/dev-test-routes.d.ts.map +1 -1
  174. package/dist/testing/dev-test-routes.js +7 -4
  175. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
  176. package/dist/tooling/cdd-service.js +1 -1
  177. package/dist/tooling/index.d.ts +1 -0
  178. package/dist/tooling/index.d.ts.map +1 -1
  179. package/dist/tooling/index.js +3 -1
  180. package/dist/tsdown.api.config.js +1 -1
  181. package/dist/types/types.d.ts +81 -1
  182. package/dist/types/types.d.ts.map +1 -1
  183. package/dist/types/types.js +2 -1
  184. package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
  185. package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
  186. package/dist/ui/__tests__/ui-test-helpers.js +75 -0
  187. package/dist/ui/access-guard.d.ts +42 -0
  188. package/dist/ui/access-guard.d.ts.map +1 -0
  189. package/dist/ui/access-guard.js +94 -0
  190. package/dist/ui/api.d.ts.map +1 -1
  191. package/dist/ui/api.js +40 -95
  192. package/dist/ui/dev-host-guard.d.ts +31 -0
  193. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  194. package/dist/ui/dev-host-guard.js +75 -0
  195. package/dist/ui/migrations-api.d.ts.map +1 -1
  196. package/dist/ui/migrations-api.js +72 -16
  197. package/dist/ui/open-vscode-api.d.ts +4 -0
  198. package/dist/ui/open-vscode-api.d.ts.map +1 -0
  199. package/dist/ui/open-vscode-api.js +65 -0
  200. package/dist/ui/scaffolding-api.d.ts +18 -0
  201. package/dist/ui/scaffolding-api.d.ts.map +1 -0
  202. package/dist/ui/scaffolding-api.js +111 -0
  203. package/dist/ui/ui-db-presets.d.ts +19 -0
  204. package/dist/ui/ui-db-presets.d.ts.map +1 -0
  205. package/dist/ui/ui-db-presets.js +34 -0
  206. package/dist/ui/ui-request-guard.d.ts +11 -0
  207. package/dist/ui/ui-request-guard.d.ts.map +1 -0
  208. package/dist/ui/ui-request-guard.js +38 -0
  209. package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
  210. package/dist/ui-web/index.html +2 -1
  211. package/package.json +1 -1
  212. package/src/__tests__/env.test.ts +121 -2
  213. package/src/api/__tests__/code-converters.union.test.ts +97 -0
  214. package/src/api/__tests__/guards.test.ts +233 -0
  215. package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
  216. package/src/api/__tests__/sonamu.dev-host-guard.test.ts +142 -0
  217. package/src/api/__tests__/sonamu.guards.test.ts +327 -0
  218. package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
  219. package/src/api/__tests__/websocket-helpers.test.ts +101 -0
  220. package/src/api/caster.ts +7 -0
  221. package/src/api/code-converters.ts +44 -12
  222. package/src/api/config.ts +22 -0
  223. package/src/api/decorators.ts +1 -0
  224. package/src/api/guards.ts +130 -0
  225. package/src/api/sonamu.ts +205 -41
  226. package/src/api/websocket-helpers.ts +11 -6
  227. package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
  228. package/src/auth/__tests__/auth-secret.test.ts +133 -0
  229. package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
  230. package/src/auth/__tests__/base-url.test.ts +117 -0
  231. package/src/auth/__tests__/better-auth-options.test.ts +194 -0
  232. package/src/auth/__tests__/better-auth-request.test.ts +45 -0
  233. package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
  234. package/src/auth/auth-entity-policy.ts +48 -0
  235. package/src/auth/auth-secret.ts +77 -0
  236. package/src/auth/base-url.ts +109 -0
  237. package/src/auth/better-auth-entities.ts +30 -30
  238. package/src/auth/better-auth-options.ts +39 -0
  239. package/src/auth/better-auth-request.ts +28 -1
  240. package/src/auth/plugins/entity-definitions/admin.ts +5 -0
  241. package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
  242. package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
  243. package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
  244. package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
  245. package/src/auth/plugins/entity-definitions/organization.ts +26 -6
  246. package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
  247. package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
  248. package/src/auth/plugins/entity-definitions/sso.ts +20 -15
  249. package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
  250. package/src/auth/verify-email-guard.ts +82 -0
  251. package/src/bin/__tests__/build-web-command.test.ts +24 -0
  252. package/src/bin/build-config.ts +5 -0
  253. package/src/cache/decorator.ts +116 -21
  254. package/src/cache/index.ts +6 -1
  255. package/src/cache/types.ts +18 -0
  256. package/src/cli/plugin-loader.ts +238 -0
  257. package/src/cli/plugin.ts +82 -0
  258. package/src/database/__tests__/db.test.ts +64 -1
  259. package/src/database/__tests__/puri.test.ts +56 -0
  260. package/src/database/db.ts +56 -6
  261. package/src/database/puri.ts +135 -125
  262. package/src/database/puri.types.test-d.ts +12 -0
  263. package/src/database/puri.types.ts +3 -0
  264. package/src/database/sql-expression-brand.ts +9 -0
  265. package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
  266. package/src/dict/en.ts +2 -0
  267. package/src/dict/ko.ts +2 -0
  268. package/src/dict/sonamu-dictionary.ts +298 -38
  269. package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
  270. package/src/entity/entity-codegen-safety.ts +126 -0
  271. package/src/entity/entity-manager.ts +29 -1
  272. package/src/entity/entity.ts +26 -12
  273. package/src/env.ts +52 -1
  274. package/src/filter/utils.ts +19 -7
  275. package/src/index.ts +4 -3
  276. package/src/logger/__tests__/configure.test.ts +51 -1
  277. package/src/logger/configure.ts +14 -1
  278. package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
  279. package/src/migration/__tests__/migrator.test.ts +76 -1
  280. package/src/migration/code-generation.ts +247 -117
  281. package/src/migration/migrator.ts +45 -4
  282. package/src/migration/slack-confirm.ts +19 -5
  283. package/src/ssr/__tests__/preload-guard.test.ts +274 -0
  284. package/src/ssr/errors.ts +11 -0
  285. package/src/ssr/index.ts +1 -0
  286. package/src/ssr/renderer.ts +12 -0
  287. package/src/storage/__tests__/upload-safety.test.ts +179 -0
  288. package/src/storage/base-file.ts +8 -4
  289. package/src/storage/buffered-file.ts +3 -1
  290. package/src/storage/index.ts +9 -0
  291. package/src/storage/upload-safety.ts +155 -0
  292. package/src/stream/__tests__/ws.test.ts +97 -0
  293. package/src/stream/ws.ts +67 -5
  294. package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
  295. package/src/syncer/code-generator.ts +34 -6
  296. package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
  297. package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
  298. package/src/template/__tests__/save-params.template.test.ts +219 -0
  299. package/src/template/implementations/entity.template.ts +53 -48
  300. package/src/template/implementations/generated.template.ts +87 -12
  301. package/src/template/implementations/generated_http.template.ts +5 -0
  302. package/src/template/implementations/init_types.template.ts +4 -22
  303. package/src/template/implementations/model.template.ts +15 -1
  304. package/src/template/implementations/sd.template.ts +4 -5
  305. package/src/template/implementations/view_form.template.ts +13 -5
  306. package/src/template/implementations/view_list.template.ts +12 -3
  307. package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
  308. package/src/testing/dev-test-routes.ts +7 -3
  309. package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
  310. package/src/tooling/index.ts +1 -0
  311. package/src/types/types.ts +22 -1
  312. package/src/ui/__tests__/access-guard.test.ts +217 -0
  313. package/src/ui/__tests__/dev-host-guard.test.ts +182 -0
  314. package/src/ui/__tests__/fixture-api.test.ts +92 -0
  315. package/src/ui/__tests__/migrations-api.test.ts +352 -0
  316. package/src/ui/__tests__/open-vscode.test.ts +151 -0
  317. package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
  318. package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
  319. package/src/ui/__tests__/ui-test-helpers.ts +71 -0
  320. package/src/ui/access-guard.ts +115 -0
  321. package/src/ui/api.ts +65 -198
  322. package/src/ui/dev-host-guard.ts +123 -0
  323. package/src/ui/migrations-api.ts +130 -24
  324. package/src/ui/open-vscode-api.ts +82 -0
  325. package/src/ui/scaffolding-api.ts +177 -0
  326. package/src/ui/ui-db-presets.ts +41 -0
  327. 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
  }
@@ -773,9 +863,17 @@ class SonamuClass {
773
863
  });
774
864
 
775
865
  // Vite middleware 등록 (Vite 에셋 처리)
866
+ // DevRunner도 Fastify 라우트이므로, Vite의 Host 검사가 server.devAllowedHosts로 들어온 Sonamu UI 테스트 패널 요청을 막지 않도록 건너뜁니다.
867
+ const fastifyOnlyPrefixes = [
868
+ this.config.api.route.prefix,
869
+ "/sonamu-ui",
870
+ ...(this.config.test?.devRunner?.enabled
871
+ ? [this.config.test.devRunner.routePrefix ?? "/__test__"]
872
+ : []),
873
+ ];
776
874
  server.use((req, res, next) => {
777
- // API와 Sonamu UI는 Fastify 라우트가 처리하도록 skip
778
- if (req.url?.startsWith(this.config.api.route.prefix) || req.url?.startsWith("/sonamu-ui")) {
875
+ // API, Sonamu UI, DevRunner는 Fastify 라우트가 처리하도록 skip
876
+ if (fastifyOnlyPrefixes.some((prefix) => req.url?.startsWith(prefix))) {
779
877
  return next();
780
878
  }
781
879
  // 나머지는 Vite middleware로 전달
@@ -1071,7 +1169,7 @@ class SonamuClass {
1071
1169
 
1072
1170
  return this.asyncLocalStorage.run({ context }, async () => {
1073
1171
  // guards 처리
1074
- runGuards({
1172
+ await runGuards({
1075
1173
  guards: api.options.guards,
1076
1174
  config,
1077
1175
  request,
@@ -1090,9 +1188,7 @@ class SonamuClass {
1090
1188
  try {
1091
1189
  const body = request[which] ?? {};
1092
1190
  if (api.uploadOptions) {
1093
- const parts = request.parts({
1094
- limits: api.uploadOptions.limits,
1095
- });
1191
+ const parts = request.parts(toMultipartPartsOptions(api.uploadOptions.limits));
1096
1192
 
1097
1193
  // FormData의 field들을 임시로 저장
1098
1194
  const fields: Record<string, string> = {};
@@ -1128,7 +1224,7 @@ class SonamuClass {
1128
1224
  });
1129
1225
 
1130
1226
  await disk.putStream(key, part.file, {
1131
- contentType: part.mimetype,
1227
+ contentType: resolveUploadContentType(part.mimetype),
1132
1228
  });
1133
1229
 
1134
1230
  const url = await disk.getUrl(key);
@@ -1161,17 +1257,10 @@ class SonamuClass {
1161
1257
  } catch (e) {
1162
1258
  const { ZodError } = await import("zod");
1163
1259
  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
1260
  const { BadRequestException } = await import("../exceptions/so-exceptions");
1169
- throw new BadRequestException(
1170
- /* SAFETY: API 데코레이터와 Zod 검증기 등록 계약이 이 값의 타입을 보장한다. */ messages as LocalizedString,
1171
- {
1172
- zodError: e,
1173
- },
1174
- );
1261
+ throw new BadRequestException(await humanizeZodErrorMessage(e), {
1262
+ zodError: e,
1263
+ });
1175
1264
  } else {
1176
1265
  throw e;
1177
1266
  }
@@ -1436,7 +1525,7 @@ class SonamuClass {
1436
1525
  wsContext = await this.createWebSocketContext(config, request, scopedWs);
1437
1526
 
1438
1527
  await this.asyncLocalStorage.run({ context: wsContext }, async () => {
1439
- runGuards({
1528
+ await runGuards({
1440
1529
  guards: api.options.guards,
1441
1530
  config,
1442
1531
  request,
@@ -1766,7 +1855,9 @@ class SonamuClass {
1766
1855
 
1767
1856
  /**
1768
1857
  * SSR용 API 호출 (HTTP 오버헤드 없이 직접 호출)
1769
- * createApiHandler의 로직을 재사용하되, request 파싱 대신 params 직접 사용
1858
+ * createApiHandler와 같은 guards와 HTTP 검증기를 거친 뒤, request 파싱 대신 preload params를 사용합니다.
1859
+ * guard가 거부하면 그 예외를 그대로 던지고, params가 검증기를 통과하지 못하면
1860
+ * SSRPreloadValidationException(400)을 던집니다.
1770
1861
  */
1771
1862
  async invokeApiForSSR(
1772
1863
  api: ExtendedApi,
@@ -1775,18 +1866,56 @@ class SonamuClass {
1775
1866
  request: FastifyRequest,
1776
1867
  reply: FastifyReply,
1777
1868
  ): Promise<ApiMethodResult> {
1869
+ // HTTP 경로와 같은 검증기(캐시·AOT·JIT 정책 포함)를 사용한다
1870
+ const preparedValidator = this.getOrCreateHttpValidator(
1871
+ api,
1872
+ defaultSonamuHttpValidatorDependencies,
1873
+ );
1874
+ const validator =
1875
+ preparedValidator instanceof Promise ? await preparedValidator : preparedValidator;
1778
1876
  // Context 생성 (기존 메소드 재사용)
1779
1877
  const context = await this.createContext(config, request, reply);
1780
1878
 
1781
1879
  return this.asyncLocalStorage.run({ context }, async () => {
1782
- // args 생성: Context 파라미터는 주입, 나머지는 params에서 가져오기
1880
+ // SSR 응답에 보호된 데이터가 실리지 않도록 HTTP 호출과 같은 guards를 먼저 실행한다.
1881
+ // guardHandler가 Promise를 돌려주는 경우에도 거부가 무시되지 않도록 await한다.
1882
+ await runGuards({
1883
+ guards: api.options.guards,
1884
+ config,
1885
+ request,
1886
+ api,
1887
+ });
1888
+
1889
+ // preload는 Context를 뺀 위치 인수를 넘기므로, HTTP 요청과 같은 이름 맵으로 바꿔 검증한다
1783
1890
  const { ApiParamType } = await import("../types/types");
1891
+ const namedParams: HttpRequestParameters = {};
1784
1892
  let paramsIndex = 0;
1893
+ for (const param of api.parameters) {
1894
+ if (!ApiParamType.isContext(param.type)) {
1895
+ namedParams[param.name] = params[paramsIndex++];
1896
+ }
1897
+ }
1898
+
1899
+ let parsedParams: Map<string, ApiArgument>;
1900
+ try {
1901
+ parsedParams = toApiArgumentMap(validator.parse(namedParams));
1902
+ } catch (e) {
1903
+ const { ZodError } = await import("zod");
1904
+ if (e instanceof ZodError) {
1905
+ const { SSRPreloadValidationException } = await import("../ssr/errors");
1906
+ throw new SSRPreloadValidationException(await humanizeZodErrorMessage(e), {
1907
+ zodError: e,
1908
+ });
1909
+ }
1910
+ throw e;
1911
+ }
1912
+
1913
+ // args 생성: Context 파라미터는 주입, 나머지는 검증된 값 사용
1785
1914
  const args = api.parameters.map((param) => {
1786
1915
  if (ApiParamType.isContext(param.type)) {
1787
1916
  return context;
1788
1917
  }
1789
- return params[paramsIndex++];
1918
+ return parsedParams.get(param.name);
1790
1919
  });
1791
1920
 
1792
1921
  // 모델 메서드 호출 (기존 메서드 재사용)
@@ -2076,11 +2205,7 @@ class SonamuClass {
2076
2205
  const resolvedPluginOptions = resolveWebSocketPluginOptions({
2077
2206
  rawPluginOption: pluginOption,
2078
2207
  });
2079
- if (resolvedPluginOptions) {
2080
- await server.register(websocketPlugin, resolvedPluginOptions);
2081
- } else {
2082
- await server.register(websocketPlugin);
2083
- }
2208
+ await server.register(websocketPlugin, resolvedPluginOptions);
2084
2209
 
2085
2210
  this.websocketPluginServers.add(server);
2086
2211
  this.warnOnPotentialWebSocketTimeoutConflicts(server);
@@ -2115,6 +2240,20 @@ class SonamuClass {
2115
2240
  }
2116
2241
  }
2117
2242
 
2243
+ /**
2244
+ * auth를 쓰는 서버를 띄우기 전에 better-auth secret이 없거나 공개된 값이면 기동을 거부합니다(test 환경 제외).
2245
+ * CLI 도구(sync·migrate 등)도 init()을 부르지만 요청을 받지 않으므로 init()이 아니라 서버 경계에서 확인합니다.
2246
+ */
2247
+ private async assertAuthSecretForServing(): Promise<void> {
2248
+ const authConfig = this.config.server.auth;
2249
+ if (!authConfig) {
2250
+ return;
2251
+ }
2252
+
2253
+ const { assertAuthSecretConfigured } = await import("../auth/auth-secret");
2254
+ assertAuthSecretConfigured(authConfig);
2255
+ }
2256
+
2118
2257
  /**
2119
2258
  * better-auth 라우트를 등록합니다.
2120
2259
  * /api/auth/* 경로로 인증 API가 자동 등록됩니다.
@@ -2125,6 +2264,13 @@ class SonamuClass {
2125
2264
  ) {
2126
2265
  if (!options) return;
2127
2266
 
2267
+ const baseURLResolution = this.authBaseURLResolution;
2268
+ if (!baseURLResolution || baseURLResolution.source === "none") {
2269
+ throw new Error(
2270
+ "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.",
2271
+ );
2272
+ }
2273
+ const { requestBaseURL } = baseURLResolution;
2128
2274
  const basePath = options.basePath ?? "/api/auth";
2129
2275
 
2130
2276
  // better-auth 라우트 등록
@@ -2133,7 +2279,11 @@ class SonamuClass {
2133
2279
  url: `${basePath}/*`,
2134
2280
  handler: async (request, reply) => {
2135
2281
  const response = await this.auth.handler(
2136
- createBetterAuthRequest(request, options.advanced?.ipAddress?.ipAddressHeaders),
2282
+ createBetterAuthRequest(
2283
+ request,
2284
+ options.advanced?.ipAddress?.ipAddressHeaders,
2285
+ requestBaseURL,
2286
+ ),
2137
2287
  );
2138
2288
 
2139
2289
  reply.status(response.status);
@@ -2313,9 +2463,10 @@ export const Sonamu = new SonamuClass();
2313
2463
 
2314
2464
  /**
2315
2465
  * stream 모드에서 키 생성 함수가 지정되지 않았을 때 사용하는 기본 함수입니다.
2466
+ * 확장자는 클라이언트 MIME 을 믿지 않고 허용 목록 안에서만 고르며, 그 밖이면 `bin` 입니다.
2316
2467
  */
2317
2468
  function defaultKeyGenerator(file: { filename: string; mimetype: string }): string {
2318
- const ext = mime.extension(file.mimetype) || "bin";
2469
+ const ext = resolveUploadExtension(file.mimetype) || "bin";
2319
2470
  const timestamp = Date.now();
2320
2471
  const random = Math.random().toString(36).slice(2, 8);
2321
2472
  return `uploads/${timestamp}-${random}.${ext}`;
@@ -2331,19 +2482,32 @@ function isLocalHost(host: string): boolean {
2331
2482
  return LOCAL_HOSTS.has(host) || host.endsWith(".local");
2332
2483
  }
2333
2484
 
2485
+ /**
2486
+ * API에 선언된 guard를 순서대로 실행합니다.
2487
+ *
2488
+ * async guardHandler의 Promise를 기다리고, 예외는 그대로 전파합니다.
2489
+ * guardHandler가 `false`를 반환하면 UnauthorizedException으로 요청을 거부합니다.
2490
+ * 호출부는 반드시 await해야 하며, 그렇지 않으면 거부가 무시되고 unhandledRejection이 발생합니다.
2491
+ */
2334
2492
  // `.every()`가 첫 guard 이후 순회를 멈추는 문제가 있어 `for...of`로 모든 guard를 순서대로 실행하도록 고정함
2335
- function runGuards({
2493
+ async function runGuards({
2336
2494
  guards,
2337
2495
  config,
2338
2496
  request,
2339
2497
  api,
2340
2498
  }: {
2341
2499
  guards: ExtendedApi["options"]["guards"] | undefined;
2342
- config: Pick<SonamuFastifyConfig, "guardHandler">;
2500
+ config: Pick<SonamuFastifyConfig, "guardHandler" | "guardKeys">;
2343
2501
  request: FastifyRequest;
2344
2502
  api: ExtendedApi;
2345
- }): void {
2503
+ }): Promise<void> {
2346
2504
  for (const guard of guards ?? []) {
2347
- config.guardHandler(guard, request, api);
2505
+ // guardKeys 밖의 키는 guardHandler가 처리하지 않는 키이므로 호출 없이 거부한다
2506
+ assertGuardKeyHandled(guard, config.guardKeys);
2507
+ const result = await config.guardHandler(guard, request, api);
2508
+ // 문서가 안내하는 "false 반환 시 차단" 계약을 지킨다. undefined/true는 통과로 본다
2509
+ if (result === false) {
2510
+ throw new UnauthorizedException(SD("error.unauthorized"));
2511
+ }
2348
2512
  }
2349
2513
  }
@@ -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
+ });