Health checks reais, cabeçalhos de segurança e Sentry por ambiente
- `/api/health/live` não toca dependência: distingue processo vivo de dependência fora do ar. `/api/health/ready` passou a tocar banco, migrations pendentes, Redis com PING, bucket com listagem, configuração e modo de job, e reporta em `reasons` só o nome do erro — nunca connection string. - Configuração inválida encerra o processo. Antes o servidor ficava no ar respondendo 500 em todas as rotas, inclusive no liveness, enganando o orquestrador: pior que não subir. - CSP, HSTS, Permissions-Policy e COOP, além dos três cabeçalhos que já existiam. `unsafe-inline` em script-src é exigência do bootstrap do App Router sem nonce; o resto é fechado e connect-src só aceita o próprio host, o Supabase do ambiente e o Sentry. - `onRequestError` registrado: sem esse export os erros de rota e de render do servidor não chegavam ao Sentry. O ambiente do evento deriva de ADAPTER_ENV, então homologação e produção não se misturam. - `withSentryConfig` só atua quando organização, projeto e token existem no build, para não quebrar build local nem CI. - `output: "standalone"` para a imagem de runtime. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f5560cc4ac
commit
d43f370359
20 files changed
+330
-47
No files matched your search
+82
-7
@@ -1,11 +1,66 @@
|
||||
import type { NextConfig } from "next";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function hostOf(value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return new URL(value).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Content-Security-Policy. `unsafe-inline` em script-src é necessário para o
|
||||
* bootstrap do App Router sem nonce; o restante é fechado. `connect-src` só
|
||||
* aceita o próprio host, o Supabase do ambiente e o Sentry.
|
||||
*/
|
||||
function contentSecurityPolicy(): string {
|
||||
const supabase = hostOf(process.env.NEXT_PUBLIC_SUPABASE_URL);
|
||||
const connect = ["'self'", supabase, supabase?.replace("https://", "wss://"), "https://*.sentry.io"].filter(
|
||||
Boolean,
|
||||
) as string[];
|
||||
return [
|
||||
"default-src 'self'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"object-src 'none'",
|
||||
"img-src 'self' data: blob:",
|
||||
"font-src 'self' data:",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"script-src 'self' 'unsafe-inline'",
|
||||
`connect-src ${connect.join(" ")}`,
|
||||
"worker-src 'self' blob:",
|
||||
"upgrade-insecure-requests",
|
||||
].join("; ");
|
||||
}
|
||||
|
||||
const securityHeaders = [
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
{ key: "Content-Security-Policy", value: contentSecurityPolicy() },
|
||||
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), payment=(), usb=()" },
|
||||
{ key: "Cross-Origin-Opener-Policy", value: "same-origin" },
|
||||
{ key: "X-DNS-Prefetch-Control", value: "off" },
|
||||
// HSTS só faz sentido atrás de TLS. O Nginx do ecossistema termina o TLS.
|
||||
{ key: "Strict-Transport-Security", value: "max-age=31536000; includeSubDomains" },
|
||||
];
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
turbopack: { root },
|
||||
// Saída autocontida para a imagem de runtime.
|
||||
output: "standalone",
|
||||
outputFileTracingRoot: root,
|
||||
// `migrations/` é lido em runtime pelo migrate e pelo health check.
|
||||
outputFileTracingIncludes: {
|
||||
"/api/health/ready": ["./migrations/**/*.sql"],
|
||||
},
|
||||
serverExternalPackages: [
|
||||
"exceljs",
|
||||
"@react-pdf/renderer",
|
||||
@@ -16,16 +71,36 @@ const nextConfig: NextConfig = {
|
||||
poweredByHeader: false,
|
||||
async headers() {
|
||||
return [
|
||||
{ source: "/:path*", headers: securityHeaders },
|
||||
{
|
||||
source: "/:path*",
|
||||
headers: [
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-Frame-Options", value: "DENY" },
|
||||
],
|
||||
source: "/api/:path*",
|
||||
headers: [...securityHeaders, { key: "Cache-Control", value: "no-store" }],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
/**
|
||||
* Upload de sourcemap e release só acontece quando a organização, o projeto e o
|
||||
* token existem no ambiente de build. Sem isto o build local e o CI continuam
|
||||
* funcionando, e o stack trace do servidor chega legível ao Sentry quando o
|
||||
* pipeline fornece os segredos.
|
||||
*/
|
||||
function withSentryIfConfigured(config: NextConfig): NextConfig {
|
||||
const org = process.env.SENTRY_ORG;
|
||||
const project = process.env.SENTRY_PROJECT;
|
||||
if (!org || !project || !process.env.SENTRY_AUTH_TOKEN) return config;
|
||||
const nodeRequire = createRequire(import.meta.url);
|
||||
const { withSentryConfig } = nodeRequire("@sentry/nextjs") as typeof import("@sentry/nextjs");
|
||||
return withSentryConfig(config, {
|
||||
org,
|
||||
project,
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN,
|
||||
silent: true,
|
||||
widenClientFileUpload: true,
|
||||
disableLogger: true,
|
||||
sourcemaps: { deleteSourcemapsAfterUpload: true },
|
||||
});
|
||||
}
|
||||
|
||||
export default withSentryIfConfigured(nextConfig);
|
||||
@@ -1,8 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { adapterEnv } from "@/config/env";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Liveness: não toca em nenhuma dependência. Se o processo responde aqui, ele
|
||||
* está vivo. Configuração inválida derruba o processo no start (ver
|
||||
* `exitOnInvalidConfig`), então esta rota nunca mente sobre o estado.
|
||||
*/
|
||||
export function GET() {
|
||||
return NextResponse.json({ status: "live", module: "spreadsheet-adapter" });
|
||||
return NextResponse.json(
|
||||
{ status: "live", module: "spreadsheet-adapter", environment: adapterEnv() },
|
||||
{ headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,80 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { collectProductionIssues } from "@/config/env";
|
||||
import { adapterEnv, collectConfigIssues, isDeployedEnv, jobRunsInline } from "@/config/env";
|
||||
import { getDb } from "@/infra/db/client";
|
||||
import { pendingMigrations } from "@/infra/db/migration-manifest";
|
||||
import { createCoordinator } from "@/infra/redis";
|
||||
import { createStorage } from "@/infra/storage";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type CheckState = "ok" | "missing" | "down";
|
||||
|
||||
/**
|
||||
* Prontidão real: cada dependência é tocada de verdade. Não basta a variável
|
||||
* existir — Redis responde PING, o bucket aceita listagem e o banco responde
|
||||
* uma consulta. Nenhuma connection string aparece na resposta.
|
||||
*/
|
||||
export async function GET() {
|
||||
const checks: Record<string, "ok" | "missing" | "down"> = {
|
||||
const checks: Record<string, CheckState> = {
|
||||
config: "ok",
|
||||
database: "down",
|
||||
redis: process.env.REDIS_URL ? "ok" : "missing",
|
||||
storage: process.env.SUPABASE_STORAGE_BUCKET && process.env.SUPABASE_STORAGE_BUCKET !== "public" ? "ok" : "missing",
|
||||
config: collectProductionIssues(process.env).length === 0 ? "ok" : "missing",
|
||||
migrations: "ok",
|
||||
redis: "down",
|
||||
storage: "down",
|
||||
job_mode: "ok",
|
||||
};
|
||||
const issues = collectConfigIssues(process.env);
|
||||
if (issues.length > 0) {
|
||||
checks.config = "missing";
|
||||
}
|
||||
|
||||
// Só o nome do erro e, para migrations, os ids pendentes. Nunca connection
|
||||
// string, credencial ou mensagem com host.
|
||||
const reasons: Record<string, string> = {};
|
||||
|
||||
try {
|
||||
const db = await getDb();
|
||||
await db.withService((query) => query.query("select 1 as ok"));
|
||||
checks.database = "ok";
|
||||
} catch {
|
||||
const pending = await pendingMigrations(db);
|
||||
checks.migrations = pending.length === 0 ? "ok" : "missing";
|
||||
if (pending.length > 0) reasons.migrations = pending.join(", ");
|
||||
} catch (error) {
|
||||
checks.database = "down";
|
||||
checks.migrations = "down";
|
||||
reasons.database = error instanceof Error ? error.name : "erro";
|
||||
}
|
||||
const ready = checks.database === "ok" && (process.env.NODE_ENV !== "production" || (checks.redis === "ok" && checks.storage === "ok" && checks.config === "ok"));
|
||||
return NextResponse.json({ status: ready ? "ready" : "not_ready", checks }, { status: ready ? 200 : 503 });
|
||||
|
||||
try {
|
||||
checks.redis = (await createCoordinator().ping()) ? "ok" : "down";
|
||||
} catch (error) {
|
||||
checks.redis = "down";
|
||||
reasons.redis = error instanceof Error ? error.name : "erro";
|
||||
}
|
||||
|
||||
try {
|
||||
checks.storage = (await createStorage().healthcheck()) ? "ok" : "down";
|
||||
} catch (error) {
|
||||
checks.storage = "down";
|
||||
reasons.storage = error instanceof Error ? error.name : "erro";
|
||||
}
|
||||
|
||||
if (isDeployedEnv() && jobRunsInline()) checks.job_mode = "missing";
|
||||
|
||||
const required = isDeployedEnv()
|
||||
? (["config", "database", "migrations", "redis", "storage", "job_mode"] as const)
|
||||
: (["database"] as const);
|
||||
const ready = required.every((key) => checks[key] === "ok");
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: ready ? "ready" : "not_ready",
|
||||
environment: adapterEnv(),
|
||||
checks,
|
||||
reasons,
|
||||
configIssues: issues.map((issue) => `${issue.variable}: ${issue.message}`),
|
||||
},
|
||||
{ status: ready ? 200 : 503, headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
}
|
||||
+14
-10
@@ -1,20 +1,24 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDb } from "@/infra/db/client";
|
||||
import { adapterEnv } from "@/config/env";
|
||||
import { probeDb } from "@/infra/db/client";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Atalho histórico, mantido para quem já aponta monitoramento aqui.
|
||||
* O detalhe está em /api/health/ready; a vida do processo, em /api/health/live.
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
const db = await getDb();
|
||||
await db.withService((query) => query.query("select 1 as ok"));
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
module: "spreadsheet-adapter",
|
||||
redis: process.env.REDIS_URL ? "configured" : "not_configured",
|
||||
storage: process.env.SUPABASE_STORAGE_BUCKET ? "supabase" : "unconfigured",
|
||||
});
|
||||
await probeDb();
|
||||
} catch {
|
||||
return NextResponse.json({ ok: false }, { status: 503 });
|
||||
return NextResponse.json({ ok: false, environment: adapterEnv() }, { status: 503 });
|
||||
}
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
module: "spreadsheet-adapter",
|
||||
environment: adapterEnv(),
|
||||
detail: "/api/health/ready",
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { presentError } from "@/domain/spreadsheet-adapter/error-catalog";
|
||||
import { AdapterError, isAdapterError } from "@/domain/spreadsheet-adapter/errors";
|
||||
import type { RequestContext } from "@/domain/spreadsheet-adapter/types";
|
||||
import { resolveAuth } from "@/server/auth/context";
|
||||
import { enforceRateLimit, type RateLimitBucket } from "@/server/rate-limit";
|
||||
import type { AppDeps } from "@/server/spreadsheet-adapter/deps";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -11,9 +12,12 @@ export const dynamic = "force-dynamic";
|
||||
export function errorResponse(error: unknown): NextResponse {
|
||||
if (isAdapterError(error)) {
|
||||
const view = presentError(error.code);
|
||||
const headers: Record<string, string> = {};
|
||||
const retryAfter = error.details?.retryAfterSeconds;
|
||||
if (typeof retryAfter === "number") headers["Retry-After"] = String(retryAfter);
|
||||
return NextResponse.json(
|
||||
{ error: { code: error.code, message: error.message, action: view.action, category: view.category, reference: error.code, details: error.details ?? null } },
|
||||
{ status: error.status },
|
||||
{ status: error.status, headers },
|
||||
);
|
||||
}
|
||||
console.error("spreadsheet-adapter", error instanceof Error ? error.name : "error");
|
||||
@@ -24,12 +28,24 @@ export function errorResponse(error: unknown): NextResponse {
|
||||
);
|
||||
}
|
||||
|
||||
export async function requireReady(): Promise<{ ctx: RequestContext; deps: AppDeps }> {
|
||||
/**
|
||||
* Sessão, workspace e dependências da requisição. O `bucket` aplica o teto de
|
||||
* abuso por usuário: upload e processamento custam muito mais que leitura.
|
||||
*/
|
||||
export async function requireReady(bucket: RateLimitBucket = "read"): Promise<{ ctx: RequestContext; deps: AppDeps }> {
|
||||
const auth = await resolveAuth();
|
||||
if (auth.kind === "anonymous" || auth.kind === "session_expired") {
|
||||
throw new AdapterError("UNAUTHENTICATED", auth.kind === "session_expired" ? "Sessão expirada. Entre novamente." : "Sessão Elo Pro necessária.", 401);
|
||||
}
|
||||
if (auth.kind === "workspace_choice" || auth.kind === "no_workspace") {
|
||||
throw new AdapterError(
|
||||
"WORKSPACE_REQUIRED",
|
||||
auth.kind === "no_workspace" ? "Sua identidade não está em nenhum workspace." : "Selecione o workspace ativo.",
|
||||
409,
|
||||
);
|
||||
}
|
||||
if (auth.kind !== "ok") throw new AdapterError("WORKSPACE_FORBIDDEN", "Workspace não autorizado.", 403);
|
||||
await enforceRateLimit(bucket, `${auth.ctx.workspaceId}:${auth.ctx.userId}`);
|
||||
const { runtimeDeps } = await import("@/server/spreadsheet-adapter/runtime");
|
||||
return { ctx: auth.ctx, deps: await runtimeDeps() };
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("download");
|
||||
const { id } = await context.params;
|
||||
const url = new URL(request.url);
|
||||
const format = url.searchParams.get("format") as OutputFormat | null;
|
||||
|
||||
@@ -8,7 +8,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const { id } = await context.params;
|
||||
const body = (await request.json()) as { sourceId?: string; mappings?: MappingInput[]; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const { id } = await context.params;
|
||||
const body = (await request.json()) as { sourceId?: string; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("process");
|
||||
const { id } = await context.params;
|
||||
const body = (await request.json()) as { sourceId?: string; idempotencyKey?: string; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(_request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("read");
|
||||
const { id } = await context.params;
|
||||
return NextResponse.json({ job: await getJob(deps, ctx, id) });
|
||||
} catch (error) {
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function PATCH(request: Request, context: { params: Promise<{ id: string; sourceId: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const { id, sourceId } = await context.params;
|
||||
const body = (await request.json()) as { sheet?: string | null; headerRow?: number; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
@@ -20,7 +20,7 @@ export async function PATCH(request: Request, context: { params: Promise<{ id: s
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string; sourceId: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const { id, sourceId } = await context.params;
|
||||
const body = await request.json().catch(() => ({}));
|
||||
await rejectWorkspaceForgery(deps, ctx, (body as { workspace_id?: string }).workspace_id);
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const body = (await request.json()) as { modelId?: string; idempotencyKey?: string; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
if (!body.modelId) return NextResponse.json({ error: { code: "NOT_FOUND", message: "Selecione um modelo." } }, { status: 400 });
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const { id } = await context.params;
|
||||
const body = await request.json().catch(() => ({}));
|
||||
await rejectWorkspaceForgery(deps, ctx, (body as { workspace_id?: string }).workspace_id);
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("read");
|
||||
return NextResponse.json({ models: await listModels(deps, ctx) });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
@@ -16,7 +16,7 @@ export async function GET() {
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("upload");
|
||||
const form = await request.formData();
|
||||
await rejectWorkspaceForgery(deps, ctx, form.get("workspace_id"));
|
||||
const file = form.get("file");
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("read");
|
||||
return NextResponse.json(await getSettings(deps, ctx));
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
@@ -16,7 +16,7 @@ export async function GET() {
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("mutation");
|
||||
const body = (await request.json()) as { allowNonAdminModelUpload?: boolean; workspace_id?: string };
|
||||
await rejectWorkspaceForgery(deps, ctx, body.workspace_id);
|
||||
if (typeof body.allowNonAdminModelUpload !== "boolean") {
|
||||
|
||||
@@ -7,7 +7,7 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { ctx, deps } = await requireReady();
|
||||
const { ctx, deps } = await requireReady("upload");
|
||||
const form = await request.formData();
|
||||
await rejectWorkspaceForgery(deps, ctx, form.get("workspace_id"));
|
||||
const file = form.get("file");
|
||||
|
||||
@@ -8,7 +8,8 @@ export type ErrorCategory =
|
||||
| "processing"
|
||||
| "timeout"
|
||||
| "storage"
|
||||
| "worker";
|
||||
| "worker"
|
||||
| "rate_limit";
|
||||
|
||||
export type PublicErrorView = {
|
||||
category: ErrorCategory;
|
||||
@@ -38,6 +39,8 @@ const VIEWS: Record<string, PublicErrorView> = {
|
||||
STORAGE_FAILURE: { category: "storage", action: "Não foi possível guardar o arquivo. Tente novamente." },
|
||||
INVALID_SETTING: { category: "invalid_configuration", action: "Revise a configuração com um administrador." },
|
||||
PROCESS_FAILED: { category: "processing", action: "Tente processar novamente." },
|
||||
RATE_LIMITED: { category: "rate_limit", action: "Aguarde o tempo indicado e tente de novo." },
|
||||
WORKSPACE_REQUIRED: { category: "authorization", action: "Selecione o workspace para continuar." },
|
||||
INTERNAL: { category: "temporary", action: "Tente novamente. Se continuar, informe a referência ao suporte." },
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { adapterEnv } from "@/config/env";
|
||||
import { scrubSentryEvent, sentrySafeError } from "./scrub";
|
||||
|
||||
export { scrubSentryEvent, sentrySafeError };
|
||||
@@ -16,6 +17,7 @@ export function captureAdapterException(error: unknown, tags: Record<string, str
|
||||
void import("@sentry/nextjs").then((Sentry) => {
|
||||
Sentry.withScope((scope) => {
|
||||
scope.setTag("module", "spreadsheet-adapter");
|
||||
scope.setTag("environment_tier", adapterEnv());
|
||||
for (const [key, value] of Object.entries(tags)) scope.setTag(key, value.slice(0, 120));
|
||||
Sentry.captureException(sentrySafeError(error));
|
||||
});
|
||||
@@ -26,8 +28,10 @@ export function sentryInitOptions(dsn: string | undefined) {
|
||||
if (!dsn) return null;
|
||||
return {
|
||||
dsn,
|
||||
environment: process.env.SENTRY_ENVIRONMENT || process.env.NODE_ENV,
|
||||
release: process.env.SENTRY_RELEASE,
|
||||
// Ambiente lógico do Adaptador: homologação e produção nunca se misturam
|
||||
// no mesmo grupo de eventos, mesmo com NODE_ENV=production nos dois.
|
||||
environment: process.env.SENTRY_ENVIRONMENT || adapterEnv(),
|
||||
release: process.env.SENTRY_RELEASE || process.env.NEXT_PUBLIC_SENTRY_RELEASE,
|
||||
sendDefaultPii: false,
|
||||
};
|
||||
}
|
||||
+37
-2
@@ -1,8 +1,20 @@
|
||||
import { assertProductionEnv } from "@/config/env";
|
||||
import { adapterEnv, assertDeployedEnv } from "@/config/env";
|
||||
import { scrubSentryEvent, sentryInitOptions } from "@/infra/observability/capture";
|
||||
|
||||
/**
|
||||
* Executa no start do servidor. Configuração inválida encerra o processo com
|
||||
* código diferente de zero: um servidor que fica no ar respondendo 500 em todas
|
||||
* as rotas engana o orquestrador e o health check.
|
||||
*/
|
||||
export async function register() {
|
||||
assertProductionEnv(process.env);
|
||||
if (process.env.NEXT_RUNTIME === "edge") {
|
||||
// No Edge Runtime não há `process.exit`: reporta e deixa o runtime Node,
|
||||
// que roda em paralelo, encerrar o processo.
|
||||
assertDeployedEnv(process.env);
|
||||
} else {
|
||||
const { exitOnInvalidConfig } = await import("@/config/fail-fast");
|
||||
exitOnInvalidConfig(process.env);
|
||||
}
|
||||
const options = sentryInitOptions(process.env.SENTRY_DSN);
|
||||
if (!options) return;
|
||||
const Sentry = await import("@sentry/nextjs");
|
||||
@@ -13,3 +25,26 @@ export async function register() {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Erros de render e de route handler. Sem este export o Sentry do Next não
|
||||
* recebe as falhas do servidor automaticamente. O payload passa pelo mesmo
|
||||
* scrub: nada de conteúdo de célula.
|
||||
*/
|
||||
export async function onRequestError(
|
||||
error: unknown,
|
||||
request: { path: string; method: string; headers: Record<string, string | undefined> },
|
||||
context: { routerKind: string; routePath: string; routeType: string },
|
||||
) {
|
||||
if (!process.env.SENTRY_DSN) return;
|
||||
const Sentry = await import("@sentry/nextjs");
|
||||
const { sentrySafeError } = await import("@/infra/observability/scrub");
|
||||
Sentry.withScope((scope) => {
|
||||
scope.setTag("module", "spreadsheet-adapter");
|
||||
scope.setTag("environment_tier", adapterEnv());
|
||||
scope.setTag("route_path", context.routePath.slice(0, 120));
|
||||
scope.setTag("route_type", context.routeType);
|
||||
scope.setTag("http_method", request.method);
|
||||
Sentry.captureException(sentrySafeError(error));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import "server-only";
|
||||
import { AdapterError } from "@/domain/spreadsheet-adapter/errors";
|
||||
import { createCoordinator } from "@/infra/redis";
|
||||
import { rateLimitKey } from "@/infra/redis/redis";
|
||||
import type { Coordinator } from "@/infra/redis/memory";
|
||||
|
||||
export type RateLimitBucket = "login" | "upload" | "process" | "download" | "mutation" | "read";
|
||||
|
||||
export type RateLimitRule = { limit: number; windowSeconds: number };
|
||||
|
||||
/**
|
||||
* Tetos por janela. São limites de abuso, não de produto: o uso normal do
|
||||
* piloto fica muito abaixo. `upload` e `process` são os caros — leem 10 MB
|
||||
* e geram XLSX, CSV e PDF.
|
||||
*/
|
||||
export const RATE_LIMITS: Record<RateLimitBucket, RateLimitRule> = {
|
||||
login: { limit: 10, windowSeconds: 300 },
|
||||
upload: { limit: 30, windowSeconds: 300 },
|
||||
process: { limit: 20, windowSeconds: 300 },
|
||||
download: { limit: 120, windowSeconds: 300 },
|
||||
mutation: { limit: 120, windowSeconds: 300 },
|
||||
read: { limit: 600, windowSeconds: 300 },
|
||||
};
|
||||
|
||||
export function windowStart(rule: RateLimitRule, now = Date.now()): number {
|
||||
return Math.floor(now / (rule.windowSeconds * 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Conta o acesso e devolve o estado da janela. Não lança: quem chama decide.
|
||||
* Falha de coordenação não bloqueia leitura — o processamento já é recusado
|
||||
* por conta própria quando o Redis está fora.
|
||||
*/
|
||||
export async function hitRateLimit(
|
||||
bucket: RateLimitBucket,
|
||||
subject: string,
|
||||
options: { coordinator?: Coordinator; now?: number } = {},
|
||||
): Promise<{ allowed: boolean; limit: number; remaining: number; retryAfterSeconds: number }> {
|
||||
const rule = RATE_LIMITS[bucket];
|
||||
const coordinator = options.coordinator ?? createCoordinator();
|
||||
const now = options.now ?? Date.now();
|
||||
const key = rateLimitKey(bucket, subject, windowStart(rule, now));
|
||||
let count: number;
|
||||
try {
|
||||
count = await coordinator.hit(key, rule.windowSeconds);
|
||||
} catch {
|
||||
// Sem coordenação não há contagem confiável. Não inventa bloqueio.
|
||||
return { allowed: true, limit: rule.limit, remaining: rule.limit, retryAfterSeconds: 0 };
|
||||
}
|
||||
const elapsed = now % (rule.windowSeconds * 1000);
|
||||
const retryAfterSeconds = Math.max(1, Math.ceil((rule.windowSeconds * 1000 - elapsed) / 1000));
|
||||
return {
|
||||
allowed: count <= rule.limit,
|
||||
limit: rule.limit,
|
||||
remaining: Math.max(0, rule.limit - count),
|
||||
retryAfterSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
/** Versão que recusa a requisição. Usada pelas rotas do módulo. */
|
||||
export async function enforceRateLimit(
|
||||
bucket: RateLimitBucket,
|
||||
subject: string,
|
||||
options: { coordinator?: Coordinator; now?: number } = {},
|
||||
): Promise<void> {
|
||||
const result = await hitRateLimit(bucket, subject, options);
|
||||
if (result.allowed) return;
|
||||
throw new AdapterError(
|
||||
"RATE_LIMITED",
|
||||
`Muitas chamadas em sequência. Aguarde ${result.retryAfterSeconds} segundos e tente de novo.`,
|
||||
429,
|
||||
{ retryAfterSeconds: result.retryAfterSeconds, limit: result.limit },
|
||||
);
|
||||
}
|
||||
|
||||
/** Identificador do chamador anônimo, para a tela de login. */
|
||||
export function requestSubject(request: Request): string {
|
||||
const forwarded = request.headers.get("x-forwarded-for");
|
||||
const ip = forwarded?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || "desconhecido";
|
||||
return ip.slice(0, 64);
|
||||
}
|
||||
Reference in new issue
Block a user