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.
- package/dist/api/caster.d.ts.map +1 -1
- package/dist/api/caster.js +2 -1
- package/dist/api/code-converters.d.ts +5 -1
- package/dist/api/code-converters.d.ts.map +1 -1
- package/dist/api/code-converters.js +24 -7
- package/dist/api/config.d.ts +7 -0
- package/dist/api/config.d.ts.map +1 -1
- package/dist/api/config.js +1 -1
- package/dist/api/decorators.d.ts +1 -0
- package/dist/api/decorators.d.ts.map +1 -1
- package/dist/api/decorators.js +1 -1
- package/dist/api/guards.d.ts +37 -0
- package/dist/api/guards.d.ts.map +1 -0
- package/dist/api/guards.js +96 -0
- package/dist/api/sonamu.d.ts +14 -1
- package/dist/api/sonamu.d.ts.map +1 -1
- package/dist/api/sonamu.js +121 -25
- package/dist/api/websocket-helpers.d.ts +6 -1
- package/dist/api/websocket-helpers.d.ts.map +1 -1
- package/dist/api/websocket-helpers.js +7 -4
- package/dist/auth/auth-entity-policy.d.ts +32 -0
- package/dist/auth/auth-entity-policy.d.ts.map +1 -0
- package/dist/auth/auth-entity-policy.js +44 -0
- package/dist/auth/auth-secret.d.ts +24 -0
- package/dist/auth/auth-secret.d.ts.map +1 -0
- package/dist/auth/auth-secret.js +46 -0
- package/dist/auth/base-url.d.ts +39 -0
- package/dist/auth/base-url.d.ts.map +1 -0
- package/dist/auth/base-url.js +84 -0
- package/dist/auth/better-auth-entities.js +20 -7
- package/dist/auth/better-auth-options.d.ts +15 -0
- package/dist/auth/better-auth-options.d.ts.map +1 -0
- package/dist/auth/better-auth-options.js +38 -0
- package/dist/auth/better-auth-request.d.ts +8 -1
- package/dist/auth/better-auth-request.d.ts.map +1 -1
- package/dist/auth/better-auth-request.js +26 -3
- package/dist/auth/plugins/entity-definitions/admin.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/admin.js +6 -1
- package/dist/auth/plugins/entity-definitions/anonymous.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/anonymous.js +2 -1
- package/dist/auth/plugins/entity-definitions/api-key.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/api-key.js +18 -2
- package/dist/auth/plugins/entity-definitions/audit-log.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/audit-log.js +27 -1
- package/dist/auth/plugins/entity-definitions/jwt.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/jwt.js +4 -2
- package/dist/auth/plugins/entity-definitions/organization.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/organization.js +15 -1
- package/dist/auth/plugins/entity-definitions/passkey.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/passkey.js +9 -1
- package/dist/auth/plugins/entity-definitions/phone-number.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/phone-number.js +2 -1
- package/dist/auth/plugins/entity-definitions/sso.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/sso.js +7 -3
- package/dist/auth/plugins/entity-definitions/two-factor.d.ts.map +1 -1
- package/dist/auth/plugins/entity-definitions/two-factor.js +8 -3
- package/dist/auth/verify-email-guard.d.ts +37 -0
- package/dist/auth/verify-email-guard.d.ts.map +1 -0
- package/dist/auth/verify-email-guard.js +48 -0
- package/dist/bin/build-config.d.ts.map +1 -1
- package/dist/bin/build-config.js +6 -2
- package/dist/bin/typecheck-web.js +1 -1
- package/dist/cache/decorator.d.ts +12 -0
- package/dist/cache/decorator.d.ts.map +1 -1
- package/dist/cache/decorator.js +86 -19
- package/dist/cache/index.d.ts +1 -1
- package/dist/cache/index.d.ts.map +1 -1
- package/dist/cache/index.js +3 -3
- package/dist/cache/types.d.ts +16 -0
- package/dist/cache/types.d.ts.map +1 -1
- package/dist/cli/plugin-loader.d.ts +17 -0
- package/dist/cli/plugin-loader.d.ts.map +1 -0
- package/dist/cli/plugin-loader.js +178 -0
- package/dist/cli/plugin.d.ts +65 -0
- package/dist/cli/plugin.d.ts.map +1 -0
- package/dist/cli/plugin.js +7 -0
- package/dist/code-formatting/oxfmt.js +1 -1
- package/dist/code-formatting/oxlint.js +1 -1
- package/dist/database/db.d.ts +35 -10
- package/dist/database/db.d.ts.map +1 -1
- package/dist/database/db.js +37 -4
- package/dist/database/puri.d.ts +8 -0
- package/dist/database/puri.d.ts.map +1 -1
- package/dist/database/puri.js +108 -171
- package/dist/database/puri.types.d.ts +2 -0
- package/dist/database/puri.types.d.ts.map +1 -1
- package/dist/database/puri.types.js +1 -1
- package/dist/database/sql-expression-brand.d.ts +10 -0
- package/dist/database/sql-expression-brand.d.ts.map +1 -0
- package/dist/database/sql-expression-brand.js +10 -0
- package/dist/dict/en.d.ts +1 -0
- package/dist/dict/en.d.ts.map +1 -1
- package/dist/dict/en.js +2 -1
- package/dist/dict/ko.d.ts +1 -0
- package/dist/dict/ko.d.ts.map +1 -1
- package/dist/dict/ko.js +2 -1
- package/dist/dict/sonamu-dictionary.d.ts +23 -1
- package/dist/dict/sonamu-dictionary.d.ts.map +1 -1
- package/dist/dict/sonamu-dictionary.js +187 -32
- package/dist/entity/entity-codegen-safety.d.ts +105 -0
- package/dist/entity/entity-codegen-safety.d.ts.map +1 -0
- package/dist/entity/entity-codegen-safety.js +70 -0
- package/dist/entity/entity-manager.d.ts +32 -0
- package/dist/entity/entity-manager.d.ts.map +1 -1
- package/dist/entity/entity-manager.js +21 -2
- package/dist/entity/entity.d.ts +5 -2
- package/dist/entity/entity.d.ts.map +1 -1
- package/dist/entity/entity.js +19 -8
- package/dist/env.d.ts +19 -0
- package/dist/env.d.ts.map +1 -1
- package/dist/env.js +31 -3
- package/dist/filter/utils.d.ts +2 -2
- package/dist/filter/utils.d.ts.map +1 -1
- package/dist/filter/utils.js +16 -11
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/logger/configure.d.ts.map +1 -1
- package/dist/logger/configure.js +10 -3
- package/dist/migration/code-generation.d.ts.map +1 -1
- package/dist/migration/code-generation.js +177 -96
- package/dist/migration/migrator.d.ts +16 -0
- package/dist/migration/migrator.d.ts.map +1 -1
- package/dist/migration/migrator.js +28 -3
- package/dist/migration/slack-confirm.d.ts +6 -2
- package/dist/migration/slack-confirm.d.ts.map +1 -1
- package/dist/migration/slack-confirm.js +11 -9
- package/dist/ssr/errors.d.ts +13 -0
- package/dist/ssr/errors.d.ts.map +1 -0
- package/dist/ssr/errors.js +12 -0
- package/dist/ssr/index.d.ts +1 -0
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +5 -2
- package/dist/ssr/renderer.d.ts +6 -0
- package/dist/ssr/renderer.d.ts.map +1 -1
- package/dist/ssr/renderer.js +10 -1
- package/dist/storage/base-file.d.ts +6 -2
- package/dist/storage/base-file.d.ts.map +1 -1
- package/dist/storage/base-file.js +10 -5
- package/dist/storage/buffered-file.d.ts +1 -0
- package/dist/storage/buffered-file.d.ts.map +1 -1
- package/dist/storage/buffered-file.js +5 -2
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +4 -2
- package/dist/storage/upload-safety.d.ts +47 -0
- package/dist/storage/upload-safety.d.ts.map +1 -0
- package/dist/storage/upload-safety.js +112 -0
- package/dist/stream/ws.d.ts +6 -0
- package/dist/stream/ws.d.ts.map +1 -1
- package/dist/stream/ws.js +52 -6
- package/dist/syncer/api-parser.js +6 -1
- package/dist/syncer/code-generator.d.ts +2 -0
- package/dist/syncer/code-generator.d.ts.map +1 -1
- package/dist/syncer/code-generator.js +21 -7
- package/dist/template/implementations/entity.template.d.ts.map +1 -1
- package/dist/template/implementations/entity.template.js +40 -35
- package/dist/template/implementations/generated.template.d.ts +10 -0
- package/dist/template/implementations/generated.template.d.ts.map +1 -1
- package/dist/template/implementations/generated.template.js +46 -7
- package/dist/template/implementations/generated_http.template.d.ts.map +1 -1
- package/dist/template/implementations/generated_http.template.js +3 -1
- package/dist/template/implementations/init_types.template.d.ts.map +1 -1
- package/dist/template/implementations/init_types.template.js +3 -8
- package/dist/template/implementations/model.template.d.ts.map +1 -1
- package/dist/template/implementations/model.template.js +9 -2
- package/dist/template/implementations/sd.template.d.ts +0 -1
- package/dist/template/implementations/sd.template.d.ts.map +1 -1
- package/dist/template/implementations/sd.template.js +2 -5
- package/dist/template/implementations/view_form.template.d.ts.map +1 -1
- package/dist/template/implementations/view_form.template.js +8 -6
- package/dist/template/implementations/view_list.template.d.ts.map +1 -1
- package/dist/template/implementations/view_list.template.js +8 -4
- package/dist/testing/dev-test-routes.d.ts.map +1 -1
- package/dist/testing/dev-test-routes.js +7 -4
- package/dist/tooling/__tests__/helpers/sonamu-test-root.js +1 -1
- package/dist/tooling/cdd-service.js +1 -1
- package/dist/tooling/index.d.ts +1 -0
- package/dist/tooling/index.d.ts.map +1 -1
- package/dist/tooling/index.js +3 -1
- package/dist/tsdown.api.config.js +1 -1
- package/dist/types/types.d.ts +81 -1
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/types.js +2 -1
- package/dist/ui/__tests__/ui-test-helpers.d.ts +10 -0
- package/dist/ui/__tests__/ui-test-helpers.d.ts.map +1 -0
- package/dist/ui/__tests__/ui-test-helpers.js +75 -0
- package/dist/ui/access-guard.d.ts +42 -0
- package/dist/ui/access-guard.d.ts.map +1 -0
- package/dist/ui/access-guard.js +94 -0
- package/dist/ui/api.d.ts.map +1 -1
- package/dist/ui/api.js +40 -95
- package/dist/ui/dev-host-guard.d.ts +28 -0
- package/dist/ui/dev-host-guard.d.ts.map +1 -0
- package/dist/ui/dev-host-guard.js +67 -0
- package/dist/ui/migrations-api.d.ts.map +1 -1
- package/dist/ui/migrations-api.js +72 -16
- package/dist/ui/open-vscode-api.d.ts +4 -0
- package/dist/ui/open-vscode-api.d.ts.map +1 -0
- package/dist/ui/open-vscode-api.js +65 -0
- package/dist/ui/scaffolding-api.d.ts +18 -0
- package/dist/ui/scaffolding-api.d.ts.map +1 -0
- package/dist/ui/scaffolding-api.js +111 -0
- package/dist/ui/ui-db-presets.d.ts +19 -0
- package/dist/ui/ui-db-presets.d.ts.map +1 -0
- package/dist/ui/ui-db-presets.js +34 -0
- package/dist/ui/ui-request-guard.d.ts +11 -0
- package/dist/ui/ui-request-guard.d.ts.map +1 -0
- package/dist/ui/ui-request-guard.js +38 -0
- package/dist/ui-web/assets/{index-QDMyy31K.js → index-BPqP-tug.js} +39 -39
- package/dist/ui-web/index.html +2 -1
- package/package.json +1 -1
- package/src/__tests__/env.test.ts +121 -2
- package/src/api/__tests__/code-converters.union.test.ts +97 -0
- package/src/api/__tests__/guards.test.ts +233 -0
- package/src/api/__tests__/sonamu.auth-secret.test.ts +77 -0
- package/src/api/__tests__/sonamu.dev-host-guard.test.ts +130 -0
- package/src/api/__tests__/sonamu.guards.test.ts +327 -0
- package/src/api/__tests__/sonamu.upload-limits.test.ts +156 -0
- package/src/api/__tests__/websocket-helpers.test.ts +101 -0
- package/src/api/caster.ts +7 -0
- package/src/api/code-converters.ts +44 -12
- package/src/api/config.ts +8 -0
- package/src/api/decorators.ts +1 -0
- package/src/api/guards.ts +130 -0
- package/src/api/sonamu.ts +195 -39
- package/src/api/websocket-helpers.ts +11 -6
- package/src/auth/__tests__/auth-entity-policy.test.ts +59 -0
- package/src/auth/__tests__/auth-secret.test.ts +133 -0
- package/src/auth/__tests__/base-url-host-poisoning.test.ts +193 -0
- package/src/auth/__tests__/base-url.test.ts +117 -0
- package/src/auth/__tests__/better-auth-options.test.ts +194 -0
- package/src/auth/__tests__/better-auth-request.test.ts +45 -0
- package/src/auth/__tests__/verify-email-guard.test.ts +228 -0
- package/src/auth/auth-entity-policy.ts +48 -0
- package/src/auth/auth-secret.ts +77 -0
- package/src/auth/base-url.ts +109 -0
- package/src/auth/better-auth-entities.ts +30 -30
- package/src/auth/better-auth-options.ts +39 -0
- package/src/auth/better-auth-request.ts +28 -1
- package/src/auth/plugins/entity-definitions/admin.ts +5 -0
- package/src/auth/plugins/entity-definitions/anonymous.ts +9 -1
- package/src/auth/plugins/entity-definitions/api-key.ts +53 -16
- package/src/auth/plugins/entity-definitions/audit-log.ts +122 -21
- package/src/auth/plugins/entity-definitions/jwt.ts +5 -4
- package/src/auth/plugins/entity-definitions/organization.ts +26 -6
- package/src/auth/plugins/entity-definitions/passkey.ts +8 -7
- package/src/auth/plugins/entity-definitions/phone-number.ts +1 -0
- package/src/auth/plugins/entity-definitions/sso.ts +20 -15
- package/src/auth/plugins/entity-definitions/two-factor.ts +21 -5
- package/src/auth/verify-email-guard.ts +82 -0
- package/src/bin/__tests__/build-web-command.test.ts +24 -0
- package/src/bin/build-config.ts +5 -0
- package/src/cache/decorator.ts +116 -21
- package/src/cache/index.ts +6 -1
- package/src/cache/types.ts +18 -0
- package/src/cli/plugin-loader.ts +238 -0
- package/src/cli/plugin.ts +82 -0
- package/src/database/__tests__/db.test.ts +64 -1
- package/src/database/__tests__/puri.test.ts +56 -0
- package/src/database/db.ts +56 -6
- package/src/database/puri.ts +135 -125
- package/src/database/puri.types.test-d.ts +12 -0
- package/src/database/puri.types.ts +3 -0
- package/src/database/sql-expression-brand.ts +9 -0
- package/src/dict/__tests__/sonamu-dictionary.test.ts +217 -0
- package/src/dict/en.ts +2 -0
- package/src/dict/ko.ts +2 -0
- package/src/dict/sonamu-dictionary.ts +298 -38
- package/src/entity/__tests__/entity-codegen-safety.test.ts +326 -0
- package/src/entity/entity-codegen-safety.ts +126 -0
- package/src/entity/entity-manager.ts +29 -1
- package/src/entity/entity.ts +26 -12
- package/src/env.ts +52 -1
- package/src/filter/utils.ts +19 -7
- package/src/index.ts +4 -3
- package/src/logger/__tests__/configure.test.ts +51 -1
- package/src/logger/configure.ts +14 -1
- package/src/migration/__tests__/code-generation.escape.test.ts +322 -0
- package/src/migration/__tests__/migrator.test.ts +76 -1
- package/src/migration/code-generation.ts +247 -117
- package/src/migration/migrator.ts +45 -4
- package/src/migration/slack-confirm.ts +19 -5
- package/src/ssr/__tests__/preload-guard.test.ts +274 -0
- package/src/ssr/errors.ts +11 -0
- package/src/ssr/index.ts +1 -0
- package/src/ssr/renderer.ts +12 -0
- package/src/storage/__tests__/upload-safety.test.ts +179 -0
- package/src/storage/base-file.ts +8 -4
- package/src/storage/buffered-file.ts +3 -1
- package/src/storage/index.ts +9 -0
- package/src/storage/upload-safety.ts +155 -0
- package/src/stream/__tests__/ws.test.ts +97 -0
- package/src/stream/ws.ts +67 -5
- package/src/syncer/__tests__/api-parser.readonly.test.ts +55 -0
- package/src/syncer/__tests__/code-generator-path-containment.test.ts +105 -0
- package/src/syncer/api-parser.ts +12 -0
- package/src/syncer/code-generator.ts +34 -6
- package/src/template/__tests__/generated.template.search-text.test.ts +5 -1
- package/src/template/__tests__/model.template.auth-entity.test.ts +42 -0
- package/src/template/__tests__/save-params.template.test.ts +219 -0
- package/src/template/implementations/entity.template.ts +53 -48
- package/src/template/implementations/generated.template.ts +87 -12
- package/src/template/implementations/generated_http.template.ts +5 -0
- package/src/template/implementations/init_types.template.ts +4 -22
- package/src/template/implementations/model.template.ts +15 -1
- package/src/template/implementations/sd.template.ts +4 -5
- package/src/template/implementations/view_form.template.ts +13 -5
- package/src/template/implementations/view_list.template.ts +12 -3
- package/src/testing/__tests__/dev-test-routes.test.ts +99 -0
- package/src/testing/dev-test-routes.ts +7 -3
- package/src/tooling/__tests__/cli-plugins.contract.test.ts +273 -0
- package/src/tooling/index.ts +1 -0
- package/src/types/types.ts +22 -1
- package/src/ui/__tests__/access-guard.test.ts +217 -0
- package/src/ui/__tests__/dev-host-guard.test.ts +161 -0
- package/src/ui/__tests__/fixture-api.test.ts +92 -0
- package/src/ui/__tests__/migrations-api.test.ts +352 -0
- package/src/ui/__tests__/open-vscode.test.ts +151 -0
- package/src/ui/__tests__/scaffolding-api.test.ts +232 -0
- package/src/ui/__tests__/ui-process-routes.test.ts +166 -0
- package/src/ui/__tests__/ui-test-helpers.ts +71 -0
- package/src/ui/access-guard.ts +115 -0
- package/src/ui/api.ts +65 -198
- package/src/ui/dev-host-guard.ts +109 -0
- package/src/ui/migrations-api.ts +130 -24
- package/src/ui/open-vscode-api.ts +82 -0
- package/src/ui/scaffolding-api.ts +177 -0
- package/src/ui/ui-db-presets.ts +41 -0
- package/src/ui/ui-request-guard.ts +53 -0
package/src/filter/utils.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { type LocalizedString } from "../dict/types";
|
|
1
2
|
import { type Entity } from "../entity/entity";
|
|
3
|
+
import { BadRequestException } from "../exceptions/so-exceptions";
|
|
2
4
|
import { isEnumProp } from "../types/types";
|
|
3
5
|
import { isObjectValue, isStringValue } from "../utils/runtime-value";
|
|
4
6
|
import { operatorsByPropType } from "./types";
|
|
@@ -104,14 +106,22 @@ function convertType<Value>(value: Value): ConvertedFilterValue<Value> {
|
|
|
104
106
|
// 메타데이터 기반으로 필터 쿼리의 유효성 검증
|
|
105
107
|
// ============================================================
|
|
106
108
|
|
|
109
|
+
/**
|
|
110
|
+
* 잘못된 필터 요청을 400으로 응답하기 위한 예외를 만듭니다.
|
|
111
|
+
*/
|
|
112
|
+
function invalidFilter(message: string): BadRequestException {
|
|
113
|
+
// SAFETY: 프레임워크 검증 메시지는 번역 키가 아닌 고정 문장이며 LocalizedString 브랜드만 붙인다.
|
|
114
|
+
return new BadRequestException(message as LocalizedString);
|
|
115
|
+
}
|
|
116
|
+
|
|
107
117
|
/**
|
|
108
118
|
* sonamuFilter를 Entity 기반으로 검증
|
|
109
119
|
*
|
|
110
|
-
* 필터링 불가능한
|
|
120
|
+
* 필터링 불가능한 필드(`toFilter`가 없는 prop 포함), 지원하지 않는 연산자, 잘못된 enum 값 등을 체크
|
|
111
121
|
*
|
|
112
122
|
* @param filters 검증할 필터 쿼리
|
|
113
123
|
* @param entity Entity 객체
|
|
114
|
-
* @throws {
|
|
124
|
+
* @throws {BadRequestException} 검증 실패 시 상세한 에러 메시지와 함께 400 예외 발생
|
|
115
125
|
*
|
|
116
126
|
* @example
|
|
117
127
|
* validateSonamuFilters({ status: "active", id: { gte: 1 } }, ProjectEntity);
|
|
@@ -132,7 +142,7 @@ export function validateSonamuFilters<TEntity = DynamicFilterEntity>(
|
|
|
132
142
|
const prop = filterableProps.get(field);
|
|
133
143
|
if (!prop) {
|
|
134
144
|
const availableFields = Array.from(filterableProps.keys()).join(", ");
|
|
135
|
-
throw
|
|
145
|
+
throw invalidFilter(
|
|
136
146
|
`필드 '${field}'는 필터링할 수 없습니다. (필터 가능한 필드: ${availableFields})`,
|
|
137
147
|
);
|
|
138
148
|
}
|
|
@@ -163,7 +173,7 @@ export function validateSonamuFilters<TEntity = DynamicFilterEntity>(
|
|
|
163
173
|
|
|
164
174
|
// 연산자가 해당 타입에서 지원되는지 검증
|
|
165
175
|
if (!allowedOperators.includes(op)) {
|
|
166
|
-
throw
|
|
176
|
+
throw invalidFilter(
|
|
167
177
|
`필드 '${field}'(타입: ${prop.type})는 '${operator}' 연산자를 지원하지 않습니다.` +
|
|
168
178
|
`(지원되는 연산자: ${allowedOperators.join(", ")})`,
|
|
169
179
|
);
|
|
@@ -174,12 +184,14 @@ export function validateSonamuFilters<TEntity = DynamicFilterEntity>(
|
|
|
174
184
|
}
|
|
175
185
|
|
|
176
186
|
if ((op === "in" || op === "notIn") && !Array.isArray(value)) {
|
|
177
|
-
throw
|
|
187
|
+
throw invalidFilter(`필드 '${field}'의 '${operator}' 연산자는 배열 값을 요구합니다.`);
|
|
178
188
|
}
|
|
179
189
|
|
|
180
190
|
if (op === "between") {
|
|
181
191
|
if (!Array.isArray(value) || value.length !== 2) {
|
|
182
|
-
throw
|
|
192
|
+
throw invalidFilter(
|
|
193
|
+
`필드 '${field}'의 'between' 연산자는 길이 2의 배열 값을 요구합니다.`,
|
|
194
|
+
);
|
|
183
195
|
}
|
|
184
196
|
}
|
|
185
197
|
|
|
@@ -210,7 +222,7 @@ function validateEnumValue<Value>(field: string, value: Value, enumValues: strin
|
|
|
210
222
|
return;
|
|
211
223
|
}
|
|
212
224
|
if (!enumValues.includes(String(value))) {
|
|
213
|
-
throw
|
|
225
|
+
throw invalidFilter(
|
|
214
226
|
`필드 '${field}'의 값 '${value}'는 유효하지 않습니다. (허용되는 값: ${enumValues.join(", ")})`,
|
|
215
227
|
);
|
|
216
228
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from "./api/base-frame";
|
|
2
2
|
export * from "./api/config";
|
|
3
|
+
export * from "./cli/plugin";
|
|
3
4
|
export type * from "./api/context";
|
|
4
5
|
export * from "./api/decorators";
|
|
5
6
|
export { fastifyCaster } from "./api/caster";
|
|
@@ -7,8 +8,8 @@ export { getZodObjectFromApi } from "./api/code-converters";
|
|
|
7
8
|
export * from "./api/http-validator";
|
|
8
9
|
export * from "./api/sonamu";
|
|
9
10
|
export * from "./auth";
|
|
10
|
-
export { cache } from "./cache/decorator";
|
|
11
|
-
export type { CacheDecoratorOptions } from "./cache/types";
|
|
11
|
+
export { cache, CacheKeySerializationError } from "./cache/decorator";
|
|
12
|
+
export type { CacheDecoratorOptions, CacheScope } from "./cache/types";
|
|
12
13
|
export * from "./cache-control/cache-control";
|
|
13
14
|
export type * from "./cache-control/types";
|
|
14
15
|
export * from "./compress/compress";
|
|
@@ -23,7 +24,7 @@ export * from "./database/puri-wrapper";
|
|
|
23
24
|
export * from "./database/upsert-builder";
|
|
24
25
|
export * from "./entity/entity";
|
|
25
26
|
export * from "./entity/entity-manager";
|
|
26
|
-
export { getSonamuEnvironment, type SonamuEnvironment } from "./env";
|
|
27
|
+
export { getSonamuEnvironment, resolveSonamuEnvironment, type SonamuEnvironment } from "./env";
|
|
27
28
|
export * from "./exceptions/error-handler";
|
|
28
29
|
export * from "./exceptions/so-exceptions";
|
|
29
30
|
export * from "./filter";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { dispose, getLogger, type Config, type LogRecord } from "@logtape/logtape";
|
|
2
|
-
import { afterEach, describe, expect, it } from "vitest";
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
3
3
|
|
|
4
4
|
import { configureLogTape } from "../configure";
|
|
5
5
|
|
|
@@ -31,3 +31,53 @@ describe("CLI LogTape 설정 합성", () => {
|
|
|
31
31
|
expect(appRecords).toHaveLength(1);
|
|
32
32
|
});
|
|
33
33
|
});
|
|
34
|
+
|
|
35
|
+
describe("fastify 기본 로그 싱크", () => {
|
|
36
|
+
const longUrl = `/api/healthcheck?x=${"a".repeat(15_000)}`;
|
|
37
|
+
let lines: string[];
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
lines = [];
|
|
41
|
+
for (const method of ["debug", "info", "warn", "error"] as const) {
|
|
42
|
+
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
|
|
43
|
+
lines.push(args.map(String).join(" "));
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
afterEach(async () => {
|
|
49
|
+
vi.restoreAllMocks();
|
|
50
|
+
await dispose();
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it("15KB URL 요청 로그를 줄바꿈 없이 빠르게 출력하고 URL을 잘라 남긴다", async () => {
|
|
54
|
+
await configureLogTape({});
|
|
55
|
+
const req = { method: "GET", url: longUrl, originalUrl: longUrl };
|
|
56
|
+
|
|
57
|
+
const startedAt = performance.now();
|
|
58
|
+
getLogger(["fastify"]).info("incoming request", { req });
|
|
59
|
+
const elapsedMs = performance.now() - startedAt;
|
|
60
|
+
|
|
61
|
+
// 수정 전에는 pretty 포매터의 줄바꿈 처리가 길이의 제곱에 비례해 수 초가 걸렸다
|
|
62
|
+
expect(elapsedMs).toBeLessThan(1_000);
|
|
63
|
+
expect(lines).toHaveLength(1);
|
|
64
|
+
expect(lines[0]).not.toContain("\n");
|
|
65
|
+
expect(lines[0]).toContain("[GET] /api/healthcheck?x=aaa");
|
|
66
|
+
expect(lines[0]).toContain("incoming request");
|
|
67
|
+
expect(lines[0]).not.toContain(longUrl);
|
|
68
|
+
expect(lines[0].length).toBeLessThan(2_000);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("req가 없는 fastify 로그에 긴 URL이 있어도 빠르게 출력한다", async () => {
|
|
72
|
+
await configureLogTape({});
|
|
73
|
+
|
|
74
|
+
const startedAt = performance.now();
|
|
75
|
+
// fastify 404 처리기가 남기는 형태의 로그
|
|
76
|
+
getLogger(["fastify"]).info(`Route GET:${longUrl} not found`);
|
|
77
|
+
const elapsedMs = performance.now() - startedAt;
|
|
78
|
+
|
|
79
|
+
expect(elapsedMs).toBeLessThan(1_000);
|
|
80
|
+
expect(lines).toHaveLength(1);
|
|
81
|
+
expect(lines[0]).not.toContain("\n");
|
|
82
|
+
});
|
|
83
|
+
});
|
package/src/logger/configure.ts
CHANGED
|
@@ -43,6 +43,16 @@ export type SonamuLoggingOptions<TSinkId extends string, TFilterId extends strin
|
|
|
43
43
|
loggers?: LoggerConfig<TSinkId, TFilterId>[];
|
|
44
44
|
};
|
|
45
45
|
|
|
46
|
+
// 요청 로그에 남기는 URL의 최대 길이. 긴 URL이 로그 용량을 키우지 않도록 앞부분만 남긴다.
|
|
47
|
+
const MAX_LOGGED_URL_LENGTH = 1024;
|
|
48
|
+
|
|
49
|
+
function truncateUrlForLog(url: string): string {
|
|
50
|
+
if (url.length <= MAX_LOGGED_URL_LENGTH) {
|
|
51
|
+
return url;
|
|
52
|
+
}
|
|
53
|
+
return `${url.slice(0, MAX_LOGGED_URL_LENGTH)}…(+${url.length - MAX_LOGGED_URL_LENGTH} chars)`;
|
|
54
|
+
}
|
|
55
|
+
|
|
46
56
|
// fastify에 대한 기본 sink 설정
|
|
47
57
|
function defaultFastifySink(fastifyCategory: readonly string[]): Sink {
|
|
48
58
|
const fastifyFormatter = ((formatRecord: TextFormatter, record: LogRecord) => {
|
|
@@ -62,7 +72,7 @@ function defaultFastifySink(fastifyCategory: readonly string[]): Sink {
|
|
|
62
72
|
...requestRecord,
|
|
63
73
|
message: [
|
|
64
74
|
...requestRecord.message.slice(0, -1),
|
|
65
|
-
`[${request.method}${responseCode ? `:${responseCode}` : ""}] ${request.originalUrl} - ${lastItem}`,
|
|
75
|
+
`[${request.method}${responseCode ? `:${responseCode}` : ""}] ${truncateUrlForLog(request.originalUrl)} - ${lastItem}`,
|
|
66
76
|
],
|
|
67
77
|
});
|
|
68
78
|
};
|
|
@@ -90,6 +100,9 @@ function defaultFastifySink(fastifyCategory: readonly string[]): Sink {
|
|
|
90
100
|
timestamp: "time",
|
|
91
101
|
categoryWidth: 20,
|
|
92
102
|
categoryTruncate: "middle",
|
|
103
|
+
// @logtape/pretty의 줄바꿈 처리는 공백 없는 긴 문자열에서 길이의 제곱에 비례해 느려진다.
|
|
104
|
+
// 공격자가 정한 URL·메시지가 이 싱크로 들어오므로 줄바꿈을 끄고 터미널의 자동 줄바꿈에 맡긴다.
|
|
105
|
+
wordWrap: false,
|
|
93
106
|
}),
|
|
94
107
|
);
|
|
95
108
|
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { runInNewContext } from "node:vm";
|
|
2
|
+
|
|
3
|
+
import knex from "knex";
|
|
4
|
+
import { transformWithOxc } from "vite";
|
|
5
|
+
import { afterEach, describe, expect, test, vi } from "vitest";
|
|
6
|
+
|
|
7
|
+
import { type MigrationColumn, type MigrationIndex, type MigrationSet } from "../../types/types";
|
|
8
|
+
import { generateAlterCode, generateCreateCode } from "../code-generation";
|
|
9
|
+
import { PostgreSQLSchemaReader } from "../postgresql-schema-reader";
|
|
10
|
+
|
|
11
|
+
type BuilderCall = { method: string; args: unknown[] };
|
|
12
|
+
type RawCall = { rawSql: string };
|
|
13
|
+
// 생성 코드가 호출하는 table builder 체인 대역 (모든 메서드가 다시 대역을 반환)
|
|
14
|
+
type TableBuilderStub = { [method: string]: (...args: unknown[]) => TableBuilderStub };
|
|
15
|
+
type KnexStub = {
|
|
16
|
+
raw: (rawSql: string) => RawCall;
|
|
17
|
+
schema: {
|
|
18
|
+
createTable: (table: string, callback: (builder: TableBuilderStub) => void) => Promise<void>;
|
|
19
|
+
alterTable: (table: string, callback: (builder: TableBuilderStub) => void) => Promise<void>;
|
|
20
|
+
dropTable: (table: string) => Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
type MigrationFunction = (knex: KnexStub) => Promise<void>;
|
|
24
|
+
// 주입된 코드가 실행되면 vm 컨텍스트(globalThis)에 남기는 표식
|
|
25
|
+
type MigrationContext = { __son624Executed?: number };
|
|
26
|
+
|
|
27
|
+
function buildSet(
|
|
28
|
+
columns: MigrationColumn[],
|
|
29
|
+
indexes: MigrationIndex[] = [],
|
|
30
|
+
table = "son624_codegen",
|
|
31
|
+
): MigrationSet {
|
|
32
|
+
return {
|
|
33
|
+
table,
|
|
34
|
+
columns: [{ name: "id", type: "integer", nullable: false }, ...columns],
|
|
35
|
+
indexes,
|
|
36
|
+
foreigns: [],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 생성된 마이그레이션을 실제로 실행하되, knex 대신 호출을 기록하는 대역을 넘긴다.
|
|
42
|
+
* 격리된 vm 컨텍스트에서 실행하므로 주입된 코드가 실행되면 컨텍스트에 표식이 남는다.
|
|
43
|
+
*/
|
|
44
|
+
async function runMigration(formatted: string | null, direction: "up" | "down" = "up") {
|
|
45
|
+
if (formatted === null) {
|
|
46
|
+
throw new Error("생성된 마이그레이션 코드가 없습니다.");
|
|
47
|
+
}
|
|
48
|
+
// 타입만 제거하고, export 선언은 스크립트 함수 선언으로 바꿔 vm에서 실행한다.
|
|
49
|
+
const { code } = await transformWithOxc(formatted, "migration.ts", { lang: "ts" });
|
|
50
|
+
const script = `${code.replace(/^export /gm, "")}\n({ up, down });`;
|
|
51
|
+
|
|
52
|
+
const rawSqls: string[] = [];
|
|
53
|
+
const builderCalls: BuilderCall[] = [];
|
|
54
|
+
// 체인의 모든 메서드 호출을 기록하고 같은 대역을 돌려준다.
|
|
55
|
+
const builder = new Proxy<TableBuilderStub>(
|
|
56
|
+
{},
|
|
57
|
+
{
|
|
58
|
+
get:
|
|
59
|
+
(_target, method) =>
|
|
60
|
+
(...args: unknown[]) => {
|
|
61
|
+
builderCalls.push({ method: String(method), args });
|
|
62
|
+
return builder;
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
);
|
|
66
|
+
const runTableCallback = async (
|
|
67
|
+
_table: string,
|
|
68
|
+
callback: (builder: TableBuilderStub) => void,
|
|
69
|
+
) => {
|
|
70
|
+
callback(builder);
|
|
71
|
+
};
|
|
72
|
+
const knexStub: KnexStub = {
|
|
73
|
+
raw: (rawSql: string): RawCall => {
|
|
74
|
+
rawSqls.push(rawSql);
|
|
75
|
+
return { rawSql };
|
|
76
|
+
},
|
|
77
|
+
schema: {
|
|
78
|
+
createTable: runTableCallback,
|
|
79
|
+
alterTable: runTableCallback,
|
|
80
|
+
dropTable: async () => {},
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const context: MigrationContext = {};
|
|
85
|
+
const migration: Record<"up" | "down", MigrationFunction> = runInNewContext(script, context);
|
|
86
|
+
await migration[direction](knexStub);
|
|
87
|
+
|
|
88
|
+
return { rawSqls, builderCalls, executedMarker: context.__son624Executed };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function findDefaultToArgs(builderCalls: BuilderCall[]): unknown[][] {
|
|
92
|
+
return builderCalls.filter((call) => call.method === "defaultTo").map((call) => call.args);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
describe("마이그레이션 코드 생성 이스케이프 (SON-624)", () => {
|
|
96
|
+
afterEach(() => {
|
|
97
|
+
vi.restoreAllMocks();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("따옴표·백틱·${}가 든 문자열 dbDefault는 하나의 문자열 값으로만 쓰여야 한다", async () => {
|
|
101
|
+
const value = 'it\'s "quoted" `tick` ${globalThis.__son624Executed = 1} \\ end';
|
|
102
|
+
const [migration] = await generateCreateCode(
|
|
103
|
+
buildSet([
|
|
104
|
+
{
|
|
105
|
+
name: "label",
|
|
106
|
+
type: "string",
|
|
107
|
+
length: 200,
|
|
108
|
+
nullable: false,
|
|
109
|
+
defaultTo: JSON.stringify(value),
|
|
110
|
+
},
|
|
111
|
+
]),
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
const result = await runMigration(migration.formatted);
|
|
115
|
+
|
|
116
|
+
expect(findDefaultToArgs(result.builderCalls)).toEqual([[value]]);
|
|
117
|
+
expect(result.executedMarker).toBeUndefined();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("따옴표·백틱·${}가 든 SQL dbDefault는 knex.raw의 SQL 문자열로만 쓰여야 한다", async () => {
|
|
121
|
+
const sqlDefault = "'it''s' || '`' || '${globalThis.__son624Executed = 1}' || '\\'";
|
|
122
|
+
const [migration] = await generateCreateCode(
|
|
123
|
+
buildSet([{ name: "label", type: "string", nullable: false, defaultTo: sqlDefault }]),
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
const result = await runMigration(migration.formatted);
|
|
127
|
+
|
|
128
|
+
expect(findDefaultToArgs(result.builderCalls)).toEqual([[{ rawSql: sqlDefault }]]);
|
|
129
|
+
expect(result.executedMarker).toBeUndefined();
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("작은따옴표를 닫고 JS를 끼워 넣는 SQL dbDefault도 실행되지 않아야 한다", async () => {
|
|
133
|
+
const sqlDefault = "0'), (globalThis.__son624Executed = 1), ('";
|
|
134
|
+
const [migration] = await generateCreateCode(
|
|
135
|
+
buildSet([{ name: "count", type: "integer", nullable: false, defaultTo: sqlDefault }]),
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
const result = await runMigration(migration.formatted);
|
|
139
|
+
|
|
140
|
+
expect(findDefaultToArgs(result.builderCalls)).toEqual([[{ rawSql: sqlDefault }]]);
|
|
141
|
+
expect(result.executedMarker).toBeUndefined();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("이스케이프된 따옴표·JS 이스케이프가 든 문자열 리터럴 dbDefault는 값으로만 쓰여야 한다", async () => {
|
|
145
|
+
const [migration] = await generateCreateCode(
|
|
146
|
+
buildSet([
|
|
147
|
+
{
|
|
148
|
+
name: "escaped",
|
|
149
|
+
type: "string",
|
|
150
|
+
nullable: false,
|
|
151
|
+
defaultTo: String.raw`"x\", (globalThis.__son624Executed = 1), \""`,
|
|
152
|
+
},
|
|
153
|
+
{ name: "legacy_hex", type: "string", nullable: false, defaultTo: String.raw`"\x5b\x5d"` },
|
|
154
|
+
]),
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
const result = await runMigration(migration.formatted);
|
|
158
|
+
|
|
159
|
+
expect(findDefaultToArgs(result.builderCalls)).toEqual([
|
|
160
|
+
['x", (globalThis.__son624Executed = 1), "'],
|
|
161
|
+
["[]"],
|
|
162
|
+
]);
|
|
163
|
+
expect(result.executedMarker).toBeUndefined();
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("큰따옴표로 시작하지만 문자열 하나가 아닌 dbDefault는 생성을 거부해야 한다", async () => {
|
|
167
|
+
const payload = '"x", (globalThis.__son624Executed = 1, {})';
|
|
168
|
+
|
|
169
|
+
await expect(
|
|
170
|
+
generateCreateCode(
|
|
171
|
+
buildSet([{ name: "label", type: "string", nullable: true, defaultTo: payload }]),
|
|
172
|
+
),
|
|
173
|
+
).rejects.toThrow("하나의 문자열 리터럴이어야 합니다");
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("DB에서 읽은 기본값이 JS 식이 되는 경우에도 alter 코드 생성을 거부해야 한다", async () => {
|
|
177
|
+
const entitySet = buildSet([
|
|
178
|
+
{ name: "label", type: "string", nullable: true, defaultTo: '"safe"' },
|
|
179
|
+
]);
|
|
180
|
+
const dbSet = buildSet([
|
|
181
|
+
{
|
|
182
|
+
name: "label",
|
|
183
|
+
type: "string",
|
|
184
|
+
nullable: true,
|
|
185
|
+
defaultTo: '"x", (globalThis.__son624Executed = 1), "',
|
|
186
|
+
},
|
|
187
|
+
]);
|
|
188
|
+
|
|
189
|
+
await expect(generateAlterCode(entitySet, dbSet)).rejects.toThrow(
|
|
190
|
+
"하나의 문자열 리터럴이어야 합니다",
|
|
191
|
+
);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("generated expression의 ${}는 JS로 평가되지 않고 SQL 문자열로 남아야 한다", async () => {
|
|
195
|
+
const expression = "length(name) + ${(globalThis.__son624Executed = 1, 0)} + length('`\\\\')";
|
|
196
|
+
const [migration] = await generateCreateCode(
|
|
197
|
+
buildSet([
|
|
198
|
+
{ name: "name", type: "string", nullable: false },
|
|
199
|
+
{
|
|
200
|
+
name: "name_length",
|
|
201
|
+
type: "integer",
|
|
202
|
+
nullable: false,
|
|
203
|
+
generated: { type: "STORED", expression },
|
|
204
|
+
},
|
|
205
|
+
]),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
const result = await runMigration(migration.formatted);
|
|
209
|
+
|
|
210
|
+
expect(result.rawSqls).toEqual([
|
|
211
|
+
`ALTER TABLE "son624_codegen" ADD COLUMN "name_length" integer GENERATED ALWAYS AS (${expression}) STORED NOT NULL`,
|
|
212
|
+
]);
|
|
213
|
+
expect(result.executedMarker).toBeUndefined();
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("index where의 ${}·백틱은 JS로 평가되지 않고 SQL 문자열로 남아야 한다", async () => {
|
|
217
|
+
const where = "name <> '${(globalThis.__son624Executed = 1, \"x\")}' AND name <> '`'";
|
|
218
|
+
const [migration] = await generateCreateCode(
|
|
219
|
+
buildSet(
|
|
220
|
+
[{ name: "name", type: "string", nullable: false }],
|
|
221
|
+
[{ type: "index", name: "son624_codegen_name_index", columns: [{ name: "name" }], where }],
|
|
222
|
+
),
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
const result = await runMigration(migration.formatted);
|
|
226
|
+
|
|
227
|
+
expect(result.rawSqls).toEqual([
|
|
228
|
+
`CREATE INDEX son624_codegen_name_index ON son624_codegen (name) WHERE ${where};`,
|
|
229
|
+
]);
|
|
230
|
+
expect(result.executedMarker).toBeUndefined();
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test.each([
|
|
234
|
+
{
|
|
235
|
+
label: "dbDefault",
|
|
236
|
+
set: buildSet([
|
|
237
|
+
{
|
|
238
|
+
name: "count",
|
|
239
|
+
type: "integer",
|
|
240
|
+
nullable: false,
|
|
241
|
+
defaultTo: "0; create table gen06_sqli_default(id int)",
|
|
242
|
+
},
|
|
243
|
+
]),
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
label: "index where",
|
|
247
|
+
set: buildSet(
|
|
248
|
+
[{ name: "name", type: "string", nullable: false }],
|
|
249
|
+
[
|
|
250
|
+
{
|
|
251
|
+
type: "index",
|
|
252
|
+
name: "son624_codegen_name_index",
|
|
253
|
+
columns: [{ name: "name" }],
|
|
254
|
+
where: "id > 0; create table gen06_sqli_where(id int)",
|
|
255
|
+
},
|
|
256
|
+
],
|
|
257
|
+
),
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
label: "generated expression",
|
|
261
|
+
set: buildSet([
|
|
262
|
+
{
|
|
263
|
+
name: "name_length",
|
|
264
|
+
type: "integer",
|
|
265
|
+
nullable: false,
|
|
266
|
+
generated: { type: "STORED", expression: "1); create table gen06_sqli_expr(id int" },
|
|
267
|
+
},
|
|
268
|
+
]),
|
|
269
|
+
},
|
|
270
|
+
])("$label 값에 ';'로 SQL 문장을 이어 붙이면 생성을 거부해야 한다", async ({ set }) => {
|
|
271
|
+
await expect(generateCreateCode(set)).rejects.toThrow("';'를 쓸 수 없습니다");
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("식별자 이름은 JS 문자열 값과 인용된 SQL 식별자로만 쓰여야 한다", async () => {
|
|
275
|
+
const columnName = "x', (globalThis.__son624Executed = 1), 'y\"z";
|
|
276
|
+
const indexName = 'bad name") ON other_table (id';
|
|
277
|
+
const [migration] = await generateCreateCode(
|
|
278
|
+
buildSet(
|
|
279
|
+
[{ name: columnName, type: "string", length: 20, nullable: false }],
|
|
280
|
+
[{ type: "index", name: indexName, columns: [{ name: columnName }] }],
|
|
281
|
+
),
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
const result = await runMigration(migration.formatted);
|
|
285
|
+
|
|
286
|
+
expect(result.builderCalls).toContainEqual({ method: "string", args: [columnName, 20] });
|
|
287
|
+
expect(result.rawSqls).toEqual([
|
|
288
|
+
'CREATE INDEX "bad name"") ON other_table (id" ON son624_codegen ("x\', (globalThis.__son624Executed = 1), \'y""z");',
|
|
289
|
+
]);
|
|
290
|
+
expect(result.executedMarker).toBeUndefined();
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
test("PK 타입 변경 주석에 DB 메타데이터의 줄바꿈이 들어가도 코드가 되지 않아야 한다", async () => {
|
|
294
|
+
vi.spyOn(PostgreSQLSchemaReader, "getReferencingForeignKeys").mockResolvedValue([
|
|
295
|
+
{
|
|
296
|
+
tableName: "son624_child\nglobalThis.__son624Executed = 1 //",
|
|
297
|
+
constraintName: "son624_child_parent_id_foreign",
|
|
298
|
+
columnName: "parent_id",
|
|
299
|
+
referencedTableName: "son624_codegen",
|
|
300
|
+
referencedColumnName: "id",
|
|
301
|
+
onUpdate: "CASCADE",
|
|
302
|
+
onDelete: "CASCADE",
|
|
303
|
+
},
|
|
304
|
+
]);
|
|
305
|
+
const compareDB = knex({ client: "pg" });
|
|
306
|
+
const entitySet = buildSet([]);
|
|
307
|
+
const dbSet = buildSet([]);
|
|
308
|
+
entitySet.columns[0] = { name: "id", type: "string", length: 36, nullable: false };
|
|
309
|
+
|
|
310
|
+
try {
|
|
311
|
+
const [migration] = await generateAlterCode(entitySet, dbSet, compareDB);
|
|
312
|
+
const result = await runMigration(migration.formatted);
|
|
313
|
+
|
|
314
|
+
expect(result.executedMarker).toBeUndefined();
|
|
315
|
+
expect(result.rawSqls).toContain(
|
|
316
|
+
'ALTER TABLE "son624_child\nglobalThis.__son624Executed = 1 //" DROP CONSTRAINT "son624_child_parent_id_foreign"',
|
|
317
|
+
);
|
|
318
|
+
} finally {
|
|
319
|
+
await compareDB.destroy();
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
});
|
|
@@ -2,10 +2,11 @@ import { type Knex } from "knex";
|
|
|
2
2
|
import knex from "knex";
|
|
3
3
|
import { afterEach, describe, expect, it } from "vitest";
|
|
4
4
|
|
|
5
|
-
import { type SonamuConfig } from "../../api/config";
|
|
5
|
+
import { type DatabaseConfig, type SonamuConfig } from "../../api/config";
|
|
6
6
|
import { Sonamu } from "../../api/sonamu";
|
|
7
7
|
import { type SonamuDBConfig, type SonamuDBPreset } from "../../database/db";
|
|
8
8
|
import { setSDConfig } from "../../dict/sd";
|
|
9
|
+
import { isUIDBPreset } from "../../ui/ui-db-presets";
|
|
9
10
|
import { Migrator } from "../migrator";
|
|
10
11
|
import { SlackConfirm } from "../slack-confirm";
|
|
11
12
|
|
|
@@ -89,6 +90,18 @@ describe("Migrator environment target filtering", () => {
|
|
|
89
90
|
"production",
|
|
90
91
|
]);
|
|
91
92
|
});
|
|
93
|
+
|
|
94
|
+
it("targetFilter로 좁힌 대상 밖의 DB는 연결하기 전에 거부한다", async () => {
|
|
95
|
+
process.env.NODE_ENV = "development";
|
|
96
|
+
Sonamu.dbConfig = dbConfig;
|
|
97
|
+
const migrator = new Migrator({ targetFilter: isUIDBPreset });
|
|
98
|
+
|
|
99
|
+
expect(migrator.getMigrationTargetKeys()).toEqual(["test", "fixture", "development"]);
|
|
100
|
+
await expect(migrator.getConnectionStatus("production")).rejects.toThrow(/not allowed/);
|
|
101
|
+
await expect(migrator.getLatestAppliedBatch("staging")).rejects.toThrow(/not allowed/);
|
|
102
|
+
await expect(migrator.rollback(["production"])).rejects.toThrow(/not allowed/);
|
|
103
|
+
await expect(migrator.apply(["staging"])).rejects.toThrow(/not allowed/);
|
|
104
|
+
});
|
|
92
105
|
});
|
|
93
106
|
|
|
94
107
|
describe("Migrator 최신 적용 batch 조회", () => {
|
|
@@ -191,3 +204,65 @@ describe("SlackConfirm target validation", () => {
|
|
|
191
204
|
expect(slackConfirm.isTargetRequiresApproval("staging")).toBe(false);
|
|
192
205
|
});
|
|
193
206
|
});
|
|
207
|
+
|
|
208
|
+
describe("Migrator 대상 제외 옵션", () => {
|
|
209
|
+
const originalEnv = { ...process.env };
|
|
210
|
+
const presetConfig = (preset: SonamuDBPreset): DatabaseConfig => ({
|
|
211
|
+
client: "postgresql",
|
|
212
|
+
connection: { host: "localhost", database: preset },
|
|
213
|
+
});
|
|
214
|
+
const dbConfig: SonamuDBConfig = {
|
|
215
|
+
test: presetConfig("test"),
|
|
216
|
+
fixture: presetConfig("fixture"),
|
|
217
|
+
development: presetConfig("development"),
|
|
218
|
+
staging: presetConfig("staging"),
|
|
219
|
+
production: presetConfig("production"),
|
|
220
|
+
test_readonly: presetConfig("test_readonly"),
|
|
221
|
+
development_readonly: presetConfig("development_readonly"),
|
|
222
|
+
staging_readonly: presetConfig("staging_readonly"),
|
|
223
|
+
production_readonly: presetConfig("production_readonly"),
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
afterEach(() => {
|
|
227
|
+
for (const key of Object.keys(process.env)) {
|
|
228
|
+
if (!(key in originalEnv)) {
|
|
229
|
+
delete process.env[key];
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
Object.assign(process.env, originalEnv);
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("제외한 대상은 로컬 개발 환경에서도 대상 목록과 커넥션 메타데이터에서 빠진다", () => {
|
|
236
|
+
process.env.NODE_ENV = "development";
|
|
237
|
+
Sonamu.dbConfig = dbConfig;
|
|
238
|
+
Sonamu.config = createConfig([]);
|
|
239
|
+
setSDConfig(Sonamu.config.i18n);
|
|
240
|
+
|
|
241
|
+
const migrator = new Migrator({ excludedTargets: ["production"] });
|
|
242
|
+
|
|
243
|
+
expect(migrator.getMigrationTargetKeys()).toEqual([
|
|
244
|
+
"test",
|
|
245
|
+
"fixture",
|
|
246
|
+
"development",
|
|
247
|
+
"staging",
|
|
248
|
+
]);
|
|
249
|
+
expect(migrator.getConnections().map(({ connKey }) => connKey)).not.toContain("production");
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("제외한 대상의 상태 조회와 적용·롤백은 DB에 연결하기 전에 거부한다", async () => {
|
|
253
|
+
process.env.NODE_ENV = "development";
|
|
254
|
+
Sonamu.dbConfig = dbConfig;
|
|
255
|
+
const migrator = new Migrator({ excludedTargets: ["production"] });
|
|
256
|
+
|
|
257
|
+
await expect(migrator.getConnectionStatus("production")).rejects.toThrow(/production/);
|
|
258
|
+
await expect(migrator.apply(["production"])).rejects.toThrow(/production/);
|
|
259
|
+
await expect(migrator.rollback(["production"])).rejects.toThrow(/production/);
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("옵션 없이 만든 Migrator(CLI 경로)는 로컬 개발 환경에서 production을 계속 허용한다", () => {
|
|
263
|
+
process.env.NODE_ENV = "development";
|
|
264
|
+
Sonamu.dbConfig = dbConfig;
|
|
265
|
+
|
|
266
|
+
expect(new Migrator().getMigrationTargetKeys()).toContain("production");
|
|
267
|
+
});
|
|
268
|
+
});
|