sonamu 0.13.10 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/dist/api/caster.d.ts.map +1 -1
  2. package/dist/api/caster.js +2 -1
  3. package/dist/api/code-converters.d.ts +5 -1
  4. package/dist/api/code-converters.d.ts.map +1 -1
  5. package/dist/api/code-converters.js +24 -7
  6. package/dist/api/config.d.ts +7 -0
  7. package/dist/api/config.d.ts.map +1 -1
  8. package/dist/api/config.js +1 -1
  9. package/dist/api/decorators.d.ts +1 -0
  10. package/dist/api/decorators.d.ts.map +1 -1
  11. package/dist/api/decorators.js +1 -1
  12. package/dist/api/guards.d.ts +37 -0
  13. package/dist/api/guards.d.ts.map +1 -0
  14. package/dist/api/guards.js +96 -0
  15. package/dist/api/sonamu.d.ts +14 -1
  16. package/dist/api/sonamu.d.ts.map +1 -1
  17. package/dist/api/sonamu.js +121 -25
  18. package/dist/api/websocket-helpers.d.ts +6 -1
  19. package/dist/api/websocket-helpers.d.ts.map +1 -1
  20. package/dist/api/websocket-helpers.js +7 -4
  21. package/dist/auth/auth-entity-policy.d.ts +32 -0
  22. package/dist/auth/auth-entity-policy.d.ts.map +1 -0
  23. package/dist/auth/auth-entity-policy.js +44 -0
  24. package/dist/auth/auth-secret.d.ts +24 -0
  25. package/dist/auth/auth-secret.d.ts.map +1 -0
  26. package/dist/auth/auth-secret.js +46 -0
  27. package/dist/auth/base-url.d.ts +39 -0
  28. package/dist/auth/base-url.d.ts.map +1 -0
  29. package/dist/auth/base-url.js +84 -0
  30. package/dist/auth/better-auth-entities.js +20 -7
  31. package/dist/auth/better-auth-options.d.ts +15 -0
  32. package/dist/auth/better-auth-options.d.ts.map +1 -0
  33. package/dist/auth/better-auth-options.js +38 -0
  34. package/dist/auth/better-auth-request.d.ts +8 -1
  35. package/dist/auth/better-auth-request.d.ts.map +1 -1
  36. package/dist/auth/better-auth-request.js +26 -3
  37. package/dist/auth/plugins/entity-definitions/admin.d.ts.map +1 -1
  38. package/dist/auth/plugins/entity-definitions/admin.js +6 -1
  39. package/dist/auth/plugins/entity-definitions/anonymous.d.ts.map +1 -1
  40. package/dist/auth/plugins/entity-definitions/anonymous.js +2 -1
  41. package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
  42. package/dist/auth/plugins/entity-definitions/api-key.js +18 -2
  43. package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
  44. package/dist/auth/plugins/entity-definitions/audit-log.js +27 -1
  45. package/dist/auth/plugins/entity-definitions/jwt.d.ts.map +1 -1
  46. package/dist/auth/plugins/entity-definitions/jwt.js +4 -2
  47. package/dist/auth/plugins/entity-definitions/organization.d.ts.map +1 -1
  48. package/dist/auth/plugins/entity-definitions/organization.js +15 -1
  49. package/dist/auth/plugins/entity-definitions/passkey.d.ts.map +1 -1
  50. package/dist/auth/plugins/entity-definitions/passkey.js +9 -1
  51. package/dist/auth/plugins/entity-definitions/phone-number.d.ts.map +1 -1
  52. package/dist/auth/plugins/entity-definitions/phone-number.js +2 -1
  53. package/dist/auth/plugins/entity-definitions/sso.d.ts.map +1 -1
  54. package/dist/auth/plugins/entity-definitions/sso.js +7 -3
  55. package/dist/auth/plugins/entity-definitions/two-factor.d.ts.map +1 -1
  56. package/dist/auth/plugins/entity-definitions/two-factor.js +8 -3
  57. package/dist/auth/verify-email-guard.d.ts +37 -0
  58. package/dist/auth/verify-email-guard.d.ts.map +1 -0
  59. package/dist/auth/verify-email-guard.js +48 -0
  60. package/dist/bin/build-config.d.ts.map +1 -1
  61. package/dist/bin/build-config.js +6 -2
  62. package/dist/bin/typecheck-web.js +1 -1
  63. package/dist/cache/decorator.d.ts +12 -0
  64. package/dist/cache/decorator.d.ts.map +1 -1
  65. package/dist/cache/decorator.js +86 -19
  66. package/dist/cache/index.d.ts +1 -1
  67. package/dist/cache/index.d.ts.map +1 -1
  68. package/dist/cache/index.js +3 -3
  69. package/dist/cache/types.d.ts +16 -0
  70. package/dist/cache/types.d.ts.map +1 -1
  71. package/dist/cli/plugin-loader.d.ts +17 -0
  72. package/dist/cli/plugin-loader.d.ts.map +1 -0
  73. package/dist/cli/plugin-loader.js +178 -0
  74. package/dist/cli/plugin.d.ts +65 -0
  75. package/dist/cli/plugin.d.ts.map +1 -0
  76. package/dist/cli/plugin.js +7 -0
  77. package/dist/code-formatting/oxfmt.js +1 -1
  78. package/dist/code-formatting/oxlint.js +1 -1
  79. package/dist/database/db.d.ts +35 -10
  80. package/dist/database/db.d.ts.map +1 -1
  81. package/dist/database/db.js +37 -4
  82. package/dist/database/puri.d.ts +8 -0
  83. package/dist/database/puri.d.ts.map +1 -1
  84. package/dist/database/puri.js +108 -171
  85. package/dist/database/puri.types.d.ts +2 -0
  86. package/dist/database/puri.types.d.ts.map +1 -1
  87. package/dist/database/puri.types.js +1 -1
  88. package/dist/database/sql-expression-brand.d.ts +10 -0
  89. package/dist/database/sql-expression-brand.d.ts.map +1 -0
  90. package/dist/database/sql-expression-brand.js +10 -0
  91. package/dist/dict/en.d.ts +1 -0
  92. package/dist/dict/en.d.ts.map +1 -1
  93. package/dist/dict/en.js +2 -1
  94. package/dist/dict/ko.d.ts +1 -0
  95. package/dist/dict/ko.d.ts.map +1 -1
  96. package/dist/dict/ko.js +2 -1
  97. package/dist/dict/sonamu-dictionary.d.ts +23 -1
  98. package/dist/dict/sonamu-dictionary.d.ts.map +1 -1
  99. package/dist/dict/sonamu-dictionary.js +187 -32
  100. package/dist/entity/entity-codegen-safety.d.ts +105 -0
  101. package/dist/entity/entity-codegen-safety.d.ts.map +1 -0
  102. package/dist/entity/entity-codegen-safety.js +70 -0
  103. package/dist/entity/entity-manager.d.ts +32 -0
  104. package/dist/entity/entity-manager.d.ts.map +1 -1
  105. package/dist/entity/entity-manager.js +21 -2
  106. package/dist/entity/entity.d.ts +5 -2
  107. package/dist/entity/entity.d.ts.map +1 -1
  108. package/dist/entity/entity.js +19 -8
  109. package/dist/env.d.ts +19 -0
  110. package/dist/env.d.ts.map +1 -1
  111. package/dist/env.js +31 -3
  112. package/dist/filter/utils.d.ts +2 -2
  113. package/dist/filter/utils.d.ts.map +1 -1
  114. package/dist/filter/utils.js +16 -11
  115. package/dist/index.d.ts +4 -3
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +7 -6
  118. package/dist/logger/configure.d.ts.map +1 -1
  119. package/dist/logger/configure.js +10 -3
  120. package/dist/migration/code-generation.d.ts.map +1 -1
  121. package/dist/migration/code-generation.js +177 -96
  122. package/dist/migration/migrator.d.ts +16 -0
  123. package/dist/migration/migrator.d.ts.map +1 -1
  124. package/dist/migration/migrator.js +28 -3
  125. package/dist/migration/slack-confirm.d.ts +6 -2
  126. package/dist/migration/slack-confirm.d.ts.map +1 -1
  127. package/dist/migration/slack-confirm.js +11 -9
  128. package/dist/ssr/errors.d.ts +13 -0
  129. package/dist/ssr/errors.d.ts.map +1 -0
  130. package/dist/ssr/errors.js +12 -0
  131. package/dist/ssr/index.d.ts +1 -0
  132. package/dist/ssr/index.d.ts.map +1 -1
  133. package/dist/ssr/index.js +5 -2
  134. package/dist/ssr/renderer.d.ts +6 -0
  135. package/dist/ssr/renderer.d.ts.map +1 -1
  136. package/dist/ssr/renderer.js +10 -1
  137. package/dist/storage/base-file.d.ts +6 -2
  138. package/dist/storage/base-file.d.ts.map +1 -1
  139. package/dist/storage/base-file.js +10 -5
  140. package/dist/storage/buffered-file.d.ts +1 -0
  141. package/dist/storage/buffered-file.d.ts.map +1 -1
  142. package/dist/storage/buffered-file.js +5 -2
  143. package/dist/storage/index.d.ts +1 -0
  144. package/dist/storage/index.d.ts.map +1 -1
  145. package/dist/storage/index.js +4 -2
  146. package/dist/storage/upload-safety.d.ts +47 -0
  147. package/dist/storage/upload-safety.d.ts.map +1 -0
  148. package/dist/storage/upload-safety.js +112 -0
  149. package/dist/stream/ws.d.ts +6 -0
  150. package/dist/stream/ws.d.ts.map +1 -1
  151. package/dist/stream/ws.js +52 -6
  152. package/dist/syncer/api-parser.js +6 -1
  153. package/dist/syncer/code-generator.d.ts +2 -0
  154. package/dist/syncer/code-generator.d.ts.map +1 -1
  155. package/dist/syncer/code-generator.js +21 -7
  156. package/dist/template/implementations/entity.template.d.ts.map +1 -1
  157. package/dist/template/implementations/entity.template.js +40 -35
  158. package/dist/template/implementations/generated.template.d.ts +10 -0
  159. package/dist/template/implementations/generated.template.d.ts.map +1 -1
  160. package/dist/template/implementations/generated.template.js +46 -7
  161. package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
  162. package/dist/template/implementations/generated_http.template.js +3 -1
  163. package/dist/template/implementations/init_types.template.d.ts.map +1 -1
  164. package/dist/template/implementations/init_types.template.js +3 -8
  165. package/dist/template/implementations/model.template.d.ts.map +1 -1
  166. package/dist/template/implementations/model.template.js +9 -2
  167. package/dist/template/implementations/sd.template.d.ts +0 -1
  168. package/dist/template/implementations/sd.template.d.ts.map +1 -1
  169. package/dist/template/implementations/sd.template.js +2 -5
  170. package/dist/template/implementations/view_form.template.d.ts.map +1 -1
  171. package/dist/template/implementations/view_form.template.js +8 -6
  172. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  173. package/dist/template/implementations/view_list.template.js +8 -4
  174. package/dist/testing/dev-test-routes.d.ts.map +1 -1
  175. package/dist/testing/dev-test-routes.js +7 -4
  176. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
  177. package/dist/tooling/cdd-service.js +1 -1
  178. package/dist/tooling/index.d.ts +1 -0
  179. package/dist/tooling/index.d.ts.map +1 -1
  180. package/dist/tooling/index.js +3 -1
  181. package/dist/tsdown.api.config.js +1 -1
  182. package/dist/types/types.d.ts +81 -1
  183. package/dist/types/types.d.ts.map +1 -1
  184. package/dist/types/types.js +2 -1
  185. package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
  186. package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
  187. package/dist/ui/__tests__/ui-test-helpers.js +75 -0
  188. package/dist/ui/access-guard.d.ts +42 -0
  189. package/dist/ui/access-guard.d.ts.map +1 -0
  190. package/dist/ui/access-guard.js +94 -0
  191. package/dist/ui/api.d.ts.map +1 -1
  192. package/dist/ui/api.js +40 -95
  193. package/dist/ui/dev-host-guard.d.ts +28 -0
  194. package/dist/ui/dev-host-guard.d.ts.map +1 -0
  195. package/dist/ui/dev-host-guard.js +67 -0
  196. package/dist/ui/migrations-api.d.ts.map +1 -1
  197. package/dist/ui/migrations-api.js +72 -16
  198. package/dist/ui/open-vscode-api.d.ts +4 -0
  199. package/dist/ui/open-vscode-api.d.ts.map +1 -0
  200. package/dist/ui/open-vscode-api.js +65 -0
  201. package/dist/ui/scaffolding-api.d.ts +18 -0
  202. package/dist/ui/scaffolding-api.d.ts.map +1 -0
  203. package/dist/ui/scaffolding-api.js +111 -0
  204. package/dist/ui/ui-db-presets.d.ts +19 -0
  205. package/dist/ui/ui-db-presets.d.ts.map +1 -0
  206. package/dist/ui/ui-db-presets.js +34 -0
  207. package/dist/ui/ui-request-guard.d.ts +11 -0
  208. package/dist/ui/ui-request-guard.d.ts.map +1 -0
  209. package/dist/ui/ui-request-guard.js +38 -0
  210. package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
  211. package/dist/ui-web/index.html +2 -1
  212. package/package.json +1 -1
  213. package/src/__tests__/env.test.ts +121 -2
  214. package/src/api/__tests__/code-converters.union.test.ts +97 -0
  215. package/src/api/__tests__/guards.test.ts +233 -0
  216. package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
  217. package/src/api/__tests__/sonamu.dev-host-guard.test.ts +130 -0
  218. package/src/api/__tests__/sonamu.guards.test.ts +327 -0
  219. package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
  220. package/src/api/__tests__/websocket-helpers.test.ts +101 -0
  221. package/src/api/caster.ts +7 -0
  222. package/src/api/code-converters.ts +44 -12
  223. package/src/api/config.ts +8 -0
  224. package/src/api/decorators.ts +1 -0
  225. package/src/api/guards.ts +130 -0
  226. package/src/api/sonamu.ts +195 -39
  227. package/src/api/websocket-helpers.ts +11 -6
  228. package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
  229. package/src/auth/__tests__/auth-secret.test.ts +133 -0
  230. package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
  231. package/src/auth/__tests__/base-url.test.ts +117 -0
  232. package/src/auth/__tests__/better-auth-options.test.ts +194 -0
  233. package/src/auth/__tests__/better-auth-request.test.ts +45 -0
  234. package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
  235. package/src/auth/auth-entity-policy.ts +48 -0
  236. package/src/auth/auth-secret.ts +77 -0
  237. package/src/auth/base-url.ts +109 -0
  238. package/src/auth/better-auth-entities.ts +30 -30
  239. package/src/auth/better-auth-options.ts +39 -0
  240. package/src/auth/better-auth-request.ts +28 -1
  241. package/src/auth/plugins/entity-definitions/admin.ts +5 -0
  242. package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
  243. package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
  244. package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
  245. package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
  246. package/src/auth/plugins/entity-definitions/organization.ts +26 -6
  247. package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
  248. package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
  249. package/src/auth/plugins/entity-definitions/sso.ts +20 -15
  250. package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
  251. package/src/auth/verify-email-guard.ts +82 -0
  252. package/src/bin/__tests__/build-web-command.test.ts +24 -0
  253. package/src/bin/build-config.ts +5 -0
  254. package/src/cache/decorator.ts +116 -21
  255. package/src/cache/index.ts +6 -1
  256. package/src/cache/types.ts +18 -0
  257. package/src/cli/plugin-loader.ts +238 -0
  258. package/src/cli/plugin.ts +82 -0
  259. package/src/database/__tests__/db.test.ts +64 -1
  260. package/src/database/__tests__/puri.test.ts +56 -0
  261. package/src/database/db.ts +56 -6
  262. package/src/database/puri.ts +135 -125
  263. package/src/database/puri.types.test-d.ts +12 -0
  264. package/src/database/puri.types.ts +3 -0
  265. package/src/database/sql-expression-brand.ts +9 -0
  266. package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
  267. package/src/dict/en.ts +2 -0
  268. package/src/dict/ko.ts +2 -0
  269. package/src/dict/sonamu-dictionary.ts +298 -38
  270. package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
  271. package/src/entity/entity-codegen-safety.ts +126 -0
  272. package/src/entity/entity-manager.ts +29 -1
  273. package/src/entity/entity.ts +26 -12
  274. package/src/env.ts +52 -1
  275. package/src/filter/utils.ts +19 -7
  276. package/src/index.ts +4 -3
  277. package/src/logger/__tests__/configure.test.ts +51 -1
  278. package/src/logger/configure.ts +14 -1
  279. package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
  280. package/src/migration/__tests__/migrator.test.ts +76 -1
  281. package/src/migration/code-generation.ts +247 -117
  282. package/src/migration/migrator.ts +45 -4
  283. package/src/migration/slack-confirm.ts +19 -5
  284. package/src/ssr/__tests__/preload-guard.test.ts +274 -0
  285. package/src/ssr/errors.ts +11 -0
  286. package/src/ssr/index.ts +1 -0
  287. package/src/ssr/renderer.ts +12 -0
  288. package/src/storage/__tests__/upload-safety.test.ts +179 -0
  289. package/src/storage/base-file.ts +8 -4
  290. package/src/storage/buffered-file.ts +3 -1
  291. package/src/storage/index.ts +9 -0
  292. package/src/storage/upload-safety.ts +155 -0
  293. package/src/stream/__tests__/ws.test.ts +97 -0
  294. package/src/stream/ws.ts +67 -5
  295. package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
  296. package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
  297. package/src/syncer/api-parser.ts +12 -0
  298. package/src/syncer/code-generator.ts +34 -6
  299. package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
  300. package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
  301. package/src/template/__tests__/save-params.template.test.ts +219 -0
  302. package/src/template/implementations/entity.template.ts +53 -48
  303. package/src/template/implementations/generated.template.ts +87 -12
  304. package/src/template/implementations/generated_http.template.ts +5 -0
  305. package/src/template/implementations/init_types.template.ts +4 -22
  306. package/src/template/implementations/model.template.ts +15 -1
  307. package/src/template/implementations/sd.template.ts +4 -5
  308. package/src/template/implementations/view_form.template.ts +13 -5
  309. package/src/template/implementations/view_list.template.ts +12 -3
  310. package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
  311. package/src/testing/dev-test-routes.ts +7 -3
  312. package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
  313. package/src/tooling/index.ts +1 -0
  314. package/src/types/types.ts +22 -1
  315. package/src/ui/__tests__/access-guard.test.ts +217 -0
  316. package/src/ui/__tests__/dev-host-guard.test.ts +161 -0
  317. package/src/ui/__tests__/fixture-api.test.ts +92 -0
  318. package/src/ui/__tests__/migrations-api.test.ts +352 -0
  319. package/src/ui/__tests__/open-vscode.test.ts +151 -0
  320. package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
  321. package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
  322. package/src/ui/__tests__/ui-test-helpers.ts +71 -0
  323. package/src/ui/access-guard.ts +115 -0
  324. package/src/ui/api.ts +65 -198
  325. package/src/ui/dev-host-guard.ts +109 -0
  326. package/src/ui/migrations-api.ts +130 -24
  327. package/src/ui/open-vscode-api.ts +82 -0
  328. package/src/ui/scaffolding-api.ts +177 -0
  329. package/src/ui/ui-db-presets.ts +41 -0
  330. package/src/ui/ui-request-guard.ts +53 -0
