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:
1 parent
0fe2624002
commit
75649a9a42
18 files changed
+249
-19
No files matched your search
@@ -1,8 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
|
import { headers } from "next/headers";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import messages from "../../../../messages/en/index";
|
import messages from "../../../../messages/en/index";
|
||||||
import { isShareSlug } from "../../../../lib/sharePaths";
|
import { isShareSlug } from "../../../../lib/sharePaths";
|
||||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
||||||
|
import { rateLimitKey } from "../../../../lib/server/rateLimit";
|
||||||
import { getSessionUser } from "../../../../lib/server/session";
|
import { getSessionUser } from "../../../../lib/server/session";
|
||||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
||||||
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
|
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
|
||||||
@@ -13,14 +15,28 @@ interface PageProps {
|
|||||||
params: Promise<{ shareSlug: string }>;
|
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) {
|
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();
|
const user = await getSessionUser();
|
||||||
return getReadablePublishedRule({
|
return getReadablePublishedRule({
|
||||||
idOrSlug: shareSlug,
|
idOrSlug: shareSlug,
|
||||||
user,
|
user,
|
||||||
viaShareSlug: true,
|
viaShareSlug: true,
|
||||||
requestPath: `/r/${shareSlug}`,
|
requestPath: `/r/${shareSlug}`,
|
||||||
|
failedLookupKey: ip,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ export const GET = apiRoute<RouteContext>(
|
|||||||
document: true,
|
document: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
userId: true,
|
userId: true,
|
||||||
|
exportTokenVersion: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!row) return notFound();
|
if (!row) return notFound();
|
||||||
@@ -60,7 +61,12 @@ export const GET = apiRoute<RouteContext>(
|
|||||||
let tokenOk = false;
|
let tokenOk = false;
|
||||||
if (token.length > 0) {
|
if (token.length > 0) {
|
||||||
try {
|
try {
|
||||||
tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper());
|
tokenOk = ruleExportTokenMatches(
|
||||||
|
row.id,
|
||||||
|
token,
|
||||||
|
getSessionPepper(),
|
||||||
|
row.exportTokenVersion,
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
tokenOk = false;
|
tokenOk = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ export const DELETE = apiRoute<RouteContext>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
await prisma.ruleStakeholder.delete({ where: { id: row.id } });
|
await prisma.ruleStakeholder.delete({ where: { id: row.id } });
|
||||||
|
await prisma.publishedRule.update({
|
||||||
|
where: { id: ruleId },
|
||||||
|
data: { exportTokenVersion: { increment: 1 } },
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
} from "../publishedRuleAccess";
|
} from "../publishedRuleAccess";
|
||||||
import { prisma } from "./db";
|
import { prisma } from "./db";
|
||||||
import { isDatabaseConfigured } from "./env";
|
import { isDatabaseConfigured } from "./env";
|
||||||
|
import { rateLimitKey } from "./rateLimit";
|
||||||
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
||||||
import { isRuleAdminEmail } from "./ruleAdmins";
|
import { isRuleAdminEmail } from "./ruleAdmins";
|
||||||
import { logAdminRuleRead } from "./adminRuleReadLog";
|
import { logAdminRuleRead } from "./adminRuleReadLog";
|
||||||
@@ -140,12 +141,16 @@ async function resolveAccessForRow(opts: {
|
|||||||
* invalidates it. Returns `null` for missing rows, denied readers, and DB
|
* invalidates it. Returns `null` for missing rows, denied readers, and DB
|
||||||
* failures — callers render the same 404 as a missing Rule.
|
* failures — callers render the same 404 as a missing Rule.
|
||||||
*/
|
*/
|
||||||
|
const SHARE_LOOKUP_MISS_INTERVAL_MS = 1_000;
|
||||||
|
|
||||||
export async function getReadablePublishedRule(opts: {
|
export async function getReadablePublishedRule(opts: {
|
||||||
idOrSlug: string;
|
idOrSlug: string;
|
||||||
user: User | null;
|
user: User | null;
|
||||||
viaShareSlug: boolean;
|
viaShareSlug: boolean;
|
||||||
requestPath: string;
|
requestPath: string;
|
||||||
lookup?: "id" | "shareSlug";
|
lookup?: "id" | "shareSlug";
|
||||||
|
/** Client IP (or similar) used to slow failed `/r/{slug}` guesses. */
|
||||||
|
failedLookupKey?: string;
|
||||||
}): Promise<ReadablePublishedRule | null> {
|
}): Promise<ReadablePublishedRule | null> {
|
||||||
if (!isDatabaseConfigured()) return null;
|
if (!isDatabaseConfigured()) return null;
|
||||||
const idOrSlug = opts.idOrSlug.trim();
|
const idOrSlug = opts.idOrSlug.trim();
|
||||||
@@ -162,7 +167,15 @@ export async function getReadablePublishedRule(opts: {
|
|||||||
where: { id: idOrSlug },
|
where: { id: idOrSlug },
|
||||||
select: RULE_ACCESS_SELECT,
|
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({
|
return resolveAccessForRow({
|
||||||
row,
|
row,
|
||||||
viaShareSlug: opts.viaShareSlug,
|
viaShareSlug: opts.viaShareSlug,
|
||||||
|
|||||||
@@ -1,19 +1,55 @@
|
|||||||
import { createHmac, timingSafeEqual } from "crypto";
|
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)
|
return createHmac("sha256", pepper)
|
||||||
.update(`rule-export:${ruleId}`)
|
.update(`rule-export:${ruleId}:${version}:${exp}`)
|
||||||
.digest("base64url");
|
.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(
|
export function ruleExportTokenMatches(
|
||||||
ruleId: string,
|
ruleId: string,
|
||||||
token: string,
|
token: string,
|
||||||
pepper: string,
|
pepper: string,
|
||||||
|
version: number,
|
||||||
|
now = new Date(),
|
||||||
): boolean {
|
): boolean {
|
||||||
if (token.length === 0) return false;
|
if (token.length === 0) return false;
|
||||||
const expected = Buffer.from(ruleExportToken(ruleId, pepper));
|
const parts = token.split(".");
|
||||||
const actual = Buffer.from(token);
|
if (parts.length !== 3) return false;
|
||||||
if (expected.length !== actual.length) return false;
|
const exp = Number(parts[0]);
|
||||||
return timingSafeEqual(expected, actual);
|
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);
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,7 @@ export async function sendDueRuleFollowUpEmails(
|
|||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
title: true,
|
title: true,
|
||||||
|
exportTokenVersion: true,
|
||||||
user: { select: { email: true } },
|
user: { select: { email: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -66,7 +67,7 @@ export async function sendDueRuleFollowUpEmails(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = ruleExportToken(row.id, pepper);
|
const token = ruleExportToken(row.id, pepper, row.exportTokenVersion);
|
||||||
try {
|
try {
|
||||||
await sendRuleFollowUpEmail({
|
await sendRuleFollowUpEmail({
|
||||||
to: email,
|
to: email,
|
||||||
|
|||||||
@@ -147,11 +147,18 @@ export async function patchOwnedRuleShare(opts: {
|
|||||||
shareSlug = await allocateShareSlug();
|
shareSlug = await allocateShareSlug();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const turningLinkOff =
|
||||||
|
opts.visibility === RULE_VISIBILITY.private &&
|
||||||
|
row.visibility !== RULE_VISIBILITY.private;
|
||||||
|
|
||||||
await prisma.publishedRule.update({
|
await prisma.publishedRule.update({
|
||||||
where: { id: row.id },
|
where: { id: row.id },
|
||||||
data: {
|
data: {
|
||||||
visibility: opts.visibility,
|
visibility: opts.visibility,
|
||||||
shareSlug,
|
shareSlug,
|
||||||
|
...(turningLinkOff
|
||||||
|
? { exportTokenVersion: { increment: 1 } }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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} */
|
/** @type {import('next').NextConfig} */
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
|
poweredByHeader: false,
|
||||||
serverExternalPackages: ["@prisma/client"],
|
serverExternalPackages: ["@prisma/client"],
|
||||||
// React Compiler — annotation mode: opt-in via the `"use memo"` directive at
|
// 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
|
// the top of a component/hook. With no annotations in the codebase yet, this
|
||||||
@@ -102,6 +134,18 @@ const nextConfig = {
|
|||||||
key: "X-XSS-Protection",
|
key: "X-XSS-Protection",
|
||||||
value: "1; mode=block",
|
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;
|
||||||
@@ -101,6 +101,9 @@ model PublishedRule {
|
|||||||
/// Set when the 48-hour print follow-up has been sent, or when a Rule
|
/// 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.
|
/// finished more than seven days before this mail existed and will not be sent.
|
||||||
followUpEmailSentAt DateTime?
|
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[]
|
stakeholders RuleStakeholder[]
|
||||||
uploads Upload[]
|
uploads Upload[]
|
||||||
|
|||||||
@@ -10,6 +10,15 @@ vi.mock("next/navigation", () => ({
|
|||||||
notFound: () => notFoundMock(),
|
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", () => ({
|
vi.mock("../../lib/server/publishedRules", () => ({
|
||||||
getReadablePublishedRule: (...args: unknown[]) =>
|
getReadablePublishedRule: (...args: unknown[]) =>
|
||||||
getReadablePublishedRuleMock(...args),
|
getReadablePublishedRuleMock(...args),
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
const isDatabaseConfiguredMock = vi.fn();
|
const isDatabaseConfiguredMock = vi.fn();
|
||||||
const findUniqueMock = vi.fn();
|
const findUniqueMock = vi.fn();
|
||||||
|
const rateLimitKeyMock = vi.fn();
|
||||||
const findManyMock = vi.fn();
|
const findManyMock = vi.fn();
|
||||||
const stakeholderFindManyMock = vi.fn();
|
const stakeholderFindManyMock = vi.fn();
|
||||||
const browserHoldsClaimForHashMock = vi.fn();
|
const browserHoldsClaimForHashMock = vi.fn();
|
||||||
@@ -12,6 +13,10 @@ vi.mock("../../lib/server/env", () => ({
|
|||||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/rateLimit", () => ({
|
||||||
|
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("../../lib/server/db", () => ({
|
vi.mock("../../lib/server/db", () => ({
|
||||||
prisma: {
|
prisma: {
|
||||||
publishedRule: {
|
publishedRule: {
|
||||||
@@ -71,9 +76,11 @@ beforeEach(() => {
|
|||||||
browserHoldsClaimForHashMock.mockReset();
|
browserHoldsClaimForHashMock.mockReset();
|
||||||
isRuleAdminEmailMock.mockReset();
|
isRuleAdminEmailMock.mockReset();
|
||||||
logAdminRuleReadMock.mockReset();
|
logAdminRuleReadMock.mockReset();
|
||||||
|
rateLimitKeyMock.mockReset();
|
||||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||||
isRuleAdminEmailMock.mockReturnValue(false);
|
isRuleAdminEmailMock.mockReturnValue(false);
|
||||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||||
|
rateLimitKeyMock.mockReturnValue({ ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("getReadablePublishedRule", () => {
|
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", () => {
|
describe("listListedPublishedRules", () => {
|
||||||
|
|||||||
@@ -1,16 +1,30 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
|
RULE_EXPORT_TOKEN_TTL_MS,
|
||||||
ruleExportToken,
|
ruleExportToken,
|
||||||
ruleExportTokenMatches,
|
ruleExportTokenMatches,
|
||||||
} from "../../lib/server/ruleExportToken";
|
} from "../../lib/server/ruleExportToken";
|
||||||
|
|
||||||
describe("ruleExportToken", () => {
|
describe("ruleExportToken", () => {
|
||||||
it("accepts the matching token and rejects another rule or token", () => {
|
const pepper = "test-pepper-16chars";
|
||||||
const pepper = "test-pepper-16chars";
|
const now = new Date("2026-11-21T12:00:00.000Z");
|
||||||
const token = ruleExportToken("rule-1", pepper);
|
|
||||||
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true);
|
it("accepts the matching token and rejects another rule, version, or token", () => {
|
||||||
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false);
|
const token = ruleExportToken("rule-1", pepper, 0, now);
|
||||||
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false);
|
expect(ruleExportTokenMatches("rule-1", token, pepper, 0, now)).toBe(true);
|
||||||
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false);
|
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);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -49,6 +49,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
|||||||
{
|
{
|
||||||
id: "rule-1",
|
id: "rule-1",
|
||||||
title: "Garden Norms",
|
title: "Garden Norms",
|
||||||
|
exportTokenVersion: 0,
|
||||||
user: { email: "pen@example.com" },
|
user: { email: "pen@example.com" },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -85,7 +86,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
|||||||
|
|
||||||
it("skips rows with no mailbox and does not mark them sent", async () => {
|
it("skips rows with no mailbox and does not mark them sent", async () => {
|
||||||
findManyMock.mockResolvedValueOnce([
|
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);
|
const result = await sendDueRuleFollowUpEmails(db as never);
|
||||||
expect(result.skipped).toBe(1);
|
expect(result.skipped).toBe(1);
|
||||||
@@ -98,6 +99,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
|||||||
{
|
{
|
||||||
id: "rule-4",
|
id: "rule-4",
|
||||||
title: "Race",
|
title: "Race",
|
||||||
|
exportTokenVersion: 0,
|
||||||
user: { email: "pen@example.com" },
|
user: { email: "pen@example.com" },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
@@ -112,6 +114,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
|||||||
{
|
{
|
||||||
id: "rule-3",
|
id: "rule-3",
|
||||||
title: "Retry",
|
title: "Retry",
|
||||||
|
exportTokenVersion: 0,
|
||||||
user: { email: "pen@example.com" },
|
user: { email: "pen@example.com" },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => {
|
|||||||
data: {
|
data: {
|
||||||
visibility: RULE_VISIBILITY.private,
|
visibility: RULE_VISIBILITY.private,
|
||||||
shareSlug: null,
|
shareSlug: null,
|
||||||
|
exportTokenVersion: { increment: 1 },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ function row() {
|
|||||||
},
|
},
|
||||||
createdAt: new Date("2026-11-08T00:00:00.000Z"),
|
createdAt: new Date("2026-11-08T00:00:00.000Z"),
|
||||||
userId: "user-1",
|
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 () => {
|
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(
|
const res = await GET(
|
||||||
new NextRequest(
|
new NextRequest(
|
||||||
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
|
`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("# Garden Norms");
|
||||||
expect(text).toContain("## Shared terms");
|
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";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
const findFirstRuleMock = vi.fn();
|
const findFirstRuleMock = vi.fn();
|
||||||
|
const publishedRuleUpdateMock = vi.fn();
|
||||||
const findFirstStakeholderMock = vi.fn();
|
const findFirstStakeholderMock = vi.fn();
|
||||||
const countMock = vi.fn();
|
const countMock = vi.fn();
|
||||||
const deleteMock = vi.fn();
|
const deleteMock = vi.fn();
|
||||||
@@ -20,6 +21,7 @@ vi.mock("../../lib/server/db", () => ({
|
|||||||
prisma: {
|
prisma: {
|
||||||
publishedRule: {
|
publishedRule: {
|
||||||
findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
|
findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
|
||||||
|
update: (...args: unknown[]) => publishedRuleUpdateMock(...args),
|
||||||
},
|
},
|
||||||
ruleStakeholder: {
|
ruleStakeholder: {
|
||||||
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
|
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
|
||||||
@@ -67,6 +69,7 @@ const memberCtx = {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
findFirstRuleMock.mockReset();
|
findFirstRuleMock.mockReset();
|
||||||
|
publishedRuleUpdateMock.mockReset();
|
||||||
findFirstStakeholderMock.mockReset();
|
findFirstStakeholderMock.mockReset();
|
||||||
countMock.mockReset();
|
countMock.mockReset();
|
||||||
deleteMock.mockReset();
|
deleteMock.mockReset();
|
||||||
@@ -177,6 +180,10 @@ describe("DELETE /api/rules/[id]/stakeholders/[stakeholderId]", () => {
|
|||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(await res.json()).toEqual({ ok: true });
|
expect(await res.json()).toEqual({ ok: true });
|
||||||
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
|
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
|
||||||
|
expect(publishedRuleUpdateMock).toHaveBeenCalledWith({
|
||||||
|
where: { id: "rule-1" },
|
||||||
|
data: { exportTokenVersion: { increment: 1 } },
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user