sonamu 0.13.10 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/dist/api/caster.d.ts.map +1 -1
  2. package/dist/api/caster.js +2 -1
  3. package/dist/api/code-converters.d.ts +5 -1
  4. package/dist/api/code-converters.d.ts.map +1 -1
  5. package/dist/api/code-converters.js +24 -7
  6. package/dist/api/config.d.ts +7 -0
  7. package/dist/api/config.d.ts.map +1 -1
  8. package/dist/api/config.js +1 -1
  9. package/dist/api/decorators.d.ts +1 -0
  10. package/dist/api/decorators.d.ts.map +1 -1
  11. package/dist/api/decorators.js +1 -1
  12. package/dist/api/guards.d.ts +37 -0
  13. package/dist/api/guards.d.ts.map +1 -0
  14. package/dist/api/guards.js +96 -0
  15. package/dist/api/sonamu.d.ts +14 -1
  16. package/dist/api/sonamu.d.ts.map +1 -1
  17. package/dist/api/sonamu.js +121 -25
  18. package/dist/api/websocket-helpers.d.ts +6 -1
  19. package/dist/api/websocket-helpers.d.ts.map +1 -1
  20. package/dist/api/websocket-helpers.js +7 -4
  21. package/dist/auth/auth-entity-policy.d.ts +32 -0
  22. package/dist/auth/auth-entity-policy.d.ts.map +1 -0
  23. package/dist/auth/auth-entity-policy.js +44 -0
  24. package/dist/auth/auth-secret.d.ts +24 -0
  25. package/dist/auth/auth-secret.d.ts.map +1 -0
  26. package/dist/auth/auth-secret.js +46 -0
  27. package/dist/auth/base-url.d.ts +39 -0
  28. package/dist/auth/base-url.d.ts.map +1 -0
  29. package/dist/auth/base-url.js +84 -0
  30. package/dist/auth/better-auth-entities.js +20 -7
  31. package/dist/auth/better-auth-options.d.ts +15 -0
  32. package/dist/auth/better-auth-options.d.ts.map +1 -0
  33. package/dist/auth/better-auth-options.js +38 -0
  34. package/dist/auth/better-auth-request.d.ts +8 -1
  35. package/dist/auth/better-auth-request.d.ts.map +1 -1
  36. package/dist/auth/better-auth-request.js +26 -3
  37. package/dist/auth/plugins/entity-definitions/admin.d.ts.map +1 -1
  38. package/dist/auth/plugins/entity-definitions/admin.js +6 -1
  39. package/dist/auth/plugins/entity-definitions/anonymous.d.ts.map +1 -1
  40. package/dist/auth/plugins/entity-definitions/anonymous.js +2 -1
  41. package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
  42. package/dist/auth/plugins/entity-definitions/api-key.js +18 -2
  43. package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
  44. package/dist/auth/plugins/entity-definitions/audit-log.js +27 -1
  45. package/dist/auth/plugins/entity-definitions/jwt.d.ts.map +1 -1
  46. package/dist/auth/plugins/entity-definitions/jwt.js +4 -2
  47. package/dist/auth/plugins/entity-definitions/organization.d.ts.map +1 -1
  48. package/dist/auth/plugins/entity-definitions/organization.js +15 -1
  49. package/dist/auth/plugins/entity-definitions/passkey.d.ts.map +1 -1
  50. package/dist/auth/plugins/entity-definitions/passkey.js +9 -1
  51. package/dist/auth/plugins/entity-definitions/phone-number.d.ts.map +1 -1
  52. package/dist/auth/plugins/entity-definitions/phone-number.js +2 -1
  53. package/dist/auth/plugins/entity-definitions/sso.d.ts.map +1 -1
  54. package/dist/auth/plugins/entity-definitions/sso.js +7 -3
  55. package/dist/auth/plugins/entity-definitions/two-factor.d.ts.map +1 -1
  56. package/dist/auth/plugins/entity-definitions/two-factor.js +8 -3
  57. package/dist/auth/verify-email-guard.d.ts +37 -0
  58. package/dist/auth/verify-email-guard.d.ts.map +1 -0
  59. package/dist/auth/verify-email-guard.js +48 -0
  60. package/dist/bin/build-config.d.ts.map +1 -1
  61. package/dist/bin/build-config.js +6 -2
  62. package/dist/bin/typecheck-web.js +1 -1
  63. package/dist/cache/decorator.d.ts +12 -0
  64. package/dist/cache/decorator.d.ts.map +1 -1
  65. package/dist/cache/decorator.js +86 -19
  66. package/dist/cache/index.d.ts +1 -1
  67. package/dist/cache/index.d.ts.map +1 -1
  68. package/dist/cache/index.js +3 -3
  69. package/dist/cache/types.d.ts +16 -0
  70. package/dist/cache/types.d.ts.map +1 -1
  71. package/dist/cli/plugin-loader.d.ts +17 -0
  72. package/dist/cli/plugin-loader.d.ts.map +1 -0
  73. package/dist/cli/plugin-loader.js +178 -0
  74. package/dist/cli/plugin.d.ts +65 -0
  75. package/dist/cli/plugin.d.ts.map +1 -0
  76. package/dist/cli/plugin.js +7 -0
  77. package/dist/code-formatting/oxfmt.js +1 -1
  78. package/dist/code-formatting/oxlint.js +1 -1
  79. package/dist/database/db.d.ts +35 -10
  80. package/dist/database/db.d.ts.map +1 -1
  81. package/dist/database/db.js +37 -4
  82. package/dist/database/puri.d.ts +8 -0
  83. package/dist/database/puri.d.ts.map +1 -1
  84. package/dist/database/puri.js +108 -171
  85. package/dist/database/puri.types.d.ts +2 -0
  86. package/dist/database/puri.types.d.ts.map +1 -1
  87. package/dist/database/puri.types.js +1 -1
  88. package/dist/database/sql-expression-brand.d.ts +10 -0
  89. package/dist/database/sql-expression-brand.d.ts.map +1 -0
  90. package/dist/database/sql-expression-brand.js +10 -0
  91. package/dist/dict/en.d.ts +1 -0
  92. package/dist/dict/en.d.ts.map +1 -1
  93. package/dist/dict/en.js +2 -1
  94. package/dist/dict/ko.d.ts +1 -0
  95. package/dist/dict/ko.d.ts.map +1 -1
  96. package/dist/dict/ko.js +2 -1
  97. package/dist/dict/sonamu-dictionary.d.ts +23 -1
  98. package/dist/dict/sonamu-dictionary.d.ts.map +1 -1
  99. package/dist/dict/sonamu-dictionary.js +187 -32
  100. package/dist/entity/entity-codegen-safety.d.ts +105 -0
  101. package/dist/entity/entity-codegen-safety.d.ts.map +1 -0
  102. package/dist/entity/entity-codegen-safety.js +70 -0
  103. package/dist/entity/entity-manager.d.ts +32 -0
  104. package/dist/entity/entity-manager.d.ts.map +1 -1
  105. package/dist/entity/entity-manager.js +21 -2
  106. package/dist/entity/entity.d.ts +5 -2
  107. package/dist/entity/entity.d.ts.map +1 -1
  108. package/dist/entity/entity.js +19 -8
  109. package/dist/env.d.ts +19 -0
  110. package/dist/env.d.ts.map +1 -1
  111. package/dist/env.js +31 -3
  112. package/dist/filter/utils.d.ts +2 -2
  113. package/dist/filter/utils.d.ts.map +1 -1
  114. package/dist/filter/utils.js +16 -11
  115. package/dist/index.d.ts +4 -3
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +7 -6
  118. package/dist/logger/configure.d.ts.map +1 -1
  119. package/dist/logger/configure.js +10 -3
  120. package/dist/migration/code-generation.d.ts.map +1 -1
  121. package/dist/migration/code-generation.js +177 -96
  122. package/dist/migration/migrator.d.ts +16 -0
  123. package/dist/migration/migrator.d.ts.map +1 -1
  124. package/dist/migration/migrator.js +28 -3
  125. package/dist/migration/slack-confirm.d.ts +6 -2
  126. package/dist/migration/slack-confirm.d.ts.map +1 -1
  127. package/dist/migration/slack-confirm.js +11 -9
  128. package/dist/ssr/errors.d.ts +13 -0
  129. package/dist/ssr/errors.d.ts.map +1 -0
  130. package/dist/ssr/errors.js +12 -0
  131. package/dist/ssr/index.d.ts +1 -0
  132. package/dist/ssr/index.d.ts.map +1 -1
  133. package/dist/ssr/index.js +5 -2
  134. package/dist/ssr/renderer.d.ts +6 -0
  135. package/dist/ssr/renderer.d.ts.map +1 -1
  136. package/dist/ssr/renderer.js +10 -1
  137. package/dist/storage/base-file.d.ts +6 -2
  138. package/dist/storage/base-file.d.ts.map +1 -1
  139. package/dist/storage/base-file.js +10 -5
  140. package/dist/storage/buffered-file.d.ts +1 -0
  141. package/dist/storage/buffered-file.d.ts.map +1 -1
  142. package/dist/storage/buffered-file.js +5 -2
  143. package/dist/storage/index.d.ts +1 -0
  144. package/dist/storage/index.d.ts.map +1 -1
  145. package/dist/storage/index.js +4 -2
  146. package/dist/storage/upload-safety.d.ts +47 -0
  147. package/dist/storage/upload-safety.d.ts.map +1 -0
  148. package/dist/storage/upload-safety.js +112 -0
  149. package/dist/stream/ws.d.ts +6 -0
  150. package/dist/stream/ws.d.ts.map +1 -1
  151. package/dist/stream/ws.js +52 -6
  152. package/dist/syncer/api-parser.js +6 -1
  153. package/dist/syncer/code-generator.d.ts +2 -0
  154. package/dist/syncer/code-generator.d.ts.map +1 -1
  155. package/dist/syncer/code-generator.js +21 -7
  156. package/dist/template/implementations/entity.template.d.ts.map +1 -1
  157. package/dist/template/implementations/entity.template.js +40 -35
  158. package/dist/template/implementations/generated.template.d.ts +10 -0
  159. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  160. package/dist/template/implementations/generated.template.js +46 -7
  161. package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
  162. package/dist/template/implementations/generated_http.template.js +3 -1
  163. package/dist/template/implementations/init_types.template.d.ts.map +1 -1
  164. package/dist/template/implementations/init_types.template.js +3 -8
  165. package/dist/template/implementations/model.template.d.ts.map +1 -1
  166. package/dist/template/implementations/model.template.js +9 -2
  167. package/dist/template/implementations/sd.template.d.ts +0 -1
  168. package/dist/template/implementations/sd.template.d.ts.map +1 -1
  169. package/dist/template/implementations/sd.template.js +2 -5
  170. package/dist/template/implementations/view_form.template.d.ts.map +1 -1
  171. package/dist/template/implementations/view_form.template.js +8 -6
  172. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  173. package/dist/template/implementations/view_list.template.js +8 -4
  174. package/dist/testing/dev-test-routes.d.ts.map +1 -1
  175. package/dist/testing/dev-test-routes.js +7 -4
  176. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
  177. package/dist/tooling/cdd-service.js +1 -1
  178. package/dist/tooling/index.d.ts +1 -0
  179. package/dist/tooling/index.d.ts.map +1 -1
  180. package/dist/tooling/index.js +3 -1
  181. package/dist/tsdown.api.config.js +1 -1
  182. package/dist/types/types.d.ts +81 -1
  183. package/dist/types/types.d.ts.map +1 -1
  184. package/dist/types/types.js +2 -1
  185. package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
  186. package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
  187. package/dist/ui/__tests__/ui-test-helpers.js +75 -0
  188. package/dist/ui/access-guard.d.ts +42 -0
  189. package/dist/ui/access-guard.d.ts.map +1 -0
  190. package/dist/ui/access-guard.js +94 -0
  191. package/dist/ui/api.d.ts.map +1 -1
  192. package/dist/ui/api.js +40 -95
  193. package/dist/ui/dev-host-guard.d.ts +28 -0
  194. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  195. package/dist/ui/dev-host-guard.js +67 -0
  196. package/dist/ui/migrations-api.d.ts.map +1 -1
  197. package/dist/ui/migrations-api.js +72 -16
  198. package/dist/ui/open-vscode-api.d.ts +4 -0
  199. package/dist/ui/open-vscode-api.d.ts.map +1 -0
  200. package/dist/ui/open-vscode-api.js +65 -0
  201. package/dist/ui/scaffolding-api.d.ts +18 -0
  202. package/dist/ui/scaffolding-api.d.ts.map +1 -0
  203. package/dist/ui/scaffolding-api.js +111 -0
  204. package/dist/ui/ui-db-presets.d.ts +19 -0
  205. package/dist/ui/ui-db-presets.d.ts.map +1 -0
  206. package/dist/ui/ui-db-presets.js +34 -0
  207. package/dist/ui/ui-request-guard.d.ts +11 -0
  208. package/dist/ui/ui-request-guard.d.ts.map +1 -0
  209. package/dist/ui/ui-request-guard.js +38 -0
  210. package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
  211. package/dist/ui-web/index.html +2 -1
  212. package/package.json +1 -1
  213. package/src/__tests__/env.test.ts +121 -2
  214. package/src/api/__tests__/code-converters.union.test.ts +97 -0
  215. package/src/api/__tests__/guards.test.ts +233 -0
  216. package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
  217. package/src/api/__tests__/sonamu.dev-host-guard.test.ts +130 -0
  218. package/src/api/__tests__/sonamu.guards.test.ts +327 -0
  219. package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
  220. package/src/api/__tests__/websocket-helpers.test.ts +101 -0
  221. package/src/api/caster.ts +7 -0
  222. package/src/api/code-converters.ts +44 -12
  223. package/src/api/config.ts +8 -0
  224. package/src/api/decorators.ts +1 -0
  225. package/src/api/guards.ts +130 -0
  226. package/src/api/sonamu.ts +195 -39
  227. package/src/api/websocket-helpers.ts +11 -6
  228. package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
  229. package/src/auth/__tests__/auth-secret.test.ts +133 -0
  230. package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
  231. package/src/auth/__tests__/base-url.test.ts +117 -0
  232. package/src/auth/__tests__/better-auth-options.test.ts +194 -0
  233. package/src/auth/__tests__/better-auth-request.test.ts +45 -0
  234. package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
  235. package/src/auth/auth-entity-policy.ts +48 -0
  236. package/src/auth/auth-secret.ts +77 -0
  237. package/src/auth/base-url.ts +109 -0
  238. package/src/auth/better-auth-entities.ts +30 -30
  239. package/src/auth/better-auth-options.ts +39 -0
  240. package/src/auth/better-auth-request.ts +28 -1
  241. package/src/auth/plugins/entity-definitions/admin.ts +5 -0
  242. package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
  243. package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
  244. package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
  245. package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
  246. package/src/auth/plugins/entity-definitions/organization.ts +26 -6
  247. package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
  248. package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
  249. package/src/auth/plugins/entity-definitions/sso.ts +20 -15
  250. package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
  251. package/src/auth/verify-email-guard.ts +82 -0
  252. package/src/bin/__tests__/build-web-command.test.ts +24 -0
  253. package/src/bin/build-config.ts +5 -0
  254. package/src/cache/decorator.ts +116 -21
  255. package/src/cache/index.ts +6 -1
  256. package/src/cache/types.ts +18 -0
  257. package/src/cli/plugin-loader.ts +238 -0
  258. package/src/cli/plugin.ts +82 -0
  259. package/src/database/__tests__/db.test.ts +64 -1
  260. package/src/database/__tests__/puri.test.ts +56 -0
  261. package/src/database/db.ts +56 -6
  262. package/src/database/puri.ts +135 -125
  263. package/src/database/puri.types.test-d.ts +12 -0
  264. package/src/database/puri.types.ts +3 -0
  265. package/src/database/sql-expression-brand.ts +9 -0
  266. package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
  267. package/src/dict/en.ts +2 -0
  268. package/src/dict/ko.ts +2 -0
  269. package/src/dict/sonamu-dictionary.ts +298 -38
  270. package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
  271. package/src/entity/entity-codegen-safety.ts +126 -0
  272. package/src/entity/entity-manager.ts +29 -1
  273. package/src/entity/entity.ts +26 -12
  274. package/src/env.ts +52 -1
  275. package/src/filter/utils.ts +19 -7
  276. package/src/index.ts +4 -3
  277. package/src/logger/__tests__/configure.test.ts +51 -1
  278. package/src/logger/configure.ts +14 -1
  279. package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
  280. package/src/migration/__tests__/migrator.test.ts +76 -1
  281. package/src/migration/code-generation.ts +247 -117
  282. package/src/migration/migrator.ts +45 -4
  283. package/src/migration/slack-confirm.ts +19 -5
  284. package/src/ssr/__tests__/preload-guard.test.ts +274 -0
  285. package/src/ssr/errors.ts +11 -0
  286. package/src/ssr/index.ts +1 -0
  287. package/src/ssr/renderer.ts +12 -0
  288. package/src/storage/__tests__/upload-safety.test.ts +179 -0
  289. package/src/storage/base-file.ts +8 -4
  290. package/src/storage/buffered-file.ts +3 -1
  291. package/src/storage/index.ts +9 -0
  292. package/src/storage/upload-safety.ts +155 -0
  293. package/src/stream/__tests__/ws.test.ts +97 -0
  294. package/src/stream/ws.ts +67 -5
  295. package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
  296. package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
  297. package/src/syncer/api-parser.ts +12 -0
  298. package/src/syncer/code-generator.ts +34 -6
  299. package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
  300. package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
  301. package/src/template/__tests__/save-params.template.test.ts +219 -0
  302. package/src/template/implementations/entity.template.ts +53 -48
  303. package/src/template/implementations/generated.template.ts +87 -12
  304. package/src/template/implementations/generated_http.template.ts +5 -0
  305. package/src/template/implementations/init_types.template.ts +4 -22
  306. package/src/template/implementations/model.template.ts +15 -1
  307. package/src/template/implementations/sd.template.ts +4 -5
  308. package/src/template/implementations/view_form.template.ts +13 -5
  309. package/src/template/implementations/view_list.template.ts +12 -3
  310. package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
  311. package/src/testing/dev-test-routes.ts +7 -3
  312. package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
  313. package/src/tooling/index.ts +1 -0
  314. package/src/types/types.ts +22 -1
  315. package/src/ui/__tests__/access-guard.test.ts +217 -0
  316. package/src/ui/__tests__/dev-host-guard.test.ts +161 -0
  317. package/src/ui/__tests__/fixture-api.test.ts +92 -0
  318. package/src/ui/__tests__/migrations-api.test.ts +352 -0
  319. package/src/ui/__tests__/open-vscode.test.ts +151 -0
  320. package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
  321. package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
  322. package/src/ui/__tests__/ui-test-helpers.ts +71 -0
  323. package/src/ui/access-guard.ts +115 -0
  324. package/src/ui/api.ts +65 -198
  325. package/src/ui/dev-host-guard.ts +109 -0
  326. package/src/ui/migrations-api.ts +130 -24
  327. package/src/ui/open-vscode-api.ts +82 -0
  328. package/src/ui/scaffolding-api.ts +177 -0
  329. package/src/ui/ui-db-presets.ts +41 -0
  330. package/src/ui/ui-request-guard.ts +53 -0
