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
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user