1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
|
'use client';
import { useState, useEffect, useTransition } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Save, Eye, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import Link from 'next/link';
import { getTemplateAction, updateTemplateAction, previewTemplateAction, TemplateFile } from '@/lib/mail/service';
type Template = TemplateFile;
interface MailTemplateEditorClientProps {
templateName: string;
initialTemplate?: Template | null;
}
// 보안: 허용된 Handlebars 헬퍼와 변수만 정의
const ALLOWED_VARIABLES = [
'userName', 'companyName', 'email', 'date', 'projectName',
'message', 'currentYear', 'language', 'name', 'loginUrl'
];
const ALLOWED_HELPERS = ['if', 'unless', 'each', 'with'];
// 보안: 위험한 패턴 탐지
const DANGEROUS_PATTERNS = [
/\{\{\s*(constructor|prototype|__proto__|process|global|require|import|eval|Function)\s*\}\}/gi,
/\{\{\s*.*\.(constructor|prototype|__proto__)\s*.*\}\}/gi,
/\{\{\s*.*\[\s*['"`]constructor['"`]\s*\]\s*.*\}\}/gi,
/\{\{\s*.*require\s*\(.*\)\s*.*\}\}/gi,
/\{\{\s*.*process\s*\..*\}\}/gi,
/\{\{\s*.*global\s*\..*\}\}/gi,
/\{\{\s*.*this\s*\..*\}\}/gi,
/\{\{\s*#with\s+.*\.\.\s*\}\}/gi, // path traversal
];
// 보안: 템플릿 내용 검증
const validateTemplateContent = (content: string): { isValid: boolean; errors: string[] } => {
const errors: string[] = [];
// 위험한 패턴 검사
for (const pattern of DANGEROUS_PATTERNS) {
if (pattern.test(content)) {
errors.push('보안상 위험한 구문이 감지되었습니다.');
break;
}
}
// 허용되지 않은 변수 검사
const variableMatches = content.match(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g);
if (variableMatches) {
for (const match of variableMatches) {
const variable = match.replace(/\{\{\s*|\s*\}\}/g, '');
if (!ALLOWED_VARIABLES.includes(variable)) {
errors.push(`허용되지 않은 변수 '${variable}'가 사용되었습니다.`);
}
}
}
// 허용되지 않은 헬퍼 검사
const helperMatches = content.match(/\{\{\s*#([a-zA-Z_][a-zA-Z0-9_]*)/g);
if (helperMatches) {
for (const match of helperMatches) {
const helper = match.replace(/\{\{\s*#/, '');
if (!ALLOWED_HELPERS.includes(helper)) {
errors.push(`허용되지 않은 헬퍼 '${helper}'가 사용되었습니다.`);
}
}
}
return {
isValid: errors.length === 0,
errors
};
};
// 보안: HTML 출력 무력화 ({{{html}}} 형태 방지)
const sanitizeTripleBraces = (content: string): string => {
return content.replace(/\{\{\{([^}]+)\}\}\}/g, (match, variable) => {
// HTML 출력을 일반 변수 출력으로 변환
return `{{${variable.trim()}}}`;
});
};
export default function MailTemplateEditorClient({
templateName,
initialTemplate
}: MailTemplateEditorClientProps) {
const router = useRouter();
const params = useParams();
const lng = (params?.lng as string) || 'ko';
const [template, setTemplate] = useState<Template | null>(initialTemplate || null);
const [content, setContent] = useState(initialTemplate?.content || '');
const [loading, setLoading] = useState(!initialTemplate);
const [saving, setSaving] = useState(false);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewHtml, setPreviewHtml] = useState<string | null>(null);
const [validationErrors, setValidationErrors] = useState<string[]>([]);
const [, startTransition] = useTransition();
// 보안: 실시간 검증
useEffect(() => {
const validation = validateTemplateContent(content);
setValidationErrors(validation.errors);
}, [content]);
// 템플릿 조회
const fetchTemplate = async () => {
if (!templateName) {
toast.error('잘못된 접근입니다.');
router.push(`/${lng}/evcp/email-template`);
return;
}
try {
setLoading(true);
startTransition(async () => {
const result = await getTemplateAction(templateName);
if (result.success && result.data) {
setTemplate(result.data);
setContent(result.data.content);
} else {
toast.error(result.error || '템플릿을 찾을 수 없습니다.');
router.push(`/${lng}/evcp/email-template`);
}
setLoading(false);
});
} catch (error) {
console.error('Error fetching template:', error);
toast.error('템플릿을 불러오는데 실패했습니다.');
router.push(`/${lng}/evcp/email-template`);
setLoading(false);
}
};
// 템플릿 저장
const handleSave = async () => {
if (!content.trim()) {
toast.error('템플릿 내용을 입력해주세요.');
return;
}
// 보안: 저장 전 검증
const validation = validateTemplateContent(content);
if (!validation.isValid) {
toast.error('보안 검증에 실패했습니다. 오류를 확인해주세요.');
return;
}
try {
setSaving(true);
startTransition(async () => {
// 보안: HTML 출력 방지 처리
const sanitizedContent = sanitizeTripleBraces(content);
const result = await updateTemplateAction(templateName, sanitizedContent);
if (result.success && result.data) {
toast.success('템플릿이 성공적으로 저장되었습니다.');
setTemplate(result.data);
} else {
toast.error(result.error || '템플릿 저장에 실패했습니다.');
}
setSaving(false);
});
} catch (error) {
console.error('Error saving template:', error);
toast.error('템플릿 저장에 실패했습니다.');
setSaving(false);
}
};
// 미리보기 생성
const handlePreview = async () => {
// 보안: 미리보기 전 검증
const validation = validateTemplateContent(content);
if (!validation.isValid) {
toast.error('보안 검증에 실패했습니다. 오류를 확인해주세요.');
return;
}
try {
setPreviewLoading(true);
startTransition(async () => {
// 보안: HTML 출력 방지 처리
const sanitizedContent = sanitizeTripleBraces(content);
const result = await previewTemplateAction(
templateName,
{
userName: '홍길동',
companyName: 'EVCP',
email: 'user@example.com',
date: new Date().toLocaleDateString('ko-KR'),
projectName: '샘플 프로젝트',
message: '이것은 샘플 메시지입니다.',
currentYear: new Date().getFullYear(),
language: 'ko',
name: '홍길동',
loginUrl: 'https://example.com/login'
},
sanitizedContent // 보안: 검증된 내용만 전달
);
if (result.success && result.data) {
setPreviewHtml(result.data.html);
} else {
toast.error(result.error || '미리보기 생성에 실패했습니다.');
}
setPreviewLoading(false);
});
} catch (error) {
console.error('Error generating preview:', error);
toast.error('미리보기 생성에 실패했습니다.');
setPreviewLoading(false);
}
};
useEffect(() => {
if (!initialTemplate) {
fetchTemplate();
}
}, [templateName, initialTemplate]);
if (loading) {
return (
<div className="text-center py-20">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
<p className="mt-4 text-gray-600">템플릿을 불러오는 중...</p>
</div>
);
}
if (!template) {
return (
<div className="text-center py-20">
<p className="text-gray-600">템플릿을 찾을 수 없습니다.</p>
<Link href={`/${lng}/evcp/email-template`}>
<Button className="mt-4">목록으로 돌아가기</Button>
</Link>
</div>
);
}
const hasValidationErrors = validationErrors.length > 0;
return (
<div className="space-y-8">
{/* 헤더 */}
<div>
<div className="flex items-center gap-4 mb-4">
<h1 className="text-3xl font-bold text-gray-900">템플릿 편집</h1>
</div>
<div>
<p className="text-gray-600">
<span className="font-medium">{template.name}</span> 템플릿을 편집합니다.
</p>
<p className="text-sm text-gray-500">
마지막 수정: {new Date(template.lastModified).toLocaleString('ko-KR')}
</p>
</div>
</div>
{/* 보안 경고 */}
{hasValidationErrors && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="h-5 w-5 text-red-600 mt-0.5" />
<div>
<h3 className="font-semibold text-red-800">보안 검증 오류</h3>
<ul className="mt-2 text-sm text-red-700 space-y-1">
{validationErrors.map((error, index) => (
<li key={index}>• {error}</li>
))}
</ul>
</div>
</div>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* 편집 영역 */}
<div className="space-y-6">
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4">템플릿 내용</h2>
<div className="space-y-4">
<div>
<Label htmlFor="content">Handlebars 템플릿</Label>
<Textarea
id="content"
value={content}
onChange={(e) => setContent(e.target.value)}
className={`min-h-[500px] font-mono text-sm ${
hasValidationErrors ? 'border-red-300 focus:border-red-500' : ''
}`}
/>
</div>
<div className="flex gap-2">
<Button
onClick={handleSave}
disabled={saving || hasValidationErrors}
className={hasValidationErrors ? 'opacity-50 cursor-not-allowed' : ''}
>
<Save className="h-4 w-4 mr-2" />
{saving ? '저장 중...' : '저장'}
</Button>
<Button
variant="outline"
onClick={handlePreview}
disabled={previewLoading || hasValidationErrors}
className={hasValidationErrors ? 'opacity-50 cursor-not-allowed' : ''}
>
<Eye className="h-4 w-4 mr-2" />
{previewLoading ? '생성 중...' : '미리보기'}
</Button>
</div>
</div>
</div>
</div>
{/* 미리보기 영역 */}
<div className="space-y-6">
<div className="bg-white p-6 rounded-lg shadow">
<h2 className="text-xl font-semibold mb-4">빠른 미리보기</h2>
<div className="border rounded-lg p-4 min-h-[500px] bg-gray-50 overflow-auto">
{previewHtml ? (
<div className="preview-content">
{/* 보안: 더 안전한 HTML 렌더링 */}
<iframe
srcDoc={previewHtml}
sandbox="allow-same-origin"
className="w-full h-96 border-0"
title="Template Preview"
/>
</div>
) : (
<div className="text-center text-gray-500 py-20">
미리보기 버튼을 클릭하여 결과를 확인하세요.
</div>
)}
</div>
</div>
{/* 보안 가이드라인 */}
<div className="bg-amber-50 border border-amber-200 p-4 rounded-lg">
<h3 className="font-semibold text-amber-900 mb-2">보안 가이드라인</h3>
<div className="text-sm text-amber-800 space-y-1">
<p>• 허용된 변수만 사용하세요: {ALLOWED_VARIABLES.join(', ')}</p>
<p>• 허용된 헬퍼만 사용하세요: {ALLOWED_HELPERS.join(', ')}</p>
<p>• HTML 출력({`{{{}}}`})은 자동으로 일반 출력으로 변환됩니다</p>
<p>• 시스템 관련 변수나 함수 접근은 차단됩니다</p>
</div>
</div>
{/* Handlebars 문법 도움말 */}
<div className="bg-blue-50 p-4 rounded-lg">
<h3 className="font-semibold text-blue-900 mb-2">Handlebars 문법 도움말</h3>
<div className="text-sm text-blue-800 space-y-1">
<p><code>{`{{variable}}`}</code> - 변수 출력 (자동 이스케이프)</p>
<p><code>{`{{#if condition}}`}</code> - 조건문</p>
<p><code>{`{{#each items}}`}</code> - 반복문</p>
<p><code>{`{{#unless condition}}`}</code> - 부정 조건문</p>
</div>
</div>
{/* 샘플 데이터 */}
<div className="bg-gray-50 p-4 rounded-lg">
<h3 className="font-semibold text-gray-900 mb-2">미리보기 샘플 데이터</h3>
<pre className="text-xs text-gray-600 overflow-auto">
{JSON.stringify({
userName: '홍길동',
companyName: 'EVCP',
email: 'user@example.com',
date: new Date().toLocaleDateString('ko-KR'),
projectName: '샘플 프로젝트',
message: '이것은 샘플 메시지입니다.',
currentYear: new Date().getFullYear(),
language: 'ko',
name: '홍길동',
loginUrl: 'https://example.com/login'
}, null, 2)}
</pre>
</div>
</div>
</div>
</div>
);
}
|