@@ -0,0 +1,193 @@
1
+ import { request as httpRequest } from "node:http";
2
+
3
+ import { betterAuth } from "better-auth";
4
+ import { memoryAdapter } from "better-auth/adapters/memory";
5
+ import Fastify, { type FastifyInstance } from "fastify";
6
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
7
+
8
+ import { type SonamuServerOptions } from "../../api/config";
9
+ import { resolveAuthBaseURL } from "../base-url";
10
+ import { createBetterAuthRequest } from "../better-auth-request";
11
+
12
+ // better-auth가 baseURL로 읽는 환경 변수들. 실행 환경 값이 섞이지 않도록 매 테스트 비운다.
13
+ const BETTER_AUTH_URL_ENV_KEYS = [
14
+ "BETTER_AUTH_URL",
15
+ "NEXT_PUBLIC_BETTER_AUTH_URL",
16
+ "PUBLIC_BETTER_AUTH_URL",
17
+ "NUXT_PUBLIC_BETTER_AUTH_URL",
18
+ "NUXT_PUBLIC_AUTH_URL",
19
+ "BASE_URL",
20
+ ];
21
+
22
+ const USER_EMAIL = "victim@example.com";
23
+
24
+ type Harness = { server: FastifyInstance; port: number; resetLinks: string[] };
25
+
26
+ /**
27
+ * Sonamu.init + registerBetterAuth와 같은 방식으로 better-auth를 구성해 실제 포트로 띄운다.
28
+ * (baseURL은 resolveAuthBaseURL로 정하고, 라우트는 createBetterAuthRequest로 변환한다)
29
+ */
30
+ async function startAuthServer(
31
+ serverOptions: Pick<SonamuServerOptions, "auth" | "baseUrl" | "listen">,
32
+ ): Promise<Harness> {
33
+ const resolution = resolveAuthBaseURL(serverOptions, { local: true });
34
+ const resetLinks: string[] = [];
35
+ const auth = betterAuth({
36
+ database: memoryAdapter({ user: [], session: [], account: [], verification: [] }),
37
+ secret: "son-612-test-secret-0123456789abcdef",
38
+ rateLimit: { enabled: false },
39
+ logger: { disabled: true },
40
+ // better-auth는 NODE_ENV=test에서 origin 검사를 끄므로 프로덕션과 같게 켠다
41
+ advanced: { disableOriginCheck: false },
42
+ emailAndPassword: {
43
+ enabled: true,
44
+ sendResetPassword: async ({ url }) => {
45
+ resetLinks.push(url);
46
+ },
47
+ },
48
+ ...serverOptions.auth,
49
+ baseURL: resolution.baseURL,
50
+ });
51
+ await auth.api.signUpEmail({
52
+ body: { email: USER_EMAIL, password: "Passw0rd!son612", name: "victim" },
53
+ });
54
+
55
+ const server = Fastify();
56
+ server.route({
57
+ method: ["GET", "POST"],
58
+ url: "/api/auth/*",
59
+ handler: async (request, reply) => {
60
+ const response = await auth.handler(
61
+ createBetterAuthRequest(request, undefined, resolution.requestBaseURL),
62
+ );
63
+ reply.status(response.status);
64
+ response.headers.forEach((value, key) => {
65
+ reply.header(key, value);
66
+ });
67
+ return reply.send(response.body ? await response.text() : null);
68
+ },
69
+ });
70
+ await server.listen({ port: 0, host: "127.0.0.1" });
71
+ // Fastify의 addresses()는 TCP listen 주소만 AddressInfo로 돌려준다.
72
+ const address = server.addresses().at(0);
73
+ if (address === undefined) {
74
+ await server.close();
75
+ throw new Error("listen한 TCP 주소를 얻지 못했습니다");
76
+ }
77
+ return { server, port: address.port, resetLinks };
78
+ }
79
+
80
+ /** 비밀번호 리셋 요청 본문 */
81
+ type PasswordResetBody = { email: string; redirectTo: string };
82
+
83
+ /** Host 헤더와 request-target을 임의로 지정해 원시 HTTP 요청을 보낸다 */
84
+ function rawPost(
85
+ port: number,
86
+ target: string,
87
+ host: string,
88
+ body: PasswordResetBody,
89
+ ): Promise<{ status: number; text: string }> {
90
+ return new Promise((resolve, reject) => {
91
+ const payload = JSON.stringify(body);
92
+ const req = httpRequest(
93
+ {
94
+ host: "127.0.0.1",
95
+ port,
96
+ method: "POST",
97
+ path: target,
98
+ headers: {
99
+ host,
100
+ "content-type": "application/json",
101
+ "content-length": Buffer.byteLength(payload),
102
+ },
103
+ },
104
+ (res) => {
105
+ let text = "";
106
+ res.setEncoding("utf8");
107
+ res.on("data", (chunk: string) => {
108
+ text += chunk;
109
+ });
110
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, text }));
111
+ },
112
+ );
113
+ req.on("error", reject);
114
+ req.end(payload);
115
+ });
116
+ }
117
+
118
+ describe("better-auth 비밀번호 리셋 링크 Host 헤더 포이즈닝 방지 (SON-612)", () => {
119
+ let harness: Harness | undefined;
120
+
121
+ beforeEach(() => {
122
+ for (const key of BETTER_AUTH_URL_ENV_KEYS) vi.stubEnv(key, "");
123
+ });
124
+
125
+ afterEach(async () => {
126
+ await harness?.server.close();
127
+ harness = undefined;
128
+ vi.unstubAllEnvs();
129
+ });
130
+
131
+ test("auth.baseURL 없이 server.baseUrl만 있을 때 Host: attacker.example로 요청해도 링크는 server.baseUrl을 가리킨다", async () => {
132
+ harness = await startAuthServer({ baseUrl: "https://app.example.com", auth: {} });
133
+
134
+ const res = await rawPost(
135
+ harness.port,
136
+ "/api/auth/request-password-reset",
137
+ "attacker.example",
138
+ {
139
+ email: USER_EMAIL,
140
+ redirectTo: "/reset",
141
+ },
142
+ );
143
+
144
+ expect(res.status).toBe(200);
145
+ expect(harness.resetLinks).toHaveLength(1);
146
+ expect(new URL(harness.resetLinks[0]).origin).toBe("https://app.example.com");
147
+ });
148
+
149
+ test("절대형 request-target(http://abs-attacker.example/...)으로 요청해도 링크 도메인이 바뀌지 않는다", async () => {
150
+ harness = await startAuthServer({ baseUrl: "https://app.example.com", auth: {} });
151
+
152
+ const res = await rawPost(
153
+ harness.port,
154
+ "http://abs-attacker.example/api/auth/request-password-reset",
155
+ `127.0.0.1:${harness.port}`,
156
+ { email: USER_EMAIL, redirectTo: "/reset" },
157
+ );
158
+
159
+ expect(res.status).toBe(200);
160
+ expect(harness.resetLinks).toHaveLength(1);
161
+ expect(new URL(harness.resetLinks[0]).origin).toBe("https://app.example.com");
162
+ });
163
+
164
+ test("로컬 환경에서 아무 설정이 없어도 Host 대신 listen 주소로 링크를 만든다", async () => {
165
+ harness = await startAuthServer({ listen: { host: "127.0.0.1", port: 4000 }, auth: {} });
166
+
167
+ await rawPost(harness.port, "/api/auth/request-password-reset", "attacker.example", {
168
+ email: USER_EMAIL,
169
+ redirectTo: "/reset",
170
+ });
171
+
172
+ expect(harness.resetLinks).toHaveLength(1);
173
+ expect(new URL(harness.resetLinks[0]).origin).toBe("http://127.0.0.1:4000");
174
+ });
175
+
176
+ test("Host 헤더의 도메인이 trustedOrigins에 들어가지 않아 외부 redirectTo를 거부한다", async () => {
177
+ harness = await startAuthServer({ baseUrl: "https://app.example.com", auth: {} });
178
+
179
+ const res = await rawPost(
180
+ harness.port,
181
+ "/api/auth/request-password-reset",
182
+ "attacker.example",
183
+ {
184
+ email: USER_EMAIL,
185
+ redirectTo: "http://attacker.example/steal",
186
+ },
187
+ );
188
+
189
+ expect(res.status).toBe(403);
190
+ expect(res.text).toContain("INVALID_REDIRECT_URL");
191
+ expect(harness.resetLinks).toHaveLength(0);
192
+ });
193
+ });
@@ -0,0 +1,117 @@
1
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
+
3
+ import { resolveAuthBaseURL } from "../base-url";
4
+
5
+ // better-auth가 baseURL로 읽는 환경 변수들. 실행 환경 값이 섞이지 않도록 매 테스트 비운다.
6
+ const BETTER_AUTH_URL_ENV_KEYS = [
7
+ "BETTER_AUTH_URL",
8
+ "NEXT_PUBLIC_BETTER_AUTH_URL",
9
+ "PUBLIC_BETTER_AUTH_URL",
10
+ "NUXT_PUBLIC_BETTER_AUTH_URL",
11
+ "NUXT_PUBLIC_AUTH_URL",
12
+ "BASE_URL",
13
+ ];
14
+
15
+ beforeEach(() => {
16
+ for (const key of BETTER_AUTH_URL_ENV_KEYS) vi.stubEnv(key, "");
17
+ });
18
+
19
+ afterEach(() => {
20
+ vi.unstubAllEnvs();
21
+ });
22
+
23
+ describe("resolveAuthBaseURL — Host 헤더 대신 설정값으로 baseURL 결정 (SON-612)", () => {
24
+ test("auth.baseURL이 있으면 다른 설정보다 우선한다", () => {
25
+ vi.stubEnv("BETTER_AUTH_URL", "https://env.example.com");
26
+ const result = resolveAuthBaseURL(
27
+ { auth: { baseURL: "https://auth.example.com" }, baseUrl: "https://server.example.com" },
28
+ { local: false },
29
+ );
30
+ expect(result).toEqual({
31
+ baseURL: "https://auth.example.com",
32
+ requestBaseURL: "https://auth.example.com",
33
+ source: "auth",
34
+ });
35
+ });
36
+
37
+ test("동적 baseURL 설정(allowedHosts)은 그대로 넘기고 요청 origin은 고정하지 않는다", () => {
38
+ const dynamic = { allowedHosts: ["app.example.com"], protocol: "https" as const };
39
+ const result = resolveAuthBaseURL({ auth: { baseURL: dynamic } }, { local: false });
40
+ expect(result).toEqual({ baseURL: dynamic, requestBaseURL: undefined, source: "auth" });
41
+ });
42
+
43
+ test("auth.baseURL이 없으면 better-auth 환경 변수를 server.baseUrl보다 먼저 쓴다", () => {
44
+ vi.stubEnv("BETTER_AUTH_URL", "https://env.example.com");
45
+ const result = resolveAuthBaseURL(
46
+ { auth: {}, baseUrl: "https://server.example.com" },
47
+ { local: false },
48
+ );
49
+ expect(result).toEqual({
50
+ baseURL: "https://env.example.com/api/auth",
51
+ requestBaseURL: "https://env.example.com/api/auth",
52
+ source: "env",
53
+ });
54
+ });
55
+
56
+ test("잘못된 환경 변수 값은 init을 깨뜨리지 않고 다음 설정으로 넘어간다", () => {
57
+ vi.stubEnv("BETTER_AUTH_URL", "not a url");
58
+ const result = resolveAuthBaseURL(
59
+ { auth: {}, baseUrl: "https://server.example.com" },
60
+ { local: false },
61
+ );
62
+ expect(result.source).toBe("server");
63
+ });
64
+
65
+ test("auth.baseURL과 환경 변수가 없으면 server.baseUrl의 origin에 basePath를 붙인다", () => {
66
+ const result = resolveAuthBaseURL(
67
+ { auth: {}, baseUrl: "https://server.example.com/ignored/path/" },
68
+ { local: false },
69
+ );
70
+ expect(result).toEqual({
71
+ baseURL: "https://server.example.com/api/auth",
72
+ requestBaseURL: "https://server.example.com/api/auth",
73
+ source: "server",
74
+ });
75
+ });
76
+
77
+ test("auth.basePath를 바꿨으면 그 경로를 붙인다", () => {
78
+ const result = resolveAuthBaseURL(
79
+ { auth: { basePath: "/auth" }, baseUrl: "https://server.example.com" },
80
+ { local: false },
81
+ );
82
+ expect(result.baseURL).toBe("https://server.example.com/auth");
83
+ });
84
+
85
+ test("로컬 환경에서 아무 설정도 없으면 listen 주소를 쓴다", () => {
86
+ const result = resolveAuthBaseURL(
87
+ { auth: {}, listen: { host: "127.0.0.1", port: 4000 } },
88
+ { local: true },
89
+ );
90
+ expect(result).toEqual({
91
+ baseURL: "http://127.0.0.1:4000/api/auth",
92
+ requestBaseURL: "http://127.0.0.1:4000/api/auth",
93
+ source: "listen",
94
+ });
95
+ });
96
+
97
+ test("로컬 환경에서 listen도 없으면 boot()와 같은 localhost:3000을 쓴다", () => {
98
+ const result = resolveAuthBaseURL({ auth: {} }, { local: true });
99
+ expect(result.baseURL).toBe("http://localhost:3000/api/auth");
100
+ });
101
+
102
+ test("원격 환경에서 아무 설정도 없으면 Host로 대체하지 않고 none을 돌려준다", () => {
103
+ const result = resolveAuthBaseURL(
104
+ { auth: {}, listen: { host: "0.0.0.0", port: 4000 } },
105
+ { local: false },
106
+ );
107
+ expect(result).toEqual({ baseURL: undefined, requestBaseURL: undefined, source: "none" });
108
+ });
109
+
110
+ test("원격 환경에서 server.baseUrl이 절대 http(s) URL이 아니면 쓰지 않는다", () => {
111
+ const result = resolveAuthBaseURL(
112
+ { auth: {}, baseUrl: "server.example.com:3000" },
113
+ { local: false },
114
+ );
115
+ expect(result.source).toBe("none");
116
+ });
117
+ });
@@ -0,0 +1,194 @@
1
+ import { betterAuth } from "better-auth";
2
+ import { memoryAdapter } from "better-auth/adapters/memory";
3
+ import { describe, expect, test } from "vitest";
4
+
5
+ import { buildBetterAuthOptions } from "../better-auth-options";
6
+ import { passkey, twoFactor } from "../plugins/wrappers";
7
+
8
+ const BASE_URL = "http://localhost:3000";
9
+
10
+ type StoredRow = { role?: string; email?: string };
11
+
12
+ // better-auth memory adapter가 테이블 이름(modelName)별로 행을 저장하는 저장소
13
+ type MemoryAuthTables = {
14
+ users: StoredRow[];
15
+ sessions: StoredRow[];
16
+ accounts: StoredRow[];
17
+ verifications: StoredRow[];
18
+ };
19
+
20
+ type AuthRequestBody = {
21
+ email?: string;
22
+ password?: string;
23
+ name?: string;
24
+ role?: string;
25
+ created_at?: string;
26
+ };
27
+
28
+ type AdditionalFields = NonNullable<
29
+ NonNullable<Parameters<typeof buildBetterAuthOptions>[0]["user"]>["additionalFields"]
30
+ >;
31
+
32
+ // 수정 전 스캐폴드 auth 예시의 additionalFields (input 미지정)
33
+ const LEGACY_SCAFFOLD_FIELDS: AdditionalFields = {
34
+ role: { type: "string", sonamuType: "UserRole" },
35
+ created_at: { type: "date" },
36
+ };
37
+
38
+ // create-sonamu 스캐폴드의 주석 처리된 auth 예시를 켠 설정 (admin 플러그인 없음)
39
+ function createScaffoldAuth(additionalFields: AdditionalFields = LEGACY_SCAFFOLD_FIELDS) {
40
+ const db: MemoryAuthTables = {
41
+ users: [],
42
+ sessions: [],
43
+ accounts: [],
44
+ verifications: [],
45
+ };
46
+ const auth = betterAuth({
47
+ database: memoryAdapter(db),
48
+ ...buildBetterAuthOptions({
49
+ appName: "Sonamu Project",
50
+ plugins: [twoFactor(), passkey()],
51
+ emailAndPassword: { enabled: true },
52
+ baseURL: BASE_URL,
53
+ secret: "son-609-test-secret-son-609-test-secret",
54
+ trustedOrigins: [BASE_URL],
55
+ user: {
56
+ fields: {
57
+ name: "username",
58
+ emailVerified: "is_verified",
59
+ },
60
+ additionalFields,
61
+ },
62
+ }),
63
+ });
64
+ return { auth, db };
65
+ }
66
+
67
+ function post(
68
+ auth: ReturnType<typeof createScaffoldAuth>["auth"],
69
+ path: string,
70
+ body: AuthRequestBody,
71
+ cookie?: string,
72
+ ) {
73
+ const headers = new Headers({ "content-type": "application/json", origin: BASE_URL });
74
+ if (cookie) {
75
+ headers.set("cookie", cookie);
76
+ }
77
+ return auth.handler(
78
+ new Request(`${BASE_URL}/api/auth${path}`, {
79
+ method: "POST",
80
+ headers,
81
+ body: JSON.stringify(body),
82
+ }),
83
+ );
84
+ }
85
+
86
+ describe("buildBetterAuthOptions", () => {
87
+ test("input을 지정하지 않은 user.additionalFields는 input: false가 된다", () => {
88
+ const options = buildBetterAuthOptions({
89
+ user: {
90
+ additionalFields: {
91
+ role: { type: "string", sonamuType: "UserRole" },
92
+ created_at: { type: "date" },
93
+ },
94
+ },
95
+ });
96
+
97
+ expect(options.user?.additionalFields).toEqual({
98
+ role: { type: "string", sonamuType: "UserRole", input: false },
99
+ created_at: { type: "date", input: false },
100
+ });
101
+ });
102
+
103
+ test("명시한 input 값은 그대로 둔다", () => {
104
+ const options = buildBetterAuthOptions({
105
+ user: {
106
+ additionalFields: {
107
+ nickname: { type: "string", input: true },
108
+ role: { type: "string", input: false, defaultValue: "user" },
109
+ },
110
+ },
111
+ });
112
+
113
+ expect(options.user?.additionalFields).toEqual({
114
+ nickname: { type: "string", input: true },
115
+ role: { type: "string", input: false, defaultValue: "user" },
116
+ });
117
+ });
118
+
119
+ test("사용자 설정 객체를 바꾸지 않고 기본 필드 매핑을 합친다", () => {
120
+ const role = { type: "string" as const };
121
+ const authConfig = { user: { additionalFields: { role } } };
122
+
123
+ const options = buildBetterAuthOptions(authConfig);
124
+
125
+ expect(role).toEqual({ type: "string" });
126
+ expect(options.user?.modelName).toBe("users");
127
+ expect(options.session?.modelName).toBe("sessions");
128
+ });
129
+
130
+ test("additionalFields가 없으면 기본 필드 매핑만 합친다", () => {
131
+ const options = buildBetterAuthOptions({ appName: "Sonamu" });
132
+
133
+ expect(options.appName).toBe("Sonamu");
134
+ expect(options.user?.additionalFields).toBeUndefined();
135
+ expect(options.user?.fields?.emailVerified).toBe("email_verified");
136
+ });
137
+ });
138
+
139
+ describe("스캐폴드 auth 예시의 role 자가 승격 방지 (SON-609)", () => {
140
+ test("sign-up 바디의 role과 created_at을 저장하지 않는다", async () => {
141
+ const { auth, db } = createScaffoldAuth();
142
+
143
+ const response = await post(auth, "/sign-up/email", {
144
+ email: "self-admin@son609.test",
145
+ password: "Passw0rd!son609",
146
+ name: "self-admin",
147
+ role: "admin",
148
+ created_at: "1999-01-01T00:00:00Z",
149
+ });
150
+
151
+ expect(response.status).toBe(400);
152
+ expect(await response.json()).toMatchObject({ code: "FIELD_NOT_ALLOWED" });
153
+ expect(db.users).toEqual([]);
154
+ });
155
+
156
+ test("현재 스캐폴드 예시(input: false, defaultValue)는 sign-up 바디의 role을 무시하고 기본값을 저장한다", async () => {
157
+ const { auth, db } = createScaffoldAuth({
158
+ role: { type: "string", sonamuType: "UserRole", input: false, defaultValue: "user" },
159
+ created_at: { type: "date", input: false },
160
+ });
161
+
162
+ const response = await post(auth, "/sign-up/email", {
163
+ email: "self-admin@son609.test",
164
+ password: "Passw0rd!son609",
165
+ name: "self-admin",
166
+ role: "admin",
167
+ });
168
+
169
+ expect(response.status).toBe(200);
170
+ expect(db.users).toHaveLength(1);
171
+ expect(db.users[0]?.role).toBe("user");
172
+ });
173
+
174
+ test("role 없이 가입한 사용자는 update-user로 role을 바꿀 수 없다", async () => {
175
+ const { auth, db } = createScaffoldAuth();
176
+ const signUp = await post(auth, "/sign-up/email", {
177
+ email: "normal@son609.test",
178
+ password: "Passw0rd!son609",
179
+ name: "normal",
180
+ });
181
+ expect(signUp.status).toBe(200);
182
+ const cookie = signUp.headers
183
+ .getSetCookie()
184
+ .map((value) => value.split(";")[0])
185
+ .join("; ");
186
+
187
+ const update = await post(auth, "/update-user", { role: "admin" }, cookie);
188
+
189
+ expect(update.status).toBe(400);
190
+ expect(await update.json()).toMatchObject({ code: "FIELD_NOT_ALLOWED" });
191
+ expect(db.users).toHaveLength(1);
192
+ expect(db.users[0]?.role).toBeUndefined();
193
+ });
194
+ });
@@ -208,3 +208,48 @@ describe("createBetterAuthRequest — 기존 동작 회귀 보장", () => {
208
208
  expect(params.get("state")).toBe("abc");
209
209
  });
