@mandujs/core 0.9.46 → 0.11.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 (56) hide show
  1. package/README.md +79 -10
  2. package/package.json +1 -1
  3. package/src/brain/doctor/config-analyzer.ts +498 -0
  4. package/src/brain/doctor/index.ts +10 -0
  5. package/src/change/snapshot.ts +46 -1
  6. package/src/change/types.ts +13 -0
  7. package/src/config/index.ts +9 -2
  8. package/src/config/mcp-ref.ts +348 -0
  9. package/src/config/mcp-status.ts +348 -0
  10. package/src/config/metadata.test.ts +308 -0
  11. package/src/config/metadata.ts +293 -0
  12. package/src/config/symbols.ts +144 -0
  13. package/src/config/validate.ts +122 -65
  14. package/src/config/watcher.ts +311 -0
  15. package/src/contract/index.ts +26 -25
  16. package/src/contract/protection.ts +364 -0
  17. package/src/error/domains.ts +265 -0
  18. package/src/error/index.ts +25 -13
  19. package/src/errors/extractor.ts +409 -0
  20. package/src/errors/index.ts +19 -0
  21. package/src/filling/context.ts +29 -1
  22. package/src/filling/deps.ts +238 -0
  23. package/src/filling/filling.ts +94 -8
  24. package/src/filling/index.ts +18 -0
  25. package/src/guard/analyzer.ts +7 -2
  26. package/src/guard/config-guard.ts +281 -0
  27. package/src/guard/decision-memory.test.ts +293 -0
  28. package/src/guard/decision-memory.ts +532 -0
  29. package/src/guard/healing.test.ts +259 -0
  30. package/src/guard/healing.ts +874 -0
  31. package/src/guard/index.ts +119 -0
  32. package/src/guard/negotiation.test.ts +282 -0
  33. package/src/guard/negotiation.ts +975 -0
  34. package/src/guard/semantic-slots.test.ts +379 -0
  35. package/src/guard/semantic-slots.ts +796 -0
  36. package/src/index.ts +4 -1
  37. package/src/lockfile/generate.ts +259 -0
  38. package/src/lockfile/index.ts +186 -0
  39. package/src/lockfile/lockfile.test.ts +410 -0
  40. package/src/lockfile/types.ts +184 -0
  41. package/src/lockfile/validate.ts +308 -0
  42. package/src/logging/index.ts +22 -0
  43. package/src/logging/transports.ts +365 -0
  44. package/src/plugins/index.ts +38 -0
  45. package/src/plugins/registry.ts +377 -0
  46. package/src/plugins/types.ts +363 -0
  47. package/src/runtime/security.ts +155 -0
  48. package/src/runtime/server.ts +318 -256
  49. package/src/runtime/session-key.ts +328 -0
  50. package/src/utils/differ.test.ts +342 -0
  51. package/src/utils/differ.ts +482 -0
  52. package/src/utils/hasher.test.ts +326 -0
  53. package/src/utils/hasher.ts +319 -0
  54. package/src/utils/index.ts +29 -0
  55. package/src/utils/safe-io.ts +188 -0
  56. package/src/utils/string-safe.ts +298 -0