package/src/ui/api.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { execFileSync, execSync } from "child_process";
1
+ import { execFileSync } from "child_process";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
4
 
@@ -14,17 +14,12 @@ import { SD } from "../dict/sd";
14
14
  import { sonamuDictionary } from "../dict/sonamu-dictionary";
15
15
  import { type Entity } from "../entity/entity";
16
16
  import { EntityManager } from "../entity/entity-manager";
17
- import {
18
- BadRequestException,
19
- isSoException,
20
- ServiceUnavailableException,
21
- } from "../exceptions/so-exceptions";
22
- import { TemplateManager } from "../template/template-manager";
17
+ import { BadRequestException } from "../exceptions/so-exceptions";
23
18
  import { DataExplorer, type DataExplorerOptions } from "../testing/data-explorer";
24
19
  import { FixtureGenerator, type FixtureGenerationSpec } from "../testing/fixture-generator";
25
20
  import { FixtureManager } from "../testing/fixture-manager";
26
21
  import { type DuplicateCheckOptions } from "../testing/fixture-manager";
27
- import { BUILT_IN_TYPE_IDS, TemplateKey } from "../types/types";
22
+ import { BUILT_IN_TYPE_IDS } from "../types/types";
28
23
  import {
29
24
  type Cone,
30
25
  type EntityIndex,
@@ -33,10 +28,14 @@ import {
33
28
  type FixtureRecord,
34
29
  type FixtureSearchOptions,
35
30
  type FlattenSubsetRow,
36
- type PathAndCode,
37
31
  } from "../types/types";
38
32
  import { isObjectValue } from "../utils/runtime-value";
39
- import { nonNullable } from "../utils/utils";
33
+ import {
34
+ canServeSonamuUIToken,
35
+ getSonamuUIToken,
36
+ requireSonamuUIToken,
37
+ SONAMU_UI_TOKEN_PLACEHOLDER,
38
+ } from "./access-guard";
40
39
  import { setAiApi } from "./ai-api";
41
40
  import { forwardAsyncErrors } from "./async-route";
42
41
  import { type CddAddRuleRequest } from "./cdd-service";
@@ -51,11 +50,10 @@ import {
51
50
  readRule,
52
51
  } from "./cdd-service";
53
52
  import { registerMigrationsApi } from "./migrations-api";
54
-
55
- interface EntityTemplateInput {
56
- entityId: string;
57
- enumId?: string;
58
- }
53
+ import { registerOpenVscodeApi } from "./open-vscode-api";
54
+ import { registerScaffoldingApi } from "./scaffolding-api";
55
+ import { assertUIDBPreset } from "./ui-db-presets";
56
+ import { requireSameOriginUIRequest } from "./ui-request-guard";
59
57
 
60
58
  async function waitForHMRCompleted<T>(fn: () => Promise<T>): Promise<T> {
61
59
  const waitPromise = new Promise<void>((resolve) => {
@@ -87,6 +85,19 @@ function flattenSubsetRows(subsetRows: EntitySubsetRow[]): FlattenSubsetRow[] {
87
85
  export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
88
86
  fastify.register(
89
87
  async (server) => {
88
+ // 이 범위에 등록되는 모든 API 라우트(이후 추가되는 라우트 포함)에 접근 토큰 검사를 붙입니다.
89
+ // 원본 URL이 아니라 매칭된 라우트 패턴으로 판정하므로 퍼센트 인코딩 등으로 우회할 수 없습니다.
90
+ server.addHook("onRoute", (routeOptions) => {
91
+ if (!routeOptions.url.startsWith(`${routeOptions.prefix}/api/`)) {
92
+ return;
93
+ }
94
+ const existing = routeOptions.onRequest;
95
+ routeOptions.onRequest = [
96
+ requireSonamuUIToken,
97
+ ...(existing === undefined ? [] : Array.isArray(existing) ? existing : [existing]),
98
+ ];
99
+ });
100
+
90
101
  await setAiApi(server);
91
102
  await registerMigrationsApi(server);
92
103
 
@@ -94,64 +105,27 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
94
105
  return Sonamu.config;
95
106
  });
96
107
 
97
- server.get<{
98
- Querystring: {
99
- entityId?: string;
100
- preset?: "types" | "entity.json" | "generated";
101
- absPath?: string;
102
- };
103
- }>("/api/tools/openVscode", (request) =>
104
- forwardAsyncErrors(async () => {
105
- const { entityId, preset, absPath } = request.query;
106
-
107
- const targetPath = (() => {
108
- if (entityId && preset) {
109
- const entity = EntityManager.get(entityId);
110
- const { names } = entity;
111
-
112
- const { apiRootPath } = Sonamu;
113
- const filename = (() => {
114
- switch (preset) {
115
- case "types":
116
- return `${names.fs}.types.ts`;
117
- case "entity.json":
118
- return `${names.fs}.entity.json`;
119
- case "generated":
120
- return `${names.fs}.generated.ts`;
121
- }
122
- return undefined;
123
- })();
124
- return `${apiRootPath}/src/application/${entity.names.parentFs}/${filename}`;
125
- } else {
126
- if (!absPath) {
127
- throw new BadRequestException(SD("sonamu.error.presetOrAbsPathRequired"));
128
- }
129
- return absPath;
130
- }
131
- })();
132
- execSync(`code ${targetPath}`);
133
- }),
134
- );
108
+ await registerOpenVscodeApi(server);
135
109
 
136
- server.get<{
137
- Querystring: {
110
+ server.post<{
111
+ Body: {
138
112
  editor: "vscode" | "cursor" | "zed";
139
113
  absPath: string;
140
114
  };
141
- }>("/api/tools/openEditor", (request) =>
115
+ }>("/api/tools/openEditor", { onRequest: requireSameOriginUIRequest }, (request) =>
142
116
  forwardAsyncErrors(async () => {
143
117
  const commands = {
144
118
  vscode: "code",
145
119
  cursor: "cursor",
146
120
  zed: "zed",
147
121
  } as const;
148
- const command = commands[request.query.editor];
122
+ const command = commands[request.body.editor];
149
123
  if (command === undefined) {
150
124
  throw new BadRequestException(SD("error.badRequest"));
151
125
  }
152
126
 
153
127
  // 셸을 거치지 않아 파일 경로가 명령으로 해석되지 않도록 합니다.
154
- execFileSync(command, [request.query.absPath]);
128
+ execFileSync(command, [request.body.absPath]);
155
129
  }),
156
130
  );
157
131
 
@@ -503,7 +477,7 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
503
477
  const { entityId, at, newProp } = request.body;
504
478
 
505
479
  const entity = EntityManager.get(entityId);
506
- entity.modifyProp(newProp, at);
480
+ await entity.modifyProp(newProp, at);
507
481
 
508
482
  return true;
509
483
  });
@@ -521,7 +495,7 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
521
495
  const { entityId, at } = request.body;
522
496
 
523
497
  const entity = EntityManager.get(entityId);
524
- entity.delProp(at);
498
+ await entity.delProp(at);
525
499
  return true;
526
500
  });
527
501
  }),
@@ -539,7 +513,7 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
539
513
  const { entityId, at, to } = request.body;
540
514
 
541
515
  const entity = EntityManager.get(entityId);
542
- entity.moveProp(at, to);
516
+ await entity.moveProp(at, to);
543
517
 
544
518
  return true;
545
519
  });
