Add a content security policy and expire mailed export links.

Responses had no CSP, the 48-hour download token never changed, and short share slugs could be guessed without a miss limit.
This commit is contained in:
adilallo committed 2026-11-21 11:46:16 -07:00
1 parent 0fe2624002
commit 75649a9a42
18 files changed
+249 -19

No files matched your search

+17 -1
View File
@@ -1,8 +1,10 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { notFound } from "next/navigation";
import messages from "../../../../messages/en/index";
import { isShareSlug } from "../../../../lib/sharePaths";
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
import { rateLimitKey } from "../../../../lib/server/rateLimit";
import { getSessionUser } from "../../../../lib/server/session";
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
@@ -13,14 +15,28 @@ interface PageProps {
params: Promise<{ shareSlug: string }>;
}
async function clientIp(): Promise<string> {
const headerStore = await headers();
return (
headerStore.get("x-forwarded-for")?.split(",")[0]?.trim() ||
headerStore.get("x-real-ip") ||
"unknown"
);
}
async function loadSharedRule(shareSlug: string) {
if (!isShareSlug(shareSlug)) return null;
const ip = await clientIp();
if (!isShareSlug(shareSlug)) {
rateLimitKey(`share-lookup-miss:${ip}`, 1_000);
return null;
}
const user = await getSessionUser();
return getReadablePublishedRule({
idOrSlug: shareSlug,
user,
viaShareSlug: true,
requestPath: `/r/${shareSlug}`,
failedLookupKey: ip,
});
}
+7 -1
View File
@@ -52,6 +52,7 @@ export const GET = apiRoute<RouteContext>(
document: true,
createdAt: true,
userId: true,
exportTokenVersion: true,
},
});
if (!row) return notFound();
@@ -60,7 +61,12 @@ export const GET = apiRoute<RouteContext>(
let tokenOk = false;
if (token.length > 0) {
try {
tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper());
tokenOk = ruleExportTokenMatches(
row.id,
token,
getSessionPepper(),
row.exportTokenVersion,
);
} catch {
tokenOk = false;
}
@@ -42,6 +42,10 @@ export const DELETE = apiRoute<RouteContext>(
}
await prisma.ruleStakeholder.delete({ where: { id: row.id } });
await prisma.publishedRule.update({
where: { id: ruleId },
data: { exportTokenVersion: { increment: 1 } },
});
return NextResponse.json({ ok: true });
},
+14 -1
View File
@@ -8,6 +8,7 @@ import {
} from "../publishedRuleAccess";
import { prisma } from "./db";
import { isDatabaseConfigured } from "./env";
import { rateLimitKey } from "./rateLimit";
import { browserHoldsClaimForHash } from "./guestRuleClaim";
import { isRuleAdminEmail } from "./ruleAdmins";
import { logAdminRuleRead } from "./adminRuleReadLog";
@@ -140,12 +141,16 @@ async function resolveAccessForRow(opts: {
* invalidates it. Returns `null` for missing rows, denied readers, and DB
* failures — callers render the same 404 as a missing Rule.
*/
const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
export async function getReadablePublishedRule(opts: {
idOrSlug: string;
user: User | null;
viaShareSlug: boolean;
requestPath: string;
lookup?: "id" | "shareSlug";
/** Client IP (or similar) used to slow failed `/r/{slug}` guesses. */
failedLookupKey?: string;
}): Promise<ReadablePublishedRule | null> {
if (!isDatabaseConfigured()) return null;
const idOrSlug = opts.idOrSlug.trim();
@@ -162,7 +167,15 @@ export async function getReadablePublishedRule(opts: {
where: { id: idOrSlug },
select: RULE_ACCESS_SELECT,
});
if (!row) return null;
if (!row) {
if (lookup === "shareSlug" && opts.failedLookupKey) {
rateLimitKey(
`share-lookup-miss:${opts.failedLookupKey}`,
SHARE_LOOKUP_MISS_INTERVAL_MS,
);
}
return null;
}
return resolveAccessForRow({
row,
viaShareSlug: opts.viaShareSlug,
+42 -6
View File
@@ -1,19 +1,55 @@
import { createHmac, timingSafeEqual } from "crypto";
export function ruleExportToken(ruleId: string, pepper: string): string {
/** How long a mailed export link stays valid after it is issued. */
export const RULE_EXPORT_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000;
function signExportMac(
ruleId: string,
version: number,
exp: number,
pepper: string,
): string {
return createHmac("sha256", pepper)
.update(`rule-export:${ruleId}`)
.update(`rule-export:${ruleId}:${version}:${exp}`)
.digest("base64url");
}
function timingSafeStringEqual(left: string, right: string): boolean {
const expected = Buffer.from(left);
const actual = Buffer.from(right);
if (expected.length !== actual.length) return false;
return timingSafeEqual(expected, actual);
}
export function ruleExportToken(
ruleId: string,
pepper: string,
version: number,
now = new Date(),
): string {
const exp = Math.floor((now.getTime() + RULE_EXPORT_TOKEN_TTL_MS) / 1000);
const mac = signExportMac(ruleId, version, exp, pepper);
return `${exp}.${version}.${mac}`;
}
export function ruleExportTokenMatches(
ruleId: string,
token: string,
pepper: string,
version: number,
now = new Date(),
): boolean {
if (token.length === 0) return false;
const expected = Buffer.from(ruleExportToken(ruleId, pepper));
const actual = Buffer.from(token);
if (expected.length !== actual.length) return false;
return timingSafeEqual(expected, actual);
const parts = token.split(".");
if (parts.length !== 3) return false;
const exp = Number(parts[0]);
const tokenVersion = Number(parts[1]);
const mac = parts[2] ?? "";
if (!Number.isFinite(exp) || !Number.isInteger(tokenVersion) || mac.length === 0) {
return false;
}
if (tokenVersion !== version) return false;
if (exp * 1000 <= now.getTime()) return false;
const expected = signExportMac(ruleId, version, exp, pepper);
return timingSafeStringEqual(expected, mac);
}
+2 -1
View File
@@ -46,6 +46,7 @@ export async function sendDueRuleFollowUpEmails(
select: {
id: true,
title: true,
exportTokenVersion: true,
user: { select: { email: true } },
},
});
@@ -66,7 +67,7 @@ export async function sendDueRuleFollowUpEmails(
continue;
}
const token = ruleExportToken(row.id, pepper);
const token = ruleExportToken(row.id, pepper, row.exportTokenVersion);
try {
await sendRuleFollowUpEmail({
to: email,
+7
View File
@@ -147,11 +147,18 @@ export async function patchOwnedRuleShare(opts: {
shareSlug = await allocateShareSlug();
}
const turningLinkOff =
opts.visibility === RULE_VISIBILITY.private &&
row.visibility !== RULE_VISIBILITY.private;
await prisma.publishedRule.update({
where: { id: row.id },
data: {
visibility: opts.visibility,
shareSlug,
...(turningLinkOff
? { exportTokenVersion: { increment: 1 } }
: {}),
},
});
+44
View File
@@ -24,9 +24,41 @@ const svgrLoaderOptions = {
},
};
function umamiOrigin() {
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
if (!src) return "";
try {
return new URL(src).origin;
} catch {
return "";
}
}
function contentSecurityPolicy() {
const umami = umamiOrigin();
const scriptSrc = umami
? `'self' 'unsafe-inline' ${umami}`
: `'self' 'unsafe-inline'`;
const connectSrc = umami ? `'self' ${umami}` : `'self'`;
return [
"default-src 'self'",
`script-src ${scriptSrc}`,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob:",
"font-src 'self'",
`connect-src ${connectSrc}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
"upgrade-insecure-requests",
].join("; ");
}
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
poweredByHeader: false,
serverExternalPackages: ["@prisma/client"],
// React Compiler — annotation mode: opt-in via the `"use memo"` directive at
// the top of a component/hook. With no annotations in the codebase yet, this
@@ -102,6 +134,18 @@ const nextConfig = {
key: "X-XSS-Protection",
value: "1; mode=block",
},
{
key: "Referrer-Policy",
value: "same-origin",
},
{
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=()",
},
{
key: "Content-Security-Policy",
value: contentSecurityPolicy(),
},
],
},
{
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "PublishedRule" ADD COLUMN "exportTokenVersion" INTEGER NOT NULL DEFAULT 0;
+3
View File
@@ -101,6 +101,9 @@ model PublishedRule {
/// Set when the 48-hour print follow-up has been sent, or when a Rule
/// finished more than seven days before this mail existed and will not be sent.
followUpEmailSentAt DateTime?
/// Bumped when a share link is turned off or a reader is removed so mailed
/// export links stop working.
exportTokenVersion Int @default(0)
stakeholders RuleStakeholder[]
uploads Upload[]
+9
View File
@@ -10,6 +10,15 @@ vi.mock("next/navigation", () => ({
notFound: () => notFoundMock(),
}));
vi.mock("next/headers", () => ({
headers: async () =>
new Headers({ "x-forwarded-for": "203.0.113.8" }),
}));
vi.mock("../../lib/server/rateLimit", () => ({
rateLimitKey: () => ({ ok: true }),
}));
vi.mock("../../lib/server/publishedRules", () => ({
getReadablePublishedRule: (...args: unknown[]) =>
getReadablePublishedRuleMock(...args),
+25
View File
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn();
const rateLimitKeyMock = vi.fn();
const findManyMock = vi.fn();
const stakeholderFindManyMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn();
@@ -12,6 +13,10 @@ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
}));
vi.mock("../../lib/server/rateLimit", () => ({
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
}));
vi.mock("../../lib/server/db", () => ({
prisma: {
publishedRule: {
@@ -71,9 +76,11 @@ beforeEach(() => {
browserHoldsClaimForHashMock.mockReset();
isRuleAdminEmailMock.mockReset();
logAdminRuleReadMock.mockReset();
rateLimitKeyMock.mockReset();
browserHoldsClaimForHashMock.mockResolvedValue(false);
isRuleAdminEmailMock.mockReturnValue(false);
logAdminRuleReadMock.mockResolvedValue(undefined);
rateLimitKeyMock.mockReturnValue({ ok: true });
});
describe("getReadablePublishedRule", () => {
@@ -220,6 +227,24 @@ describe("getReadablePublishedRule", () => {
}),
);
});
it("rate limits failed share-slug lookups", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(null);
expect(
await getReadablePublishedRule({
idOrSlug: "k7f2-9qxm",
user: null,
viaShareSlug: true,
requestPath: "/r/k7f2-9qxm",
failedLookupKey: "203.0.113.8",
}),
).toBeNull();
expect(rateLimitKeyMock).toHaveBeenCalledWith(
"share-lookup-miss:203.0.113.8",
1_000,
);
});
});
describe("listListedPublishedRules", () => {
+21 -7
View File
@@ -1,16 +1,30 @@
import { describe, expect, it } from "vitest";
import {
RULE_EXPORT_TOKEN_TTL_MS,
ruleExportToken,
ruleExportTokenMatches,
} from "../../lib/server/ruleExportToken";
describe("ruleExportToken", () => {
it("accepts the matching token and rejects another rule or token", () => {
const pepper = "test-pepper-16chars";
const token = ruleExportToken("rule-1", pepper);
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true);
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false);
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false);
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false);
const pepper = "test-pepper-16chars";
const now = new Date("2026-11-21T12:00:00.000Z");
it("accepts the matching token and rejects another rule, version, or token", () => {
const token = ruleExportToken("rule-1", pepper, 0, now);
expect(ruleExportTokenMatches("rule-1", token, pepper, 0, now)).toBe(true);
expect(ruleExportTokenMatches("rule-2", token, pepper, 0, now)).toBe(false);
expect(ruleExportTokenMatches("rule-1", token, pepper, 1, now)).toBe(false);
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper, 0, now)).toBe(
false,
);
expect(ruleExportTokenMatches("rule-1", "", pepper, 0, now)).toBe(false);
});
it("rejects a token after it expires", () => {
const token = ruleExportToken("rule-1", pepper, 0, now);
const afterExpiry = new Date(now.getTime() + RULE_EXPORT_TOKEN_TTL_MS + 1);
expect(
ruleExportTokenMatches("rule-1", token, pepper, 0, afterExpiry),
).toBe(false);
});
});
+4 -1
View File
@@ -49,6 +49,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{
id: "rule-1",
title: "Garden Norms",
exportTokenVersion: 0,
user: { email: "pen@example.com" },
},
]);
@@ -85,7 +86,7 @@ describe("sendDueRuleFollowUpEmails", () => {
it("skips rows with no mailbox and does not mark them sent", async () => {
findManyMock.mockResolvedValueOnce([
{ id: "rule-2", title: "Guest", user: { email: "" } },
{ id: "rule-2", title: "Guest", exportTokenVersion: 0, user: { email: "" } },
]);
const result = await sendDueRuleFollowUpEmails(db as never);
expect(result.skipped).toBe(1);
@@ -98,6 +99,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{
id: "rule-4",
title: "Race",
exportTokenVersion: 0,
user: { email: "pen@example.com" },
},
]);
@@ -112,6 +114,7 @@ describe("sendDueRuleFollowUpEmails", () => {
{
id: "rule-3",
title: "Retry",
exportTokenVersion: 0,
user: { email: "pen@example.com" },
},
]);
+1
View File
@@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => {
data: {
visibility: RULE_VISIBILITY.private,
shareSlug: null,
exportTokenVersion: { increment: 1 },
},
}),
);
+17 -1
View File
@@ -52,6 +52,7 @@ function row() {
},
createdAt: new Date("2026-11-08T00:00:00.000Z"),
userId: "user-1",
exportTokenVersion: 0,
};
}
@@ -86,7 +87,7 @@ describe("GET /api/rules/[id]/export/[format]", () => {
});
it("returns a PDF attachment when the export token matches", async () => {
const token = ruleExportToken("rule-1", PEPPER);
const token = ruleExportToken("rule-1", PEPPER, 0);
const res = await GET(
new NextRequest(
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
@@ -117,4 +118,19 @@ describe("GET /api/rules/[id]/export/[format]", () => {
expect(text).toContain("# Garden Norms");
expect(text).toContain("## Shared terms");
});
it("rejects a mailed token after the share link is turned off", async () => {
const token = ruleExportToken("rule-1", PEPPER, 0);
findUniqueMock.mockResolvedValueOnce({
...row(),
exportTokenVersion: 1,
});
const res = await GET(
new NextRequest(
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
),
makeContext("rule-1", "pdf"),
);
expect(res.status).toBe(401);
});
});
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
const findFirstRuleMock = vi.fn();
const publishedRuleUpdateMock = vi.fn();
const findFirstStakeholderMock = vi.fn();
const countMock = vi.fn();
const deleteMock = vi.fn();
@@ -20,6 +21,7 @@ vi.mock("../../lib/server/db", () => ({
prisma: {
publishedRule: {
findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
update: (...args: unknown[]) => publishedRuleUpdateMock(...args),
},
ruleStakeholder: {
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
@@ -67,6 +69,7 @@ const memberCtx = {
beforeEach(() => {
findFirstRuleMock.mockReset();
publishedRuleUpdateMock.mockReset();
findFirstStakeholderMock.mockReset();
countMock.mockReset();
deleteMock.mockReset();
@@ -177,6 +180,10 @@ describe("DELETE /api/rules/[id]/stakeholders/[stakeholderId]", () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
expect(publishedRuleUpdateMock).toHaveBeenCalledWith({
where: { id: "rule-1" },
data: { exportTokenVersion: { increment: 1 } },
});
});
});
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import nextConfig from "../../next.config.mjs";
describe("security headers", () => {
it("drops X-Powered-By and sends a same-origin CSP", async () => {
expect(nextConfig.poweredByHeader).toBe(false);
const rows = await nextConfig.headers();
const globalHeaders = rows.find((row) => row.source === "/(.*)")?.headers;
expect(globalHeaders).toBeDefined();
const byKey = Object.fromEntries(
(globalHeaders ?? []).map((header) => [header.key, header.value]),
);
expect(byKey["Content-Security-Policy"]).toContain("default-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("script-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("style-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("font-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("img-src 'self'");
expect(byKey["Permissions-Policy"]).toBe(
"camera=(), microphone=(), geolocation=()",
);
expect(byKey["Referrer-Policy"]).toBe("same-origin");
});
});