Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/api/src/routes/maintenance-routes.ts
T

358 lines
15 KiB
TypeScript

import { Hono, type Context } from "hono";
import { getApiAppDependencies, type ExportJobDownloadRecord, type LegacyEventWebhookAttempt } from "../app-dependencies.js";
import type { ApiEnv } from "../api-types.js";
import { getApiRuntimeConfig } from "../config.js";
import { normalizeIdempotencyKey } from "../idempotency/store.js";
import { postMailjetEmailSequenceWebhookRequest } from "../email-sequences/provider-webhook-route.js";
import { apiError } from "../middleware/error-envelope.js";
import { runWithVerifiedApiRlsContext } from "../rls-context.js";
import { verifyMailjetWebhookAuth } from "../webhooks/mailjet-webhook-auth.js";
import {
parseMaintenanceTake,
parseOptionalTenantId,
readOptionalJsonObjectBody,
requireWorkspaceServiceCredential,
authenticateServiceCredentialRequest,
apiKeyScopedMissingResourceError,
forbiddenApiKeyScopeError,
} from "./shared.js";
import { resolveApiTenantScope } from "../auth/scope.js";
import { parseInboundEmailPayload } from "./inbound-email-payload.js";
export function registerMaintenanceRoutes(app: Hono<ApiEnv>) {
app.post("/v1/support/inbound-email", postSupportInboundEmailRequest);
app.post("/v1/email/inbound-mailjet", postTenantInboundEmailRequest);
app.post("/v1/email-sequences/mailjet/webhooks", (c) =>
postMailjetEmailSequenceWebhookRequest(c, {
webhookSecret: getApiRuntimeConfig().mailjet.webhookSecret,
markEmailSequenceDeliveryBounced: getApiAppDependencies().markEmailSequenceDeliveryBounced,
resolveEmailSequenceProviderMessageRlsIdentity: getApiAppDependencies().resolveEmailSequenceProviderMessageRlsIdentity,
markCampaignOutboundEmailBounced: getApiAppDependencies().markCampaignOutboundEmailBounced,
resolveCampaignOutboundEmailRlsIdentity: getApiAppDependencies().resolveOutboundEmailClickRlsIdentity,
// AK-P14a: a bounce/complaint also suppresses the recipient (best-effort).
recordSuppression: getApiAppDependencies().recordSuppression,
})
);
app.post("/v1/events/webhooks/attempts/:id", postEventWebhookAttemptRequest);
app.post("/v1/maintenance/export-retention/enqueue", postExportRetentionEnqueueRequest);
app.get("/v1/exports/:exportJobId/download-url", getExportDownloadUrlRequest);
app.get("/v1/exports/:exportJobId/progress", getExportProgressRequest);
}
async function postSupportInboundEmailRequest(c: Context<ApiEnv>) {
const authResult = verifyMailjetWebhookAuth({
secret: getApiRuntimeConfig().mailjet.webhookSecret,
headers: c.req.header(),
});
if (!authResult.ok) {
if (authResult.reason === "missing-secret") {
return apiError(c, 500, "webhook_signing_not_configured", "Mailjet webhook authentication is not configured.");
}
return apiError(c, 401, "invalid_webhook_signature", `Invalid Mailjet webhook credentials: ${authResult.reason}.`);
}
const rawBody = await c.req.raw.text();
const payloadResult = parseInboundEmailPayload(rawBody);
if (!payloadResult.ok) {
return apiError(c, 400, "invalid_request", payloadResult.error);
}
const dependencies = getApiAppDependencies();
const identity = await dependencies.resolveTenantInboundAddressRlsIdentity([payloadResult.value.toEmail]).catch(() => null);
if (!identity) {
return c.json({ accepted: true, status: "ignored" }, 202);
}
return runWithVerifiedApiRlsContext({ tenantId: identity.tenantId }, async () => {
const result = await dependencies.createInboundSupportTicketFromEmail({
messageId: payloadResult.value.messageId,
fromEmail: payloadResult.value.fromEmail,
toEmail: payloadResult.value.toEmail,
subject: payloadResult.value.subject,
message: payloadResult.value.message,
});
if (result.status === "unknown-recipient") {
return c.json({ accepted: true, status: "ignored" }, 202);
}
return c.json({ accepted: true, status: result.status, ticketId: result.ticketId }, result.status === "created" ? 201 : 202);
});
}
async function postTenantInboundEmailRequest(c: Context<ApiEnv>) {
const authResult = verifyMailjetWebhookAuth({
secret: getApiRuntimeConfig().mailjet.webhookSecret,
headers: c.req.header(),
});
if (!authResult.ok) {
if (authResult.reason === "missing-secret") {
return apiError(c, 500, "webhook_signing_not_configured", "Mailjet webhook authentication is not configured.");
}
return apiError(c, 401, "invalid_webhook_signature", `Invalid Mailjet webhook credentials: ${authResult.reason}.`);
}
const rawBody = await c.req.raw.text();
const payloadResult = parseInboundEmailPayload(rawBody);
if (!payloadResult.ok) {
return apiError(c, 400, "invalid_request", payloadResult.error);
}
const dependencies = getApiAppDependencies();
const identity = await dependencies.resolveTenantInboundAddressRlsIdentity(payloadResult.value.recipientEmails).catch(() => null);
if (!identity) {
return c.json({ accepted: true, status: "ignored", reason: "unknown-recipient" }, 202);
}
return runWithVerifiedApiRlsContext({ tenantId: identity.tenantId }, async () => {
const result = await dependencies.ingestTenantInboundEmail({
messageId: payloadResult.value.messageId,
fromEmail: payloadResult.value.fromEmail,
toEmail: payloadResult.value.toEmail,
recipientEmails: payloadResult.value.recipientEmails,
subject: payloadResult.value.subject,
textBody: payloadResult.value.message,
htmlBody: payloadResult.value.htmlMessage,
});
if (result.status === "ignored") {
return c.json({ accepted: true, status: "ignored", reason: result.reason }, 202);
}
return c.json(
{
accepted: true,
status: result.status,
emailId: result.emailId,
purpose: result.purpose,
...(result.status === "created"
? { leadId: result.leadId, kontaktId: result.kontaktId, projektId: result.projektId, activityId: result.activityId }
: {}),
},
result.status === "created" ? 201 : 202
);
});
}
async function postEventWebhookAttemptRequest(c: Context<ApiEnv>) {
const authResult = verifyMailjetWebhookAuth({
secret: getApiRuntimeConfig().mailjet.webhookSecret,
headers: c.req.header(),
});
if (!authResult.ok) {
if (authResult.reason === "missing-secret") {
return apiError(c, 500, "webhook_signing_not_configured", "Mailjet webhook authentication is not configured.");
}
return apiError(c, 401, "invalid_webhook_signature", `Invalid Mailjet webhook credentials: ${authResult.reason}.`);
}
const rawBody = await c.req.raw.text();
const dependencies = getApiAppDependencies();
const attemptId = c.req.param("id") || "";
const identity = await dependencies.resolveEventWebhookAttemptRlsIdentity(attemptId).catch(() => null);
if (!identity) {
return apiError(c, 400, "webhook_delivery_failed", "Webhook delivery request could not be accepted.");
}
return runWithVerifiedApiRlsContext({ tenantId: identity.tenantId }, async () => {
const attempt = await dependencies.findLegacyEventWebhookAttemptById(identity.resourceId).catch(() => null);
if (!attempt || attempt.id !== attemptId || attempt.tenantId !== identity.tenantId) {
return apiError(c, 400, "webhook_delivery_failed", "Webhook delivery request could not be accepted.");
}
try {
await dependencies.updateLegacyEventWebhookAttempt({ id: attempt.id, tenantId: attempt.tenantId }, { startedAt: new Date() });
let queueResult;
try {
queueResult = await dependencies.queueLegacyEventWebhookAttemptDelivery({
attempt,
body: JSON.parse(rawBody) as unknown,
requestId: c.get("requestId"),
});
} catch {
await markWebhookAttemptUnavailable(attempt);
return apiError(c, 503, "maintenance_queue_unavailable", "Webhook delivery queue is unavailable.");
}
if (!queueResult.enqueued) {
await markWebhookAttemptUnavailable(attempt);
return apiError(c, 503, "maintenance_queue_unavailable", "Webhook delivery queue is unavailable.");
}
return c.json({}, 200);
} catch {
await dependencies.updateLegacyEventWebhookAttempt(
{ id: attempt.id, tenantId: attempt.tenantId },
{ finishedAt: new Date(), success: false, status: 400, message: "Webhook delivery request could not be accepted." }
);
return apiError(c, 400, "webhook_delivery_failed", "Webhook delivery request could not be accepted.");
}
});
}
async function markWebhookAttemptUnavailable(attempt: LegacyEventWebhookAttempt) {
await getApiAppDependencies().updateLegacyEventWebhookAttempt(
{ id: attempt.id, tenantId: attempt.tenantId },
{ finishedAt: new Date(), success: false, status: 503, message: "Webhook delivery queue is unavailable." }
);
}
async function postExportRetentionEnqueueRequest(c: Context<ApiEnv>) {
const credentialError = requireWorkspaceServiceCredential(c);
if (credentialError) {
return credentialError;
}
const bodyResult = await readOptionalJsonObjectBody(c.req.raw);
if (!bodyResult.ok) {
return apiError(c, 400, "invalid_request", bodyResult.error);
}
const body = bodyResult.value;
const unexpectedKeys = Object.keys(body ?? {}).filter((key) => key !== "take");
if (unexpectedKeys.length > 0) {
return apiError(c, 400, "invalid_request", "Unexpected export retention enqueue fields.");
}
const rawIdempotencyKey = c.req.header("idempotency-key");
const idempotencyKey = normalizeIdempotencyKey(rawIdempotencyKey) ?? undefined;
if (rawIdempotencyKey !== undefined && !idempotencyKey) {
return apiError(c, 400, "invalid_request", "Idempotency-Key header must be a non-empty string when provided.");
}
const takeResult = parseMaintenanceTake(body);
if (!takeResult.ok) {
return apiError(c, 400, "invalid_request", takeResult.error);
}
const requestId = c.get("requestId");
let queueResult;
try {
queueResult = await getApiAppDependencies().queueExportArtifactRetention({ requestId, idempotencyKey, take: takeResult.value });
} catch {
return apiError(c, 503, "maintenance_queue_unavailable", "Maintenance queue is unavailable: queue enqueue failed.");
}
if (!queueResult.enqueued) {
if (queueResult.reason === "maintenance-worker-disabled") {
return apiError(c, 503, "maintenance_queue_unavailable", "Maintenance queue is unavailable: export retention worker is disabled.");
}
return apiError(c, 503, "maintenance_queue_unavailable", "Maintenance queue is unavailable: missing Redis connection.");
}
return c.json({ enqueued: true, task: "expired-export-artifacts", jobId: String(queueResult.job.id ?? ""), requestId }, 202);
}
async function getExportDownloadUrlRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential or API key is required.");
}
const exportJobId = c.req.param("exportJobId");
if (!exportJobId) {
return apiError(c, 400, "invalid_request", "Expected exportJobId.");
}
const requestedTenantScope = parseOptionalTenantId(c);
if (!requestedTenantScope.ok) {
return apiError(c, 400, "invalid_request", requestedTenantScope.error);
}
const resolvedTenantScope = resolveApiTenantScope(principal, requestedTenantScope.value);
if (!resolvedTenantScope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const lookupTenantId = resolvedTenantScope.tenantId;
if (!lookupTenantId) {
return apiError(c, 400, "invalid_request", "tenantId is required.");
}
return runWithVerifiedApiRlsContext({ tenantId: lookupTenantId }, async () => {
try {
const exportJob = await getApiAppDependencies().findExportJobForDownload({ id: exportJobId, tenantId: lookupTenantId });
if (!exportJob) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, 404, "export_job_not_found", `Export job ${exportJobId} not found.`);
}
if (exportJob.errorName === "ExportPaused") {
return apiError(c, 409, "export_job_paused", "Export job is paused and cannot be downloaded.");
}
if (exportJob.status !== "COMPLETED") {
return apiError(c, 409, "export_job_not_completed", "Export job is not completed.");
}
if (!exportJob.artifactBucket || !exportJob.artifactKey) {
return apiError(c, 409, "export_artifact_missing", "Export artifact is not available.");
}
if (exportJob.expiresAt && exportJob.expiresAt.getTime() <= Date.now()) {
return apiError(c, 409, "export_job_expired", "Export job has expired.");
}
const signedUrl = await getApiAppDependencies().createSignedDownloadUrl(exportJob.artifactBucket, {
key: exportJob.artifactKey,
expiresInSeconds: 300,
responseContentDisposition: `attachment; filename="${exportJob.id}.${getExportArtifactExtension(exportJob)}"`,
});
return c.json({
exportJobId: exportJob.id,
requestId: c.get("requestId"),
method: signedUrl.method,
url: signedUrl.url,
expiresAt: signedUrl.expiresAt.toISOString(),
expiresInSeconds: signedUrl.expiresInSeconds,
headers: signedUrl.headers,
});
} catch {
return apiError(c, 500, "export_download_url_failed", "Export download URL could not be created.");
}
});
}
function getExportArtifactExtension(exportJob: Pick<ExportJobDownloadRecord, "format" | "artifactKey">) {
const artifactExtension = exportJob.artifactKey?.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase();
if (artifactExtension && ["csv", "json", "xlsx"].includes(artifactExtension)) {
return artifactExtension;
}
return exportJob.format;
}
async function getExportProgressRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential or API key is required.");
}
const exportJobId = c.req.param("exportJobId");
if (!exportJobId) {
return apiError(c, 400, "invalid_request", "Expected exportJobId.");
}
const requestedTenantScope = parseOptionalTenantId(c);
if (!requestedTenantScope.ok) {
return apiError(c, 400, "invalid_request", requestedTenantScope.error);
}
const resolvedTenantScope = resolveApiTenantScope(principal, requestedTenantScope.value);
if (!resolvedTenantScope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const lookupTenantId = resolvedTenantScope.tenantId;
if (!lookupTenantId) {
return apiError(c, 400, "invalid_request", "tenantId is required.");
}
const progress = await runWithVerifiedApiRlsContext({ tenantId: lookupTenantId }, () =>
getApiAppDependencies().readExportProgress({ exportJobId, tenantId: lookupTenantId })
);
if (!progress) {
return c.json({ exportJobId, processedRows: 0, totalEstimate: null, updatedAt: null, requestId: c.get("requestId") });
}
return c.json({
exportJobId,
processedRows: progress.processedRows,
totalEstimate: progress.totalEstimate,
updatedAt: progress.updatedAt,
requestId: c.get("requestId"),
});
}