refactor(api): enhance donation creation with rate limiting, Zod validation, and secure logging
- Add rate limiting to prevent abuse on /api/donations/create endpoint - Replace manual input validation with Zod schema for better error handling and type safety - Switch from console.log to secureLogger to comply with LGPD and avoid exposing sensitive data - Remove sensitive request body logging in AbacatePay client for improved security
This commit is contained in:
1 parent
bb6b320d1f
commit
a1800227a7
11 files changed
+876
-138
No files matched your search
@@ -1,56 +1,58 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { abacatePay } from "@/lib/abacatepay";
|
||||
import { DONATION_PRODUCTS, DonorData } from "@/types/donation";
|
||||
import { createDonationSchema } from "@/lib/validation-schemas";
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIP,
|
||||
createRateLimitResponse,
|
||||
} from "@/lib/rate-limiter";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const ip = getClientIP(request);
|
||||
const rateLimit = checkRateLimit(ip, "/api/donations/create");
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit.resetAt);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Validar tier
|
||||
const validTiers: Array<keyof typeof DONATION_PRODUCTS> = [
|
||||
"coffee",
|
||||
"snack",
|
||||
"lunch",
|
||||
"custom",
|
||||
];
|
||||
if (!body.tier || !validTiers.includes(body.tier)) {
|
||||
// Validação com Zod
|
||||
const validationResult = createDonationSchema.safeParse(body);
|
||||
|
||||
if (!validationResult.success) {
|
||||
const errors = validationResult.error.issues.map((err: any) => ({
|
||||
field: err.path.join("."),
|
||||
message: err.message,
|
||||
}));
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Tier de doação inválido" },
|
||||
{
|
||||
success: false,
|
||||
error: "Dados de entrada inválidos",
|
||||
details: errors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const product =
|
||||
DONATION_PRODUCTS[body.tier as keyof typeof DONATION_PRODUCTS];
|
||||
const validatedData = validationResult.data;
|
||||
|
||||
// Se for custom, validar valor enviado
|
||||
const product =
|
||||
DONATION_PRODUCTS[validatedData.tier as keyof typeof DONATION_PRODUCTS];
|
||||
|
||||
// Calcular valor final
|
||||
let finalAmount: number;
|
||||
let finalDescription: string;
|
||||
|
||||
if (body.tier === "custom") {
|
||||
if (!body.customAmount || typeof body.customAmount !== "number") {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Valor customizado inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const minAmount = DONATION_PRODUCTS.custom.minAmount;
|
||||
const maxAmount = DONATION_PRODUCTS.custom.maxAmount;
|
||||
|
||||
if (body.customAmount < minAmount || body.customAmount > maxAmount) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: `Valor deve estar entre R$ ${minAmount} e R$ ${maxAmount}`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (validatedData.tier === "custom") {
|
||||
// Converter para centavos
|
||||
finalAmount = Math.round(body.customAmount * 100);
|
||||
finalDescription = `Doação Personalizada - R$ ${body.customAmount.toFixed(
|
||||
finalAmount = Math.round(validatedData.customAmount! * 100);
|
||||
finalDescription = `Doação Personalizada - R$ ${validatedData.customAmount!.toFixed(
|
||||
2
|
||||
)}`;
|
||||
} else {
|
||||
@@ -61,7 +63,7 @@ export async function POST(request: NextRequest) {
|
||||
let pixData;
|
||||
|
||||
// Fluxo: Anônimo ou Identificado
|
||||
if (body.anonymous === true) {
|
||||
if (validatedData.anonymous === true) {
|
||||
// Doação anônima - sem customer
|
||||
pixData = await abacatePay.createPixQrCode({
|
||||
amount: finalAmount,
|
||||
@@ -69,89 +71,35 @@ export async function POST(request: NextRequest) {
|
||||
expiresIn: 600,
|
||||
});
|
||||
|
||||
console.log("🔍 PIX criado (anônimo):", pixData);
|
||||
|
||||
console.log("📝 Registro de doação anônima:", {
|
||||
type: "donation_created",
|
||||
secureLogger.info("PIX criado (anônimo)", {
|
||||
pixId: pixData.id,
|
||||
amount: finalAmount,
|
||||
tier: body.tier,
|
||||
customAmount: body.tier === "custom" ? body.customAmount : undefined,
|
||||
anonymous: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
tier: validatedData.tier,
|
||||
});
|
||||
} else {
|
||||
// Doação identificada - validar campos obrigatórios
|
||||
if (!body.donorName || body.donorName.trim().length < 3) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Nome é obrigatório (mínimo 3 caracteres)" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorPhone || body.donorPhone.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Telefone é obrigatório" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorEmail) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Email é obrigatório para doação identificada",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.donorTaxId || body.donorTaxId.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "CPF/CNPJ é obrigatório" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (body.donorMessage && body.donorMessage.length > 280) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Mensagem deve ter no máximo 280 caracteres",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Doação identificada - dados já validados pelo Zod
|
||||
pixData = await abacatePay.createPixQrCode({
|
||||
amount: finalAmount,
|
||||
description: finalDescription,
|
||||
expiresIn: 600,
|
||||
customer: {
|
||||
name: body.donorName.trim(),
|
||||
email: body.donorEmail.trim(),
|
||||
cellphone: body.donorPhone.trim(),
|
||||
taxId: body.donorTaxId.trim(),
|
||||
name: validatedData.donorName,
|
||||
email: validatedData.donorEmail,
|
||||
cellphone: validatedData.donorPhone,
|
||||
taxId: validatedData.donorTaxId,
|
||||
},
|
||||
});
|
||||
|
||||
console.log("🔍 PIX criado (identificado):", pixData);
|
||||
|
||||
console.log("📝 Registro de doação identificada:", {
|
||||
type: "donation_created",
|
||||
secureLogger.info("PIX criado (identificado)", {
|
||||
pixId: pixData.id,
|
||||
amount: finalAmount,
|
||||
tier: body.tier,
|
||||
customAmount: body.tier === "custom" ? body.customAmount : undefined,
|
||||
anonymous: false,
|
||||
tier: validatedData.tier,
|
||||
donor: {
|
||||
name: body.donorName,
|
||||
email: body.donorEmail,
|
||||
phone: body.donorPhone,
|
||||
taxId: body.donorTaxId,
|
||||
message: body.donorMessage,
|
||||
name: validatedData.donorName,
|
||||
email: validatedData.donorEmail,
|
||||
phone: validatedData.donorPhone,
|
||||
taxId: validatedData.donorTaxId,
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -163,7 +111,7 @@ export async function POST(request: NextRequest) {
|
||||
expiresAt: pixData.expiresAt,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Donation creation error:", error);
|
||||
secureLogger.error("Donation creation error", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getPaymentStatus } from "@/lib/payment-cache";
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIP,
|
||||
createRateLimitResponse,
|
||||
} from "@/lib/rate-limiter";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const ip = getClientIP(request);
|
||||
const rateLimit = checkRateLimit(ip, "/api/donations/status");
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit.resetAt);
|
||||
}
|
||||
const { searchParams } = new URL(request.url);
|
||||
const pixId = searchParams.get("pixId");
|
||||
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { abacatePay } from "@/lib/abacatepay";
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIP,
|
||||
createRateLimitResponse,
|
||||
} from "@/lib/rate-limiter";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const ip = getClientIP(request);
|
||||
const rateLimit = checkRateLimit(ip, "/api/donations/verify");
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit.resetAt);
|
||||
}
|
||||
const { searchParams } = new URL(request.url);
|
||||
const billingId = searchParams.get("billingId");
|
||||
|
||||
|
||||
@@ -1,9 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { abacatePay } from "@/lib/abacatepay";
|
||||
import { markAsPaid } from "@/lib/payment-cache";
|
||||
import {
|
||||
checkRateLimit,
|
||||
getClientIP,
|
||||
createRateLimitResponse,
|
||||
} from "@/lib/rate-limiter";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
// Whitelist de IPs do AbacatePay (configurável via env)
|
||||
const ABACATEPAY_IPS = process.env.ABACATEPAY_WHITELIST_IPS?.split(",") || [];
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Rate limiting
|
||||
const ip = getClientIP(request);
|
||||
const rateLimit = checkRateLimit(ip, "/api/webhooks/abacatepay");
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return createRateLimitResponse(rateLimit.resetAt);
|
||||
}
|
||||
|
||||
// Validar IP de origem (se configurado)
|
||||
if (ABACATEPAY_IPS.length > 0 && !ABACATEPAY_IPS.includes(ip)) {
|
||||
secureLogger.warn("Webhook rejeitado: IP não autorizado", { ip });
|
||||
return NextResponse.json({ error: "IP não autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const payload = await request.text();
|
||||
|
||||
// AbacatePay envia webhookSecret como query param
|
||||
@@ -13,15 +36,34 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// Validar secret
|
||||
if (!webhookSecret || !expectedSecret || webhookSecret !== expectedSecret) {
|
||||
console.error("🔒 Webhook rejeitado: secret inválido ou ausente");
|
||||
secureLogger.warn("Webhook rejeitado: secret inválido ou ausente");
|
||||
return NextResponse.json({ error: "Secret inválido" }, { status: 401 });
|
||||
}
|
||||
|
||||
console.log("✅ Webhook autenticado com sucesso");
|
||||
secureLogger.info("Webhook autenticado com sucesso");
|
||||
|
||||
const event = JSON.parse(payload);
|
||||
|
||||
console.log("🔔 Webhook recebido:", JSON.stringify(event, null, 2));
|
||||
secureLogger.debug("Webhook recebido", event);
|
||||
|
||||
// Validar timestamp do evento (prevenir replay attacks)
|
||||
const eventTimestamp = event.timestamp || event.data?.pixQrCode?.createdAt;
|
||||
if (eventTimestamp) {
|
||||
const eventTime = new Date(eventTimestamp).getTime();
|
||||
const now = Date.now();
|
||||
const timeDiff = Math.abs(now - eventTime);
|
||||
|
||||
// Rejeitar eventos com mais de 5 minutos de diferença
|
||||
if (timeDiff > 5 * 60 * 1000) {
|
||||
secureLogger.warn("Webhook rejeitado: timestamp inválido", {
|
||||
timeDiff: timeDiff / 1000 + "s",
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "Timestamp inválido" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar se é evento de pagamento confirmado
|
||||
const isPaidEvent =
|
||||
@@ -35,11 +77,14 @@ export async function POST(request: NextRequest) {
|
||||
const payment = event.data.payment;
|
||||
|
||||
if (!pixQrCode || pixQrCode.status !== "PAID") {
|
||||
console.log("⚠️ Webhook recebido mas status não é PAID");
|
||||
secureLogger.info("Webhook recebido mas status não é PAID");
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
console.log("✅ Doação confirmada via webhook:", pixQrCode.id);
|
||||
secureLogger.info("Doação confirmada via webhook", {
|
||||
pixId: pixQrCode.id,
|
||||
amount: pixQrCode.amount,
|
||||
});
|
||||
|
||||
// Detectar se é doação anônima ou identificada
|
||||
const isAnonymous = !pixQrCode.customer;
|
||||
@@ -67,13 +112,15 @@ export async function POST(request: NextRequest) {
|
||||
taxId: pixQrCode.customer.metadata.taxId,
|
||||
};
|
||||
|
||||
console.log(
|
||||
"📧 Email disponível para agradecimento:",
|
||||
pixQrCode.customer.metadata.email
|
||||
);
|
||||
secureLogger.info("Email disponível para agradecimento", {
|
||||
maskedEmail: pixQrCode.customer.metadata.email,
|
||||
});
|
||||
}
|
||||
|
||||
console.log("📝 Registro de pagamento:", donationRecord);
|
||||
secureLogger.info(
|
||||
"Registro de pagamento criado",
|
||||
secureLogger.mask(donationRecord)
|
||||
);
|
||||
|
||||
// Salvar no cache para frontend detectar via polling
|
||||
markAsPaid(pixQrCode.id, donationRecord);
|
||||
@@ -93,12 +140,14 @@ export async function POST(request: NextRequest) {
|
||||
// TODO: Atualizar estatísticas
|
||||
// await updateDonationStats(donationRecord.amount);
|
||||
} else {
|
||||
console.log("ℹ️ Evento de webhook (não é pagamento):", event.event);
|
||||
secureLogger.info("Evento de webhook (não é pagamento)", {
|
||||
event: event.event,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Webhook error:", error);
|
||||
secureLogger.error("Webhook error", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erro ao processar webhook" },
|
||||
{ status: 500 }
|
||||
|
||||
Reference in new issue
Block a user