sonamu 0.13.11 → 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 (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 +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/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 +28 -0
  193. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  194. package/dist/ui/dev-host-guard.js +67 -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 +130 -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 +8 -0
  223. package/src/api/decorators.ts +1 -0
  224. package/src/api/guards.ts +130 -0
  225. package/src/api/sonamu.ts +195 -39
  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 +161 -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 +109 -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
@@ -0,0 +1,130 @@
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { type FastifyInstance } from "fastify";
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+
8
+ import { setSDConfig } from "../../dict/sd";
9
+ import { DevVitestManager } from "../../testing/dev-vitest-manager";
10
+ import { type SonamuFastifyConfig } from "../../types/types";
11
+ import { getSonamuUIToken, SONAMU_UI_TOKEN_HEADER } from "../../ui/access-guard";
12
+ import { type SonamuConfig, type SonamuServerOptions } from "../config";
13
+ import { Sonamu } from "../sonamu";
14
+
15
+ const apiConfig: SonamuFastifyConfig = {
16
+ contextProvider: (defaultContext) => defaultContext,
17
+ guardHandler: () => undefined,
18
+ };
19
+ // 허용 Host 요청이 SON-618 접근 토큰 검사까지 통과해야 Host 검사만의 허용 여부를 확인할 수 있습니다.
20
+ const UI_TOKEN_HEADERS = { [SONAMU_UI_TOKEN_HEADER]: getSonamuUIToken() };
21
+
22
+ describe("로컬 서버의 Sonamu UI·dev 라우트 Host 검사", () => {
23
+ const originalSnapshot = Sonamu.captureTestingSnapshot();
24
+ const originalIsInitialized = Sonamu.isInitialized;
25
+ const originalForTesting = Sonamu.forTesting;
26
+ const originalServer = Sonamu.server;
27
+ const originalDevVitestManager = Sonamu.devVitestManager;
28
+ const originalNodeEnv = process.env.NODE_ENV;
29
+ const servers: FastifyInstance[] = [];
30
+ const tempRoots: string[] = [];
31
+
32
+ beforeEach(async () => {
33
+ process.env.NODE_ENV = "development";
34
+ Sonamu.isInitialized = true;
35
+ Sonamu.forTesting = false;
36
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), "sonamu-dev-host-guard-"));
37
+ tempRoots.push(tempRoot);
38
+ Reflect.set(Sonamu, "apiRootPathValue", path.join(tempRoot, "api"));
39
+ Reflect.set(Sonamu, "syncerValue", { apis: [], models: {}, types: {} });
40
+ // DevRunner 라우트가 실제 vitest를 띄우지 않도록 시작만 건너뜁니다.
41
+ vi.spyOn(DevVitestManager.prototype, "start").mockResolvedValue(undefined);
42
+ });
43
+
44
+ afterEach(async () => {
45
+ try {
46
+ await Promise.allSettled(servers.splice(0).map(async (server) => await server.close()));
47
+ } finally {
48
+ Sonamu.restoreTestingSnapshot(originalSnapshot);
49
+ Reflect.deleteProperty(Sonamu, "boot");
50
+ Sonamu.isInitialized = originalIsInitialized;
51
+ Sonamu.forTesting = originalForTesting;
52
+ Sonamu.server = originalServer;
53
+ Sonamu.devVitestManager = originalDevVitestManager;
54
+ if (originalNodeEnv === undefined) {
55
+ delete process.env.NODE_ENV;
56
+ } else {
57
+ process.env.NODE_ENV = originalNodeEnv;
58
+ }
59
+ await Promise.all(
60
+ tempRoots.splice(0).map(async (tempRoot) => {
61
+ await rm(tempRoot, { recursive: true, force: true });
62
+ }),
63
+ );
64
+ vi.restoreAllMocks();
65
+ }
66
+ });
67
+
68
+ async function createDevServer(
69
+ server: SonamuServerOptions = { apiConfig },
70
+ ): Promise<FastifyInstance> {
71
+ const config: SonamuConfig = {
72
+ api: { dir: "src", route: { prefix: "/api" } },
73
+ i18n: { defaultLocale: "ko", supportedLocales: ["ko"] },
74
+ sync: { targets: [] },
75
+ validation: { zodCompiler: false },
76
+ database: {},
77
+ logging: false,
78
+ test: { devRunner: { enabled: true } },
79
+ server,
80
+ };
81
+ Reflect.set(Sonamu, "configValue", config);
82
+ setSDConfig(config.i18n);
83
+ // 프로세스 시그널을 등록하고 포트를 여는 private boot만 인스턴스 속성으로 가립니다(afterEach에서 제거).
84
+ Reflect.set(Sonamu, "boot", async () => undefined);
85
+
86
+ const created = await Sonamu.createServer({ enableSync: false, doSilent: true });
87
+ servers.push(created);
88
+ await created.ready();
89
+ return created;
90
+ }
91
+
92
+ it.each(["/sonamu-ui/api/sonamu/config", "/sonamu-ui/", "/__test__/status"])(
93
+ "Host: attacker.example 로 온 %s 요청은 403으로 거부한다",
94
+ async (url) => {
95
+ const server = await createDevServer();
96
+
97
+ const response = await server.inject({ url, headers: { host: "attacker.example:34900" } });
98
+
99
+ expect(response.statusCode).toBe(403);
100
+ },
101
+ );
102
+
103
+ it.each(["/sonamu-ui/api/sonamu/config", "/__test__/status"])(
104
+ "Host: localhost 로 온 %s 요청은 그대로 처리한다",
105
+ async (url) => {
106
+ const server = await createDevServer();
107
+
108
+ const response = await server.inject({
109
+ url,
110
+ headers: { host: "localhost:34900", ...UI_TOKEN_HEADERS },
111
+ });
112
+
113
+ expect(response.statusCode).toBe(200);
114
+ },
115
+ );
116
+
117
+ it("listen.host로 설정한 호스트 이름은 허용한다", async () => {
118
+ const server = await createDevServer({
119
+ apiConfig,
120
+ listen: { port: 34900, host: "dev.example.test" },
121
+ });
122
+
123
+ const response = await server.inject({
124
+ url: "/sonamu-ui/api/sonamu/config",
125
+ headers: { host: "dev.example.test:34900", ...UI_TOKEN_HEADERS },
126
+ });
127
+
128
+ expect(response.statusCode).toBe(200);
129
+ });
130
+ });
@@ -0,0 +1,327 @@
1
+ import fastifyWebsocket from "@fastify/websocket";
2
+ import Fastify, { type FastifyInstance } from "fastify";
3
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { type WebSocket } from "ws";
5
+ import { z } from "zod";
6
+
7
+ import { SD, setSDConfig } from "../../dict/sd";
8
+ import { UnauthorizedException } from "../../exceptions/so-exceptions";
9
+ import { WebSocketRuntime } from "../../stream/ws";
10
+ import { type SonamuFastifyConfig } from "../../types/types";
11
+ import { type WebSocketContext } from "../context";
12
+ import { type ExtendedApi, type GuardKey } from "../decorators";
13
+ import { Sonamu } from "../sonamu";
14
+
15
+ type GuardHandler = SonamuFastifyConfig["guardHandler"];
16
+ type ApiHandler = ReturnType<typeof Sonamu.createApiHandler>;
17
+ type RuntimeWebSocketConnection = Awaited<ReturnType<WebSocketRuntime["registerConnection"]>>;
18
+
19
+ function createHttpApi(guards: GuardKey[]): ExtendedApi {
20
+ return {
21
+ modelName: "AdminModel",
22
+ methodName: "secret",
23
+ path: "/admin/secret",
24
+ options: {
25
+ httpMethod: "GET",
26
+ guards,
27
+ },
28
+ typeParameters: [],
29
+ parameters: [],
30
+ returnType: "unknown",
31
+ };
32
+ }
33
+
34
+ function createConfig(guardHandler: GuardHandler): SonamuFastifyConfig {
35
+ return {
36
+ contextProvider: (defaultContext) => defaultContext,
37
+ guardHandler,
38
+ };
39
+ }
40
+
41
+ // 테스트가 만든 fastify 인스턴스와 WebSocket 클라이언트를 afterEach에서 정리한다
42
+ const servers: FastifyInstance[] = [];
43
+ const clients: WebSocket[] = [];
44
+
45
+ async function cleanupConnections(): Promise<void> {
46
+ for (const client of clients.splice(0)) {
47
+ client.terminate();
48
+ }
49
+ await Promise.all(servers.splice(0).map((server) => server.close()));
50
+ }
51
+
52
+ /**
53
+ * 실제 fastify 서버에 핸들러를 올리고 inject로 요청해, 실제 FastifyRequest/FastifyReply로 실행된 핸들러의 결과 Promise를 돌려줍니다.
54
+ * Promise를 그대로 반환하면 async 함수가 풀어버리므로 객체로 감싸서 반환합니다.
55
+ */
56
+ async function invokeWithRealRequest(
57
+ handler: ApiHandler,
58
+ ): Promise<{ outcome: ReturnType<ApiHandler> }> {
59
+ const server = Fastify();
60
+ servers.push(server);
61
+ const outcomes: ReturnType<ApiHandler>[] = [];
62
+ server.get("/admin/secret", (request, reply) => {
63
+ const outcome = handler(request, reply);
64
+ outcomes.push(outcome);
65
+ return outcome;
66
+ });
67
+
68
+ await server.inject({ method: "GET", url: "/admin/secret" });
69
+
70
+ const outcome = outcomes[0];
71
+ if (outcome === undefined) {
72
+ throw new Error("API 핸들러가 호출되지 않았습니다");
73
+ }
74
+ return { outcome };
75
+ }
76
+
77
+ // 마이크로태스크와 setImmediate를 모두 비워 버려진 Promise rejection이 드러나게 한다
78
+ async function flushAsync(): Promise<void> {
79
+ await new Promise<void>((resolve) => setImmediate(resolve));
80
+ }
81
+
82
+ // false 거부 시 SD 사전 메시지를 쓰므로 Sonamu.init이 하는 i18n 설정을 테스트에서 대신한다
83
+ beforeAll(() => {
84
+ setSDConfig({ defaultLocale: "ko", supportedLocales: ["ko", "en"] });
85
+ });
86
+
87
+ describe("HTTP API guardHandler 실행", () => {
88
+ const originalState = Sonamu.captureTestingSnapshot();
89
+ const unhandledRejections: unknown[] = [];
90
+ const onUnhandledRejection: NodeJS.UnhandledRejectionListener = (reason) => {
91
+ unhandledRejections.push(reason);
92
+ };
93
+ let invokeModelMethod: ReturnType<typeof vi.spyOn>;
94
+
95
+ beforeEach(() => {
96
+ unhandledRejections.length = 0;
97
+ process.on("unhandledRejection", onUnhandledRejection);
98
+ Reflect.set(Sonamu, "httpValidators", new WeakMap());
99
+ Reflect.set(Sonamu, "pendingHttpValidators", new WeakMap());
100
+ Reflect.set(Sonamu, "aotHttpValidatorRegistry", undefined);
101
+ Reflect.set(Sonamu, "configValue", {
102
+ sync: { targets: [] },
103
+ validation: { zodCompiler: false },
104
+ // 실제 createContext가 locale을 정할 때 읽는 i18n 설정
105
+ i18n: { defaultLocale: "ko", supportedLocales: ["ko", "en"] },
106
+ });
107
+ Reflect.set(Sonamu, "syncerValue", { types: {} });
108
+ invokeModelMethod = vi
109
+ .spyOn(Sonamu, "invokeModelMethod")
110
+ .mockImplementation(async () => "top-secret");
111
+ });
112
+
113
+ afterEach(async () => {
114
+ process.off("unhandledRejection", onUnhandledRejection);
115
+ await cleanupConnections();
116
+ Sonamu.restoreTestingSnapshot(originalState);
117
+ vi.restoreAllMocks();
118
+ });
119
+
120
+ it("async guardHandler가 throw하면 요청을 거부하고 모델 메서드를 호출하지 않는다", async () => {
121
+ const guardError = new UnauthorizedException(SD("error.unauthorized"));
122
+ const handler = Sonamu.createApiHandler(
123
+ createHttpApi(["admin"]),
124
+ createConfig(async () => {
125
+ await flushAsync();
126
+ throw guardError;
127
+ }),
128
+ );
129
+
130
+ const { outcome } = await invokeWithRealRequest(handler);
131
+ await expect(outcome).rejects.toBe(guardError);
132
+ await flushAsync();
133
+
134
+ expect(invokeModelMethod).not.toHaveBeenCalled();
135
+ expect(unhandledRejections).toEqual([]);
136
+ });
137
+
138
+ it("guardHandler가 false를 반환하면 401로 요청을 거부한다", async () => {
139
+ const handler = Sonamu.createApiHandler(
140
+ createHttpApi(["admin"]),
141
+ createConfig(() => false),
142
+ );
143
+
144
+ const { outcome } = await invokeWithRealRequest(handler);
145
+ await expect(outcome).rejects.toMatchObject({
146
+ statusCode: 401,
147
+ });
148
+ expect(invokeModelMethod).not.toHaveBeenCalled();
149
+ });
150
+
151
+ it("async guardHandler가 false로 resolve되면 401로 요청을 거부한다", async () => {
152
+ const handler = Sonamu.createApiHandler(
153
+ createHttpApi(["admin"]),
154
+ createConfig(async () => false),
155
+ );
156
+
157
+ const { outcome } = await invokeWithRealRequest(handler);
158
+ await expect(outcome).rejects.toBeInstanceOf(UnauthorizedException);
159
+ expect(invokeModelMethod).not.toHaveBeenCalled();
160
+ });
161
+
162
+ it("동기 guardHandler의 throw는 기존처럼 요청을 거부한다", async () => {
163
+ const guardError = new Error("Authentication required");
164
+ const handler = Sonamu.createApiHandler(
165
+ createHttpApi(["user"]),
166
+ createConfig(() => {
167
+ throw guardError;
168
+ }),
169
+ );
170
+
171
+ const { outcome } = await invokeWithRealRequest(handler);
172
+ await expect(outcome).rejects.toBe(guardError);
173
+ expect(invokeModelMethod).not.toHaveBeenCalled();
174
+ });
175
+
176
+ it.each([
177
+ ["undefined 반환", () => undefined],
178
+ ["true 반환", () => true],
179
+ ["async undefined", async () => undefined],
180
+ ["async true", async () => true],
181
+ ] satisfies [string, GuardHandler][])(
182
+ "guardHandler가 %s이면 요청을 통과시킨다",
183
+ async (_label, guardHandler) => {
184
+ const handler = Sonamu.createApiHandler(createHttpApi(["user"]), createConfig(guardHandler));
185
+
186
+ const { outcome } = await invokeWithRealRequest(handler);
187
+ await expect(outcome).resolves.toBe("top-secret");
188
+ expect(invokeModelMethod).toHaveBeenCalledTimes(1);
189
+ },
190
+ );
191
+
192
+ it("여러 guard를 순서대로 기다리고 첫 거부에서 멈춘다", async () => {
193
+ const calls: string[] = [];
194
+ const handler = Sonamu.createApiHandler(
195
+ createHttpApi(["user", "admin", "query"]),
196
+ createConfig(async (guard) => {
197
+ calls.push(`start:${guard}`);
198
+ await flushAsync();
199
+ calls.push(`end:${guard}`);
200
+ return guard !== "admin";
201
+ }),
202
+ );
203
+
204
+ const { outcome } = await invokeWithRealRequest(handler);
205
+ await expect(outcome).rejects.toMatchObject({
206
+ statusCode: 401,
207
+ });
208
+ expect(calls).toEqual(["start:user", "end:user", "start:admin", "end:admin"]);
209
+ expect(invokeModelMethod).not.toHaveBeenCalled();
210
+ });
211
+ });
212
+
213
+ describe("WebSocket guardHandler 실행", () => {
214
+ const originalState = Sonamu.captureTestingSnapshot();
215
+
216
+ afterEach(async () => {
217
+ await cleanupConnections();
218
+ Sonamu.restoreTestingSnapshot(originalState);
219
+ vi.restoreAllMocks();
220
+ });
221
+
222
+ async function runWebSocketHandler(guardHandler: GuardHandler) {
223
+ const closeCalls: [number | undefined, string | undefined][] = [];
224
+ const rawWs: RuntimeWebSocketConnection = {
225
+ id: "ws-guard",
226
+ namespace: "chat",
227
+ transport: "ws" as const,
228
+ closed: false,
229
+ publishUntyped() {},
230
+ close(code, reason) {
231
+ closeCalls.push([code, reason]);
232
+ },
233
+ onClose() {},
234
+ onMessage() {},
235
+ publish() {},
236
+ waitForClose() {
237
+ return Promise.resolve();
238
+ },
239
+ join() {
240
+ return Promise.resolve();
241
+ },
242
+ leave() {
243
+ return Promise.resolve();
244
+ },
245
+ setUserId() {
246
+ return Promise.resolve();
247
+ },
248
+ clearUserId() {
249
+ return Promise.resolve();
250
+ },
251
+ };
252
+ const runtime = new WebSocketRuntime({ nodeId: "websocket-guard-await-test" });
253
+ vi.spyOn(runtime, "registerConnection").mockResolvedValue(rawWs);
254
+ const activateConnection = vi
255
+ .spyOn(runtime, "activateConnection")
256
+ .mockImplementation(async () => {});
257
+ vi.spyOn(Sonamu, "createWebSocketContext").mockImplementation(async (_config, request, ws) => {
258
+ const context: WebSocketContext = {
259
+ transport: "ws",
260
+ request,
261
+ headers: request.headers,
262
+ ws,
263
+ naiteStore: new Map(),
264
+ locale: "ko",
265
+ user: null,
266
+ session: null,
267
+ };
268
+ return context;
269
+ });
270
+ const invokeModelMethod = vi
271
+ .spyOn(Sonamu, "invokeModelMethod")
272
+ .mockImplementation(async () => {});
273
+ vi.spyOn(console, "warn").mockImplementation(() => {});
274
+ vi.spyOn(console, "error").mockImplementation(() => {});
275
+
276
+ const api: ExtendedApi = {
277
+ modelName: "ChatFrame",
278
+ methodName: "subscribe",
279
+ path: "/chat/subscribe",
280
+ options: { guards: ["admin"] },
281
+ websocketOptions: {
282
+ outEvents: z.object({}),
283
+ inEvents: z.object({}),
284
+ },
285
+ typeParameters: [],
286
+ parameters: [],
287
+ returnType: "void",
288
+ };
289
+ Sonamu.websocketRuntime = runtime;
290
+ Reflect.set(Sonamu, "syncerValue", { types: {} });
291
+
292
+ // 실제 @fastify/websocket 라우트에 연결해 실제 socket과 FastifyRequest로 핸들러를 실행한다
293
+ const wsHandler = Sonamu.createWebSocketHandlerForTesting(api, createConfig(guardHandler));
294
+ const server = Fastify();
295
+ servers.push(server);
296
+ await server.register(fastifyWebsocket);
297
+ const handled = new Promise<void>((resolve, reject) => {
298
+ server.get(api.path, { websocket: true }, (socket, request) => {
299
+ wsHandler(socket, request).then(resolve, reject);
300
+ });
301
+ });
302
+ await server.ready();
303
+ clients.push(await server.injectWS(api.path));
304
+ await handled;
305
+
306
+ return { closeCalls, activateConnection, invokeModelMethod };
307
+ }
308
+
309
+ it("async guardHandler가 throw하면 1008로 닫고 핸들러를 실행하지 않는다", async () => {
310
+ const result = await runWebSocketHandler(async () => {
311
+ await flushAsync();
312
+ throw new UnauthorizedException(SD("error.unauthorized"));
313
+ });
314
+
315
+ expect(result.closeCalls).toEqual([[1008, "Unauthorized websocket connection"]]);
316
+ expect(result.activateConnection).not.toHaveBeenCalled();
317
+ expect(result.invokeModelMethod).not.toHaveBeenCalled();
318
+ });
319
+
320
+ it("guardHandler가 false를 반환하면 1008로 닫고 핸들러를 실행하지 않는다", async () => {
321
+ const result = await runWebSocketHandler(async () => false);
322
+
323
+ expect(result.closeCalls).toEqual([[1008, "Unauthorized websocket connection"]]);
324
+ expect(result.activateConnection).not.toHaveBeenCalled();
325
+ expect(result.invokeModelMethod).not.toHaveBeenCalled();
326
+ });
327
+ });
@@ -0,0 +1,156 @@
1
+ import multipart from "@fastify/multipart";
2
+ import Fastify, { type FastifyInstance } from "fastify";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { type SonamuFastifyConfig } from "../../types/types";
6
+ import { type ExtendedApi, type UploadDecoratorOptions } from "../decorators";
7
+ import { Sonamu } from "../sonamu";
8
+
9
+ const BOUNDARY = "son631boundary";
10
+ // 전역(plugin) multipart 한도: 실제 앱의 `plugins.multipart.limits` 설정에 해당한다.
11
+ const GLOBAL_FILE_SIZE = 1024;
12
+ const GLOBAL_PARTS = 10;
13
+
14
+ type Part = { name: string; filename?: string; content: string };
15
+
16
+ function createMultipartBody(parts: Part[]): Buffer {
17
+ const chunks = parts.map((part) => {
18
+ const disposition = part.filename
19
+ ? `form-data; name="${part.name}"; filename="${part.filename}"\r\nContent-Type: application/octet-stream`
20
+ : `form-data; name="${part.name}"`;
21
+ return `--${BOUNDARY}\r\nContent-Disposition: ${disposition}\r\n\r\n${part.content}\r\n`;
22
+ });
23
+ return Buffer.from(`${chunks.join("")}--${BOUNDARY}--\r\n`);
24
+ }
25
+
26
+ function createUploadApi(uploadOptions: UploadDecoratorOptions): ExtendedApi {
27
+ return {
28
+ modelName: "FileModel",
29
+ methodName: "upload",
30
+ path: "/file/upload",
31
+ options: { httpMethod: "POST" },
32
+ uploadOptions,
33
+ typeParameters: [],
34
+ parameters: [],
35
+ returnType: "unknown",
36
+ };
37
+ }
38
+
39
+ describe("@upload multipart 한도", () => {
40
+ const originalState = Sonamu.captureTestingSnapshot();
41
+ let server: FastifyInstance;
42
+
43
+ beforeEach(() => {
44
+ Reflect.set(Sonamu, "httpValidators", new WeakMap());
45
+ Reflect.set(Sonamu, "pendingHttpValidators", new WeakMap());
46
+ Reflect.set(Sonamu, "aotHttpValidatorRegistry", undefined);
47
+ Reflect.set(Sonamu, "preparedApis", []);
48
+ Reflect.set(Sonamu, "configValue", {
49
+ sync: { targets: [] },
50
+ validation: { zodCompiler: false },
51
+ i18n: { defaultLocale: "ko", supportedLocales: ["ko"] },
52
+ });
53
+ Reflect.set(Sonamu, "syncerValue", { types: {} });
54
+ // 핸들러가 채운 context.bufferedFiles를 그대로 응답으로 돌려준다.
55
+ vi.spyOn(Sonamu, "invokeModelMethod").mockImplementation(async () => {
56
+ const context = Sonamu.getContext();
57
+ return { sizes: (context.bufferedFiles ?? []).map((file) => file.size) };
58
+ });
59
+ });
60
+
61
+ afterEach(async () => {
62
+ await server?.close();
63
+ Sonamu.restoreTestingSnapshot(originalState);
64
+ vi.restoreAllMocks();
65
+ });
66
+
67
+ async function createServer(uploadOptions: UploadDecoratorOptions) {
68
+ server = Fastify();
69
+ await server.register(multipart, {
70
+ limits: { fileSize: GLOBAL_FILE_SIZE, parts: GLOBAL_PARTS },
71
+ });
72
+ // 실제 createContext가 만든 기본 HTTP context를 그대로 사용한다.
73
+ const config: SonamuFastifyConfig = {
74
+ contextProvider: (defaultContext) => defaultContext,
75
+ guardHandler: () => {},
76
+ };
77
+ const handler = Sonamu.createApiHandler(createUploadApi(uploadOptions), config);
78
+ server.post("/upload", handler);
79
+ await server.ready();
80
+ return server;
81
+ }
82
+
83
+ function post(parts: Part[]) {
84
+ return server.inject({
85
+ method: "POST",
86
+ url: "/upload",
87
+ headers: { "content-type": `multipart/form-data; boundary=${BOUNDARY}` },
88
+ payload: createMultipartBody(parts),
89
+ });
90
+ }
91
+
92
+ it("인자 없는 @upload()에서도 전역 fileSize 한도를 넘는 파일은 413으로 거부한다", async () => {
93
+ await createServer({ consume: "buffer" });
94
+
95
+ const response = await post([
96
+ { name: "file", filename: "big.bin", content: "x".repeat(GLOBAL_FILE_SIZE + 1) },
97
+ ]);
98
+
99
+ expect(response.statusCode).toBe(413);
100
+ expect(response.json()).toMatchObject({ code: "FST_REQ_FILE_TOO_LARGE" });
101
+ });
102
+
103
+ it("인자 없는 @upload()에서도 전역 parts 한도를 넘는 요청은 413으로 거부한다", async () => {
104
+ await createServer({ consume: "buffer" });
105
+
106
+ const parts = Array.from({ length: GLOBAL_PARTS + 1 }, (_, index) => ({
107
+ name: `f${index}`,
108
+ filename: `a${index}.bin`,
109
+ content: "x",
110
+ }));
111
+ const response = await post(parts);
112
+
113
+ expect(response.statusCode).toBe(413);
114
+ expect(response.json()).toMatchObject({ code: "FST_PARTS_LIMIT" });
115
+ });
116
+
117
+ it("데코레이터 limits의 undefined 항목은 전역 한도를 지우지 않는다", async () => {
118
+ await createServer({ limits: { fileSize: undefined, files: 2 } });
119
+
120
+ const response = await post([
121
+ { name: "file", filename: "big.bin", content: "x".repeat(GLOBAL_FILE_SIZE + 1) },
122
+ ]);
123
+
124
+ expect(response.statusCode).toBe(413);
125
+ expect(response.json()).toMatchObject({ code: "FST_REQ_FILE_TOO_LARGE" });
126
+ });
127
+
128
+ it("데코레이터 limits는 전역 한도와 병합되어 함께 적용된다", async () => {
129
+ await createServer({ limits: { files: 1 } });
130
+
131
+ const tooMany = await post([
132
+ { name: "a", filename: "a.bin", content: "x" },
133
+ { name: "b", filename: "b.bin", content: "x" },
134
+ ]);
135
+ expect(tooMany.statusCode).toBe(413);
136
+ expect(tooMany.json()).toMatchObject({ code: "FST_FILES_LIMIT" });
137
+
138
+ const tooLarge = await post([
139
+ { name: "a", filename: "a.bin", content: "x".repeat(GLOBAL_FILE_SIZE + 1) },
140
+ ]);
141
+ expect(tooLarge.statusCode).toBe(413);
142
+ expect(tooLarge.json()).toMatchObject({ code: "FST_REQ_FILE_TOO_LARGE" });
143
+ });
144
+
145
+ it("한도 안의 업로드는 그대로 받아 context.bufferedFiles로 전달한다", async () => {
146
+ await createServer({ consume: "buffer" });
147
+
148
+ const response = await post([
149
+ { name: "a", filename: "a.bin", content: "x".repeat(GLOBAL_FILE_SIZE) },
150
+ { name: "title", content: "hello" },
151
+ ]);
152
+
153
+ expect(response.statusCode).toBe(200);
154
+ expect(response.json()).toEqual({ sizes: [GLOBAL_FILE_SIZE] });
155
+ });
156
+ });