@mandujs/mcp 0.13.0 → 0.17.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/README.md +102 -7
- package/package.json +3 -2
- package/src/adapters/index.ts +20 -20
- package/src/adapters/monitor-adapter.ts +100 -100
- package/src/adapters/tool-adapter.ts +88 -88
- package/src/executor/error-handler.ts +250 -250
- package/src/executor/index.ts +22 -22
- package/src/executor/tool-executor.ts +148 -148
- package/src/hooks/config-watcher.ts +174 -174
- package/src/hooks/index.ts +23 -23
- package/src/hooks/mcp-hooks.ts +227 -227
- package/src/logging/index.ts +15 -15
- package/src/logging/mcp-transport.ts +134 -134
- package/src/registry/index.ts +13 -13
- package/src/registry/mcp-tool-registry.ts +298 -298
- package/src/resources/skills/guides.ts +1136 -1136
- package/src/resources/skills/index.ts +12 -12
- package/src/resources/skills/loader.ts +218 -218
- package/src/resources/skills/mandu-composition/SKILL.md +91 -91
- package/src/resources/skills/mandu-composition/metadata.json +13 -13
- package/src/resources/skills/mandu-composition/rules/_sections.md +26 -26
- package/src/resources/skills/mandu-composition/rules/_template.md +77 -77
- package/src/resources/skills/mandu-composition/rules/comp-arch-avoid-boolean-props.md +146 -146
- package/src/resources/skills/mandu-composition/rules/comp-arch-compound-components.md +164 -164
- package/src/resources/skills/mandu-composition/rules/comp-island-event.md +161 -161
- package/src/resources/skills/mandu-composition/rules/comp-island-slot-split.md +167 -167
- package/src/resources/skills/mandu-composition/rules/comp-pattern-children.md +149 -149
- package/src/resources/skills/mandu-composition/rules/comp-state-context-interface.md +148 -148
- package/src/resources/skills/mandu-composition/rules/comp-state-lift-state.md +150 -150
- package/src/resources/skills/mandu-deployment/SKILL.md +92 -92
- package/src/resources/skills/mandu-deployment/_sections.md +41 -41
- package/src/resources/skills/mandu-deployment/_template.md +38 -38
- package/src/resources/skills/mandu-deployment/metadata.json +13 -13
- package/src/resources/skills/mandu-deployment/rules/deploy-build-bun.md +109 -109
- package/src/resources/skills/mandu-deployment/rules/deploy-build-output.md +115 -115
- package/src/resources/skills/mandu-deployment/rules/deploy-cicd-github.md +219 -219
- package/src/resources/skills/mandu-deployment/rules/deploy-docker-bun.md +150 -150
- package/src/resources/skills/mandu-deployment/rules/deploy-docker-compose.md +223 -223
- package/src/resources/skills/mandu-deployment/rules/deploy-platform-fly.md +152 -152
- package/src/resources/skills/mandu-deployment/rules/deploy-platform-render.md +179 -179
- package/src/resources/skills/mandu-deployment/rules/deploy-platform-supabase.md +323 -323
- package/src/resources/skills/mandu-deployment/rules/deploy-platform-vercel.md +140 -140
- package/src/resources/skills/mandu-fs-routes/SKILL.md +82 -82
- package/src/resources/skills/mandu-fs-routes/metadata.json +12 -12
- package/src/resources/skills/mandu-fs-routes/rules/_sections.md +36 -36
- package/src/resources/skills/mandu-fs-routes/rules/_template.md +69 -69
- package/src/resources/skills/mandu-fs-routes/rules/routes-api-methods.md +65 -65
- package/src/resources/skills/mandu-fs-routes/rules/routes-dynamic-param.md +93 -93
- package/src/resources/skills/mandu-fs-routes/rules/routes-naming-page.md +55 -55
- package/src/resources/skills/mandu-guard/SKILL.md +129 -129
- package/src/resources/skills/mandu-guard/metadata.json +12 -12
- package/src/resources/skills/mandu-guard/rules/_sections.md +36 -36
- package/src/resources/skills/mandu-guard/rules/_template.md +82 -82
- package/src/resources/skills/mandu-guard/rules/guard-config-rules.md +100 -100
- package/src/resources/skills/mandu-guard/rules/guard-layer-direction.md +76 -76
- package/src/resources/skills/mandu-guard/rules/guard-preset-mandu.md +81 -81
- package/src/resources/skills/mandu-guard/rules/guard-validate-import.md +80 -80
- package/src/resources/skills/mandu-hydration/SKILL.md +91 -91
- package/src/resources/skills/mandu-hydration/metadata.json +12 -12
- package/src/resources/skills/mandu-hydration/rules/_sections.md +31 -31
- package/src/resources/skills/mandu-hydration/rules/_template.md +72 -72
- package/src/resources/skills/mandu-hydration/rules/hydration-data-event.md +109 -109
- package/src/resources/skills/mandu-hydration/rules/hydration-directive-use-client.md +55 -55
- package/src/resources/skills/mandu-hydration/rules/hydration-island-setup.md +113 -113
- package/src/resources/skills/mandu-hydration/rules/hydration-priority-visible.md +68 -68
- package/src/resources/skills/mandu-performance/SKILL.md +85 -85
- package/src/resources/skills/mandu-performance/metadata.json +14 -14
- package/src/resources/skills/mandu-performance/rules/_sections.md +31 -31
- package/src/resources/skills/mandu-performance/rules/_template.md +64 -64
- package/src/resources/skills/mandu-performance/rules/perf-async-defer-await.md +103 -103
- package/src/resources/skills/mandu-performance/rules/perf-async-parallel.md +95 -95
- package/src/resources/skills/mandu-performance/rules/perf-bun-file.md +124 -124
- package/src/resources/skills/mandu-performance/rules/perf-bun-serve.md +125 -125
- package/src/resources/skills/mandu-performance/rules/perf-bundle-imports.md +80 -80
- package/src/resources/skills/mandu-performance/rules/perf-bundle-island-lazy.md +145 -145
- package/src/resources/skills/mandu-performance/rules/perf-cache-react.md +98 -98
- package/src/resources/skills/mandu-performance/rules/perf-render-transitions.md +154 -154
- package/src/resources/skills/mandu-security/SKILL.md +87 -87
- package/src/resources/skills/mandu-security/metadata.json +13 -13
- package/src/resources/skills/mandu-security/rules/_sections.md +31 -31
- package/src/resources/skills/mandu-security/rules/_template.md +74 -74
- package/src/resources/skills/mandu-security/rules/sec-auth-guard.md +127 -127
- package/src/resources/skills/mandu-security/rules/sec-env-management.md +133 -133
- package/src/resources/skills/mandu-security/rules/sec-input-validate.md +148 -148
- package/src/resources/skills/mandu-security/rules/sec-protect-csrf.md +146 -146
- package/src/resources/skills/mandu-security/rules/sec-protect-headers.md +138 -138
- package/src/resources/skills/mandu-slot/SKILL.md +85 -85
- package/src/resources/skills/mandu-slot/metadata.json +12 -12
- package/src/resources/skills/mandu-slot/rules/_sections.md +36 -36
- package/src/resources/skills/mandu-slot/rules/_template.md +63 -63
- package/src/resources/skills/mandu-slot/rules/slot-basic-structure.md +38 -38
- package/src/resources/skills/mandu-slot/rules/slot-ctx-response.md +56 -56
- package/src/resources/skills/mandu-slot/rules/slot-guard-auth.md +59 -59
- package/src/resources/skills/mandu-slot/rules/slot-http-methods.md +64 -64
- package/src/resources/skills/mandu-styling/SKILL.md +154 -154
- package/src/resources/skills/mandu-styling/_sections.md +43 -43
- package/src/resources/skills/mandu-styling/_template.md +32 -32
- package/src/resources/skills/mandu-styling/metadata.json +15 -15
- package/src/resources/skills/mandu-styling/rules/style-component-compound.md +235 -235
- package/src/resources/skills/mandu-styling/rules/style-component-slots.md +255 -255
- package/src/resources/skills/mandu-styling/rules/style-component-tokens.md +205 -205
- package/src/resources/skills/mandu-styling/rules/style-island-animations.md +272 -272
- package/src/resources/skills/mandu-styling/rules/style-island-scoping.md +167 -167
- package/src/resources/skills/mandu-styling/rules/style-island-variants.md +221 -221
- package/src/resources/skills/mandu-styling/rules/style-perf-critical.md +209 -209
- package/src/resources/skills/mandu-styling/rules/style-perf-purge.md +192 -192
- package/src/resources/skills/mandu-styling/rules/style-setup-modules.md +162 -162
- package/src/resources/skills/mandu-styling/rules/style-setup-panda.md +164 -164
- package/src/resources/skills/mandu-styling/rules/style-setup-tailwind.md +170 -170
- package/src/resources/skills/mandu-styling/rules/style-tailwind-v4-gotchas.md +179 -179
- package/src/resources/skills/mandu-styling/rules/style-theme-darkmode.md +229 -229
- package/src/resources/skills/mandu-testing/SKILL.md +99 -99
- package/src/resources/skills/mandu-testing/metadata.json +13 -13
- package/src/resources/skills/mandu-testing/rules/_sections.md +26 -26
- package/src/resources/skills/mandu-testing/rules/_template.md +65 -65
- package/src/resources/skills/mandu-testing/rules/test-component-island.md +195 -195
- package/src/resources/skills/mandu-testing/rules/test-e2e-playwright.md +196 -196
- package/src/resources/skills/mandu-testing/rules/test-mock-fetch.md +219 -219
- package/src/resources/skills/mandu-testing/rules/test-slot-unit.md +192 -192
- package/src/resources/skills/mandu-ui/SKILL.md +117 -117
- package/src/resources/skills/mandu-ui/_sections.md +23 -23
- package/src/resources/skills/mandu-ui/_template.md +32 -32
- package/src/resources/skills/mandu-ui/metadata.json +13 -13
- package/src/resources/skills/mandu-ui/rules/ui-accessibility-aria.md +232 -232
- package/src/resources/skills/mandu-ui/rules/ui-accessibility-focus.md +238 -238
- package/src/resources/skills/mandu-ui/rules/ui-composition-patterns.md +259 -259
- package/src/resources/skills/mandu-ui/rules/ui-island-integration.md +258 -258
- package/src/resources/skills/mandu-ui/rules/ui-radix-patterns.md +213 -213
- package/src/resources/skills/mandu-ui/rules/ui-shadcn-setup.md +209 -209
- package/src/resources/skills/recipes.ts +932 -932
- package/src/tools/ate.ts +219 -0
- package/src/tools/index.ts +4 -1
- package/src/tools/project.ts +334 -334
- package/src/tools/runtime.ts +497 -497
- package/src/tools/seo.ts +417 -417
- package/src/utils/withWarnings.ts +83 -83
|
@@ -1,148 +1,148 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Always Validate and Sanitize Input
|
|
3
|
-
impact: CRITICAL
|
|
4
|
-
impactDescription: Prevents injection attacks
|
|
5
|
-
tags: security, input, validation, sanitize
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Always Validate and Sanitize Input
|
|
9
|
-
|
|
10
|
-
**Impact: CRITICAL (Prevents injection attacks)**
|
|
11
|
-
|
|
12
|
-
모든 사용자 입력을 서버에서 검증하고 살균하세요. 클라이언트 검증은 우회될 수 있습니다.
|
|
13
|
-
|
|
14
|
-
**Vulnerable (검증 없음):**
|
|
15
|
-
|
|
16
|
-
```typescript
|
|
17
|
-
// ❌ 입력 검증 없이 직접 사용
|
|
18
|
-
export default Mandu.filling()
|
|
19
|
-
.post(async (ctx) => {
|
|
20
|
-
const body = await ctx.body();
|
|
21
|
-
|
|
22
|
-
// SQL Injection 취약
|
|
23
|
-
const user = await db.$queryRaw`
|
|
24
|
-
SELECT * FROM users WHERE email = '${body.email}'
|
|
25
|
-
`;
|
|
26
|
-
|
|
27
|
-
return ctx.ok({ user });
|
|
28
|
-
});
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
**Secure (Zod로 검증):**
|
|
32
|
-
|
|
33
|
-
```typescript
|
|
34
|
-
import { z } from "zod";
|
|
35
|
-
|
|
36
|
-
// ✅ 스키마 정의
|
|
37
|
-
const createUserSchema = z.object({
|
|
38
|
-
email: z.string().email().max(255),
|
|
39
|
-
name: z.string().min(1).max(100),
|
|
40
|
-
age: z.number().int().min(0).max(150).optional(),
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
export default Mandu.filling()
|
|
44
|
-
.post(async (ctx) => {
|
|
45
|
-
const body = await ctx.body();
|
|
46
|
-
|
|
47
|
-
// 스키마로 검증
|
|
48
|
-
const result = createUserSchema.safeParse(body);
|
|
49
|
-
|
|
50
|
-
if (!result.success) {
|
|
51
|
-
return ctx.error({
|
|
52
|
-
message: "Validation failed",
|
|
53
|
-
errors: result.error.flatten(),
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// 검증된 데이터 사용 (Parameterized query)
|
|
58
|
-
const user = await db.user.create({
|
|
59
|
-
data: result.data,
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
return ctx.created({ user });
|
|
63
|
-
});
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
## 입력 유형별 검증
|
|
67
|
-
|
|
68
|
-
```typescript
|
|
69
|
-
const schema = z.object({
|
|
70
|
-
// 문자열
|
|
71
|
-
username: z.string()
|
|
72
|
-
.min(3)
|
|
73
|
-
.max(20)
|
|
74
|
-
.regex(/^[a-zA-Z0-9_]+$/), // 알파벳, 숫자, 언더스코어만
|
|
75
|
-
|
|
76
|
-
// 이메일
|
|
77
|
-
email: z.string().email(),
|
|
78
|
-
|
|
79
|
-
// URL
|
|
80
|
-
website: z.string().url().optional(),
|
|
81
|
-
|
|
82
|
-
// 숫자
|
|
83
|
-
age: z.number().int().positive().max(150),
|
|
84
|
-
|
|
85
|
-
// Enum
|
|
86
|
-
role: z.enum(["user", "admin", "moderator"]),
|
|
87
|
-
|
|
88
|
-
// 배열
|
|
89
|
-
tags: z.array(z.string().max(50)).max(10),
|
|
90
|
-
|
|
91
|
-
// 중첩 객체
|
|
92
|
-
address: z.object({
|
|
93
|
-
street: z.string().max(200),
|
|
94
|
-
city: z.string().max(100),
|
|
95
|
-
}).optional(),
|
|
96
|
-
});
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## 파일 업로드 검증
|
|
100
|
-
|
|
101
|
-
```typescript
|
|
102
|
-
export default Mandu.filling()
|
|
103
|
-
.post(async (ctx) => {
|
|
104
|
-
const formData = await ctx.req.formData();
|
|
105
|
-
const file = formData.get("file") as File;
|
|
106
|
-
|
|
107
|
-
// 파일 존재 확인
|
|
108
|
-
if (!file) {
|
|
109
|
-
return ctx.error("File is required");
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// 파일 크기 제한 (5MB)
|
|
113
|
-
if (file.size > 5 * 1024 * 1024) {
|
|
114
|
-
return ctx.error("File too large (max 5MB)");
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// 파일 타입 확인
|
|
118
|
-
const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
|
|
119
|
-
if (!allowedTypes.includes(file.type)) {
|
|
120
|
-
return ctx.error("Invalid file type");
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// 파일 확장자 확인 (MIME 스푸핑 방지)
|
|
124
|
-
const ext = file.name.split(".").pop()?.toLowerCase();
|
|
125
|
-
if (!["jpg", "jpeg", "png", "webp"].includes(ext || "")) {
|
|
126
|
-
return ctx.error("Invalid file extension");
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// 안전하게 처리
|
|
130
|
-
const buffer = await file.arrayBuffer();
|
|
131
|
-
// ... 저장 로직
|
|
132
|
-
});
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
## XSS 방지를 위한 출력 이스케이프
|
|
136
|
-
|
|
137
|
-
```typescript
|
|
138
|
-
import { escapeHtml } from "@/lib/security";
|
|
139
|
-
|
|
140
|
-
// HTML 컨텍스트에서 사용될 데이터
|
|
141
|
-
const safeContent = escapeHtml(userInput);
|
|
142
|
-
|
|
143
|
-
// 또는 라이브러리 사용
|
|
144
|
-
import DOMPurify from "isomorphic-dompurify";
|
|
145
|
-
const sanitized = DOMPurify.sanitize(userHtml);
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
Reference: [OWASP Input Validation](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)
|
|
1
|
+
---
|
|
2
|
+
title: Always Validate and Sanitize Input
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: Prevents injection attacks
|
|
5
|
+
tags: security, input, validation, sanitize
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Always Validate and Sanitize Input
|
|
9
|
+
|
|
10
|
+
**Impact: CRITICAL (Prevents injection attacks)**
|
|
11
|
+
|
|
12
|
+
모든 사용자 입력을 서버에서 검증하고 살균하세요. 클라이언트 검증은 우회될 수 있습니다.
|
|
13
|
+
|
|
14
|
+
**Vulnerable (검증 없음):**
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
// ❌ 입력 검증 없이 직접 사용
|
|
18
|
+
export default Mandu.filling()
|
|
19
|
+
.post(async (ctx) => {
|
|
20
|
+
const body = await ctx.body();
|
|
21
|
+
|
|
22
|
+
// SQL Injection 취약
|
|
23
|
+
const user = await db.$queryRaw`
|
|
24
|
+
SELECT * FROM users WHERE email = '${body.email}'
|
|
25
|
+
`;
|
|
26
|
+
|
|
27
|
+
return ctx.ok({ user });
|
|
28
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**Secure (Zod로 검증):**
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { z } from "zod";
|
|
35
|
+
|
|
36
|
+
// ✅ 스키마 정의
|
|
37
|
+
const createUserSchema = z.object({
|
|
38
|
+
email: z.string().email().max(255),
|
|
39
|
+
name: z.string().min(1).max(100),
|
|
40
|
+
age: z.number().int().min(0).max(150).optional(),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export default Mandu.filling()
|
|
44
|
+
.post(async (ctx) => {
|
|
45
|
+
const body = await ctx.body();
|
|
46
|
+
|
|
47
|
+
// 스키마로 검증
|
|
48
|
+
const result = createUserSchema.safeParse(body);
|
|
49
|
+
|
|
50
|
+
if (!result.success) {
|
|
51
|
+
return ctx.error({
|
|
52
|
+
message: "Validation failed",
|
|
53
|
+
errors: result.error.flatten(),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 검증된 데이터 사용 (Parameterized query)
|
|
58
|
+
const user = await db.user.create({
|
|
59
|
+
data: result.data,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
return ctx.created({ user });
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## 입력 유형별 검증
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
const schema = z.object({
|
|
70
|
+
// 문자열
|
|
71
|
+
username: z.string()
|
|
72
|
+
.min(3)
|
|
73
|
+
.max(20)
|
|
74
|
+
.regex(/^[a-zA-Z0-9_]+$/), // 알파벳, 숫자, 언더스코어만
|
|
75
|
+
|
|
76
|
+
// 이메일
|
|
77
|
+
email: z.string().email(),
|
|
78
|
+
|
|
79
|
+
// URL
|
|
80
|
+
website: z.string().url().optional(),
|
|
81
|
+
|
|
82
|
+
// 숫자
|
|
83
|
+
age: z.number().int().positive().max(150),
|
|
84
|
+
|
|
85
|
+
// Enum
|
|
86
|
+
role: z.enum(["user", "admin", "moderator"]),
|
|
87
|
+
|
|
88
|
+
// 배열
|
|
89
|
+
tags: z.array(z.string().max(50)).max(10),
|
|
90
|
+
|
|
91
|
+
// 중첩 객체
|
|
92
|
+
address: z.object({
|
|
93
|
+
street: z.string().max(200),
|
|
94
|
+
city: z.string().max(100),
|
|
95
|
+
}).optional(),
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## 파일 업로드 검증
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
export default Mandu.filling()
|
|
103
|
+
.post(async (ctx) => {
|
|
104
|
+
const formData = await ctx.req.formData();
|
|
105
|
+
const file = formData.get("file") as File;
|
|
106
|
+
|
|
107
|
+
// 파일 존재 확인
|
|
108
|
+
if (!file) {
|
|
109
|
+
return ctx.error("File is required");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 파일 크기 제한 (5MB)
|
|
113
|
+
if (file.size > 5 * 1024 * 1024) {
|
|
114
|
+
return ctx.error("File too large (max 5MB)");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 파일 타입 확인
|
|
118
|
+
const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
|
|
119
|
+
if (!allowedTypes.includes(file.type)) {
|
|
120
|
+
return ctx.error("Invalid file type");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 파일 확장자 확인 (MIME 스푸핑 방지)
|
|
124
|
+
const ext = file.name.split(".").pop()?.toLowerCase();
|
|
125
|
+
if (!["jpg", "jpeg", "png", "webp"].includes(ext || "")) {
|
|
126
|
+
return ctx.error("Invalid file extension");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 안전하게 처리
|
|
130
|
+
const buffer = await file.arrayBuffer();
|
|
131
|
+
// ... 저장 로직
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## XSS 방지를 위한 출력 이스케이프
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
import { escapeHtml } from "@/lib/security";
|
|
139
|
+
|
|
140
|
+
// HTML 컨텍스트에서 사용될 데이터
|
|
141
|
+
const safeContent = escapeHtml(userInput);
|
|
142
|
+
|
|
143
|
+
// 또는 라이브러리 사용
|
|
144
|
+
import DOMPurify from "isomorphic-dompurify";
|
|
145
|
+
const sanitized = DOMPurify.sanitize(userHtml);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Reference: [OWASP Input Validation](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)
|
|
@@ -1,146 +1,146 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Implement CSRF Protection
|
|
3
|
-
impact: HIGH
|
|
4
|
-
impactDescription: Prevents cross-site request forgery
|
|
5
|
-
tags: security, csrf, protection, token
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Implement CSRF Protection
|
|
9
|
-
|
|
10
|
-
**Impact: HIGH (Prevents cross-site request forgery)**
|
|
11
|
-
|
|
12
|
-
상태를 변경하는 요청(POST, PUT, DELETE)에 CSRF 토큰을 적용하세요.
|
|
13
|
-
|
|
14
|
-
**Vulnerable (CSRF 보호 없음):**
|
|
15
|
-
|
|
16
|
-
```typescript
|
|
17
|
-
// ❌ CSRF 토큰 없이 상태 변경
|
|
18
|
-
export default Mandu.filling()
|
|
19
|
-
.post(async (ctx) => {
|
|
20
|
-
// 악의적인 사이트에서 이 요청을 보낼 수 있음
|
|
21
|
-
await db.user.delete({
|
|
22
|
-
where: { id: ctx.get("user").id },
|
|
23
|
-
});
|
|
24
|
-
return ctx.ok({ message: "Account deleted" });
|
|
25
|
-
});
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
**Secure (CSRF 토큰 검증):**
|
|
29
|
-
|
|
30
|
-
```typescript
|
|
31
|
-
import { verifyCsrfToken } from "@/lib/csrf";
|
|
32
|
-
|
|
33
|
-
export default Mandu.filling()
|
|
34
|
-
.guard((ctx) => {
|
|
35
|
-
const user = ctx.get("user");
|
|
36
|
-
if (!user) return ctx.unauthorized();
|
|
37
|
-
|
|
38
|
-
// CSRF 토큰 검증
|
|
39
|
-
const token = ctx.headers.get("x-csrf-token");
|
|
40
|
-
if (!verifyCsrfToken(token, user.sessionId)) {
|
|
41
|
-
return ctx.forbidden("Invalid CSRF token");
|
|
42
|
-
}
|
|
43
|
-
})
|
|
44
|
-
.post(async (ctx) => {
|
|
45
|
-
await db.user.delete({
|
|
46
|
-
where: { id: ctx.get("user").id },
|
|
47
|
-
});
|
|
48
|
-
return ctx.ok({ message: "Account deleted" });
|
|
49
|
-
});
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
## CSRF 토큰 생성
|
|
53
|
-
|
|
54
|
-
```typescript
|
|
55
|
-
// lib/csrf.ts
|
|
56
|
-
import { createHmac, randomBytes } from "crypto";
|
|
57
|
-
|
|
58
|
-
const SECRET = process.env.CSRF_SECRET!;
|
|
59
|
-
|
|
60
|
-
export function generateCsrfToken(sessionId: string): string {
|
|
61
|
-
const timestamp = Date.now().toString();
|
|
62
|
-
const random = randomBytes(16).toString("hex");
|
|
63
|
-
const data = `${sessionId}:${timestamp}:${random}`;
|
|
64
|
-
|
|
65
|
-
const signature = createHmac("sha256", SECRET)
|
|
66
|
-
.update(data)
|
|
67
|
-
.digest("hex");
|
|
68
|
-
|
|
69
|
-
return `${data}:${signature}`;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export function verifyCsrfToken(token: string | null, sessionId: string): boolean {
|
|
73
|
-
if (!token) return false;
|
|
74
|
-
|
|
75
|
-
const parts = token.split(":");
|
|
76
|
-
if (parts.length !== 4) return false;
|
|
77
|
-
|
|
78
|
-
const [tokenSessionId, timestamp, random, signature] = parts;
|
|
79
|
-
|
|
80
|
-
// 세션 ID 확인
|
|
81
|
-
if (tokenSessionId !== sessionId) return false;
|
|
82
|
-
|
|
83
|
-
// 만료 확인 (1시간)
|
|
84
|
-
const tokenTime = parseInt(timestamp, 10);
|
|
85
|
-
if (Date.now() - tokenTime > 3600000) return false;
|
|
86
|
-
|
|
87
|
-
// 서명 확인
|
|
88
|
-
const data = `${tokenSessionId}:${timestamp}:${random}`;
|
|
89
|
-
const expectedSignature = createHmac("sha256", SECRET)
|
|
90
|
-
.update(data)
|
|
91
|
-
.digest("hex");
|
|
92
|
-
|
|
93
|
-
return signature === expectedSignature;
|
|
94
|
-
}
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
## 클라이언트에서 CSRF 토큰 전송
|
|
98
|
-
|
|
99
|
-
```tsx
|
|
100
|
-
// Island에서 CSRF 토큰 사용
|
|
101
|
-
"use client";
|
|
102
|
-
|
|
103
|
-
export function DeleteAccountButton({ csrfToken }: { csrfToken: string }) {
|
|
104
|
-
const handleDelete = async () => {
|
|
105
|
-
const res = await fetch("/api/account", {
|
|
106
|
-
method: "DELETE",
|
|
107
|
-
headers: {
|
|
108
|
-
"Content-Type": "application/json",
|
|
109
|
-
"X-CSRF-Token": csrfToken, // CSRF 토큰 포함
|
|
110
|
-
},
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
if (res.ok) {
|
|
114
|
-
window.location.href = "/goodbye";
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
return <button onClick={handleDelete}>Delete Account</button>;
|
|
119
|
-
}
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
## SameSite 쿠키와 함께 사용
|
|
123
|
-
|
|
124
|
-
```typescript
|
|
125
|
-
// 세션 쿠키 설정
|
|
126
|
-
ctx.cookie("session", sessionId, {
|
|
127
|
-
httpOnly: true,
|
|
128
|
-
secure: true,
|
|
129
|
-
sameSite: "lax", // 또는 "strict"
|
|
130
|
-
maxAge: 86400,
|
|
131
|
-
});
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
## 추가 방어 (Double Submit)
|
|
135
|
-
|
|
136
|
-
```typescript
|
|
137
|
-
// 쿠키와 헤더 모두에서 토큰 확인
|
|
138
|
-
const cookieToken = ctx.cookies.get("csrf");
|
|
139
|
-
const headerToken = ctx.headers.get("x-csrf-token");
|
|
140
|
-
|
|
141
|
-
if (!cookieToken || cookieToken !== headerToken) {
|
|
142
|
-
return ctx.forbidden("CSRF validation failed");
|
|
143
|
-
}
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
Reference: [OWASP CSRF Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
|
|
1
|
+
---
|
|
2
|
+
title: Implement CSRF Protection
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: Prevents cross-site request forgery
|
|
5
|
+
tags: security, csrf, protection, token
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Implement CSRF Protection
|
|
9
|
+
|
|
10
|
+
**Impact: HIGH (Prevents cross-site request forgery)**
|
|
11
|
+
|
|
12
|
+
상태를 변경하는 요청(POST, PUT, DELETE)에 CSRF 토큰을 적용하세요.
|
|
13
|
+
|
|
14
|
+
**Vulnerable (CSRF 보호 없음):**
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
// ❌ CSRF 토큰 없이 상태 변경
|
|
18
|
+
export default Mandu.filling()
|
|
19
|
+
.post(async (ctx) => {
|
|
20
|
+
// 악의적인 사이트에서 이 요청을 보낼 수 있음
|
|
21
|
+
await db.user.delete({
|
|
22
|
+
where: { id: ctx.get("user").id },
|
|
23
|
+
});
|
|
24
|
+
return ctx.ok({ message: "Account deleted" });
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**Secure (CSRF 토큰 검증):**
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { verifyCsrfToken } from "@/lib/csrf";
|
|
32
|
+
|
|
33
|
+
export default Mandu.filling()
|
|
34
|
+
.guard((ctx) => {
|
|
35
|
+
const user = ctx.get("user");
|
|
36
|
+
if (!user) return ctx.unauthorized();
|
|
37
|
+
|
|
38
|
+
// CSRF 토큰 검증
|
|
39
|
+
const token = ctx.headers.get("x-csrf-token");
|
|
40
|
+
if (!verifyCsrfToken(token, user.sessionId)) {
|
|
41
|
+
return ctx.forbidden("Invalid CSRF token");
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
.post(async (ctx) => {
|
|
45
|
+
await db.user.delete({
|
|
46
|
+
where: { id: ctx.get("user").id },
|
|
47
|
+
});
|
|
48
|
+
return ctx.ok({ message: "Account deleted" });
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## CSRF 토큰 생성
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// lib/csrf.ts
|
|
56
|
+
import { createHmac, randomBytes } from "crypto";
|
|
57
|
+
|
|
58
|
+
const SECRET = process.env.CSRF_SECRET!;
|
|
59
|
+
|
|
60
|
+
export function generateCsrfToken(sessionId: string): string {
|
|
61
|
+
const timestamp = Date.now().toString();
|
|
62
|
+
const random = randomBytes(16).toString("hex");
|
|
63
|
+
const data = `${sessionId}:${timestamp}:${random}`;
|
|
64
|
+
|
|
65
|
+
const signature = createHmac("sha256", SECRET)
|
|
66
|
+
.update(data)
|
|
67
|
+
.digest("hex");
|
|
68
|
+
|
|
69
|
+
return `${data}:${signature}`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function verifyCsrfToken(token: string | null, sessionId: string): boolean {
|
|
73
|
+
if (!token) return false;
|
|
74
|
+
|
|
75
|
+
const parts = token.split(":");
|
|
76
|
+
if (parts.length !== 4) return false;
|
|
77
|
+
|
|
78
|
+
const [tokenSessionId, timestamp, random, signature] = parts;
|
|
79
|
+
|
|
80
|
+
// 세션 ID 확인
|
|
81
|
+
if (tokenSessionId !== sessionId) return false;
|
|
82
|
+
|
|
83
|
+
// 만료 확인 (1시간)
|
|
84
|
+
const tokenTime = parseInt(timestamp, 10);
|
|
85
|
+
if (Date.now() - tokenTime > 3600000) return false;
|
|
86
|
+
|
|
87
|
+
// 서명 확인
|
|
88
|
+
const data = `${tokenSessionId}:${timestamp}:${random}`;
|
|
89
|
+
const expectedSignature = createHmac("sha256", SECRET)
|
|
90
|
+
.update(data)
|
|
91
|
+
.digest("hex");
|
|
92
|
+
|
|
93
|
+
return signature === expectedSignature;
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## 클라이언트에서 CSRF 토큰 전송
|
|
98
|
+
|
|
99
|
+
```tsx
|
|
100
|
+
// Island에서 CSRF 토큰 사용
|
|
101
|
+
"use client";
|
|
102
|
+
|
|
103
|
+
export function DeleteAccountButton({ csrfToken }: { csrfToken: string }) {
|
|
104
|
+
const handleDelete = async () => {
|
|
105
|
+
const res = await fetch("/api/account", {
|
|
106
|
+
method: "DELETE",
|
|
107
|
+
headers: {
|
|
108
|
+
"Content-Type": "application/json",
|
|
109
|
+
"X-CSRF-Token": csrfToken, // CSRF 토큰 포함
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (res.ok) {
|
|
114
|
+
window.location.href = "/goodbye";
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
return <button onClick={handleDelete}>Delete Account</button>;
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## SameSite 쿠키와 함께 사용
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
// 세션 쿠키 설정
|
|
126
|
+
ctx.cookie("session", sessionId, {
|
|
127
|
+
httpOnly: true,
|
|
128
|
+
secure: true,
|
|
129
|
+
sameSite: "lax", // 또는 "strict"
|
|
130
|
+
maxAge: 86400,
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## 추가 방어 (Double Submit)
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
// 쿠키와 헤더 모두에서 토큰 확인
|
|
138
|
+
const cookieToken = ctx.cookies.get("csrf");
|
|
139
|
+
const headerToken = ctx.headers.get("x-csrf-token");
|
|
140
|
+
|
|
141
|
+
if (!cookieToken || cookieToken !== headerToken) {
|
|
142
|
+
return ctx.forbidden("CSRF validation failed");
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Reference: [OWASP CSRF Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
|