210
210
  });
211
+
212
+ describe("createBetterAuthRequest — baseURL로 요청 origin 고정 (SON-612)", () => {
213
+ const baseURL = "https://app.example.com/api/auth";
214
+
215
+ test("Host 헤더를 바꿔도 요청 URL의 origin은 설정된 baseURL을 따른다", () => {
216
+ const request = createMockFastifyRequest({
217
+ url: "/api/auth/request-password-reset?foo=bar",
218
+ headers: { host: "attacker.example" },
219
+ });
220
+
221
+ const result = createBetterAuthRequest(request, undefined, baseURL);
222
+
223
+ expect(result.url).toBe("https://app.example.com/api/auth/request-password-reset?foo=bar");
224
+ });
225
+
226
+ test("절대형 request-target의 스킴·호스트는 버리고 경로·쿼리만 쓴다", () => {
227
+ const request = createMockFastifyRequest({
228
+ url: "http://abs-attacker.example/api/auth/request-password-reset?x=1",
229
+ });
230
+
231
+ const result = createBetterAuthRequest(request, undefined, baseURL);
232
+
233
+ expect(result.url).toBe("https://app.example.com/api/auth/request-password-reset?x=1");
234
+ });
235
+
236
+ test("'//'로 시작하는 경로도 호스트로 해석하지 않는다", () => {
237
+ const request = createMockFastifyRequest({
238
+ url: "http://abs-attacker.example//evil.example/x",
239
+ });
240
+
241
+ const result = createBetterAuthRequest(request, undefined, baseURL);
242
+
243
+ expect(new URL(result.url).host).toBe("app.example.com");
244
+ expect(new URL(result.url).pathname).toBe("//evil.example/x");
245
+ });
246
+
247
+ test("Host 헤더가 없어도(HTTP/2 등) 설정된 origin으로 요청을 만든다", () => {
248
+ const request = createMockFastifyRequest({ url: "/api/auth/session" });
249
+ delete request.headers.host;
250
+
251
+ const result = createBetterAuthRequest(request, undefined, baseURL);
252
+
253
+ expect(result.url).toBe("https://app.example.com/api/auth/session");
254
+ });
255
+ });