@@ -794,130 +768,7 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
794
768
  }),
795
769
  );
796
770
 
797
- server.post<{
798
- Body: {
799
- entityIds: string[];
800
- templateKeys: string[];
801
- };
802
- }>("/api/scaffolding/getStatus", (request) =>
803
- forwardAsyncErrors(async () => {
804
- const { entityIds, templateKeys: _templateKeys } = request.body;
805
- if ((entityIds ?? []).length === 0) {
806
- throw new BadRequestException(SD("sonamu.error.entityIdsRequired"));
807
- } else if ((_templateKeys ?? []).length === 0) {
808
- throw new BadRequestException(SD("sonamu.error.templateKeysRequired"));
809
- }
810
-
811
- // sorting
812
- entityIds.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
813
- const templateKeys = TemplateKey.options.filter((tk) => _templateKeys.includes(tk));
814
-
815
- const combinations = entityIds.flatMap((entityId) => {
816
- return templateKeys.map((templateKey) => [entityId, templateKey]);
817
- });
818
-
819
- const statuses = await Promise.all(
820
- combinations.map(async ([entityId, templateKey]) => {
821
- const { subPath, fullPath, isExists } = await Sonamu.syncer.checkExistsGenCode(
822
- entityId,
823
- /* SAFETY: UI 도구의 Zod 입력 스키마가 이 값의 타입을 보장한다. */ templateKey as TemplateKey,
824
- );
825
- return {
826
- entityId,
827
- templateKey,
828
- subPath,
829
- fullPath,
830
- isExists,
831
- };
832
- }),
833
- );
834
- return { statuses };
835
- }),
836
- );
837
-
838
- server.post<{
839
- Body: {
840
- options: {
841
- entityId: string;
842
- templateKey: string;
843
- enumId?: string;
844
- overwrite?: boolean;
845
- }[];
846
- };
847
- }>("/api/scaffolding/generate", (request) =>
848
- forwardAsyncErrors(async () => {
849
- const { options } = request.body;
850
- if (options.length === 0) {
851
- throw new BadRequestException(SD("sonamu.error.optionsRequired"));
852
- }
853
-
854
- // 1. 모든 템플릿에서 필요한 dict 키를 수집
855
- const keys = options.flatMap(({ templateKey }) => {
856
- const template = TemplateManager.get(templateKey);
857
- return template.getRequiredDictKeys() ?? [];
858
- });
859
-
860
- // 2. target별로 ensureDictKeys 호출 (순차 처리)
861
- await sonamuDictionary.ensureDictKeys([...new Set(keys)]);
862
-
863
- // 3. 템플릿 생성 (병렬 처리)
864
- const result = await Promise.all(
865
- options.map(async ({ entityId, templateKey, enumId, overwrite }) => {
866
- try {
867
- return await Sonamu.syncer.generateTemplate(
868
- /* SAFETY: UI 도구의 Zod 입력 스키마가 이 값의 타입을 보장한다. */ templateKey as TemplateKey,
869
- /* SAFETY: UI 도구의 Zod 입력 스키마가 Entity 템플릿 옵션을 보장한다. */ {
870
- entityId,
871
- enumId,
872
- } as EntityTemplateInput,
873
- {
874
- overwrite,
875
- },
876
- );
877
- } catch (e) {
878
- if (isSoException(e) && e.statusCode === 541) {
879
- return null;
880
- } else {
881
- console.error(e);
882
- throw e;
883
- }
884
- }
885
- }),
886
- );
887
-
888
- if (result.filter(nonNullable).length === 0) {
889
- throw new ServiceUnavailableException(SD("sonamu.error.allFilesGenerated"));
890
- }
891
- return result;
892
- }),
893
- );
894
-
895
- server.post<{
896
- Body: {
897
- option: {
898
- entityId: string;
899
- templateKey: string;
900
- enumId?: string;
901
- };
902
- };
903
- }>("/api/scaffolding/preview", (request): Promise<{ pathAndCodes: PathAndCode[] }> =>
904
- forwardAsyncErrors(async () => {
905
- const { option } = request.body;
906
-
907
- try {
908
- const { templateKey, ...templateOptions } = option;
909
- const pathAndCodes = await Sonamu.syncer.renderTemplate(
910
- /* SAFETY: UI 도구의 Zod 입력 스키마가 이 값의 타입을 보장한다. */ templateKey as TemplateKey,
911
- templateOptions,
912
- );
913
-
914
- return { pathAndCodes };
915
- } catch (e) {
916
- console.error(e);
917
- throw e;
918
- }
919
- }),
920
- );
771
+ await registerScaffoldingApi(server);
921
772
 
