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
@@ -0,0 +1,352 @@
1
+ import Fastify, { type FastifyInstance } from "fastify";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ import { type DatabaseConfig, type SonamuConfig } from "../../api/config";
5
+ import { Sonamu } from "../../api/sonamu";
6
+ import { type SonamuDBConfig, type SonamuDBPreset } from "../../database/db";
7
+ import { setSDConfig } from "../../dict/sd";
8
+ import { type MigrationResult, Migrator } from "../../migration/migrator";
9
+ import { type MigrationConnectionStatus, type MigrationTarget } from "../../migration/types";
10
+ import { registerMigrationsApi } from "../migrations-api";
11
+ import { createConfig, createDBConfig, setupSonamu } from "./ui-test-helpers";
12
+
13
+ // 운영 자격증명이 있는 dev 머신처럼 production preset이 원격 운영 DB를 가리키게 둡니다.
14
+ // 테스트는 이 주소에 연결하지 않으며, 연결을 시도하면 거부 대신 타임아웃이 나므로 회귀가 드러납니다.
15
+ function presetConfig(preset: SonamuDBPreset): DatabaseConfig {
16
+ return {
17
+ client: "postgresql",
18
+ connection: preset.startsWith("production")
19
+ ? { host: "prod-db.invalid", user: "prod_user", database: "app_production" }
20
+ : { host: "localhost", database: preset },
21
+ };
22
+ }
23
+
24
+ const dbConfig: SonamuDBConfig = {
25
+ test: presetConfig("test"),
26
+ fixture: presetConfig("fixture"),
27
+ development: presetConfig("development"),
28
+ staging: presetConfig("staging"),
29
+ production: presetConfig("production"),
30
+ test_readonly: presetConfig("test_readonly"),
31
+ development_readonly: presetConfig("development_readonly"),
32
+ staging_readonly: presetConfig("staging_readonly"),
33
+ production_readonly: presetConfig("production_readonly"),
34
+ };
35
+
36
+ const config: SonamuConfig = {
37
+ projectName: "sonamu-test",
38
+ api: { dir: "src", route: { prefix: "/api" } },
39
+ i18n: { defaultLocale: "ko", supportedLocales: ["ko", "en"] },
40
+ sync: { targets: [] },
41
+ database: {},
42
+ server: {
43
+ apiConfig: {
44
+ contextProvider: (defaultContext) => defaultContext,
45
+ guardHandler: () => undefined,
46
+ },
47
+ },
48
+ };
49
+
50
+ const PENDING_FILE = "20260101000000_create__posts";
51
+ const APPLIED_FILE = "20251201000000_create__users";
52
+
53
+ type SlackCall = { url: string; body: string };
54
+
55
+ /** Slack API를 흉내 내고 호출 내역과 승인 상태를 조절할 수 있는 fetch 대역입니다. */
56
+ function stubSlack() {
57
+ const calls: SlackCall[] = [];
58
+ const state = { approved: false, nextTs: 1 };
59
+ vi.stubGlobal(
60
+ "fetch",
61
+ vi.fn(async (input: string, init?: RequestInit) => {
62
+ const body = String(init?.body ?? "");
63
+ calls.push({ url: input, body });
64
+ if (input.startsWith("https://slack.com/api/reactions.get")) {
65
+ return Response.json({
66
+ ok: true,
67
+ message: {
68
+ reactions: state.approved ? [{ name: "white_check_mark", users: ["U1"] }] : [],
69
+ },
70
+ });
71
+ }
72
+ const ts = `${state.nextTs}.000100`;
73
+ state.nextTs += 1;
74
+ return Response.json({ ok: true, channel: "C123", ts });
75
+ }),
76
+ );
77
+ const posted = () =>
78
+ calls
79
+ .filter(({ url }) => url === "https://slack.com/api/chat.postMessage")
80
+ .map(({ body }) => body);
81
+ return { calls, state, posted };
82
+ }
83
+
84
+ function readyStatus(connKey: MigrationTarget): MigrationConnectionStatus {
85
+ return {
86
+ connKey,
87
+ currentVersion: APPLIED_FILE,
88
+ status: 1,
89
+ pending: [PENDING_FILE],
90
+ latencyMs: 1,
91
+ };
92
+ }
93
+
94
+ describe("Sonamu UI 마이그레이션 API의 production 대상 제외", () => {
95
+ const originalEnv = { ...process.env };
96
+ let server: FastifyInstance;
97
+
98
+ beforeEach(async () => {
99
+ process.env.NODE_ENV = "development";
100
+ Sonamu.dbConfig = dbConfig;
101
+ Sonamu.config = config;
102
+ setSDConfig(config.i18n);
103
+ server = Fastify();
104
+ await registerMigrationsApi(server);
105
+ await server.ready();
106
+ });
107
+
108
+ afterEach(async () => {
109
+ await server.close();
110
+ for (const key of Object.keys(process.env)) {
111
+ if (!(key in originalEnv)) {
112
+ delete process.env[key];
113
+ }
114
+ }
115
+ Object.assign(process.env, originalEnv);
116
+ });
117
+
118
+ it("커넥션 목록에 production이 없고 운영 DB 접속 정보도 노출하지 않는다", async () => {
119
+ const response = await server.inject({ method: "GET", url: "/api/migrations/connections" });
120
+
121
+ expect(response.statusCode).toBe(200);
122
+ const body: { connections: { connKey: string }[] } = response.json();
123
+ // SON-620의 UI 허용 목록이 staging도 제외하므로 개발용 DB만 남습니다.
124
+ expect(body.connections.map(({ connKey }) => connKey)).toEqual([
125
+ "test",
126
+ "fixture",
127
+ "development",
128
+ ]);
129
+ expect(response.body).not.toContain("prod-db.invalid");
130
+ });
131
+
132
+ it.each([
133
+ "/api/migrations/apply",
134
+ "/api/migrations/rollback",
135
+ "/api/migrations/request-approval",
136
+ ])("%s는 production 대상을 400으로 거부한다", async (url) => {
137
+ const response = await server.inject({
138
+ method: "POST",
139
+ url,
140
+ payload: { targets: ["production"] },
141
+ });
142
+
143
+ expect(response.statusCode).toBe(400);
144
+ });
145
+
146
+ it("레거시 runAction 경로도 production 대상을 거부한다", async () => {
147
+ const responses = await Promise.all(
148
+ (["apply", "rollback"] as const).map((action) =>
149
+ server.inject({
150
+ method: "POST",
151
+ url: "/api/migrations/runAction",
152
+ payload: { action, targets: ["production"] },
153
+ }),
154
+ ),
155
+ );
156
+
157
+ for (const response of responses) {
158
+ expect(response.statusCode).toBe(400);
159
+ }
160
+ });
161
+
162
+ it("production 단일 상태 조회와 비교 코드 조회는 DB 연결 전에 실패한다", async () => {
163
+ const responses = await Promise.all([
164
+ server.inject({ method: "GET", url: "/api/migrations/status?connKey=production" }),
165
+ server.inject({
166
+ method: "GET",
167
+ url: "/api/migrations/prepared-codes?compareConnKey=production",
168
+ }),
169
+ server.inject({
170
+ method: "POST",
171
+ url: "/api/migrations/generatePreparedCodes",
172
+ payload: { compareConnKey: "production" },
173
+ }),
174
+ ]);
175
+
176
+ for (const response of responses) {
177
+ expect(response.statusCode).toBeGreaterThanOrEqual(400);
178
+ expect(response.body).toContain("Migration target is not allowed");
179
+ }
180
+ });
181
+ });
182
+
183
+ // 이 describe는 Migrator.prototype 스파이를 복원하지 않으므로 실제 Migrator로 거부를 확인하는 위 describe보다 뒤에 둡니다.
184
+ describe("Sonamu UI 마이그레이션 API", () => {
185
+ let app: ReturnType<typeof Fastify>;
186
+ let cleanup: () => Promise<void>;
187
+ const applySpy = vi.spyOn(Migrator.prototype, "apply");
188
+ const rollbackSpy = vi.spyOn(Migrator.prototype, "rollback");
189
+
190
+ async function start(options: { slackTargets?: MigrationTarget[]; remoteDevelopment?: boolean }) {
191
+ ({ cleanup } = await setupSonamu(
192
+ createConfig(options.slackTargets),
193
+ createDBConfig(
194
+ options.remoteDevelopment === true ? { development: "db.internal.example" } : {},
195
+ ),
196
+ ));
197
+ app = Fastify();
198
+ await registerMigrationsApi(app);
199
+ }
200
+
201
+ beforeEach(() => {
202
+ vi.spyOn(Migrator.prototype, "getConnectionStatus").mockImplementation(async (connKey) =>
203
+ readyStatus(connKey),
204
+ );
205
+ vi.spyOn(Migrator.prototype, "getLatestAppliedBatch").mockResolvedValue({
206
+ batchNo: 3,
207
+ files: [APPLIED_FILE],
208
+ });
209
+ const result = (targets: MigrationTarget[], files: string[]): MigrationResult =>
210
+ targets.map((connKey) => ({ connKey, batchNo: 3, applied: files }));
211
+ applySpy.mockImplementation(async (targets) => result(targets, [PENDING_FILE]));
212
+ rollbackSpy.mockImplementation(async (targets) => result(targets, [APPLIED_FILE]));
213
+ });
214
+
215
+ afterEach(async () => {
216
+ await app.close();
217
+ await cleanup();
218
+ vi.unstubAllGlobals();
219
+ vi.clearAllMocks();
220
+ });
221
+
222
+ describe("운영 계열 DB 대상 거부", () => {
223
+ beforeEach(async () => {
224
+ await start({});
225
+ });
226
+
227
+ it("연결 목록에 staging·production을 노출하지 않는다", async () => {
228
+ const res = await app.inject({ method: "GET", url: "/api/migrations/connections" });
229
+
230
+ expect(res.statusCode).toBe(200);
231
+ expect(res.json().connections.map(({ connKey }: { connKey: string }) => connKey)).toEqual([
232
+ "test",
233
+ "fixture",
234
+ "development",
235
+ ]);
236
+ });
237
+
238
+ it.each([
239
+ ["/api/migrations/rollback", { targets: ["production"] }],
240
+ ["/api/migrations/rollback", { targets: ["test", "staging"] }],
241
+ ["/api/migrations/apply", { targets: ["production"] }],
242
+ ["/api/migrations/request-approval", { targets: ["production"] }],
243
+ ["/api/migrations/runAction", { action: "rollback", targets: ["production"] }],
244
+ ["/api/migrations/runAction", { action: "apply", targets: ["staging"] }],
245
+ ["/api/migrations/rollback", { targets: "production" }],
246
+ ])("%s 요청이 %j 이면 400으로 거부하고 실행하지 않는다", async (url, payload) => {
247
+ const res = await app.inject({ method: "POST", url, payload });
248
+
249
+ expect(res.statusCode).toBe(400);
250
+ expect(applySpy).not.toHaveBeenCalled();
251
+ expect(rollbackSpy).not.toHaveBeenCalled();
252
+ });
253
+
254
+ it("허용된 로컬 DB는 승인 설정이 없으면 바로 rollback한다", async () => {
255
+ const res = await app.inject({
256
+ method: "POST",
257
+ url: "/api/migrations/rollback",
258
+ payload: { targets: ["test"] },
259
+ });
260
+
261
+ expect(res.statusCode).toBe(200);
262
+ expect(res.body).toContain('"type":"complete"');
263
+ expect(rollbackSpy).toHaveBeenCalledWith(["test"], expect.anything());
264
+ });
265
+ });
266
+
267
+ describe("rollback 승인", () => {
268
+ beforeEach(async () => {
269
+ await start({ slackTargets: ["development"], remoteDevelopment: true });
270
+ });
271
+
272
+ it("승인 요청 없이 승인 대상 DB를 rollback하면 거부한다", async () => {
273
+ const slack = stubSlack();
274
+
275
+ const res = await app.inject({
276
+ method: "POST",
277
+ url: "/api/migrations/rollback",
278
+ payload: { targets: ["development"] },
279
+ });
280
+
281
+ expect(res.statusCode).toBe(400);
282
+ expect(rollbackSpy).not.toHaveBeenCalled();
283
+ expect(slack.posted()).toHaveLength(0);
284
+ });
285
+
286
+ it("rollback 승인 요청을 보내고 승인된 뒤에만 rollback한다", async () => {
287
+ const slack = stubSlack();
288
+
289
+ const requested = await app.inject({
290
+ method: "POST",
291
+ url: "/api/migrations/request-approval",
292
+ payload: { targets: ["development"], action: "rollback" },
293
+ });
294
+ expect(requested.json()).toMatchObject({ type: "pending", channel: "C123" });
295
+ expect(slack.posted()[0]).toContain("롤백 승인 요청");
296
+ expect(slack.posted()[0]).toContain(`[rollback:development#3] ${APPLIED_FILE}`);
297
+
298
+ const whilePending = await app.inject({
299
+ method: "POST",
300
+ url: "/api/migrations/rollback",
301
+ payload: { targets: ["development"] },
302
+ });
303
+ expect(whilePending.statusCode).toBe(400);
304
+ expect(rollbackSpy).not.toHaveBeenCalled();
305
+
306
+ slack.state.approved = true;
307
+ const approved = await app.inject({
308
+ method: "POST",
309
+ url: "/api/migrations/rollback",
310
+ payload: { targets: ["development"] },
311
+ });
312
+ expect(approved.statusCode).toBe(200);
313
+ expect(approved.body).toContain('"type":"complete"');
314
+ expect(rollbackSpy).toHaveBeenCalledTimes(1);
315
+ expect(slack.posted().at(-1)).toContain("롤백 완료");
316
+ });
317
+
318
+ it("apply 승인으로는 rollback을 실행할 수 없다", async () => {
319
+ const slack = stubSlack();
320
+ await app.inject({
321
+ method: "POST",
322
+ url: "/api/migrations/request-approval",
323
+ payload: { targets: ["development"] },
324
+ });
325
+ slack.state.approved = true;
326
+
327
+ const res = await app.inject({
328
+ method: "POST",
329
+ url: "/api/migrations/rollback",
330
+ payload: { targets: ["development"] },
331
+ });
332
+
333
+ expect(res.statusCode).toBe(400);
334
+ expect(rollbackSpy).not.toHaveBeenCalled();
335
+ });
336
+
337
+ it("이전 runAction rollback도 승인 요청만 만들고 실행하지 않는다", async () => {
338
+ const slack = stubSlack();
339
+
340
+ const res = await app.inject({
341
+ method: "POST",
342
+ url: "/api/migrations/runAction",
343
+ payload: { action: "rollback", targets: ["development"], force: true },
344
+ });
345
+
346
+ expect(res.statusCode).toBe(200);
347
+ expect(res.json()).toMatchObject({ type: "pending" });
348
+ expect(rollbackSpy).not.toHaveBeenCalled();
349
+ expect(slack.posted()[0]).toContain("롤백 승인 요청");
350
+ });
351
+ });
352
+ });
@@ -0,0 +1,151 @@
1
+ import { existsSync } from "node:fs";
2
+ import {
3
+ chmod,
4
+ mkdir,
5
+ mkdtemp,
6
+ readFile,
7
+ realpath,
8
+ rm,
9
+ symlink,
10
+ writeFile,
11
+ } from "node:fs/promises";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ import Fastify, { type FastifyInstance } from "fastify";
16
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
17
+
18
+ import { Sonamu } from "../../api/sonamu";
19
+ import { setSDConfig } from "../../dict/sd";
20
+ import { type AbsolutePath } from "../../utils/path-utils";
21
+ import { registerOpenVscodeApi } from "../open-vscode-api";
22
+
23
+ /** 문자열이 `/`로 시작하는 절대 경로인지 확인해 AbsolutePath로 좁힙니다. */
24
+ function isAbsolutePath(value: string): value is AbsolutePath {
25
+ return value.startsWith("/");
26
+ }
27
+
28
+ describe("POST /sonamu-ui/api/tools/openVscode", () => {
29
+ const originalState = Sonamu.captureTestingSnapshot();
30
+ const originalPath = process.env.PATH;
31
+ let tempRoot: string;
32
+ let appRoot: string;
33
+ let markerPath: string;
34
+ let shimLogPath: string;
35
+ let server: FastifyInstance;
36
+
37
+ beforeEach(async () => {
38
+ tempRoot = await realpath(await mkdtemp(path.join(os.tmpdir(), "sonamu-open-vscode-test-")));
39
+ appRoot = path.join(tempRoot, "app");
40
+ await mkdir(path.join(appRoot, "api", "src"), { recursive: true });
41
+ markerPath = path.join(tempRoot, "pwned.txt");
42
+ shimLogPath = path.join(tempRoot, "code-args.log");
43
+
44
+ // 실제 VS Code 대신 받은 인자를 한 줄씩 기록하는 가짜 code 명령을 PATH 맨 앞에 둡니다.
45
+ const binPath = path.join(tempRoot, "bin");
46
+ await mkdir(binPath);
47
+ const shimPath = path.join(binPath, "code");
48
+ await writeFile(
49
+ shimPath,
50
+ `#!/bin/sh\nfor arg in "$@"; do printf '%s\\n' "$arg" >> '${shimLogPath}'; done\n`,
51
+ );
52
+ await chmod(shimPath, 0o755);
53
+ process.env.PATH = `${binPath}${path.delimiter}${originalPath ?? ""}`;
54
+
55
+ const apiRootPath = path.join(appRoot, "api");
56
+ if (!isAbsolutePath(apiRootPath)) {
57
+ throw new Error(`apiRootPath가 절대 경로가 아닙니다: ${apiRootPath}`);
58
+ }
59
+ Sonamu.apiRootPath = apiRootPath;
60
+ // 거부 응답의 오류 메시지를 만들 수 있도록 i18n 설정을 주입합니다.
61
+ setSDConfig({ defaultLocale: "ko", supportedLocales: ["ko"] });
62
+ server = Fastify();
63
+ await server.register(registerOpenVscodeApi, { prefix: "/sonamu-ui" });
64
+ await server.ready();
65
+ });
66
+
67
+ afterEach(async () => {
68
+ await server.close();
69
+ process.env.PATH = originalPath;
70
+ Sonamu.restoreTestingSnapshot(originalState);
71
+ await rm(tempRoot, { recursive: true, force: true });
72
+ });
73
+
74
+ async function openVscode(absPath: string) {
75
+ // 동일 출처 가드를 통과하는 Sonamu UI 요청 형식(JSON + X-Sonamu-UI)으로 보냅니다.
76
+ return server.inject({
77
+ method: "POST",
78
+ url: "/sonamu-ui/api/tools/openVscode",
79
+ headers: { "content-type": "application/json", "x-sonamu-ui": "1" },
80
+ payload: JSON.stringify({ absPath }),
81
+ });
82
+ }
83
+
84
+ async function readShimArgs(): Promise<string[] | null> {
85
+ if (!existsSync(shimLogPath)) {
86
+ return null;
87
+ }
88
+ return (await readFile(shimLogPath, "utf-8")).split("\n").filter((line) => line !== "");
89
+ }
90
+
91
+ it.each([
92
+ ["세미콜론", (marker: string) => `/tmp/x; touch '${marker}'`],
93
+ ["명령 치환 $( )", (marker: string) => `$(touch '${marker}')`],
94
+ ["백틱", (marker: string) => `\`touch '${marker}'\``],
95
+ ["파이프", (marker: string) => `/tmp/x | touch '${marker}'`],
96
+ ])("absPath에 %s가 있어도 셸 명령이 실행되지 않음", async (_label, buildPayload) => {
97
+ const response = await openVscode(buildPayload(markerPath));
98
+
99
+ expect(existsSync(markerPath)).toBe(false);
100
+ expect(await readShimArgs()).toBeNull();
101
+ expect(response.statusCode).toBe(400);
102
+ });
103
+
104
+ it("앱 루트 아래 파일 이름에 셸 메타문자가 있어도 인자 하나로만 전달됨", async () => {
105
+ const filePath = path.join(appRoot, "api", "src", "a; id $(id) `id` | id.ts");
106
+ await writeFile(filePath, "");
107
+
108
+ const response = await openVscode(filePath);
109
+
110
+ expect(response.statusCode).toBe(200);
111
+ expect(await readShimArgs()).toEqual(["--", filePath]);
112
+ });
113
+
114
+ it("옵션처럼 보이는 경로도 code 옵션으로 해석되지 않음", async () => {
115
+ const filePath = path.join(appRoot, "--install-extension=evil.ext");
116
+ await writeFile(filePath, "");
117
+
118
+ const response = await openVscode(filePath);
119
+
120
+ expect(response.statusCode).toBe(200);
121
+ expect(await readShimArgs()).toEqual(["--", filePath]);
122
+ });
123
+
124
+ it("앱 루트 밖 파일, 상위 경로 우회, 없는 파일, 디렉터리는 거부함", async () => {
125
+ const outsidePath = path.join(tempRoot, "outside.ts");
126
+ await writeFile(outsidePath, "");
127
+
128
+ for (const absPath of [
129
+ outsidePath,
130
+ path.join(appRoot, "api", "..", "..", "outside.ts"),
131
+ path.join(appRoot, "api", "src", "missing.ts"),
132
+ path.join(appRoot, "api", "src"),
133
+ ]) {
134
+ const response = await openVscode(absPath);
135
+ expect(response.statusCode).toBe(400);
136
+ }
137
+ expect(await readShimArgs()).toBeNull();
138
+ });
139
+
140
+ it("앱 루트 밖을 가리키는 심볼릭 링크는 거부함", async () => {
141
+ const outsidePath = path.join(tempRoot, "outside.ts");
142
+ await writeFile(outsidePath, "");
143
+ const linkPath = path.join(appRoot, "api", "src", "link.ts");
144
+ await symlink(outsidePath, linkPath);
145
+
146
+ const response = await openVscode(linkPath);
147
+
148
+ expect(response.statusCode).toBe(400);
149
+ expect(await readShimArgs()).toBeNull();
150
+ });
151
+ });