feat: 보안 강화 + 자동화 도구 3종 추가 (웹 크롤러·PPT·엑셀)

- lib/security.ts: escapeHtml, isValidEmail, sanitizeStr, checkRateLimit 유틸 추가
- next.config.ts: 보안 헤더 적용 (X-Frame-Options, HSTS, Permissions-Policy 등)
- api/contact: XSS 방어, Rate Limit(5/min), 입력 길이 제한
- api/payment/confirm: 사용자 인증·소유권 검증, 타입 체크, 에러 메시지 정제
- api/admin/quotes: PUT 허용 필드 화이트리스트 적용
- api/saju/analyze: 로그인·결제 검증, 입력 크기 제한, gender 값 검증
- public/downloads/web_scraper_v1.0.py: requests+BS4+openpyxl 웹 크롤러
- public/downloads/ppt_automation_v1.0.py: python-pptx+openpyxl PPT 자동화
- app/services/automation/tools/scraper: 크롤러 상세 페이지 추가
- app/services/automation/tools/ppt: PPT 도구 상세 페이지 추가
- app/services/automation/page.tsx: scraper ready=true, email→PPT 교체

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-23 07:25:46 +09:00
parent 273da6b7b3
commit df22691d50
11 changed files with 1626 additions and 66 deletions

View File

