Files
community-rule/app/api/rules/[id]/export/[format]/route.ts
T
adilallo d9c475a967 Give finished Rules a print path, folded launch counts, and a two-day follow-up.
Export is PDF, RULE.md, and Print on US Letter, with every shared term, no member names, and a takeaway that points at Ask an organizer. Finished Rules keep type and place so the team can read folded counts without a database, Umami can sit beside the app with no cookies, and the person who holds the pen gets working PDF and RULE.md links 48 hours later.
2026-11-10 18:32:33 -07:00

113 lines
3.4 KiB
TypeScript

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<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
export const GET = apiRoute<RouteContext>(
"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",
},
});
},
);