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.
- 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 +20 -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 +127 -26
- 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/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 +31 -0
- package/dist/ui/dev-host-guard.d.ts.map +1 -0
- package/dist/ui/dev-host-guard.js +75 -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 +142 -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 +22 -0
- package/src/api/decorators.ts +1 -0
- package/src/api/guards.ts +130 -0
- package/src/api/sonamu.ts +205 -41
- 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__/code-generator-path-containment.test.ts +105 -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 +182 -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 +123 -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
|
@@ -4,6 +4,7 @@ import { type MultipartFile } from "@fastify/multipart";
|
|
|
4
4
|
|
|
5
5
|
import { BaseFile } from "./base-file";
|
|
6
6
|
import { type DiskName } from "./types";
|
|
7
|
+
import { resolveUploadContentType } from "./upload-safety";
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* Buffer 모드로 업로드된 파일
|
|
@@ -35,6 +36,7 @@ export class BufferedFile extends BaseFile {
|
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* 파일을 디스크에 저장
|
|
39
|
+
* Content-Type 은 resolveUploadContentType 으로 정해, 허용 목록 밖의 MIME 은 `application/octet-stream` 으로 저장합니다.
|
|
38
40
|
* @param diskName 설정에 등록한 디스크 이름
|
|
39
41
|
* @param key 저장 경로 (예: 'uploads/avatar.png')
|
|
40
42
|
* @returns 저장된 파일의 URL
|
|
@@ -45,7 +47,7 @@ export class BufferedFile extends BaseFile {
|
|
|
45
47
|
const disk = Sonamu.storage.use(diskName);
|
|
46
48
|
|
|
47
49
|
await disk.put(key, new Uint8Array(this.bufferValue), {
|
|
48
|
-
contentType: this.mimetype,
|
|
50
|
+
contentType: resolveUploadContentType(this.mimetype),
|
|
49
51
|
});
|
|
50
52
|
|
|
51
53
|
this["_url"] = await disk.getUrl(key);
|
package/src/storage/index.ts
CHANGED
|
@@ -4,4 +4,13 @@ export { BufferedFile } from "./buffered-file";
|
|
|
4
4
|
export { type DriverKey, drivers } from "./drivers";
|
|
5
5
|
export { StorageManager } from "./storage-manager";
|
|
6
6
|
export type { DiskName, KeyGenerator, StorageConfig } from "./types";
|
|
7
|
+
export {
|
|
8
|
+
createUploadStaticHeaders,
|
|
9
|
+
isPassiveUploadMimeType,
|
|
10
|
+
resolveUploadContentType,
|
|
11
|
+
resolveUploadExtension,
|
|
12
|
+
UPLOAD_FALLBACK_CONTENT_TYPE,
|
|
13
|
+
UPLOAD_FALLBACK_EXTENSION,
|
|
14
|
+
type UploadStaticSetHeaders,
|
|
15
|
+
} from "./upload-safety";
|
|
7
16
|
export { UploadedFile as StreamedFile } from "./uploaded-file";
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { type Stats } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { type FastifyReply } from "fastify";
|
|
5
|
+
import mime from "mime-types";
|
|
6
|
+
|
|
7
|
+
/** 브라우저가 내용을 판별하지 못하게 할 때 쓰는 기본 MIME 타입 */
|
|
8
|
+
export const UPLOAD_FALLBACK_CONTENT_TYPE = "application/octet-stream";
|
|
9
|
+
|
|
10
|
+
/** 허용 목록 밖의 업로드 파일에 붙이는 확장자 */
|
|
11
|
+
export const UPLOAD_FALLBACK_EXTENSION = "bin";
|
|
12
|
+
|
|
13
|
+
// 브라우저가 문서로 렌더링하거나 스크립트로 실행하지 않는 타입만 둔다.
|
|
14
|
+
// text/html, image/svg+xml, *+xml, JavaScript 같은 능동 콘텐츠는 의도적으로 빠져 있다.
|
|
15
|
+
const PASSIVE_UPLOAD_MIME_TYPES = new Set([
|
|
16
|
+
"application/pdf",
|
|
17
|
+
"text/plain",
|
|
18
|
+
"text/csv",
|
|
19
|
+
"application/json",
|
|
20
|
+
"application/rtf",
|
|
21
|
+
"application/zip",
|
|
22
|
+
"application/gzip",
|
|
23
|
+
"application/x-7z-compressed",
|
|
24
|
+
"application/x-tar",
|
|
25
|
+
"application/vnd.rar",
|
|
26
|
+
"application/x-rar-compressed",
|
|
27
|
+
"application/msword",
|
|
28
|
+
"application/vnd.ms-excel",
|
|
29
|
+
"application/vnd.ms-powerpoint",
|
|
30
|
+
"application/vnd.hancom.hwp",
|
|
31
|
+
"application/vnd.hancom.hwpx",
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
const PASSIVE_UPLOAD_MIME_PREFIXES = [
|
|
35
|
+
"image/",
|
|
36
|
+
"audio/",
|
|
37
|
+
"video/",
|
|
38
|
+
"application/vnd.openxmlformats-officedocument.",
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/** MIME 파라미터(charset 등)를 떼고 소문자로 맞춥니다. */
|
|
42
|
+
function normalizeMimeType(mimetype: string): string {
|
|
43
|
+
return (mimetype.split(";")[0] ?? "").trim().toLowerCase();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** XML 기반 타입은 SVG처럼 스크립트를 품을 수 있으므로 접두사가 맞아도 제외한다. */
|
|
47
|
+
function isXmlBasedMimeType(mimetype: string): boolean {
|
|
48
|
+
return mimetype.endsWith("/xml") || mimetype.endsWith("+xml") || mimetype.includes("svg");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 브라우저가 실행하지 않는 수동(passive) 콘텐츠 타입인지 판정합니다.
|
|
53
|
+
* 업로드 MIME 은 클라이언트가 보낸 값이므로, 이 판정은 내용을 보장하지 않고
|
|
54
|
+
* 저장 확장자와 Content-Type 을 안전한 쪽으로 고르는 데만 씁니다.
|
|
55
|
+
*/
|
|
56
|
+
export function isPassiveUploadMimeType(mimetype: string): boolean {
|
|
57
|
+
const normalized = normalizeMimeType(mimetype);
|
|
58
|
+
if (normalized === "" || isXmlBasedMimeType(normalized)) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
return (
|
|
62
|
+
PASSIVE_UPLOAD_MIME_TYPES.has(normalized) ||
|
|
63
|
+
PASSIVE_UPLOAD_MIME_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 브라우저가 문서가 아닌 미디어로 바로 보여주는 타입(이미지·오디오·비디오)인지 판정합니다. */
|
|
68
|
+
function isInlineMediaMimeType(mimetype: string): boolean {
|
|
69
|
+
const normalized = normalizeMimeType(mimetype);
|
|
70
|
+
if (isXmlBasedMimeType(normalized)) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
return ["image/", "audio/", "video/"].some((prefix) => normalized.startsWith(prefix));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 업로드 MIME 으로 저장 키의 확장자를 정합니다.
|
|
78
|
+
* 허용 목록 밖이면 `bin` 을 돌려주고, MIME 을 알 수 없으면 `false` 를 돌려줍니다.
|
|
79
|
+
*/
|
|
80
|
+
export function resolveUploadExtension(mimetype: string): string | false {
|
|
81
|
+
const extension = mime.extension(normalizeMimeType(mimetype));
|
|
82
|
+
if (!extension) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
// 확장자로 다시 서빙될 타입도 허용 목록 안이어야 한다(정적 서빙은 확장자로 Content-Type 을 정함).
|
|
86
|
+
const servedType = mime.lookup(extension);
|
|
87
|
+
if (!isPassiveUploadMimeType(mimetype) || !servedType || !isPassiveUploadMimeType(servedType)) {
|
|
88
|
+
return UPLOAD_FALLBACK_EXTENSION;
|
|
89
|
+
}
|
|
90
|
+
return extension;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 저장소에 기록할 Content-Type 을 정합니다.
|
|
95
|
+
* 허용 목록 밖의 타입은 브라우저가 렌더링하지 않도록 `application/octet-stream` 으로 바꿉니다.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveUploadContentType(mimetype: string): string {
|
|
98
|
+
return isPassiveUploadMimeType(mimetype)
|
|
99
|
+
? normalizeMimeType(mimetype)
|
|
100
|
+
: UPLOAD_FALLBACK_CONTENT_TYPE;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @fastify/static 의 setHeaders 시그니처 */
|
|
104
|
+
export type UploadStaticSetHeaders = (reply: FastifyReply, filePath: string, stat: Stats) => void;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 업로드 디렉터리를 @fastify/static 으로 서빙할 때 쓰는 setHeaders 를 만듭니다.
|
|
108
|
+
*
|
|
109
|
+
* `uploadDir` 안의 파일에만 아래 헤더를 붙여, 업로드된 HTML·SVG 가 앱 오리진에서 실행되지 않게 합니다.
|
|
110
|
+
* - `X-Content-Type-Options: nosniff`
|
|
111
|
+
* - `Content-Security-Policy: sandbox`
|
|
112
|
+
* - 이미지·오디오·비디오가 아니면 `Content-Disposition: attachment`
|
|
113
|
+
* - 확장자로 정해진 타입이 허용 목록 밖이면(예: 원본 파일명의 `.html`) `Content-Type: application/octet-stream`
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* static: {
|
|
117
|
+
* root: publicDir,
|
|
118
|
+
* prefix: "/api/public",
|
|
119
|
+
* setHeaders: createUploadStaticHeaders({ uploadDir }),
|
|
120
|
+
* }
|
|
121
|
+
*/
|
|
122
|
+
export function createUploadStaticHeaders(options: {
|
|
123
|
+
/** 업로드 파일이 저장되는 디렉터리(fs 드라이버의 location) */
|
|
124
|
+
uploadDir: string;
|
|
125
|
+
/** 함께 실행할 기존 setHeaders */
|
|
126
|
+
setHeaders?: UploadStaticSetHeaders;
|
|
127
|
+
}): UploadStaticSetHeaders {
|
|
128
|
+
const uploadDir = path.resolve(options.uploadDir);
|
|
129
|
+
|
|
130
|
+
return (reply, filePath, stat) => {
|
|
131
|
+
options.setHeaders?.(reply, filePath, stat);
|
|
132
|
+
|
|
133
|
+
const relative = path.relative(uploadDir, path.resolve(filePath));
|
|
134
|
+
const isInsideUploadDir =
|
|
135
|
+
relative !== "" &&
|
|
136
|
+
relative !== ".." &&
|
|
137
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
138
|
+
!path.isAbsolute(relative);
|
|
139
|
+
if (!isInsideUploadDir) {
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
reply.header("X-Content-Type-Options", "nosniff");
|
|
144
|
+
reply.header("Content-Security-Policy", "sandbox");
|
|
145
|
+
|
|
146
|
+
// @fastify/static 은 확장자로 Content-Type 을 정하므로 같은 기준으로 판정한다.
|
|
147
|
+
const servedType = mime.lookup(filePath);
|
|
148
|
+
if (!servedType || !isPassiveUploadMimeType(servedType)) {
|
|
149
|
+
reply.header("Content-Type", UPLOAD_FALLBACK_CONTENT_TYPE);
|
|
150
|
+
}
|
|
151
|
+
if (!servedType || !isInlineMediaMimeType(servedType)) {
|
|
152
|
+
reply.header("Content-Disposition", "attachment");
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
@@ -378,6 +378,88 @@ describe("WebSocketRuntime", () => {
|
|
|
378
378
|
expect(runtime.registry.getConnectionCount("chat")).toBe(1);
|
|
379
379
|
});
|
|
380
380
|
|
|
381
|
+
it("활성화 전에 도착한 프레임은 파싱하지 않고 보관했다가 활성화 뒤 순서대로 처리한다", async () => {
|
|
382
|
+
const runtime = createWebSocketRuntime();
|
|
383
|
+
const socket = new FakeWebSocket();
|
|
384
|
+
const connection = await runtime.registerConnection(asWebSocket(socket), {
|
|
385
|
+
outEvents: OutEvents,
|
|
386
|
+
inEvents: InEvents,
|
|
387
|
+
namespace: "chat",
|
|
388
|
+
active: false,
|
|
389
|
+
});
|
|
390
|
+
const handler = vi.fn();
|
|
391
|
+
connection.onMessage("joinRoom", handler);
|
|
392
|
+
|
|
393
|
+
socket.emit("message", JSON.stringify({ event: "joinRoom", data: { roomId: "alpha" } }));
|
|
394
|
+
socket.emit(
|
|
395
|
+
"message",
|
|
396
|
+
Buffer.from(JSON.stringify({ event: "joinRoom", data: { roomId: "beta" } })),
|
|
397
|
+
);
|
|
398
|
+
await waitForAsyncQueue();
|
|
399
|
+
|
|
400
|
+
expect(handler).not.toHaveBeenCalled();
|
|
401
|
+
|
|
402
|
+
await runtime.activateConnection(connection.id);
|
|
403
|
+
await waitForAsyncQueue();
|
|
404
|
+
|
|
405
|
+
expect(handler.mock.calls.map(([data]) => data)).toEqual([
|
|
406
|
+
{ roomId: "alpha" },
|
|
407
|
+
{ roomId: "beta" },
|
|
408
|
+
]);
|
|
409
|
+
expect(socket.closedWith).toBeNull();
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
it("가드가 끝나기 전 잘못된 프레임은 파싱하지 않으며, 가드 거부로 닫히면 그대로 버린다", async () => {
|
|
413
|
+
const runtime = createWebSocketRuntime();
|
|
414
|
+
const socket = new FakeWebSocket();
|
|
415
|
+
const connection = await runtime.registerConnection(asWebSocket(socket), {
|
|
416
|
+
outEvents: OutEvents,
|
|
417
|
+
inEvents: InEvents,
|
|
418
|
+
namespace: "chat",
|
|
419
|
+
active: false,
|
|
420
|
+
});
|
|
421
|
+
const handler = vi.fn();
|
|
422
|
+
connection.onMessage("joinRoom", handler);
|
|
423
|
+
|
|
424
|
+
socket.emit("message", "{not-json");
|
|
425
|
+
socket.emit("message", JSON.stringify({ event: "joinRoom", data: { roomId: "alpha" } }));
|
|
426
|
+
await waitForAsyncQueue();
|
|
427
|
+
|
|
428
|
+
// 파싱했다면 1007로 닫혔을 것이다
|
|
429
|
+
expect(socket.closedWith).toBeNull();
|
|
430
|
+
|
|
431
|
+
// 가드 거부를 흉내 내 1008로 닫는다
|
|
432
|
+
connection.close(1008, "Unauthorized websocket connection");
|
|
433
|
+
await runtime.activateConnection(connection.id);
|
|
434
|
+
await waitForAsyncQueue();
|
|
435
|
+
|
|
436
|
+
expect(socket.closedWith).toEqual({ code: 1008, reason: "Unauthorized websocket connection" });
|
|
437
|
+
expect(handler).not.toHaveBeenCalled();
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
it("활성화 전 보관 프레임은 개수 상한을 넘으면 오래된 것부터 버린다", async () => {
|
|
441
|
+
const runtime = createWebSocketRuntime();
|
|
442
|
+
const socket = new FakeWebSocket();
|
|
443
|
+
const connection = await runtime.registerConnection(asWebSocket(socket), {
|
|
444
|
+
outEvents: OutEvents,
|
|
445
|
+
inEvents: InEvents,
|
|
446
|
+
namespace: "chat",
|
|
447
|
+
active: false,
|
|
448
|
+
});
|
|
449
|
+
const handler = vi.fn();
|
|
450
|
+
connection.onMessage("joinRoom", handler);
|
|
451
|
+
|
|
452
|
+
for (let index = 0; index < 101; index += 1) {
|
|
453
|
+
socket.emit("message", JSON.stringify({ event: "joinRoom", data: { roomId: `r${index}` } }));
|
|
454
|
+
}
|
|
455
|
+
await runtime.activateConnection(connection.id);
|
|
456
|
+
await waitForAsyncQueue(10);
|
|
457
|
+
|
|
458
|
+
expect(handler).toHaveBeenCalledTimes(100);
|
|
459
|
+
expect(handler.mock.calls[0]?.[0]).toEqual({ roomId: "r1" });
|
|
460
|
+
expect(handler.mock.calls[99]?.[0]).toEqual({ roomId: "r100" });
|
|
461
|
+
});
|
|
462
|
+
|
|
381
463
|
it("manages rooms and user fan-out through the registry", async () => {
|
|
382
464
|
const runtime = createWebSocketRuntime();
|
|
383
465
|
const socketA = new FakeWebSocket();
|
|
@@ -589,6 +671,21 @@ describe("WebSocketRuntime", () => {
|
|
|
589
671
|
expect(socket.closedWith?.code).toBe(1007);
|
|
590
672
|
});
|
|
591
673
|
|
|
674
|
+
it("data 키가 없는 envelope은 계속 잘못된 payload로 닫는다", async () => {
|
|
675
|
+
const runtime = createWebSocketRuntime();
|
|
676
|
+
const socket = new FakeWebSocket();
|
|
677
|
+
await runtime.registerConnection(asWebSocket(socket), {
|
|
678
|
+
outEvents: OutEvents,
|
|
679
|
+
inEvents: InEvents,
|
|
680
|
+
namespace: "chat",
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
socket.emit("message", JSON.stringify({ event: "joinRoom" }));
|
|
684
|
+
await waitForAsyncQueue();
|
|
685
|
+
|
|
686
|
+
expect(socket.closedWith).toEqual({ code: 1007, reason: "Invalid message payload" });
|
|
687
|
+
});
|
|
688
|
+
|
|
592
689
|
it("still closes and unregisters when onClose callbacks throw", async () => {
|
|
593
690
|
const runtime = createWebSocketRuntime();
|
|
594
691
|
const socket = new FakeWebSocket();
|
package/src/stream/ws.ts
CHANGED
|
@@ -49,11 +49,15 @@ const MAX_SOCKET_BUFFERED_AMOUNT = 1_048_576;
|
|
|
49
49
|
const OUTBOUND_BATCH_SIZE = 50;
|
|
50
50
|
const OUTBOUND_RETRY_DELAY_MS = 5;
|
|
51
51
|
|
|
52
|
+
type WebSocketEnvelopeData = z.output<ReturnType<typeof z.json>>;
|
|
53
|
+
|
|
52
54
|
// envelope을 `{event, data}` 형태로 고정해 server handler와 generated client가 같은 framing contract를 쓰게 함
|
|
53
55
|
// meta는 optional이므로 기존 `{event, data}` 메시지도 그대로 파싱됨 (backward-compatible)
|
|
56
|
+
// data는 JSON.parse 결과라 항상 JSON 값이므로 z.json()으로 모든 노드를 다시 재귀 검증하지 않고 타입만 선언함(키 누락은 그대로 거부).
|
|
57
|
+
// 실제 값 검증은 이벤트 스키마가 맡음
|
|
54
58
|
const WebSocketEnvelopeSchema = z.object({
|
|
55
59
|
event: z.string(),
|
|
56
|
-
data: z.
|
|
60
|
+
data: z.custom<WebSocketEnvelopeData>(),
|
|
57
61
|
meta: z
|
|
58
62
|
.object({
|
|
59
63
|
traceparent: z.string().optional(),
|
|
@@ -142,6 +146,8 @@ export type WebSocketRuntimeOptions = {
|
|
|
142
146
|
export class WebSocketRuntime {
|
|
143
147
|
readonly registry: WebSocketRegistry;
|
|
144
148
|
readonly telemetryController: WebSocketTelemetryController;
|
|
149
|
+
// active: false로 등록돼 아직 인바운드 프레임을 처리하지 않는 연결. activateConnection에서 꺼내 인바운드를 연다
|
|
150
|
+
private readonly inactiveConnections = new Map<string, { openInbound(): void }>();
|
|
145
151
|
|
|
146
152
|
constructor(options: WebSocketRuntimeOptions = {}) {
|
|
147
153
|
// nodeId를 주지 않으면 store/bus가 가진 nodeId를 따르고, 둘 다 없으면 hostname-pid-랜덤으로 만든다.
|
|
@@ -177,6 +183,8 @@ export class WebSocketRuntime {
|
|
|
177
183
|
|
|
178
184
|
/**
|
|
179
185
|
* 소켓 리스너를 동기로 붙이고 registry에 등록한다. store.register가 끝나면(실패해도) resolve한다.
|
|
186
|
+
* active: false면 activateConnection 전까지 인바운드 프레임을 파싱하지 않고 최대 100개까지 보관하며,
|
|
187
|
+
* 넘치면 가장 오래된 프레임을 버린다.
|
|
180
188
|
*/
|
|
181
189
|
async registerConnection<
|
|
182
190
|
TOutSchema extends WebSocketEventFields,
|
|
@@ -195,12 +203,24 @@ export class WebSocketRuntime {
|
|
|
195
203
|
registry: this.registry,
|
|
196
204
|
telemetryController: this.telemetryController,
|
|
197
205
|
});
|
|
206
|
+
if (options.active === false) {
|
|
207
|
+
this.inactiveConnections.set(connection.id, connection);
|
|
208
|
+
connection.onClose(() => {
|
|
209
|
+
this.inactiveConnections.delete(connection.id);
|
|
210
|
+
});
|
|
211
|
+
}
|
|
198
212
|
await this.registry.register(connection, options.active ?? true);
|
|
199
213
|
return connection;
|
|
200
214
|
}
|
|
201
215
|
|
|
202
|
-
|
|
203
|
-
|
|
216
|
+
/**
|
|
217
|
+
* 연결을 registry에서 활성화한 뒤, 활성화 전까지 파싱하지 않고 보관하던 인바운드 프레임을 도착 순서대로 처리한다.
|
|
218
|
+
*/
|
|
219
|
+
async activateConnection(connectionId: string): Promise<void> {
|
|
220
|
+
const connection = this.inactiveConnections.get(connectionId);
|
|
221
|
+
this.inactiveConnections.delete(connectionId);
|
|
222
|
+
await this.registry.activate(connectionId);
|
|
223
|
+
connection?.openInbound();
|
|
204
224
|
}
|
|
205
225
|
|
|
206
226
|
leaveUser(
|
|
@@ -270,6 +290,8 @@ class WebSocketConnectionImpl<
|
|
|
270
290
|
private readonly closeCallbacks: CloseHandler[] = [];
|
|
271
291
|
private readonly messageHandlers = new Map<string, Array<MessageHandler<unknown>>>();
|
|
272
292
|
private readonly pendingMessages: ParsedEnvelope[] = [];
|
|
293
|
+
// 가드 통과(활성화) 전에 도착한 프레임. 비인가 연결이 파싱 비용을 쓰게 하지 않도록 raw 그대로 보관한다
|
|
294
|
+
private readonly heldInboundFrames: RawData[] = [];
|
|
273
295
|
private readonly pendingOutboundMessages: Array<{ payload: string; event: string }> = [];
|
|
274
296
|
private readonly closePromise: Promise<void>;
|
|
275
297
|
private readonly resolveClosePromise: () => void;
|
|
@@ -291,6 +313,7 @@ class WebSocketConnectionImpl<
|
|
|
291
313
|
|
|
292
314
|
private closedInternal = false;
|
|
293
315
|
private closeStarted = false;
|
|
316
|
+
private inboundOpen: boolean;
|
|
294
317
|
private awaitingPong = false;
|
|
295
318
|
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
296
319
|
private messageQueue: Promise<void> = Promise.resolve();
|
|
@@ -310,6 +333,7 @@ class WebSocketConnectionImpl<
|
|
|
310
333
|
this.connectionParentSpanId = options.parentSpanId;
|
|
311
334
|
this.connectionSampled = options.sampled;
|
|
312
335
|
this.eventSchemasIn = options.inEvents["shape"];
|
|
336
|
+
this.inboundOpen = options.active ?? true;
|
|
313
337
|
|
|
314
338
|
let resolveClosePromise!: () => void;
|
|
315
339
|
this.closePromise = new Promise<void>((resolve) => {
|
|
@@ -391,7 +415,7 @@ class WebSocketConnectionImpl<
|
|
|
391
415
|
|
|
392
416
|
getTelemetrySnapshot(): WebSocketTelemetryConnectionSnapshot {
|
|
393
417
|
return {
|
|
394
|
-
pendingInboundMessages: this.pendingMessages.length,
|
|
418
|
+
pendingInboundMessages: this.pendingMessages.length + this.heldInboundFrames.length,
|
|
395
419
|
pendingOutboundMessages: this.pendingOutboundMessages.length,
|
|
396
420
|
socketBufferedBytes: this.socket.readyState === WS_OPEN ? this.socket.bufferedAmount : 0,
|
|
397
421
|
};
|
|
@@ -454,6 +478,43 @@ class WebSocketConnectionImpl<
|
|
|
454
478
|
|
|
455
479
|
// 인바운드 메시지를 순차 처리 큐에 올림. Sonamu envelope 검증 수행
|
|
456
480
|
private readonly handleMessage = (raw: RawData) => {
|
|
481
|
+
if (!this.inboundOpen) {
|
|
482
|
+
this.holdInboundFrame(raw);
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
this.enqueueInboundFrame(raw);
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* 활성화(가드 통과) 뒤 호출된다. 보관하던 raw 프레임을 도착 순서대로 처리 큐에 올리고 이후 프레임은 바로 처리한다.
|
|
491
|
+
*/
|
|
492
|
+
openInbound(): void {
|
|
493
|
+
if (this.inboundOpen || this.closedInternal) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
this.inboundOpen = true;
|
|
498
|
+
for (const raw of this.heldInboundFrames.splice(0)) {
|
|
499
|
+
this.enqueueInboundFrame(raw);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// 활성화 전 보관 개수는 handler 대기 버퍼와 같은 상한을 쓰고, 넘치면 오래된 프레임부터 버린다
|
|
504
|
+
private holdInboundFrame(raw: RawData): void {
|
|
505
|
+
if (this.heldInboundFrames.length >= MAX_PENDING_MESSAGES) {
|
|
506
|
+
this.options.telemetryController.emit({
|
|
507
|
+
name: "ws.message.buffer.dropped",
|
|
508
|
+
level: "warn",
|
|
509
|
+
...this.telemetryFields(),
|
|
510
|
+
detail: { reason: "inactive" },
|
|
511
|
+
});
|
|
512
|
+
this.heldInboundFrames.shift();
|
|
513
|
+
}
|
|
514
|
+
this.heldInboundFrames.push(raw);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
private enqueueInboundFrame(raw: RawData): void {
|
|
457
518
|
this.enqueueMessageTask(async () => {
|
|
458
519
|
const text = normalizeMessage(raw);
|
|
459
520
|
const parsedEnvelope = safeParseEnvelope(text);
|
|
@@ -473,7 +534,7 @@ class WebSocketConnectionImpl<
|
|
|
473
534
|
this.options.registry.touch(this.id);
|
|
474
535
|
await this.dispatchEnvelope(parsedEnvelope);
|
|
475
536
|
});
|
|
476
|
-
}
|
|
537
|
+
}
|
|
477
538
|
|
|
478
539
|
private readonly handleClose = (code?: number, reason?: Buffer | string) => {
|
|
479
540
|
const reasonText = isStringValue(reason) ? reason : reason?.toString();
|
|
@@ -700,6 +761,7 @@ class WebSocketConnectionImpl<
|
|
|
700
761
|
this.socket.off("pong", this.handlePong);
|
|
701
762
|
this.awaitingPong = false;
|
|
702
763
|
this.pendingMessages.length = 0;
|
|
764
|
+
this.heldInboundFrames.length = 0;
|
|
703
765
|
this.pendingOutboundMessages.length = 0;
|
|
704
766
|
this.options.registry.unregister(this.id);
|
|
705
767
|
for (const callback of this.closeCallbacks.splice(0)) {
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
7
|
+
|
|
8
|
+
import { type SonamuConfig } from "../../api/config";
|
|
9
|
+
import { Sonamu } from "../../api/sonamu";
|
|
10
|
+
import { type RenderedTemplate, Template } from "../../template/template";
|
|
11
|
+
import { TemplateManager } from "../../template/template-manager";
|
|
12
|
+
import { type AbsolutePath } from "../../utils/path-utils";
|
|
13
|
+
import { generateTemplate } from "../code-generator";
|
|
14
|
+
|
|
15
|
+
/** 문자열이 AbsolutePath 형식(`/`로 시작)인지 런타임에 확인합니다. */
|
|
16
|
+
function isAbsolutePath(value: string): value is AbsolutePath {
|
|
17
|
+
return value.startsWith("/");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 지정한 경로로 렌더링되는 테스트용 템플릿입니다. */
|
|
21
|
+
class FixedPathTemplate extends Template {
|
|
22
|
+
constructor(private readonly renderedPath: string) {
|
|
23
|
+
super("model_test");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
render(): RenderedTemplate {
|
|
27
|
+
return {
|
|
28
|
+
target: "api/src/application",
|
|
29
|
+
path: this.renderedPath,
|
|
30
|
+
body: "export const marker = 1;",
|
|
31
|
+
importKeys: [],
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
getTargetAndPath() {
|
|
36
|
+
return { target: "api/src/application", path: this.renderedPath };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createConfig(): SonamuConfig {
|
|
41
|
+
return {
|
|
42
|
+
projectName: "sonamu-test",
|
|
43
|
+
api: { dir: "api", route: { prefix: "/api" } },
|
|
44
|
+
i18n: { defaultLocale: "ko", supportedLocales: ["ko"] },
|
|
45
|
+
sync: { targets: ["web"] },
|
|
46
|
+
database: {},
|
|
47
|
+
server: {
|
|
48
|
+
apiConfig: {
|
|
49
|
+
contextProvider: (defaultContext) => defaultContext,
|
|
50
|
+
guardHandler: () => undefined,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
describe("generateTemplate의 생성 경로 제한", () => {
|
|
57
|
+
const originalState = Sonamu.captureTestingSnapshot();
|
|
58
|
+
let workspace: string;
|
|
59
|
+
let appRoot: string;
|
|
60
|
+
|
|
61
|
+
beforeEach(async () => {
|
|
62
|
+
// 앱 루트를 한 단계 안쪽에 두어, 탈출한 파일도 임시 디렉터리 안에만 생기게 합니다.
|
|
63
|
+
workspace = await mkdtemp(path.join(os.tmpdir(), "sonamu-codegen-containment-"));
|
|
64
|
+
appRoot = path.join(workspace, "app");
|
|
65
|
+
await mkdir(path.join(appRoot, "api", "src", "application"), { recursive: true });
|
|
66
|
+
const apiRootPath = path.join(appRoot, "api");
|
|
67
|
+
if (!isAbsolutePath(apiRootPath)) {
|
|
68
|
+
throw new Error(`테스트용 apiRootPath가 절대 경로가 아닙니다: ${apiRootPath}`);
|
|
69
|
+
}
|
|
70
|
+
Sonamu.apiRootPath = apiRootPath;
|
|
71
|
+
Sonamu.config = createConfig();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
afterEach(async () => {
|
|
75
|
+
vi.restoreAllMocks();
|
|
76
|
+
Sonamu.restoreTestingSnapshot(originalState);
|
|
77
|
+
await rm(workspace, { recursive: true, force: true });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it.each(["../../../../outside.model.test.ts", "../../../../outside/x/x.model.test.ts"])(
|
|
81
|
+
"앱 루트 밖을 가리키는 경로 %j는 파일을 만들지 않고 거부한다",
|
|
82
|
+
async (renderedPath) => {
|
|
83
|
+
vi.spyOn(TemplateManager, "get").mockReturnValue(new FixedPathTemplate(renderedPath));
|
|
84
|
+
|
|
85
|
+
await expect(
|
|
86
|
+
generateTemplate("model_test", { entityId: "Post" }, { overwrite: true }),
|
|
87
|
+
).rejects.toThrow("앱 루트 밖");
|
|
88
|
+
|
|
89
|
+
expect(existsSync(path.join(workspace, "outside.model.test.ts"))).toBe(false);
|
|
90
|
+
expect(existsSync(path.join(workspace, "outside"))).toBe(false);
|
|
91
|
+
},
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
it("앱 루트 안의 경로는 그대로 생성한다", async () => {
|
|
95
|
+
vi.spyOn(TemplateManager, "get").mockReturnValue(
|
|
96
|
+
new FixedPathTemplate("post/post.model.test.ts"),
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
const written = await generateTemplate("model_test", { entityId: "Post" }, { overwrite: true });
|
|
100
|
+
|
|
101
|
+
const expected = path.join(appRoot, "api/src/application/post/post.model.test.ts");
|
|
102
|
+
expect(written).toEqual([expected]);
|
|
103
|
+
await expect(readFile(expected, "utf8")).resolves.toContain("marker");
|
|
104
|
+
});
|
|
105
|
+
});
|
|
@@ -28,6 +28,8 @@ import { syncerFileExists, syncerFilesystem } from "./filesystem-dependencies";
|
|
|
28
28
|
/**
|
|
29
29
|
* 템플릿을 렌더링하고 파일로 생성합니다.
|
|
30
30
|
* overwrite 옵션이 false인 경우, 이미 존재하는 파일은 건너뜁니다.
|
|
31
|
+
* sync target을 치환해 정규화한 출력 경로가 하나라도 Sonamu.appRootPath 밖이면 파일을 쓰기 전에 Error를 던집니다.
|
|
32
|
+
* 심볼릭 링크의 실제 경로는 확인하지 않습니다.
|
|
31
33
|
* @param key - 템플릿 키 (예: "entity", "model", "service" 등)
|
|
32
34
|
* @param templateOptions - 템플릿 렌더링에 필요한 옵션
|
|
33
35
|
* @param _generateOptions - 생성 옵션 (overwrite 여부)
|
|
@@ -56,16 +58,16 @@ export async function generateTemplate<T extends TemplateKey>(
|
|
|
56
58
|
)
|
|
57
59
|
).flat();
|
|
58
60
|
|
|
61
|
+
// 존재 확인이나 쓰기 전에 모든 대상 경로가 앱 루트 안인지 먼저 확인한다.
|
|
62
|
+
pathAndCodes.forEach(getDstFilePaths);
|
|
63
|
+
|
|
59
64
|
const filteredPathAndCodes: PathAndCode[] = await (async () => {
|
|
60
65
|
if (generateOptions.overwrite) {
|
|
61
66
|
return pathAndCodes;
|
|
62
67
|
} else {
|
|
63
68
|
return await filterAsync(pathAndCodes, async (pathAndCode) => {
|
|
64
|
-
const { targets } = Sonamu.config.sync;
|
|
65
|
-
const filePath = `${Sonamu.appRootPath}/${pathAndCode.path}`;
|
|
66
|
-
const dstFilePaths = targets.map((target) => filePath.replace("/:target/", `/${target}/`));
|
|
67
69
|
return await everyAsync(
|
|
68
|
-
|
|
70
|
+
getDstFilePaths(pathAndCode),
|
|
69
71
|
async (dstPath) => !(await syncerFileExists(dstPath)),
|
|
70
72
|
);
|
|
71
73
|
});
|
|
@@ -96,6 +98,9 @@ export async function renderTemplate<T extends keyof TemplateOptions>(
|
|
|
96
98
|
): Promise<PathAndCode[]> {
|
|
97
99
|
Naite.t("renderTemplate", { key, options });
|
|
98
100
|
|
|
101
|
+
// 메모리에서 바뀐 엔티티 값이 검증 없이 생성 코드로 나가지 않도록 렌더 직전에 다시 확인합니다.
|
|
102
|
+
EntityManager.assertAllCodegenSafe();
|
|
103
|
+
|
|
99
104
|
const template = TemplateManager.get(key);
|
|
100
105
|
|
|
101
106
|
const rendered = await template.render(options);
|
|
@@ -198,9 +203,12 @@ async function resolveRenderedTemplate(
|
|
|
198
203
|
};
|
|
199
204
|
}
|
|
200
205
|
|
|
201
|
-
|
|
206
|
+
/**
|
|
207
|
+
* 렌더링된 경로를 sync target별 절대 경로로 펼칩니다.
|
|
208
|
+
* `..` 등으로 앱 루트 밖을 가리키는 경로가 하나라도 있으면 예외를 던져 파일을 만들지 않습니다.
|
|
209
|
+
*/
|
|
210
|
+
function getDstFilePaths(pathAndCode: PathAndCode): AbsolutePath[] {
|
|
202
211
|
const { targets } = Sonamu.config.sync;
|
|
203
|
-
const { appRootPath } = Sonamu;
|
|
204
212
|
const filePath =
|
|
205
213
|
/* SAFETY: TypeScript AST 파싱과 동기화 입력 계약이 이 값의 타입을 보장한다. */ `${Sonamu.appRootPath}/${pathAndCode.path}` as AbsolutePath;
|
|
206
214
|
|
|
@@ -209,6 +217,26 @@ async function writeCodeToPathEachTarget(pathAndCode: PathAndCode): Promise<Abso
|
|
|
209
217
|
(target) => filePath.replace("/:target/", `/${target}/`),
|
|
210
218
|
) as AbsolutePath[],
|
|
211
219
|
);
|
|
220
|
+
|
|
221
|
+
// 심볼릭 링크로 연결된 target 디렉터리는 그대로 허용하도록 실제 경로가 아닌 정규화한 경로로 판정한다.
|
|
222
|
+
const appRootPath = path.resolve(Sonamu.appRootPath);
|
|
223
|
+
for (const dstFilePath of dstFilePaths) {
|
|
224
|
+
const relativePath = path.relative(appRootPath, path.resolve(dstFilePath));
|
|
225
|
+
const isInsideAppRoot =
|
|
226
|
+
relativePath !== "" &&
|
|
227
|
+
relativePath !== ".." &&
|
|
228
|
+
!relativePath.startsWith(`..${path.sep}`) &&
|
|
229
|
+
!path.isAbsolute(relativePath);
|
|
230
|
+
if (!isInsideAppRoot) {
|
|
231
|
+
throw new Error(`생성 경로가 앱 루트 밖을 가리킵니다: ${pathAndCode.path}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return dstFilePaths;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function writeCodeToPathEachTarget(pathAndCode: PathAndCode): Promise<AbsolutePath[]> {
|
|
238
|
+
const { appRootPath } = Sonamu;
|
|
239
|
+
const dstFilePaths = getDstFilePaths(pathAndCode);
|
|
212
240
|
return await Promise.all(
|
|
213
241
|
dstFilePaths.map(async (dstFilePath) => {
|
|
214
242
|
const dir = path.dirname(dstFilePath);
|
|
@@ -147,9 +147,13 @@ describe("Template__generated searchText", () => {
|
|
|
147
147
|
template.getTargetAndPath = () => ({ target: "", path: "" });
|
|
148
148
|
|
|
149
149
|
const { body } = template.render({ entityId: entity.id });
|
|
150
|
+
const { lines } = new Template__generated().getBaseSaveParamsSourceCode(entity);
|
|
150
151
|
|
|
152
|
+
expect(lines[0]).toBe(
|
|
153
|
+
`export const ${entity.id}BaseSaveParams = ${entity.id}BaseSchema.omit({ slug: true, search_text: true });`,
|
|
154
|
+
);
|
|
151
155
|
expect(body).toContain(
|
|
152
|
-
`export const ${entity.id}SaveParams = ${entity.id}
|
|
156
|
+
`export const ${entity.id}SaveParams = ${entity.id}BaseSaveParams.partial({ id: true });`,
|
|
153
157
|
);
|
|
154
158
|
});
|
|
155
159
|
});
|