import { NextRequest, NextResponse } from "next/server"; import { apiRoute } from "../../../../../../lib/server/apiRoute"; import { prisma } from "../../../../../../lib/server/db"; import { getSessionPepper, isDatabaseConfigured, } from "../../../../../../lib/server/env"; import { getPublicOrigin } from "../../../../../../lib/server/publicOrigin"; import { dbUnavailable, forbidden, notFound, unauthorized, } from "../../../../../../lib/server/responses"; import { isRuleAdminEmail } from "../../../../../../lib/server/ruleAdmins"; import { ruleExportTokenMatches } from "../../../../../../lib/server/ruleExportToken"; import { getSessionUser } from "../../../../../../lib/server/session"; import { RULE_MD_FILENAME, buildStoredRulePdfBytes, exportPdfFilename, exportStoredRuleAsMarkdown, } from "../../../../../../lib/create/ruleExport"; type RouteContext = { params: Promise<{ id: string; format: string }> }; function attachmentDisposition(filename: string): string { const ascii = filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, ""); const encoded = encodeURIComponent(filename); return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`; } function documentRecord(value: unknown): Record | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; return value as Record; } export const GET = apiRoute( "rules.export", async (request: NextRequest, context) => { if (!isDatabaseConfigured()) return dbUnavailable(); const { id, format } = await context.params; if (format !== "pdf" && format !== "md") return notFound(); const row = await prisma.publishedRule.findUnique({ where: { id }, select: { id: true, title: true, summary: true, document: true, createdAt: true, userId: true, }, }); if (!row) return notFound(); const token = request.nextUrl.searchParams.get("t") ?? ""; let tokenOk = false; if (token.length > 0) { try { tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper()); } catch { tokenOk = false; } } if (!tokenOk) { const user = await getSessionUser(); if (!user) return unauthorized(); const isOwner = row.userId === user.id; if (!isOwner && !isRuleAdminEmail(user.email)) { return forbidden("You do not have permission to export this rule"); } } const document = documentRecord(row.document); if (!document) return notFound(); const origin = getPublicOrigin(request); const source = { id: row.id, title: row.title, summary: row.summary, document, finishedAt: row.createdAt, }; if (format === "pdf") { const bytes = buildStoredRulePdfBytes(source, origin); return new NextResponse(Buffer.from(bytes), { headers: { "Content-Type": "application/pdf", "Content-Disposition": attachmentDisposition( exportPdfFilename(row.title), ), "Cache-Control": "private, no-store", }, }); } const markdown = exportStoredRuleAsMarkdown(source, origin); return new NextResponse(markdown, { headers: { "Content-Type": "text/markdown; charset=utf-8", "Content-Disposition": attachmentDisposition(RULE_MD_FILENAME), "Cache-Control": "private, no-store", }, }); }, );