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
@@ -43,6 +43,36 @@ export type MigrationResult = {
43
43
 
44
44
  type ShadowMigrationTarget = Extract<MigrationTarget, "fixture" | "test">;
45
45
 
46
+ // satisfies로 키 누락·초과를 타입 오류로 잡아 SonamuDBConfig의 preset 집합과 항상 일치시킵니다.
47
+ const MIGRATION_TARGET_KEYS = {
48
+ test: true,
49
+ fixture: true,
50
+ development: true,
51
+ staging: true,
52
+ production: true,
53
+ test_readonly: true,
54
+ development_readonly: true,
55
+ staging_readonly: true,
56
+ production_readonly: true,
57
+ } satisfies Record<MigrationTarget, true>;
58
+
59
+ function isMigrationTarget(key: string): key is MigrationTarget {
60
+ return Object.hasOwn(MIGRATION_TARGET_KEYS, key);
61
+ }
62
+
63
+ export type MigratorOptions = {
64
+ /**
65
+ * 현재 실행 환경에서 허용되더라도 이 Migrator로는 다룰 수 없게 막을 대상입니다.
66
+ * 목록·상태 조회와 적용·롤백 모두 이 대상을 허용 목록에서 제외합니다.
67
+ */
68
+ excludedTargets?: readonly MigrationTarget[];
69
+ /**
70
+ * 실행 환경 규칙으로 허용된 대상 중 호출자가 다룰 수 있는 대상을 한 번 더 좁힙니다.
71
+ * 연결 목록, 상태 조회, 비교, apply/rollback이 모두 이 필터를 거칩니다.
72
+ */
73
+ targetFilter?: (target: MigrationTarget) => boolean;
74
+ };
75
+
46
76
  function padDatePart(number: number, size: number = 2): string {
47
77
  return number.toString().padStart(size, "0");
48
78
  }
@@ -89,6 +119,12 @@ function withTimeout<T>(promise: Promise<T>, ms: number, onTimeout: () => Error)
89
119
  * CLI 리팩토링 시점에서 제거해주셔도 무방합니다.
90
120
  */
91
121
  export class Migrator {
122
+ private readonly excludedTargets: ReadonlySet<MigrationTarget>;
123
+
124
+ constructor(private readonly options: MigratorOptions = {}) {
125
+ this.excludedTargets = new Set(options.excludedTargets ?? []);
126
+ }
127
+
92
128
  private isMissingMigrationTableError<Value>(error: Value): boolean {
93
129
  if (!isObjectValue(error) || error === null) {
94
130
  return false;
@@ -104,10 +140,15 @@ export class Migrator {
104
140
 
105
141
  /** 현재 실행 환경에서 허용된 마이그레이션 대상 키를 반환합니다. */
106
142
  getMigrationTargetKeys(): MigrationTarget[] {
107
- const connKeys =
108
- /* SAFETY: Knex와 PostgreSQL 스키마 조회 계약이 이 값의 타입을 보장한다. */ Object.keys(
109
- Sonamu.dbConfig,
110
- ).filter((key) => !key.endsWith("_readonly")) as (keyof SonamuDBConfig)[];
143
+ const { targetFilter } = this.options;
144
+ const keys = this.getEnvironmentTargetKeys();
145
+ return targetFilter === undefined ? keys : keys.filter((key) => targetFilter(key));
146
+ }
147
+
148
+ private getEnvironmentTargetKeys(): MigrationTarget[] {
149
+ const connKeys = Object.keys(Sonamu.dbConfig)
150
+ .filter(isMigrationTarget)
151
+ .filter((key) => !key.endsWith("_readonly") && !this.excludedTargets.has(key));
111
152
 
112
153
  if (isLocal()) {
113
154
  return connKeys;
@@ -8,6 +8,9 @@ import { Sonamu } from "../api/sonamu";
8
8
  import { type SonamuDBConfig } from "../database/db";
9
9
  import { SD } from "../dict/sd";
10
10
  import { type MigrationResult } from "./migrator";
11
+ import { type MigrationAction } from "./types";
12
+
13
+ type SlackConfirmAction = Exclude<MigrationAction, "shadow">;
11
14
 
12
15
  export type SlackConfirmResult = {
13
16
  status: "approved" | "rejected" | "pending" | "not_configured" | "error";
@@ -111,11 +114,13 @@ export class SlackConfirm {
111
114
 
112
115
  /**
113
116
  * 슬랙 메시지를 발송합니다.
117
+ * rollback 요청은 승인자가 되돌리는 작업임을 알 수 있도록 별도 문구로 보냅니다.
114
118
  */
115
119
  async postApprovalRequest(
116
120
  migrations: string[],
117
121
  targets: string[],
118
122
  requestor?: string,
123
+ action: SlackConfirmAction = "apply",
119
124
  ): Promise<{ channel: string; ts: string }> {
120
125
  assert(this.config, SD("sonamu.error.slackConfirmNotConfigured"));
121
126
  this.validateConfiguredTargets();
@@ -128,7 +133,7 @@ export class SlackConfirm {
128
133
  },
129
134
  body: JSON.stringify({
130
135
  channel: this.config.channelId,
131
- text: this.buildMessageText(migrations, targets, requestor ?? this.getRequestor()),
136
+ text: this.buildMessageText(migrations, targets, requestor ?? this.getRequestor(), action),
132
137
  unfurl_links: false,
133
138
  unfurl_media: false,
134
139
  }),
@@ -158,21 +163,29 @@ export class SlackConfirm {
158
163
  /**
159
164
  * 메시지 텍스트를 생성합니다.
160
165
  */
161
- private buildMessageText(migrations: string[], targets: string[], requestor: string): string {
166
+ private buildMessageText(
167
+ migrations: string[],
168
+ targets: string[],
169
+ requestor: string,
170
+ action: SlackConfirmAction,
171
+ ): string {
162
172
  const projectName = Sonamu.config.projectName ?? "Unknown";
163
173
  const timestamp = new Date().toLocaleString("ko-KR", {
164
174
  timeZone: "Asia/Seoul",
165
175
  });
166
176
  const migrationsText = migrations.map((m) => `• ${m}`).join("\n");
167
177
  const targetsText = targets.join(", ");
178
+ const title =
179
+ action === "rollback" ? "마이그레이션 롤백 승인 요청" : "Production 마이그레이션 승인 요청";
180
+ const listTitle = action === "rollback" ? "롤백 예정 마이그레이션" : "적용 예정 마이그레이션";
168
181
 
169
- return `🗄️ *[${projectName}] Production 마이그레이션 승인 요청*
182
+ return `🗄️ *[${projectName}] ${title}*
170
183
 
171
184
  *요청자:* ${requestor}
172
185
  *대상 DB:* ${targetsText}
173
186
  *시간:* ${timestamp}
174
187
 
175
- *적용 예정 마이그레이션:*
188
+ *${listTitle}:*
176
189
  ${migrationsText}`;
177
190
  }
178
191
 
@@ -286,6 +299,7 @@ ${migrationsText}`;
286
299
  ts: string,
287
300
  results: MigrationResult,
288
301
  requestor?: string,
302
+ action: SlackConfirmAction = "apply",
289
303
  ): Promise<void> {
290
304
  const config = this.config;
291
305
  assert(config, SD("sonamu.error.slackConfirmNotConfigured"));
@@ -313,7 +327,7 @@ ${migrationsText}`;
313
327
  body: JSON.stringify({
314
328
  channel,
315
329
  thread_ts: ts,
316
- text: `✅ *마이그레이션 실행 완료*\n실행자: ${actualRequestor}\n시간: ${timestamp}\n\n적용됨:\n${appliedText}`,
330
+ text: `✅ *마이그레이션 ${action === "rollback" ? "롤백" : "실행"} 완료*\n실행자: ${actualRequestor}\n시간: ${timestamp}\n\n${action === "rollback" ? "롤백됨" : "적용됨"}:\n${appliedText}`,
317
331
  }),
318
332
  });
319
333
 
@@ -0,0 +1,274 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import fastify, { type FastifyReply, type FastifyRequest } from "fastify";
6
+ import { createServer, type ViteDevServer } from "vite";
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8
+ import { z, ZodError } from "zod";
9
+
10
+ import { type Context } from "../../api/context";
11
+ import { type ExtendedApi, type GuardKey } from "../../api/decorators";
12
+ import { Sonamu } from "../../api/sonamu";
13
+ import { SD, setSDConfig } from "../../dict/sd";
14
+ import { UnauthorizedException } from "../../exceptions/so-exceptions";
15
+ import { type SonamuFastifyConfig } from "../../types/types";
16
+ import { SSRPreloadValidationException } from "../errors";
17
+ import { renderSSR } from "../renderer";
18
+ import { type SSRQuery, type SSRRoute } from "../types";
19
+
20
+ const SECRET = "ADMIN-ONLY-SECRET";
21
+
22
+ // guard 통과 여부를 가르는 로그인 사용자: better-auth User의 필수 필드를 모두 채운다
23
+ const ADMIN_USER: NonNullable<Context["user"]> = {
24
+ id: "admin",
25
+ name: "관리자",
26
+ email: "admin@example.com",
27
+ emailVerified: true,
28
+ createdAt: new Date(0),
29
+ updatedAt: new Date(0),
30
+ };
31
+
32
+ // 테스트 라우트 path(:id)의 params 모양을 런타임에 확인한다
33
+ const routeParamsSchema = z.object({ id: z.string() });
34
+
35
+ function createApi(guards?: GuardKey[]): ExtendedApi {
36
+ const options: ExtendedApi["options"] = { httpMethod: "GET" };
37
+ if (guards !== undefined) {
38
+ options.guards = guards;
39
+ }
40
+ return {
41
+ modelName: "SecretModel",
42
+ methodName: "findById",
43
+ path: "/secret/findById",
44
+ options,
45
+ typeParameters: [],
46
+ parameters: [
47
+ { name: "subset", type: "string", optional: false },
48
+ { name: "id", type: "number", optional: false },
49
+ { name: "context", type: { t: "ref", id: "Context" }, optional: false },
50
+ ],
51
+ returnType: "unknown",
52
+ };
53
+ }
54
+
55
+ function createQuery(params: unknown[]): SSRQuery {
56
+ // 생성된 queries 코드의 createSSRQuery와 같이 브랜드 필드까지 채운다
57
+ return {
58
+ modelName: "SecretModel",
59
+ methodName: "findById",
60
+ params,
61
+ serviceKey: ["Secret", "getSecret"],
62
+ __brand: "SSRQuery",
63
+ };
64
+ }
65
+
66
+ /**
67
+ * 실제 Fastify 요청 핸들러 안에서 fn을 실행해 진짜 FastifyRequest와 FastifyReply를 넘긴다.
68
+ * fn의 결과를 그대로 돌려주고, fn이 거부하면 같은 이유로 거부한다.
69
+ */
70
+ async function withRealRequest<T>(
71
+ fn: (request: FastifyRequest, reply: FastifyReply) => Promise<T>,
72
+ ): Promise<T> {
73
+ const server = fastify();
74
+ let outcome: PromiseSettledResult<T> | undefined;
75
+ server.get("/admin/secret/:id", async (request, reply) => {
76
+ [outcome] = await Promise.allSettled([fn(request, reply)]);
77
+ return "";
78
+ });
79
+ try {
80
+ await server.inject({ method: "GET", url: "/admin/secret/1" });
81
+ } finally {
82
+ await server.close();
83
+ }
84
+ if (outcome === undefined) {
85
+ throw new Error("요청 핸들러가 실행되지 않았습니다");
86
+ }
87
+ if (outcome.status === "rejected") {
88
+ throw outcome.reason;
89
+ }
90
+ return outcome.value;
91
+ }
92
+
93
+ // renderSSR dev 경로가 불러오는 entry 모듈: preload 데이터를 그대로 dehydratedState에 싣는다
94
+ const ENTRY_SERVER_SOURCE = `export async function render(_url: string, preloadedData: unknown[]) {
95
+ return {
96
+ html: "<html><body></body></html>",
97
+ dehydratedState: { queries: preloadedData },
98
+ };
99
+ }
100
+ `;
101
+
102
+ describe("SSR preload의 guards와 입력 검증", () => {
103
+ const originalState = Sonamu.captureTestingSnapshot();
104
+ const tempRoots: string[] = [];
105
+ const viteServers: ViteDevServer[] = [];
106
+ let api: ExtendedApi;
107
+ let findById: ReturnType<typeof vi.fn>;
108
+ let user: Context["user"];
109
+
110
+ // 실제 createContext가 만든 기본 컨텍스트에 테스트의 로그인 사용자를 얹는다.
111
+ // admin 가드는 컨텍스트에 로그인 사용자가 없으면 거부한다.
112
+ function createConfig(): SonamuFastifyConfig {
113
+ return {
114
+ contextProvider(defaultContext) {
115
+ return { ...defaultContext, user };
116
+ },
117
+ guardHandler(guard) {
118
+ if (guard === "admin" && Sonamu.getContext().user === null) {
119
+ throw new UnauthorizedException(SD("error.unauthorized"));
120
+ }
121
+ },
122
+ };
123
+ }
124
+
125
+ async function createDevVite(): Promise<ViteDevServer> {
126
+ const root = await mkdtemp(path.join(os.tmpdir(), "sonamu-ssr-preload-"));
127
+ tempRoots.push(root);
128
+ await writeFile(path.join(root, "index.html"), "<html><body></body></html>");
129
+ await mkdir(path.join(root, "src"));
130
+ await writeFile(path.join(root, "src", "entry-server.generated.tsx"), ENTRY_SERVER_SOURCE);
131
+ // 포트·HMR 웹소켓·파일 감시 없이 미들웨어 모드로만 띄운다
132
+ const vite = await createServer({
133
+ root,
134
+ configFile: false,
135
+ logLevel: "silent",
136
+ appType: "custom",
137
+ server: { middlewareMode: true, hmr: false, ws: false, watch: null },
138
+ });
139
+ viteServers.push(vite);
140
+ return vite;
141
+ }
142
+
143
+ beforeEach(() => {
144
+ api = createApi(["admin"]);
145
+ findById = vi.fn(async (subset: string, id: number) => ({ subset, id, secret: SECRET }));
146
+ user = null;
147
+ Reflect.set(Sonamu, "httpValidators", new WeakMap());
148
+ Reflect.set(Sonamu, "pendingHttpValidators", new WeakMap());
149
+ const i18n = { defaultLocale: "ko", supportedLocales: ["ko", "en"] };
150
+ Reflect.set(Sonamu, "configValue", {
151
+ sync: { targets: [] },
152
+ validation: { zodCompiler: false },
153
+ i18n,
154
+ });
155
+ // guard 거부 메시지가 SD 사전을 쓰므로 Sonamu.init이 하는 i18n 설정을 테스트에서 대신한다
156
+ setSDConfig(i18n);
157
+ Reflect.set(Sonamu, "syncerValue", {
158
+ types: {},
159
+ apis: [api],
160
+ models: { SecretModel: { findById } },
161
+ });
162
+ });
163
+
164
+ afterEach(async () => {
165
+ Sonamu.restoreTestingSnapshot(originalState);
166
+ vi.restoreAllMocks();
167
+ await Promise.all(viteServers.splice(0).map((vite) => vite.close()));
168
+ await Promise.all(
169
+ tempRoots.splice(0).map((rootPath) => rm(rootPath, { recursive: true, force: true })),
170
+ );
171
+ });
172
+
173
+ it("guard가 거부하면 invokeApiForSSR이 모델 메서드를 호출하지 않는다", async () => {
174
+ await expect(
175
+ withRealRequest((request, reply) =>
176
+ Sonamu.invokeApiForSSR(api, ["A", 1], createConfig(), request, reply),
177
+ ),
178
+ ).rejects.toBeInstanceOf(UnauthorizedException);
179
+ expect(findById).not.toHaveBeenCalled();
180
+ });
181
+
182
+ it("검증기를 통과하지 못한 params는 400 예외가 되고 모델 메서드를 호출하지 않는다", async () => {
183
+ user = ADMIN_USER;
184
+
185
+ const result = withRealRequest((request, reply) =>
186
+ Sonamu.invokeApiForSSR(api, ["A", Number("abc")], createConfig(), request, reply),
187
+ );
188
+ await expect(result).rejects.toBeInstanceOf(SSRPreloadValidationException);
189
+ await expect(result).rejects.toMatchObject({
190
+ statusCode: 400,
191
+ payload: { zodError: expect.any(ZodError) },
192
+ });
193
+ expect(findById).not.toHaveBeenCalled();
194
+ });
195
+
196
+ it("guard와 검증을 통과하면 검증된 값과 Context로 모델 메서드를 호출한다", async () => {
197
+ user = ADMIN_USER;
198
+
199
+ await expect(
200
+ withRealRequest((request, reply) =>
201
+ Sonamu.invokeApiForSSR(api, ["A", 1], createConfig(), request, reply),
202
+ ),
203
+ ).resolves.toEqual({ subset: "A", id: 1, secret: SECRET });
204
+ expect(findById).toHaveBeenCalledWith("A", 1, expect.objectContaining({ user }));
205
+ });
206
+
207
+ it("비인증 SSR 렌더링은 가드된 preload 데이터를 HTML에 싣지 않는다", async () => {
208
+ vi.spyOn(console, "error").mockImplementation(() => {});
209
+ const route: SSRRoute = {
210
+ path: "/admin/secret/:id",
211
+ preload: (params) => [createQuery(["A", Number(params.id)])],
212
+ };
213
+ const vite = await createDevVite();
214
+
215
+ const html = await withRealRequest((request, reply) =>
216
+ renderSSR("/admin/secret/1", route, { id: "1" }, request, reply, createConfig(), vite),
217
+ );
218
+
219
+ expect(html).not.toContain(SECRET);
220
+ expect(html).toContain('window.__SONAMU_SSR__ = {"queries":[]}');
221
+ expect(findById).not.toHaveBeenCalled();
222
+ });
223
+
224
+ it("관리자 SSR 렌더링은 preload 데이터를 HTML에 싣는다", async () => {
225
+ user = ADMIN_USER;
226
+ const route: SSRRoute = {
227
+ path: "/admin/secret/:id",
228
+ preload: (params) => [createQuery(["A", Number(params.id)])],
229
+ };
230
+ const vite = await createDevVite();
231
+
232
+ const html = await withRealRequest((request, reply) =>
233
+ renderSSR("/admin/secret/1", route, { id: "1" }, request, reply, createConfig(), vite),
234
+ );
235
+
236
+ expect(html).toContain(SECRET);
237
+ });
238
+
239
+ it("잘못된 path param으로 만든 preload 인자는 SSR 응답을 400으로 만든다", async () => {
240
+ // 가드 없는 API여도 검증은 적용된다
241
+ api = createApi();
242
+ Reflect.set(Sonamu, "syncerValue", {
243
+ types: {},
244
+ apis: [api],
245
+ models: { SecretModel: { findById } },
246
+ });
247
+ const route: SSRRoute = {
248
+ path: "/admin/secret/:id",
249
+ preload: (params) => [createQuery(["A", Number(params.id)])],
250
+ };
251
+ const vite = await createDevVite();
252
+ const config = createConfig();
253
+
254
+ const server = fastify();
255
+ server.get("/admin/secret/:id", async (request, reply) => {
256
+ const params = routeParamsSchema.parse(request.params);
257
+ const html = await renderSSR(request.url, route, params, request, reply, config, vite);
258
+ reply.type("text/html");
259
+ return html;
260
+ });
261
+
262
+ try {
263
+ const invalid = await server.inject({ method: "GET", url: "/admin/secret/abc" });
264
+ expect(invalid.statusCode).toBe(400);
265
+ expect(findById).not.toHaveBeenCalled();
266
+
267
+ const valid = await server.inject({ method: "GET", url: "/admin/secret/1" });
268
+ expect(valid.statusCode).toBe(200);
269
+ expect(valid.body).toContain(SECRET);
270
+ } finally {
271
+ await server.close();
272
+ }
273
+ });
274
+ });
@@ -0,0 +1,11 @@
1
+ import { type ZodError } from "zod";
2
+
3
+ import { BadRequestException } from "../exceptions/so-exceptions";
4
+
5
+ /**
6
+ * SSR preload 인자가 API의 HTTP 검증기를 통과하지 못했을 때 던지는 예외입니다.
7
+ *
8
+ * 가드 실패나 모델 오류는 해당 preload만 건너뛰지만, 이 예외는 renderSSR이 다시 던져
9
+ * SSR 응답이 400이 되게 합니다.
10
+ */
11
+ export class SSRPreloadValidationException extends BadRequestException<{ zodError: ZodError }> {}
package/src/ssr/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { SSRPreloadValidationException } from "./errors";
1
2
  export { clearSSRRoutes, getSSRRoutes, matchSSRRoute, registerSSR } from "./registry";
2
3
  export { renderSSR } from "./renderer";
3
4
  export type { PreloadConfig, PreloadedData, SSRQuery, SSRRoute } from "./types";
@@ -6,9 +6,16 @@ import { type ViteDevServer } from "vite";
6
6
  import { applyCacheHeaders } from "../cache-control/cache-control";
7
7
  import { type CacheControlRequest } from "../cache-control/types";
8
8
  import { type SonamuFastifyConfig } from "../types/types";
9
+ import { SSRPreloadValidationException } from "./errors";
9
10
  import { HMR_OPT_OUT_SCRIPT, isHmrDisabledByQuery } from "./hmr-opt-out";
10
11
  import { type PreloadedData, type SSRRoute } from "./types";
11
12
 
13
+ /**
14
+ * 등록된 SSR 라우트의 preload를 실행하고 HTML을 렌더링합니다.
15
+ * preload의 가드 거부나 모델 오류는 해당 preload만 건너뜁니다.
16
+ *
17
+ * @throws {SSRPreloadValidationException} 가드를 통과한 preload 인자가 API 입력 검증에 실패한 경우(400)
18
+ */
12
19
  export async function renderSSR(
13
20
  url: string,
14
21
  route: SSRRoute,
@@ -41,6 +48,11 @@ export async function renderSSR(
41
48
  data: result,
42
49
  });
43
50
  } catch (e) {
51
+ // 잘못된 preload 인자는 HTTP 호출처럼 400으로 응답한다.
52
+ // guard 거부·모델 오류는 이 preload만 건너뛰어 데이터를 싣지 않고, 클라이언트가 API로 다시 조회한다.
53
+ if (e instanceof SSRPreloadValidationException) {
54
+ throw e;
55
+ }
44
56
  console.error(`Failed to preload ${modelName}.${methodName}:`, e);
45
57
  }
46
58
  }
@@ -0,0 +1,179 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { Readable } from "node:stream";
5
+
6
+ import { type MultipartFile } from "@fastify/multipart";
7
+ import fastifyStatic from "@fastify/static";
8
+ import fastify, { type FastifyInstance, type FastifyReply } from "fastify";
9
+ import { FSDriver } from "flydrive/drivers/fs";
10
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11
+
12
+ import { Sonamu } from "../../api/sonamu";
13
+ import {
14
+ BufferedFile,
15
+ createUploadStaticHeaders,
16
+ resolveUploadContentType,
17
+ resolveUploadExtension,
18
+ StorageManager,
19
+ } from "../index";
20
+
21
+ /** BufferedFile 에 넘길 MultipartFile 을 모든 필드를 채워 만든다. */
22
+ function createMultipartFile(filename: string, mimetype: string, buffer: Buffer): MultipartFile {
23
+ const file = Object.assign(Readable.from([buffer]), {
24
+ truncated: false,
25
+ bytesRead: buffer.length,
26
+ });
27
+ return {
28
+ type: "file",
29
+ toBuffer: async () => buffer,
30
+ file,
31
+ fieldname: "file",
32
+ filename,
33
+ encoding: "7bit",
34
+ mimetype,
35
+ fields: {},
36
+ };
37
+ }
38
+
39
+ describe("업로드 확장자와 Content-Type 판정", () => {
40
+ it.each([
41
+ ["text/html", "bin"],
42
+ ["TEXT/HTML; charset=utf-8", "bin"],
43
+ ["image/svg+xml", "bin"],
44
+ ["application/xhtml+xml", "bin"],
45
+ ["text/xml", "bin"],
46
+ ["text/javascript", "bin"],
47
+ ["application/x-msdownload", "bin"],
48
+ ["image/png", "png"],
49
+ ["image/jpeg", "jpg"],
50
+ ["application/pdf", "pdf"],
51
+ ["text/plain", "txt"],
52
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"],
53
+ ])("%s 는 확장자 %s 로 저장한다", (mimetype, extension) => {
54
+ expect(resolveUploadExtension(mimetype)).toBe(extension);
55
+ });
56
+
57
+ it("알 수 없는 MIME 은 기존처럼 false 를 돌려준다", () => {
58
+ expect(resolveUploadExtension("application/x-unknown-sonamu")).toBe(false);
59
+ });
60
+
61
+ it.each([
62
+ ["text/html", "application/octet-stream"],
63
+ ["image/svg+xml", "application/octet-stream"],
64
+ ["application/x-unknown-sonamu", "application/octet-stream"],
65
+ ["", "application/octet-stream"],
66
+ ["Image/PNG", "image/png"],
67
+ ["application/pdf", "application/pdf"],
68
+ ])("%s 는 Content-Type %s 로 저장한다", (mimetype, contentType) => {
69
+ expect(resolveUploadContentType(mimetype)).toBe(contentType);
70
+ });
71
+
72
+ it("BufferedFile.extname 은 text/html 업로드에 html 확장자를 주지 않는다", () => {
73
+ const htmlBuffer = Buffer.from("<script></script>");
74
+ const pngBuffer = Buffer.from("png");
75
+ const html = createMultipartFile("evil.html", "text/html", htmlBuffer);
76
+ const png = createMultipartFile("a.png", "image/png", pngBuffer);
77
+ expect(new BufferedFile(html, htmlBuffer).extname).toBe("bin");
78
+ expect(new BufferedFile(png, pngBuffer).extname).toBe("png");
79
+ });
80
+ });
81
+
82
+ describe("BufferedFile.saveToDisk 의 Content-Type", () => {
83
+ const originalStorage = Sonamu["storageValue"];
84
+ let directory: string;
85
+
86
+ beforeEach(async () => {
87
+ directory = await mkdtemp(path.join(tmpdir(), "sonamu-upload-safety-"));
88
+ });
89
+
90
+ afterEach(async () => {
91
+ Reflect.set(Sonamu, "storageValue", originalStorage);
92
+ await rm(directory, { recursive: true, force: true });
93
+ });
94
+
95
+ it("클라이언트가 보낸 text/html 대신 application/octet-stream 으로 저장한다", async () => {
96
+ const driver = new FSDriver({
97
+ location: directory,
98
+ visibility: "public",
99
+ urlBuilder: {
100
+ async generateURL(key) {
101
+ return `/files/${key}`;
102
+ },
103
+ async generateSignedURL(key) {
104
+ return `/files/${key}`;
105
+ },
106
+ },
107
+ });
108
+ const put = vi.spyOn(driver, "put");
109
+ Reflect.set(Sonamu, "storageValue", new StorageManager({ drivers: { fs: () => driver } }));
110
+
111
+ const buffer = Buffer.from("<script>1</script>");
112
+ const multipart = createMultipartFile("evil.html", "text/html", buffer);
113
+ const file = new BufferedFile(multipart, buffer);
114
+ await file.saveToDisk("fs", "evil.bin");
115
+
116
+ expect(put).toHaveBeenCalledWith("evil.bin", expect.anything(), {
117
+ contentType: "application/octet-stream",
118
+ });
119
+ });
120
+ });
121
+
122
+ describe("createUploadStaticHeaders", () => {
123
+ let directory: string;
124
+ let server: FastifyInstance;
125
+
126
+ beforeEach(async () => {
127
+ directory = await mkdtemp(path.join(tmpdir(), "sonamu-upload-static-"));
128
+ const uploadDir = path.join(directory, "uploaded");
129
+ await mkdir(uploadDir, { recursive: true });
130
+ await writeFile(path.join(directory, "page.html"), "<p>public</p>");
131
+ await writeFile(path.join(uploadDir, "evil.html"), "<script>1</script>");
132
+ await writeFile(path.join(uploadDir, "evil.svg"), "<svg onload='1'></svg>");
133
+ await writeFile(path.join(uploadDir, "..evil.html"), "<script>1</script>");
134
+ await writeFile(path.join(uploadDir, "pic.png"), "png");
135
+
136
+ const userSetHeaders = vi.fn((reply: FastifyReply) => {
137
+ reply.header("X-Custom", "1");
138
+ });
139
+ server = fastify();
140
+ await server.register(fastifyStatic, {
141
+ root: directory,
142
+ prefix: "/api/public",
143
+ setHeaders: createUploadStaticHeaders({ uploadDir, setHeaders: userSetHeaders }),
144
+ });
145
+ });
146
+
147
+ afterEach(async () => {
148
+ await server.close();
149
+ await rm(directory, { recursive: true, force: true });
150
+ });
151
+
152
+ it.each(["evil.html", "evil.svg", "..evil.html"])(
153
+ "업로드된 %s 는 nosniff·sandbox·attachment 로 서빙되어 실행되지 않는다",
154
+ async (name) => {
155
+ const res = await server.inject({ method: "GET", url: `/api/public/uploaded/${name}` });
156
+ expect(res.statusCode).toBe(200);
157
+ expect(res.headers["content-type"]).toBe("application/octet-stream");
158
+ expect(res.headers["x-content-type-options"]).toBe("nosniff");
159
+ expect(res.headers["content-security-policy"]).toBe("sandbox");
160
+ expect(res.headers["content-disposition"]).toBe("attachment");
161
+ expect(res.headers["x-custom"]).toBe("1");
162
+ },
163
+ );
164
+
165
+ it("업로드된 이미지는 attachment 없이 nosniff·sandbox 만 붙는다", async () => {
166
+ const res = await server.inject({ method: "GET", url: "/api/public/uploaded/pic.png" });
167
+ expect(res.headers["content-type"]).toBe("image/png");
168
+ expect(res.headers["x-content-type-options"]).toBe("nosniff");
169
+ expect(res.headers["content-security-policy"]).toBe("sandbox");
170
+ expect(res.headers["content-disposition"]).toBeUndefined();
171
+ });
172
+
173
+ it("업로드 디렉터리 밖의 정적 파일에는 헤더를 붙이지 않는다", async () => {
174
+ const res = await server.inject({ method: "GET", url: "/api/public/page.html" });
175
+ expect(res.headers["content-security-policy"]).toBeUndefined();
176
+ expect(res.headers["content-disposition"]).toBeUndefined();
177
+ expect(res.headers["x-custom"]).toBe("1");
178
+ });
179
+ });
@@ -1,4 +1,4 @@
1
- import mime from "mime-types";
1
+ import { resolveUploadExtension } from "./upload-safety";
2
2
 
3
3
  /**
4
4
  * 파일의 기본 메타데이터(filename, mimetype, size 등)에 대한 접근자 제공
@@ -29,7 +29,7 @@ export abstract class BaseFile {
29
29
  return this["_filename"];
30
30
  }
31
31
 
32
- /** MIME 타입 */
32
+ /** MIME 타입. 클라이언트가 보낸 값이며 파일 내용을 검증한 결과가 아닙니다. */
33
33
  get mimetype(): string {
34
34
  return this["_mimetype"];
35
35
  }
@@ -39,9 +39,13 @@ export abstract class BaseFile {
39
39
  return this["_size"];
40
40
  }
41
41
 
42
- /** 확장자 (점 제외) */
42
+ /**
43
+ * 확장자 (점 제외)
44
+ * MIME 은 클라이언트가 보낸 값이므로, 업로드 허용 목록 밖의 타입(HTML·SVG 등)은 `bin` 으로 바꿉니다.
45
+ * MIME 을 알 수 없으면 `false` 입니다.
46
+ */
43
47
  get extname(): string | false {
44
- return mime.extension(this["_mimetype"]);
48
+ return resolveUploadExtension(this["_mimetype"]);
45
49
  }
46
50
 
47
51
  /** 저장된 URL (Unsigned) */