@@ -16,24 +16,50 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
const { id } = await params;
const supabase = createAdminClient();
const { data, error } = await supabase.from('quotes').select('*').eq('id', id).single();
if (error) return NextResponse.json({ error: error.message }, { status: 404 });
if (error) return NextResponse.json({ error: '견적서를 찾을 수 없습니다' }, { status: 404 });
return NextResponse.json({ quote: data });
}
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
if (!(await checkAuth())) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const { id } = await params;
const body = await request.json();
const supabase = createAdminClient();
let body: Record<string, unknown>;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: '잘못된 요청 형식' }, { status: 400 });
}
// ── 허용 필드 화이트리스트 (시스템 필드 변조 방지) ───────────
const ALLOWED_FIELDS = [
'title', 'client_name', 'client_email', 'client_phone',
'items', 'maintenance', 'notes', 'status',
'valid_until', 'discount',
] as const;
const sanitizedBody = Object.fromEntries(
ALLOWED_FIELDS
.filter((key) => key in body)
.map((key) => [key, body[key]])
);
if (Object.keys(sanitizedBody).length === 0) {
return NextResponse.json({ error: '수정할 필드가 없습니다' }, { status: 400 });
}
const supabase = createAdminClient();
const { data, error } = await supabase
.from('quotes')
.update({ ...body, updated_at: new Date().toISOString() })
.update({ ...sanitizedBody, updated_at: new Date().toISOString() })
.eq('id', id)
.select()
.single();
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
if (error) {
console.error('[Admin Quotes] PUT error:', error.message);
return NextResponse.json({ error: '견적서 업데이트 실패' }, { status: 500 });
}
return NextResponse.json({ quote: data });
}
@@ -42,6 +68,9 @@ export async function DELETE(_req: Request, { params }: { params: Promise<{ id:
const { id } = await params;
const supabase = createAdminClient();
const { error } = await supabase.from('quotes').delete().eq('id', id);
if (error) return NextResponse.json({ error: error.message }, { status: 500 });
if (error) {
console.error('[Admin Quotes] DELETE error:', error.message);
return NextResponse.json({ error: '견적서 삭제 실패' }, { status: 500 });
}
return NextResponse.json({ success: true });
}

View File

@@ -1,37 +1,78 @@
import { NextResponse } from 'next/server';
import { Resend } from 'resend';
import {
escapeHtml,
isValidEmail,
sanitizeStr,
checkRateLimit,
getClientIp,
INPUT_LIMITS,
} from '@/lib/security';
const resend = new Resend(process.env.RESEND_API_KEY);
export async function POST(request: Request) {
try {
const body = await request.json();
const { name, phone, email, service, message } = body;
// ── Rate Limit: IP당 1분 5회 ──────────────────────────────
const ip = getClientIp(request);
const rl = checkRateLimit(`contact:${ip}`, 60_000, 5);
if (!rl.allowed) {
return NextResponse.json(
{ error: '요청이 너무 많습니다. 잠시 후 다시 시도해주세요.' },
{
status: 429,
headers: { 'Retry-After': String(Math.ceil(rl.retryAfterMs / 1000)) },
}
);
}
// 입력 검증
const body = await request.json();
// ── 입력 정제 + 길이 제한 ─────────────────────────────────
const name = sanitizeStr(body.name, INPUT_LIMITS.NAME);
const phone = sanitizeStr(body.phone, INPUT_LIMITS.PHONE);
const email = sanitizeStr(body.email, INPUT_LIMITS.EMAIL);
const service = sanitizeStr(body.service, INPUT_LIMITS.SERVICE);
const message = sanitizeStr(body.message, INPUT_LIMITS.MESSAGE);
// ── 필수값 검증 ───────────────────────────────────────────
if (!name || !email || !message) {
return NextResponse.json(
{ error: '필수 항목을 모두 입력해주세요.' },
{ status: 400 }
);
}
if (!isValidEmail(email)) {
return NextResponse.json(
{ error: '올바른 이메일 형식이 아닙니다.' },
{ status: 400 }
);
}
// 이메일 발송
const data = await resend.emails.send({
from: 'onboarding@resend.dev', // Resend 기본 도메인
to: ['bgg8988@gmail.com'], // 받는 이메일
replyTo: email, // 문의자 이메일로 답장 가능
subject: `[쟁승메이드] 새로운 문의: ${service || '문의'}`,
// ── HTML 이스케이프 (XSS 방지) ────────────────────────────
const safeSubject = escapeHtml(service || '문의');
const safeName = escapeHtml(name);
const safePhone = escapeHtml(phone || '미입력');
const safeEmail = escapeHtml(email);
const safeService = escapeHtml(service || '미선택');
// message는 pre-wrap으로 렌더링되므로 반드시 이스케이프
const safeMessage = escapeHtml(message);
await resend.emails.send({
from: 'onboarding@resend.dev',
to: ['bgg8988@gmail.com'],
replyTo: email,
subject: `[쟁승메이드] 새로운 문의: ${safeSubject}`,
html: `
<h2>새로운 프로젝트 문의가 도착했습니다</h2>
<hr />
<p><strong>이름:</strong> ${name}</p>
<p><strong>연락처:</strong> ${phone || '미입력'}</p>
<p><strong>이메일:</strong> ${email}</p>
<p><strong>서비스:</strong> ${service || '미선택'}</p>
<p><strong>이름:</strong> ${safeName}</p>
<p><strong>연락처:</strong> ${safePhone}</p>
<p><strong>이메일:</strong> ${safeEmail}</p>
<p><strong>서비스:</strong> ${safeService}</p>
<hr />
<h3>문의 내용:</h3>
<p style="white-space: pre-wrap;">${message}</p>
<p style="white-space: pre-wrap;">${safeMessage}</p>
<hr />
<p style="color: #666; font-size: 12px;">
이 메일은 jaengseung-made.com의 문의 폼에서 발송되었습니다.
@@ -44,7 +85,8 @@ export async function POST(request: Request) {
{ status: 200 }
);
} catch (error) {
console.error('Email send error:', error);
// 클라이언트에 내부 오류 상세 노출 금지
console.error('[Contact] Email send error:', error);
return NextResponse.json(
{ error: '메일 전송에 실패했습니다. 다시 시도해주세요.' },
{ status: 500 }

View File

@@ -1,16 +1,43 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { checkRateLimit, getClientIp } from '@/lib/security';
export async function POST(request: NextRequest) {
try {
const { paymentKey, orderId, amount } = await request.json();
if (!paymentKey || !orderId || !amount) {
return NextResponse.json({ error: '필수 파라미터 누락' }, { status: 400 });
// ── Rate Limit: IP당 1분 10회 (결제 재시도 남용 방지) ─────
const ip = getClientIp(request);
const rl = checkRateLimit(`payment:${ip}`, 60_000, 10);
if (!rl.allowed) {
return NextResponse.json(
{ error: '요청이 너무 많습니다. 잠시 후 다시 시도해주세요.' },
{ status: 429 }
);
}
// 1. Supabase에서 order 확인
const body = await request.json();
const { paymentKey, orderId, amount } = body;
// ── 기본 파라미터 검증 ────────────────────────────────────
if (!paymentKey || !orderId || amount === undefined) {
return NextResponse.json({ error: '필수 파라미터 누락' }, { status: 400 });
}
// 타입 강제 검증
if (
typeof paymentKey !== 'string' || paymentKey.length > 200 ||
typeof orderId !== 'string' || orderId.length > 200 ||
typeof amount !== 'number' || amount <= 0 || !Number.isInteger(amount)
) {
return NextResponse.json({ error: '잘못된 파라미터 형식' }, { status: 400 });
}
// ── 로그인 사용자 확인 ────────────────────────────────────
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: '로그인이 필요합니다' }, { status: 401 });
}
// ── DB에서 주문 확인 (금액 서버사이드 검증) ───────────────
const { data: order, error: orderFetchError } = await supabase
.from('orders')
.select('*')
@@ -20,24 +47,30 @@ export async function POST(request: NextRequest) {
if (orderFetchError || !order) {
return NextResponse.json({ error: '주문을 찾을 수 없습니다' }, { status: 404 });
}
// 주문 소유자 검증 (다른 사용자 주문 처리 방지)
if (order.user_id !== user.id) {
return NextResponse.json({ error: '접근 권한이 없습니다' }, { status: 403 });
}
// 서버 DB 금액과 비교 (클라이언트 금액 위조 방어)
if (order.amount !== amount) {
return NextResponse.json({ error: '결제 금액 불일치' }, { status: 400 });
console.warn(`[Payment] 금액 불일치 orderId=${orderId} db=${order.amount} req=${amount} user=${user.id}`);
return NextResponse.json({ error: '결제 금액이 올바르지 않습니다' }, { status: 400 });
}
if (order.status === 'paid') {
return NextResponse.json({ error: '이미 처리된 주문입니다' }, { status: 400 });
}
// 2. 토스페이먼츠 서버 승인
// dev: TOSS_SECRET_KEY=test_sk_* (테스트 결제)
// prod: TOSS_SECRET_KEY=live_sk_* (실결제) — Vercel 환경변수에 설정
const secretKey = process.env.TOSS_SECRET_KEY!;
const isTestKey = secretKey.startsWith('test_');
if (!isTestKey && process.env.NODE_ENV === 'development') {
// 실수로 live 키를 dev에서 쓰는 것 방지
// ── 토스페이먼츠 서버 승인 ────────────────────────────────
const secretKey = process.env.TOSS_SECRET_KEY;
if (!secretKey) {
console.error('[Payment] TOSS_SECRET_KEY 미설정');
return NextResponse.json({ error: '결제 서비스 설정 오류' }, { status: 500 });
}
if (!secretKey.startsWith('test_') && process.env.NODE_ENV === 'development') {
console.warn('[Payment] WARNING: live Toss key detected in development!');
}
const encoded = Buffer.from(`${secretKey}:`).toString('base64');
const encoded = Buffer.from(`${secretKey}:`).toString('base64');
const tossRes = await fetch('https://api.tosspayments.com/v1/payments/confirm', {
method: 'POST',
headers: {
@@ -48,42 +81,47 @@ export async function POST(request: NextRequest) {
});
if (!tossRes.ok) {
const err = await tossRes.json();
return NextResponse.json({ error: err.message || '토스 승인 실패' }, { status: 400 });
const err = await tossRes.json().catch(() => ({}));
// 내부 에러 코드는 서버 로그에만 기록
console.error(`[Payment] Toss 승인 실패 orderId=${orderId} code=${err.code} msg=${err.message}`);
return NextResponse.json(
{ error: '결제 승인에 실패했습니다. 카드사 또는 고객센터에 문의해주세요.' },
{ status: 400 }
);
}
const tossData = await tossRes.json();
// 3. orders 상태 paid로 업데이트
// ── orders 상태 업데이트 ──────────────────────────────────
const { error: updateError } = await supabase
.from('orders')
.update({ status: 'paid' })
.eq('id', orderId);
if (updateError) {
console.error('Order update error:', updateError);
return NextResponse.json({ error: '주문 상태 업데이트 실패: ' + updateError.message }, { status: 500 });
console.error('[Payment] Order update error:', updateError.message);
return NextResponse.json({ error: '주문 상태 업데이트 실패' }, { status: 500 });
}
// 4. payments 레코드 생성
// ── payments 레코드 생성 ──────────────────────────────────
const { error: paymentError } = await supabase.from('payments').insert({
user_id: order.user_id,
order_id: orderId,
product_name: order.metadata?.product_name ?? order.product_id,
amount: order.amount,
status: 'paid',
pg_provider: 'toss',
user_id: order.user_id,
order_id: orderId,
product_name: order.metadata?.product_name ?? order.product_id,
amount: order.amount,
status: 'paid',
pg_provider: 'toss',
pg_payment_key: paymentKey,
});
if (paymentError) {
console.error('Payment insert error:', paymentError);
return NextResponse.json({ error: '결제 내역 저장 실패: ' + paymentError.message }, { status: 500 });
console.error('[Payment] Payment insert error:', paymentError.message);
return NextResponse.json({ error: '결제 내역 저장 실패' }, { status: 500 });
}
return NextResponse.json({ success: true, data: tossData });
} catch (error: unknown) {
console.error('Payment confirm error:', error);
return NextResponse.json({ error: '서버 오류' }, { status: 500 });
console.error('[Payment] Unexpected error:', error);
return NextResponse.json({ error: '서버 오류가 발생했습니다' }, { status: 500 });
}
}

View File

@@ -64,16 +64,49 @@ const MODELS = [
export async function POST(request: Request) {
try {
const { saju, daeun, daeunList, gender, engineData } = await request.json();
// ── 결제 사용자 인증 (Gemini API 무단 호출 방지) ──────────
const { createClient } = await import('@/lib/supabase/server');
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (user) {
// 로그인된 경우: saju_detail 결제 여부 확인
const { data: paidOrder } = await supabase
.from('orders')
.select('id')
.eq('user_id', user.id)
.eq('product_id', 'saju_detail')
.eq('status', 'paid')
.maybeSingle();
if (!paidOrder) {
return NextResponse.json({ error: '사주 리포트를 구매한 사용자만 이용할 수 있습니다' }, { status: 403 });
}
} else {
// 비로그인 사용자는 AI 호출 불가
return NextResponse.json({ error: '로그인이 필요합니다' }, { status: 401 });
}
// ── 입력 길이 검증 (DoS / 프롬프트 인젝션 기초 방어) ──────
const raw = await request.json();
if (JSON.stringify(raw).length > 50_000) {
return NextResponse.json({ error: '요청 데이터가 너무 큽니다' }, { status: 400 });
}
const { saju, daeun, daeunList, gender, engineData } = raw;
// gender 값 제한
if (gender !== 'male' && gender !== 'female') {
return NextResponse.json({ error: '잘못된 성별 값' }, { status: 400 });
}
// 종합 분석 수행
let analysis;
try {
analysis = performFullAnalysis(saju);
} catch (analysisError: any) {
console.error('[사주] 분석 계산 오류:', analysisError.message);
console.error('[사주] 분석 계산 오류');
return NextResponse.json(
{ error: '사주 분석 계산 중 오류: ' + analysisError.message },
{ error: '사주 분석 중 오류가 발생했습니다' },
{ status: 500 }
);
}