922
773
  server.post("/api/fixture", (request) =>
923
774
  forwardAsyncErrors(async () => {
@@ -928,6 +779,9 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
928
779
  search: FixtureSearchOptions;
929
780
  duplicateCheck?: DuplicateCheckOptions;
930
781
  };
782
+ // 운영 계열 DB를 브라우저 요청으로 조회하거나 비교하지 않도록 프리셋을 제한합니다.
783
+ assertUIDBPreset(sourceDB, Sonamu.dbConfig, "sourceDB");
784
+ assertUIDBPreset(targetDB, Sonamu.dbConfig, "targetDB");
931
785
 
932
786
  return FixtureManager.getFixtures(sourceDB, targetDB, search, duplicateCheck);
933
787
  }),
@@ -940,6 +794,7 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
940
794
  db: keyof SonamuDBConfig;
941
795
  fixtures: FixtureRecord[];
942
796
  };
797
+ assertUIDBPreset(db, Sonamu.dbConfig, "db");
943
798
 
944
799
  return FixtureManager.insertFixtures(db, fixtures);
945
800
  }),
@@ -1369,19 +1224,25 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
1369
1224
  }),
1370
1225
  );
1371
1226
 
1372
- server.post<{ Body: { filePath: string } }>("/api/cdd/editContent", (request) =>
1373
- forwardAsyncErrors(async () => {
1374
- const { filePath } = request.body;
1375
- return editContent(filePath);
1376
- }),
1227
+ server.post<{ Body: { filePath: string } }>(
1228
+ "/api/cdd/editContent",
1229
+ { onRequest: requireSameOriginUIRequest },
1230
+ (request) =>
1231
+ forwardAsyncErrors(async () => {
1232
+ const { filePath } = request.body;
1233
+ return editContent(filePath);
1234
+ }),
1377
1235
  );
1378
1236
 
1379
- server.post<{ Body: { filePath: string } }>("/api/cdd/openSource", (request) =>
1380
- forwardAsyncErrors(async () => {
1381
- const { filePath } = request.body;
1382
- openSourceFile(filePath);
1383
- return { success: true };
1384
- }),
1237
+ server.post<{ Body: { filePath: string } }>(
1238
+ "/api/cdd/openSource",
1239
+ { onRequest: requireSameOriginUIRequest },
1240
+ (request) =>
1241
+ forwardAsyncErrors(async () => {
1242
+ const { filePath } = request.body;
1243
+ openSourceFile(filePath);
1244
+ return { success: true };
1245
+ }),
1385
1246
  );
1386
1247
 
1387
1248
  // CDD Rules API
@@ -1416,15 +1277,21 @@ export async function sonamuUIApiPlugin(fastify: FastifyInstance) {
1416
1277
  prefix: "/",
1417
1278
  decorateReply: false,
1418
1279
  wildcard: false,
1280
+ // index.html은 접근 토큰을 넣어야 하므로 아래 SPA fallback에서만 내려줍니다.
1281
+ index: false,
1419
1282
  });
1420
1283
 
1421
1284
  // SPA fallback - 정적 파일이 없는 모든 경로는 index.html로
1422
- server.get("*", async (_request, reply) => {
1285
+ server.get("*", async (request, reply) => {
1286
+ if (!canServeSonamuUIToken(request)) {
1287
+ return reply.code(403).send({ message: SD("error.forbidden"), issues: [] });
1288
+ }
1423
1289
  reply.headers({ "Content-type": "text/html" }).send(
1424
1290
  fs
1425
1291
  .readFileSync(path.resolve(uiDistPath, "index.html"))
1426
1292
  .toString()
1427
- .replace("{{projectName}}", Sonamu.config.projectName ?? "UnknownSonamuProject"),
1293
+ .replace("{{projectName}}", Sonamu.config.projectName ?? "UnknownSonamuProject")
1294
+ .replace(SONAMU_UI_TOKEN_PLACEHOLDER, getSonamuUIToken()),
1428
1295
  );
1429
1296
  });
1430
1297
  },
@@ -0,0 +1,109 @@
1
+ import { isIP } from "node:net";
2
+
3
+ import { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
4
+
5
+ import { type SonamuServerOptions } from "../api/config";
6
+ import { SD } from "../dict/sd";
7
+
8
+ /** Host 헤더에서 호스트 이름과 포트만 받아들입니다. userinfo·경로·공백이 섞인 값은 거부합니다. */
9
+ const HOST_HEADER_PATTERN =
10
+ /^(?:\[(?<ipv6>[0-9a-f:.]+)\]|(?<name>[^\s:@/?#[\]\\]+))(?::\d{1,5})?$/i;
11
+
12
+ /**
13
+ * 개발 서버의 Sonamu UI·dev 라우트가 받아들일 Host 헤더인지 판정합니다.
14
+ *
15
+ * DNS rebinding은 공격자가 소유한 도메인 이름을 개발자 PC 주소로 바꿔치기하므로
16
+ * 브라우저가 보내는 Host에는 공격자 도메인이 남습니다. 따라서 공격자가 이름을 소유할 수 없는
17
+ * localhost, *.localhost, IP 리터럴과 설정에 적힌 호스트만 허용합니다.
18
+ *
19
+ * @param hostHeader 요청의 Host 헤더 값
20
+ * @param configuredHostnames server.listen.host, server.baseUrl처럼 앱이 직접 설정한 호스트 이름
21
+ */
22
+ export function isAllowedDevHost(
23
+ hostHeader: string | undefined,
24
+ configuredHostnames: readonly string[] = [],
25
+ ): boolean {
26
+ if (hostHeader === undefined) {
27
+ return false;
28
+ }
29
+ const groups = HOST_HEADER_PATTERN.exec(hostHeader.trim())?.groups;
30
+ if (groups === undefined) {
31
+ return false;
32
+ }
33
+
34
+ const ipv6 = groups.ipv6;
35
+ if (ipv6 !== undefined) {
36
+ return isIP(ipv6) === 6;
37
+ }
38
+
39
+ const hostname = groups.name?.toLowerCase();
40
+ if (hostname === undefined) {
41
+ return false;
42
+ }
43
+ // IP 리터럴은 DNS를 거치지 않아 rebinding 대상이 될 수 없습니다(Vite allowedHosts 기본 규칙과 같음).
44
+ if (isIP(hostname) !== 0) {
45
+ return true;
46
+ }
47
+ if (hostname === "localhost" || hostname.endsWith(".localhost")) {
48
+ return true;
49
+ }
50
+ return configuredHostnames.some((configured) => configured.toLowerCase() === hostname);
51
+ }
52
+
53
+ /**
54
+ * 서버 설정에서 개발자가 직접 지정한 호스트 이름(listen.host, baseUrl의 호스트)을 모읍니다.
55
+ */
56
+ export function getConfiguredDevHostnames(
57
+ serverOptions: Pick<SonamuServerOptions, "baseUrl" | "listen">,
58
+ ): string[] {
59
+ const hostnames: string[] = [];
60
+ const listenHost = serverOptions.listen?.host;
61
+ if (listenHost !== undefined && listenHost !== "") {
62
+ hostnames.push(listenHost);
63
+ }
64
+ if (serverOptions.baseUrl !== undefined) {
65
+ try {
66
+ hostnames.push(new URL(serverOptions.baseUrl).hostname.replace(/^\[(.*)\]$/, "$1"));
67
+ } catch {
68
+ // URL이 아닌 baseUrl은 허용 호스트에 더하지 않습니다.
69
+ }
70
+ }
71
+ return hostnames;
72
+ }
73
+
74
+ function isUnderPrefix(routeUrl: string, prefix: string): boolean {
75
+ // prefix를 둔 플러그인의 "*" 라우트는 "/sonamu-ui*"로 합쳐지므로 "*" 경계도 같은 라우트 묶음으로 봅니다.
76
+ return (
77
+ routeUrl === prefix || routeUrl.startsWith(`${prefix}/`) || routeUrl.startsWith(`${prefix}*`)
78
+ );
79
+ }
80
+
81
+ /**
82
+ * 허용되지 않은 Host로 들어온 Sonamu UI·dev 라우트 요청을 403으로 거부하는 onRequest 훅을 등록합니다.
83
+ *
84
+ * 매칭된 라우트 경로(routeOptions.url)가 protectedPrefixes 아래일 때만 검사하므로
85
+ * 앱 API와 404 응답에는 영향을 주지 않습니다. 보호할 라우트를 등록하기 전에 호출해야 합니다.
86
+ */
87
+ export function registerDevHostGuard(
88
+ server: FastifyInstance,
89
+ options: { configuredHostnames: readonly string[]; protectedPrefixes: readonly string[] },
90
+ ): void {
91
+ const prefixes = options.protectedPrefixes
92
+ .map((prefix) => prefix.replace(/\/+$/, ""))
93
+ .filter((prefix) => prefix !== "");
94
+
95
+ server.addHook(
96
+ "onRequest",
97
+ async (request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply | undefined> => {
98
+ const routeUrl = request.routeOptions.url;
99
+ if (routeUrl === undefined || !prefixes.some((prefix) => isUnderPrefix(routeUrl, prefix))) {
100
+ return undefined;
101
+ }
102
+ if (isAllowedDevHost(request.headers.host, options.configuredHostnames)) {
103
+ return undefined;
104
+ }
105
+ // async 훅에서 응답을 끝낼 때는 reply를 반환해야 핸들러로 넘어가지 않습니다.
106
+ return reply.code(403).send({ message: SD("error.forbidden"), issues: [] });
107
+ },
108
+ );
109
+ }