@@ -0,0 +1,363 @@
1
+ /**
2
+ * DNA-001: Plugin Adapter Pattern - Core Types
3
+ *
4
+ * 플러그인 시스템의 핵심 인터페이스 정의
5
+ * - 타입 안전한 플러그인 등록
6
+ * - 설정 스키마 검증
7
+ * - 라이프사이클 훅
8
+ */
9
+
10
+ import type { z, ZodSchema } from "zod";
11
+
12
+ /**
13
+ * 플러그인 카테고리
14
+ */
15
+ export type PluginCategory =
16
+ | "guard-preset" // Guard 아키텍처 프리셋
17
+ | "build" // 빌드 플러그인 (analyzer, minifier)
18
+ | "logger" // 로깅 전송
19
+ | "mcp-tool" // MCP 도구 확장
20
+ | "middleware" // 글로벌 미들웨어
21
+ | "custom"; // 사용자 정의
22
+
23
+ /**
24
+ * 플러그인 메타데이터
25
+ */
26
+ export interface PluginMeta {
27
+ /** 고유 ID (예: "guard-preset-fsd", "build-analyzer") */
28
+ id: string;
29
+
30
+ /** 표시 이름 */
31
+ name: string;
32
+
33
+ /** 설명 */
34
+ description?: string;
35
+
36
+ /** 버전 (semver) */
37
+ version: string;
38
+
39
+ /** 카테고리 */
40
+ category: PluginCategory;
41
+
42
+ /** 작성자 */
43
+ author?: string;
44
+
45
+ /** 저장소 URL */
46
+ repository?: string;
47
+
48
+ /** 태그 (검색용) */
49
+ tags?: string[];
50
+ }
51
+
52
+ /**
53
+ * 플러그인 API - 플러그인이 프레임워크와 상호작용하는 인터페이스
54
+ */
55
+ export interface PluginApi {
56
+ /**
57
+ * Guard 프리셋 등록
58
+ */
59
+ registerGuardPreset: (preset: GuardPresetPlugin) => void;
60
+
61
+ /**
62
+ * 빌드 플러그인 등록
63
+ */
64
+ registerBuildPlugin: (plugin: BuildPlugin) => void;
65
+
66
+ /**
67
+ * 로거 전송 등록
68
+ */
69
+ registerLoggerTransport: (transport: LoggerTransportPlugin) => void;
70
+
71
+ /**
72
+ * MCP 도구 등록
73
+ */
74
+ registerMcpTool: (tool: McpToolPlugin) => void;
75
+
76
+ /**
77
+ * 미들웨어 등록
78
+ */
79
+ registerMiddleware: (middleware: MiddlewarePlugin) => void;
80
+
81
+ /**
82
+ * 설정 가져오기
83
+ */
84
+ getConfig: <T>(key: string) => T | undefined;
85
+
86
+ /**
87
+ * 로거
88
+ */
89
+ logger: {
90
+ debug: (msg: string, data?: unknown) => void;
91
+ info: (msg: string, data?: unknown) => void;
92
+ warn: (msg: string, data?: unknown) => void;
93
+ error: (msg: string, data?: unknown) => void;
94
+ };
95
+ }
96
+
97
+ /**
98
+ * 플러그인 라이프사이클 훅
99
+ */
100
+ export interface PluginHooks {
101
+ /**
102
+ * 플러그인 로드 시 (설정 검증 후)
103
+ */
104
+ onLoad?: () => void | Promise<void>;
105
+
106
+ /**
107
+ * 플러그인 언로드 시
108
+ */
109
+ onUnload?: () => void | Promise<void>;
110
+
111
+ /**
112
+ * 서버 시작 시
113
+ */
114
+ onServerStart?: () => void | Promise<void>;
115
+
116
+ /**
117
+ * 서버 종료 시
118
+ */
119
+ onServerStop?: () => void | Promise<void>;
120
+ }
121
+
122
+ /**
123
+ * 기본 플러그인 인터페이스
124
+ */
125
+ export interface Plugin<TConfig = unknown> extends PluginHooks {
126
+ /** 플러그인 메타데이터 */
127
+ meta: PluginMeta;
128
+
129
+ /** 설정 스키마 (Zod) */
130
+ configSchema?: ZodSchema<TConfig>;
131
+
132
+ /**
133
+ * 플러그인 등록 함수
134
+ * @param api - 플러그인 API
135
+ * @param config - 검증된 설정
136
+ */
137
+ register: (api: PluginApi, config: TConfig) => void | Promise<void>;
138
+ }
139
+
140
+ // ============================================================================
141
+ // 카테고리별 플러그인 타입
142
+ // ============================================================================
143
+
144
+ /**
145
+ * Guard 프리셋 플러그인
146
+ */
147
+ export interface GuardPresetPlugin {
148
+ /** 프리셋 ID (예: "fsd", "clean", "hexagonal") */
149
+ id: string;
150
+
151
+ /** 표시 이름 */
152
+ name: string;
153
+
154
+ /** 설명 */
155
+ description?: string;
156
+
157
+ /**
158
+ * 프리셋 규칙 정의
159
+ * @returns 규칙 배열
160
+ */
161
+ getRules: () => GuardRule[];
162
+
163
+ /**
164
+ * 레이어 정의 (있는 경우)
165
+ */
166
+ getLayers?: () => LayerDefinition[];
167
+ }
168
+
169
+ /**
170
+ * Guard 규칙
171
+ */
172
+ export interface GuardRule {
173
+ id: string;
174
+ name: string;
175
+ description?: string;
176
+ severity: "error" | "warn" | "off";
177
+ check: (context: GuardRuleContext) => GuardViolation[];
178
+ }
179
+
180
+ /**
181
+ * Guard 규칙 실행 컨텍스트
182
+ */
183
+ export interface GuardRuleContext {
184
+ filePath: string;
185
+ sourceCode: string;
186
+ imports: ImportInfo[];
187
+ exports: ExportInfo[];
188
+ projectRoot: string;
189
+ }
190
+
191
+ /**
192
+ * Import 정보
193
+ */
194
+ export interface ImportInfo {
195
+ source: string;
196
+ specifiers: string[];
197
+ isTypeOnly: boolean;
198
+ line: number;
199
+ }
200
+
201
+ /**
202
+ * Export 정보
203
+ */
204
+ export interface ExportInfo {
205
+ name: string;
206
+ isDefault: boolean;
207
+ isTypeOnly: boolean;
208
+ line: number;
209
+ }
210
+
211
+ /**
212
+ * Guard 위반
213
+ */
214
+ export interface GuardViolation {
215
+ ruleId: string;
216
+ message: string;
217
+ severity: "error" | "warn";
218
+ filePath: string;
219
+ line?: number;
220
+ column?: number;
221
+ fix?: {
222
+ description: string;
223
+ replacement?: string;
224
+ };
225
+ }
226
+
227
+ /**
228
+ * 레이어 정의
229
+ */
230
+ export interface LayerDefinition {
231
+ name: string;
232
+ pattern: string | RegExp;
233
+ allowedDependencies: string[];
234
+ }
235
+
236
+ /**
237
+ * 빌드 플러그인
238
+ */
239
+ export interface BuildPlugin {
240
+ /** 플러그인 ID */
241
+ id: string;
242
+
243
+ /** 표시 이름 */
244
+ name: string;
245
+
246
+ /**
247
+ * 빌드 전 훅
248
+ */
249
+ onBuildStart?: (context: BuildContext) => void | Promise<void>;
250
+
251
+ /**
252
+ * 번들 처리
253
+ */
254
+ transform?: (code: string, id: string) => string | null | Promise<string | null>;
255
+
256
+ /**
257
+ * 빌드 후 훅
258
+ */
259
+ onBuildEnd?: (context: BuildContext, result: BuildResult) => void | Promise<void>;
260
+ }
261
+
262
+ /**
263
+ * 빌드 컨텍스트
264
+ */
265
+ export interface BuildContext {
266
+ outDir: string;
267
+ minify: boolean;
268
+ sourcemap: boolean;
269
+ mode: "development" | "production";
270
+ }
271
+
272
+ /**
273
+ * 빌드 결과
274
+ */
275
+ export interface BuildResult {
276
+ success: boolean;
277
+ outputFiles: string[];
278
+ errors?: string[];
279
+ stats?: {
280
+ duration: number;
281
+ totalSize: number;
282
+ };
283
+ }
284
+
285
+ /**
286
+ * 로거 전송 플러그인
287
+ */
288
+ export interface LoggerTransportPlugin {
289
+ /** 전송 ID */
290
+ id: string;
291
+
292
+ /** 표시 이름 */
293
+ name: string;
294
+
295
+ /**
296
+ * 로그 전송
297
+ */
298
+ send: (entry: LogEntry) => void | Promise<void>;
299
+
300
+ /**
301
+ * 배치 전송 (옵션)
302
+ */
303
+ sendBatch?: (entries: LogEntry[]) => void | Promise<void>;
304
+
305
+ /**
306
+ * 종료 시 플러시
307
+ */
308
+ flush?: () => void | Promise<void>;
309
+ }
310
+
311
+ /**
312
+ * 로그 항목
313
+ */
314
+ export interface LogEntry {
315
+ level: "debug" | "info" | "warn" | "error";
316
+ message: string;
317
+ timestamp: Date;
318
+ data?: unknown;
319
+ context?: Record<string, unknown>;
320
+ }
321
+
322
+ /**
323
+ * MCP 도구 플러그인
324
+ */
325
+ export interface McpToolPlugin {
326
+ /** 도구 이름 */
327
+ name: string;
328
+
329
+ /** 설명 */
330
+ description: string;
331
+
332
+ /**
333
+ * 입력 스키마 (JSON Schema)
334
+ */
335
+ inputSchema: Record<string, unknown>;
336
+
337
+ /**
338
+ * 도구 실행
339
+ */
340
+ execute: (input: unknown) => unknown | Promise<unknown>;
341
+ }
342
+
343
+ /**
344
+ * 미들웨어 플러그인
345
+ */
346
+ export interface MiddlewarePlugin {
347
+ /** 미들웨어 ID */
348
+ id: string;
349
+
350
+ /** 표시 이름 */
351
+ name: string;
352
+
353
+ /** 실행 순서 (낮을수록 먼저) */
354
+ order?: number;
355
+
356
+ /**
357
+ * 미들웨어 함수
358
+ */
359
+ handler: (
360
+ request: Request,
361
+ next: () => Promise<Response>
362
+ ) => Response | Promise<Response>;
363
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Runtime Security
3
+ *
4
+ * 동적 import 및 경로 접근 보안 검증
5
+ */
6
+
7
+ import path from "path";
8
+ import type { Result } from "../error/result";
9
+ import { ok, err } from "../error/result";
10
+ import { SecurityError } from "../error/domains";
11
+
12
+ /**
13
+ * 허용된 import 경로 패턴
14
+ */
15
+ const ALLOWED_IMPORT_PATTERNS = [
16
+ /^app\//, // app/ 디렉토리 (FS Routes)
17
+ /^src\/client\//, // 클라이언트 코드
18
+ /^src\/server\//, // 서버 코드
19
+ /^src\/shared\//, // 공유 코드
20
+ /^spec\//, // Spec 디렉토리 (레거시)
21
+ ];
22
+
23
+ /**
24
+ * 허용된 파일 확장자
25
+ */
26
+ const ALLOWED_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs"];
27
+
28
+ /**
29
+ * 차단된 경로 패턴
30
+ */
31
+ const BLOCKED_PATTERNS = [
32
+ /node_modules/, // node_modules 직접 접근 차단
33
+ /\.env/, // 환경 변수 파일
34
+ /\.git/, // Git 디렉토리
35
+ /\.mandu\/.*\.json$/, // 설정 파일
36
+ ];
37
+
38
+ /**
39
+ * 동적 import 경로 검증
40
+ *
41
+ * @param rootDir 프로젝트 루트 디렉토리
42
+ * @param modulePath 상대 모듈 경로 (예: "app/layout.tsx")
43
+ * @returns 검증된 전체 경로 또는 에러
44
+ */
45
+ export function validateImportPath(
46
+ rootDir: string,
47
+ modulePath: string
48
+ ): Result<string> {
49
+ // 1. 경로 정규화
50
+ const normalized = path.posix.normalize(modulePath).replace(/\\/g, "/");
51
+
52
+ // 2. Path traversal 체크
53
+ if (normalized.includes("..")) {
54
+ return err(
55
+ new SecurityError(
56
+ "path_traversal",
57
+ `경로 탐색 공격 감지: ${modulePath}`,
58
+ modulePath
59
+ ).toManduError()
60
+ );
61
+ }
62
+
63
+ // 3. 차단된 패턴 체크
64
+ for (const pattern of BLOCKED_PATTERNS) {
65
+ if (pattern.test(normalized)) {
66
+ return err(
67
+ new SecurityError(
68
+ "import_violation",
69
+ `차단된 경로 접근: ${modulePath}`,
70
+ modulePath
71
+ ).toManduError()
72
+ );
73
+ }
74
+ }
75
+
76
+ // 4. 화이트리스트 검증
77
+ const isAllowed = ALLOWED_IMPORT_PATTERNS.some((pattern) =>
78
+ pattern.test(normalized)
79
+ );
80
+
81
+ if (!isAllowed) {
82
+ return err(
83
+ new SecurityError(
84
+ "import_violation",
85
+ `허용되지 않은 import 경로: ${modulePath}. 허용된 경로: app/, src/client/, src/server/, src/shared/, spec/`,
86
+ modulePath
87
+ ).toManduError()
88
+ );
89
+ }
90
+
91
+ // 5. 확장자 검증 (있는 경우만)
92
+ const ext = path.extname(normalized);
93
+ if (ext && !ALLOWED_EXTENSIONS.includes(ext)) {
94
+ return err(
95
+ new SecurityError(
96
+ "import_violation",
97
+ `허용되지 않은 파일 확장자: ${ext}`,
98
+ modulePath
99
+ ).toManduError()
100
+ );
101
+ }
102
+
103
+ // 6. 전체 경로 생성
104
+ const fullPath = path.join(rootDir, normalized);
105
+
106
+ // 7. 최종 경로가 rootDir 내에 있는지 확인
107
+ const resolvedPath = path.resolve(fullPath);
108
+ const resolvedRoot = path.resolve(rootDir);
109
+
110
+ if (!resolvedPath.startsWith(resolvedRoot + path.sep)) {
111
+ return err(
112
+ new SecurityError(
113
+ "path_traversal",
114
+ `루트 디렉토리 외부 접근 시도: ${modulePath}`,
115
+ modulePath
116
+ ).toManduError()
117
+ );
118
+ }
119
+
120
+ return ok(fullPath);
121
+ }
122
+
123
+ /**
124
+ * 안전한 동적 import
125
+ *
126
+ * @param rootDir 프로젝트 루트 디렉토리
127
+ * @param modulePath 상대 모듈 경로
128
+ * @returns 로드된 모듈 또는 null
129
+ */
130
+ export async function safeImport<T = unknown>(
131
+ rootDir: string,
132
+ modulePath: string
133
+ ): Promise<T | null> {
134
+ const validation = validateImportPath(rootDir, modulePath);
135
+
136
+ if (!validation.ok) {
137
+ console.error(`[Mandu Security] ${validation.error.message}`);
138
+ return null;
139
+ }
140
+
141
+ try {
142
+ const module = await import(validation.value);
143
+ return module as T;
144
+ } catch (error) {
145
+ console.error(`[Mandu] Failed to import: ${modulePath}`, error);
146
+ return null;
147
+ }
148
+ }
149
+
150
+ /**
151
+ * 모듈 경로 검증 (boolean 반환)
152
+ */
153
+ export function isValidImportPath(rootDir: string, modulePath: string): boolean {
154
+ return validateImportPath(rootDir, modulePath).ok;
155
+ }