Keep finished Rules private until a rotating share link is on, and delete files with the Rule #102
No files matched your search
@@ -46,6 +46,9 @@ NEXT_PUBLIC_ENABLE_BACKEND_SYNC=
|
||||
# SITE_INDEXING=true
|
||||
# SITE_INDEXING=false
|
||||
|
||||
# Named admins who may open a private Rule. Comma-separated emails. Every such read is logged.
|
||||
# RULE_ADMIN_EMAILS=ops@example.org
|
||||
|
||||
# Writable directory for `POST /api/uploads` (community photo + custom-method attachments).
|
||||
# In production (e.g. Cloudron localstorage mount), set to the mounted path. Local dev example:
|
||||
# UPLOAD_ROOT="/absolute/path/to/community-rule/var/uploads"
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import messages from "../../../../messages/en/index";
|
||||
import { isShareSlug } from "../../../../lib/sharePaths";
|
||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
||||
import { getSessionUser } from "../../../../lib/server/session";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
||||
import { NO_INDEX_ROBOTS, routeMetadata } from "../../../../lib/siteMetadata";
|
||||
import CommunityRule from "../../../components/type/CommunityRule";
|
||||
import HeaderLockup from "../../../components/type/HeaderLockup";
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ shareSlug: string }>;
|
||||
}
|
||||
|
||||
async function loadSharedRule(shareSlug: string) {
|
||||
if (!isShareSlug(shareSlug)) return null;
|
||||
const user = await getSessionUser();
|
||||
return getReadablePublishedRule({
|
||||
idOrSlug: shareSlug,
|
||||
user,
|
||||
viaShareSlug: true,
|
||||
requestPath: `/r/${shareSlug}`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { shareSlug } = await params;
|
||||
const resolved = await loadSharedRule(shareSlug);
|
||||
if (!resolved) {
|
||||
return {
|
||||
title: messages.pages.ruleDetail.notFoundTitle,
|
||||
description: "The requested CommunityRule could not be found.",
|
||||
};
|
||||
}
|
||||
const { rule } = resolved;
|
||||
const description =
|
||||
typeof rule.summary === "string" && rule.summary.trim().length > 0
|
||||
? rule.summary
|
||||
: undefined;
|
||||
return routeMetadata(`/r/${shareSlug}`, {
|
||||
title: rule.title,
|
||||
description,
|
||||
robots: NO_INDEX_ROBOTS,
|
||||
openGraph: {
|
||||
title: rule.title,
|
||||
description,
|
||||
type: "article",
|
||||
url: `/r/${shareSlug}`,
|
||||
siteName: messages.metadata.siteName,
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: rule.title,
|
||||
description,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export default async function SharedRuleDetailPage({ params }: PageProps) {
|
||||
const { shareSlug } = await params;
|
||||
const resolved = await loadSharedRule(shareSlug);
|
||||
if (!resolved) {
|
||||
notFound();
|
||||
}
|
||||
const { rule } = resolved;
|
||||
|
||||
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
const description =
|
||||
typeof rule.summary === "string" && rule.summary.trim().length > 0
|
||||
? rule.summary
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<article className="min-h-screen bg-[var(--color-teal-teal50,#c9fef9)]">
|
||||
<div className="mx-auto flex max-w-[1200px] flex-col gap-[var(--space-1200)] px-5 py-[var(--space-1200)] md:px-12 md:py-[var(--space-1800)]">
|
||||
<HeaderLockup
|
||||
title={rule.title}
|
||||
description={description}
|
||||
justification="left"
|
||||
size="L"
|
||||
palette="inverse"
|
||||
/>
|
||||
<CommunityRule sections={sections} />
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import messages from "../../../../messages/en/index";
|
||||
import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules";
|
||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
||||
import { getSessionUser } from "../../../../lib/server/session";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
|
||||
import {
|
||||
robotsForPublishedRule,
|
||||
@@ -14,17 +15,28 @@ interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
async function loadReadableRule(id: string) {
|
||||
const user = await getSessionUser();
|
||||
return getReadablePublishedRule({
|
||||
idOrSlug: id,
|
||||
user,
|
||||
viaShareSlug: false,
|
||||
requestPath: `/rules/${id}`,
|
||||
});
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: PageProps): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
const rule = await getPublicPublishedRuleById(id);
|
||||
if (!rule) {
|
||||
const resolved = await loadReadableRule(id);
|
||||
if (!resolved) {
|
||||
return {
|
||||
title: messages.pages.ruleDetail.notFoundTitle,
|
||||
description: "The requested CommunityRule could not be found.",
|
||||
};
|
||||
}
|
||||
const { rule } = resolved;
|
||||
const description =
|
||||
typeof rule.summary === "string" && rule.summary.trim().length > 0
|
||||
? rule.summary
|
||||
@@ -51,10 +63,11 @@ export async function generateMetadata({
|
||||
|
||||
export default async function PublicRuleDetailPage({ params }: PageProps) {
|
||||
const { id } = await params;
|
||||
const rule = await getPublicPublishedRuleById(id);
|
||||
if (!rule) {
|
||||
const resolved = await loadReadableRule(id);
|
||||
if (!resolved) {
|
||||
notFound();
|
||||
}
|
||||
const { rule } = resolved;
|
||||
|
||||
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
const description =
|
||||
|
||||
@@ -11,6 +11,8 @@ import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||
import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
|
||||
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
|
||||
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
|
||||
import { deleteUploadsForDraft } from "../../../../lib/server/uploads/deleteUploadedFiles";
|
||||
import { linkUploadsToDraft } from "../../../../lib/server/uploads/linkUploads";
|
||||
|
||||
export const GET = apiRoute("drafts.me.get", async () => {
|
||||
if (!isDatabaseConfigured()) {
|
||||
@@ -67,6 +69,11 @@ export const PUT = apiRoute("drafts.me.put", async (request: NextRequest) => {
|
||||
payload: jsonPayload,
|
||||
},
|
||||
});
|
||||
await linkUploadsToDraft({
|
||||
draftId: draft.id,
|
||||
payload,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
draft: { payload: draft.payload, updatedAt: draft.updatedAt },
|
||||
@@ -85,6 +92,13 @@ export const DELETE = apiRoute("drafts.me.delete", async () => {
|
||||
|
||||
// Idempotent: missing draft is a no-op so callers can fire-and-forget after
|
||||
// publish / exit without worrying about prior state.
|
||||
const draft = await prisma.ruleDraft.findUnique({
|
||||
where: { userId: user.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (draft) {
|
||||
await deleteUploadsForDraft(draft.id);
|
||||
}
|
||||
await prisma.ruleDraft.deleteMany({ where: { userId: user.id } });
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
|
||||
+22
-16
@@ -8,9 +8,11 @@ import {
|
||||
notFound,
|
||||
unauthorized,
|
||||
} from "../../../../lib/server/responses";
|
||||
import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules";
|
||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
||||
import { getSessionUser } from "../../../../lib/server/session";
|
||||
import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||
import { deleteUploadsForRule } from "../../../../lib/server/uploads/deleteUploadedFiles";
|
||||
import { linkUploadsToRule } from "../../../../lib/server/uploads/linkUploads";
|
||||
import { publishRuleBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
|
||||
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
|
||||
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
|
||||
@@ -19,29 +21,27 @@ type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiRoute<RouteContext>(
|
||||
"rules.byId",
|
||||
async (_request, context) => {
|
||||
async (request, context) => {
|
||||
if (!isDatabaseConfigured()) {
|
||||
return dbUnavailable();
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
|
||||
const rule = await getPublicPublishedRuleById(id);
|
||||
if (!rule) {
|
||||
const user = await getSessionUser();
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: id,
|
||||
user,
|
||||
viaShareSlug: false,
|
||||
requestPath: request.nextUrl.pathname,
|
||||
});
|
||||
if (!resolved) {
|
||||
return notFound();
|
||||
}
|
||||
|
||||
const user = await getSessionUser();
|
||||
let viewerIsOwner = false;
|
||||
if (user) {
|
||||
const ownerRow = await prisma.publishedRule.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
viewerIsOwner = ownerRow?.userId === user.id;
|
||||
}
|
||||
|
||||
return NextResponse.json({ rule, viewerIsOwner });
|
||||
return NextResponse.json({
|
||||
rule: resolved.rule,
|
||||
viewerIsOwner: resolved.viewerIsOwner,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -90,6 +90,11 @@ export const PATCH = apiRoute<RouteContext>(
|
||||
document: document as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
await linkUploadsToRule({
|
||||
ruleId: row.id,
|
||||
document,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
},
|
||||
@@ -120,6 +125,7 @@ export const DELETE = apiRoute<RouteContext>(
|
||||
return forbidden("You do not have permission to delete this rule");
|
||||
}
|
||||
|
||||
await deleteUploadsForRule(row.id);
|
||||
await prisma.publishedRule.delete({ where: { id: row.id } });
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
||||
import { isDatabaseConfigured } from "../../../../../lib/server/env";
|
||||
import { getPublicOrigin } from "../../../../../lib/server/publicOrigin";
|
||||
import {
|
||||
dbUnavailable,
|
||||
errorJson,
|
||||
forbidden,
|
||||
notFound,
|
||||
unauthorized,
|
||||
} from "../../../../../lib/server/responses";
|
||||
import {
|
||||
getOwnedRuleShareSettings,
|
||||
patchOwnedRuleShare,
|
||||
} from "../../../../../lib/server/ruleShare";
|
||||
import { getSessionUser } from "../../../../../lib/server/session";
|
||||
import { patchRuleShareBodySchema } from "../../../../../lib/server/validation/createFlowSchemas";
|
||||
import { readLimitedJson } from "../../../../../lib/server/validation/requestBody";
|
||||
import { jsonFromZodError } from "../../../../../lib/server/validation/zodHttp";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = apiRoute<RouteContext>(
|
||||
"rules.share.get",
|
||||
async (request, context) => {
|
||||
if (!isDatabaseConfigured()) {
|
||||
return dbUnavailable();
|
||||
}
|
||||
const user = await getSessionUser();
|
||||
if (!user) {
|
||||
return unauthorized();
|
||||
}
|
||||
const { id } = await context.params;
|
||||
const settings = await getOwnedRuleShareSettings({
|
||||
ruleId: id,
|
||||
user,
|
||||
origin: getPublicOrigin(request),
|
||||
});
|
||||
if (settings === "not_found") return notFound();
|
||||
if (settings === "forbidden") {
|
||||
return forbidden("You do not have permission to share this rule");
|
||||
}
|
||||
return NextResponse.json({ share: settings });
|
||||
},
|
||||
);
|
||||
|
||||
export const PATCH = apiRoute<RouteContext>(
|
||||
"rules.share.patch",
|
||||
async (request: NextRequest, context) => {
|
||||
if (!isDatabaseConfigured()) {
|
||||
return dbUnavailable();
|
||||
}
|
||||
const user = await getSessionUser();
|
||||
if (!user) {
|
||||
return unauthorized();
|
||||
}
|
||||
const { id } = await context.params;
|
||||
const parsedBody = await readLimitedJson(request);
|
||||
if (parsedBody.ok === false) {
|
||||
return parsedBody.response;
|
||||
}
|
||||
const validated = patchRuleShareBodySchema.safeParse(parsedBody.value);
|
||||
if (!validated.success) {
|
||||
return jsonFromZodError(validated.error);
|
||||
}
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: id,
|
||||
user,
|
||||
origin: getPublicOrigin(request),
|
||||
visibility: validated.data.visibility,
|
||||
communityAgreed: validated.data.communityAgreed,
|
||||
});
|
||||
if (result.ok === false) {
|
||||
if (result.reason === "not_found") return notFound();
|
||||
if (result.reason === "community_agreed") {
|
||||
return errorJson(
|
||||
"validation_error",
|
||||
"Our community agreed to share this Rule is required.",
|
||||
400,
|
||||
);
|
||||
}
|
||||
return forbidden("You do not have permission to change this rule");
|
||||
}
|
||||
return NextResponse.json({ share: result.settings });
|
||||
},
|
||||
);
|
||||
@@ -25,6 +25,7 @@ import { stakeholderInviteVerifyUrl } from "../../../lib/server/ruleStakeholderI
|
||||
import { STAKEHOLDER_INVITE_TTL_MS } from "../../../lib/server/ruleStakeholders";
|
||||
import { getSessionUser } from "../../../lib/server/session";
|
||||
import { issueGuestRuleClaimCookie } from "../../../lib/server/guestRuleClaim";
|
||||
import { linkUploadsToRule } from "../../../lib/server/uploads/linkUploads";
|
||||
import { apiRoute } from "../../../lib/server/apiRoute";
|
||||
import { getPublicOrigin } from "../../../lib/server/publicOrigin";
|
||||
import {
|
||||
@@ -123,6 +124,12 @@ export const POST = apiRoute(
|
||||
});
|
||||
}
|
||||
|
||||
await linkUploadsToRule({
|
||||
ruleId: rule.id,
|
||||
document,
|
||||
userId: null,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
rule: {
|
||||
id: rule.id,
|
||||
@@ -155,6 +162,11 @@ export const POST = apiRoute(
|
||||
document: document as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
await linkUploadsToRule({
|
||||
ruleId: rule.id,
|
||||
document,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
rule: {
|
||||
@@ -241,6 +253,12 @@ export const POST = apiRoute(
|
||||
);
|
||||
}
|
||||
|
||||
await linkUploadsToRule({
|
||||
ruleId: rule.id,
|
||||
document,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
rule: {
|
||||
id: rule.id,
|
||||
|
||||
@@ -1,30 +1,91 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { NextResponse } from "next/server";
|
||||
import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||
import { prisma } from "../../../../lib/server/db";
|
||||
import { isDatabaseConfigured } from "../../../../lib/server/env";
|
||||
import {
|
||||
dbUnavailable,
|
||||
notFound,
|
||||
serverMisconfigured,
|
||||
} from "../../../../lib/server/responses";
|
||||
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
|
||||
import { getSessionUser } from "../../../../lib/server/session";
|
||||
import { isValidUploadFileId } from "../../../../lib/server/uploads/uploadConstants";
|
||||
import { resolveUploadedFileById } from "../../../../lib/server/uploads/resolveUploadedFile";
|
||||
import { getUploadRootFromEnv } from "../../../../lib/server/uploads/uploadRoot";
|
||||
import { browserHoldsUploadGrant } from "../../../../lib/server/uploads/uploadGrantCookie";
|
||||
import { RULE_VISIBILITY } from "../../../../lib/ruleVisibility";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* Public read for opaque upload ids (no auth). Unguessable UUID stem;
|
||||
* do not use for sensitive documents without revisiting policy.
|
||||
*/
|
||||
function cacheControlForVisibility(
|
||||
visibility: "private" | "shared_by_link" | "public_and_featured" | null,
|
||||
): string {
|
||||
if (visibility === RULE_VISIBILITY.public_and_featured) {
|
||||
return "public, max-age=3600";
|
||||
}
|
||||
return "private, no-store";
|
||||
}
|
||||
|
||||
export const GET = apiRoute<RouteContext>(
|
||||
"uploads.byId",
|
||||
async (_request, context) => {
|
||||
async (request, context) => {
|
||||
if (!getUploadRootFromEnv()) {
|
||||
return serverMisconfigured(
|
||||
"File uploads are not configured (UPLOAD_ROOT is unset).",
|
||||
);
|
||||
}
|
||||
if (!isDatabaseConfigured()) {
|
||||
return dbUnavailable();
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
const resolved = await resolveUploadedFileById(id);
|
||||
if (!isValidUploadFileId(id)) {
|
||||
return notFound("Upload not found");
|
||||
}
|
||||
|
||||
const row = await prisma.upload.findUnique({
|
||||
where: { id: id.toLowerCase() },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
draftId: true,
|
||||
ruleId: true,
|
||||
rule: { select: { visibility: true } },
|
||||
draft: { select: { userId: true } },
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
return notFound("Upload not found");
|
||||
}
|
||||
|
||||
const user = await getSessionUser();
|
||||
let allowed = false;
|
||||
let visibility: "private" | "shared_by_link" | "public_and_featured" | null =
|
||||
row.rule?.visibility ?? null;
|
||||
|
||||
if (row.ruleId) {
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: row.ruleId,
|
||||
user,
|
||||
viaShareSlug: visibility === RULE_VISIBILITY.shared_by_link,
|
||||
requestPath: request.nextUrl.pathname,
|
||||
});
|
||||
allowed = resolved != null;
|
||||
visibility = resolved?.visibility ?? visibility;
|
||||
} else if (row.draftId) {
|
||||
allowed = Boolean(user && row.draft?.userId === user.id);
|
||||
} else if (user && row.userId === user.id) {
|
||||
allowed = true;
|
||||
} else if (!user) {
|
||||
allowed = await browserHoldsUploadGrant(row.id);
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
return notFound("Upload not found");
|
||||
}
|
||||
|
||||
const resolved = await resolveUploadedFileById(row.id);
|
||||
if (!resolved) {
|
||||
return notFound("Upload not found");
|
||||
}
|
||||
@@ -34,7 +95,7 @@ export const GET = apiRoute<RouteContext>(
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": resolved.contentType,
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
"Cache-Control": cacheControlForVisibility(visibility),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getSessionUser } from "../../../lib/server/session";
|
||||
import { apiRoute } from "../../../lib/server/apiRoute";
|
||||
import { rateLimitKey } from "../../../lib/server/rateLimit";
|
||||
import { saveCreateFlowUpload } from "../../../lib/server/uploads/saveCreateFlowUpload";
|
||||
import { issueGuestUploadGrantCookie } from "../../../lib/server/uploads/uploadGrantCookie";
|
||||
import { getUploadRootFromEnv } from "../../../lib/server/uploads/uploadRoot";
|
||||
import {
|
||||
CREATE_FLOW_UPLOAD_MAX_BYTES,
|
||||
@@ -146,6 +147,7 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
|
||||
const saved = await saveCreateFlowUpload({
|
||||
purpose: purposeRaw,
|
||||
buffer: buf,
|
||||
userId: user?.id ?? null,
|
||||
});
|
||||
|
||||
if ("error" in saved) {
|
||||
@@ -171,6 +173,14 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
try {
|
||||
await issueGuestUploadGrantCookie(saved.id);
|
||||
} catch {
|
||||
// Cookie is best-effort; the file is already stored.
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
url: saved.urlPath,
|
||||
id: saved.id,
|
||||
|
||||
@@ -11,15 +11,13 @@ import {
|
||||
getSessionUser,
|
||||
} from "../../../../lib/server/session";
|
||||
import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||
import { deleteUploadsForUser } from "../../../../lib/server/uploads/deleteUploadedFiles";
|
||||
|
||||
/**
|
||||
* Delete the signed-in user and associated data.
|
||||
*
|
||||
* **Policy (CR-86 / Ticket 15):** Prisma `User` deletion cascades `Session` and
|
||||
* `RuleDraft`. `PublishedRule` uses `onDelete: SetNull` on `userId`, so published
|
||||
* rules remain public with `userId = null` (anonymous/orphan rows) rather than
|
||||
* being removed with the account. Change would require a schema migration if
|
||||
* product later requires deleting all published rules with the user.
|
||||
* Prisma `User` deletion cascades `Session`, `RuleDraft`, and `PublishedRule`
|
||||
* (and uploads linked to those rows). Disk files are removed first.
|
||||
*/
|
||||
export const DELETE = apiRoute("user.me.delete", async () => {
|
||||
if (!isDatabaseConfigured()) {
|
||||
@@ -32,6 +30,7 @@ export const DELETE = apiRoute("user.me.delete", async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteUploadsForUser(user.id);
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
} catch {
|
||||
return internalError("Failed to delete account");
|
||||
|
||||
@@ -8,10 +8,12 @@ import type {
|
||||
import type { StoredLastPublishedRule } from "./lastPublishedRule";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
|
||||
|
||||
export function buildPublicRuleUrl(origin: string, ruleId: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}/rules/${encodeURIComponent(ruleId)}`;
|
||||
}
|
||||
export {
|
||||
buildPublicRuleUrl,
|
||||
buildShareRuleUrl,
|
||||
formatShareUrlDisplay,
|
||||
shareCopyUrl,
|
||||
} from "../sharePaths";
|
||||
|
||||
/** Safe filename fragment from rule title, with stable fallback. */
|
||||
export function exportFilenameBase(rule: StoredLastPublishedRule): string {
|
||||
|
||||
@@ -1,24 +1,15 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { RULE_VISIBILITY } from "./ruleVisibility";
|
||||
|
||||
/**
|
||||
* Access model for published CommunityRules:
|
||||
*
|
||||
* - **Readable without sign-in:** every published row is share-by-link at
|
||||
* `/rules/[id]` and `GET /api/rules/[id]`.
|
||||
* - **Listed** (public catalog `GET /api/rules`, sitemap, indexable): owned
|
||||
* rows, and ownerless rows that are *not* waiting on a guest claim
|
||||
* (including rules orphaned when an account is deleted).
|
||||
* - **Unlisted** (omitted from the catalog and sitemap, `noindex`): guest
|
||||
* publishes with `userId` null and `claimTokenHash` set, until claimed.
|
||||
*/
|
||||
export function isListedPublishedRule(row: {
|
||||
userId: string | null;
|
||||
claimTokenHash: string | null;
|
||||
}): boolean {
|
||||
return row.userId != null || row.claimTokenHash == null;
|
||||
}
|
||||
export {
|
||||
RULE_VISIBILITY,
|
||||
isListedPublishedRule,
|
||||
canReadPublishedRule,
|
||||
isPrivilegedAdminRead,
|
||||
} from "./ruleVisibility";
|
||||
export type { RuleVisibility, PublishedRuleReadAccess } from "./ruleVisibility";
|
||||
|
||||
/** Prisma `where` for the public catalog and sitemap. */
|
||||
export const LISTED_PUBLISHED_RULE_WHERE: Prisma.PublishedRuleWhereInput = {
|
||||
OR: [{ userId: { not: null } }, { claimTokenHash: null }],
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { RuleVisibility } from "./ruleVisibility";
|
||||
|
||||
export type SharePerson = {
|
||||
email: string;
|
||||
initials: string;
|
||||
role: "owner" | "reader";
|
||||
};
|
||||
|
||||
export type RuleShareSettings = {
|
||||
visibility: RuleVisibility;
|
||||
shareSlug: string | null;
|
||||
shareUrl: string;
|
||||
shareUrlDisplay: string | null;
|
||||
title: string;
|
||||
ownerEmail: string;
|
||||
ownerInitials: string;
|
||||
readers: SharePerson[];
|
||||
copyEnabled: boolean;
|
||||
};
|
||||
|
||||
export function emailInitials(email: string): string {
|
||||
const local = email.split("@")[0] ?? "";
|
||||
const ch = local.trim().charAt(0);
|
||||
return ch.length > 0 ? ch.toUpperCase() : "?";
|
||||
}
|
||||
|
||||
/** Owner is shown separately. List the first reader, then an overflow line. */
|
||||
export function visibleShareReaders(readers: SharePerson[]): {
|
||||
shown: SharePerson[];
|
||||
overflowCount: number;
|
||||
} {
|
||||
if (readers.length <= 1) {
|
||||
return { shown: readers, overflowCount: 0 };
|
||||
}
|
||||
return { shown: readers.slice(0, 1), overflowCount: readers.length - 1 };
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
export const RULE_VISIBILITY = {
|
||||
private: "private",
|
||||
shared_by_link: "shared_by_link",
|
||||
public_and_featured: "public_and_featured",
|
||||
} as const;
|
||||
|
||||
export type RuleVisibility =
|
||||
(typeof RULE_VISIBILITY)[keyof typeof RULE_VISIBILITY];
|
||||
|
||||
export function isRuleVisibility(value: unknown): value is RuleVisibility {
|
||||
return (
|
||||
value === RULE_VISIBILITY.private ||
|
||||
value === RULE_VISIBILITY.shared_by_link ||
|
||||
value === RULE_VISIBILITY.public_and_featured
|
||||
);
|
||||
}
|
||||
|
||||
/** Listed / indexed / sitemap: public and featured only. */
|
||||
export function isListedPublishedRule(row: {
|
||||
visibility: RuleVisibility;
|
||||
}): boolean {
|
||||
return row.visibility === RULE_VISIBILITY.public_and_featured;
|
||||
}
|
||||
|
||||
export type PublishedRuleReadAccess = {
|
||||
visibility: RuleVisibility;
|
||||
/** True when the request used `/r/{shareSlug}` (or treated a file as shared-by-link). */
|
||||
viaShareSlug: boolean;
|
||||
userId: string | null;
|
||||
ownerUserId: string | null;
|
||||
viewerEmail: string | null;
|
||||
invitedEmails: string[];
|
||||
invitedUserIds: string[];
|
||||
isAdmin: boolean;
|
||||
holdsGuestClaim: boolean;
|
||||
};
|
||||
|
||||
function isOwner(opts: PublishedRuleReadAccess): boolean {
|
||||
return opts.userId != null && opts.userId === opts.ownerUserId;
|
||||
}
|
||||
|
||||
function isInvited(opts: PublishedRuleReadAccess): boolean {
|
||||
if (opts.userId != null && opts.invitedUserIds.includes(opts.userId)) {
|
||||
return true;
|
||||
}
|
||||
if (opts.viewerEmail != null && opts.invitedEmails.includes(opts.viewerEmail)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who can read a published Rule.
|
||||
*
|
||||
* Private: owner, invited people, guest-claim browser, named admins.
|
||||
* Shared by link: those readers plus anyone who arrived via the rotating slug.
|
||||
* Public and featured: anyone.
|
||||
*/
|
||||
export function canReadPublishedRule(opts: PublishedRuleReadAccess): boolean {
|
||||
if (isOwner(opts) || opts.holdsGuestClaim) return true;
|
||||
if (isInvited(opts)) return true;
|
||||
if (opts.isAdmin) return true;
|
||||
if (opts.visibility === RULE_VISIBILITY.public_and_featured) return true;
|
||||
if (
|
||||
opts.visibility === RULE_VISIBILITY.shared_by_link &&
|
||||
opts.viaShareSlug
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the viewer is a named admin who would not otherwise be able to
|
||||
* read the Rule (so the read must be logged).
|
||||
*/
|
||||
export function isPrivilegedAdminRead(opts: PublishedRuleReadAccess): boolean {
|
||||
if (!opts.isAdmin) return false;
|
||||
if (isOwner(opts) || opts.holdsGuestClaim || isInvited(opts)) return false;
|
||||
if (opts.visibility === RULE_VISIBILITY.public_and_featured) return false;
|
||||
if (
|
||||
opts.visibility === RULE_VISIBILITY.shared_by_link &&
|
||||
opts.viaShareSlug
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { logger } from "../logger";
|
||||
import { prisma } from "./db";
|
||||
|
||||
/** Best-effort audit row. Never throws to the caller. */
|
||||
export async function logAdminRuleRead(opts: {
|
||||
ruleId: string;
|
||||
adminEmail: string;
|
||||
adminUserId: string | null;
|
||||
path: string;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await prisma.adminRuleReadLog.create({
|
||||
data: {
|
||||
ruleId: opts.ruleId,
|
||||
adminEmail: opts.adminEmail.trim().toLowerCase(),
|
||||
adminUserId: opts.adminUserId,
|
||||
path: opts.path.slice(0, 500),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[admin-rule-read] failed to write log", err);
|
||||
}
|
||||
}
|
||||
@@ -29,3 +29,13 @@ export function getSmtpUrl(): string | undefined {
|
||||
export function isDatabaseConfigured(): boolean {
|
||||
return Boolean(getDatabaseUrl());
|
||||
}
|
||||
|
||||
/** Named admins who may open a private Rule. Comma-separated emails. */
|
||||
export function getRuleAdminEmails(): string[] {
|
||||
const raw = process.env.RULE_ADMIN_EMAILS?.trim();
|
||||
if (!raw) return [];
|
||||
return raw
|
||||
.split(",")
|
||||
.map((item) => item.trim().toLowerCase())
|
||||
.filter((item) => item.length > 0);
|
||||
}
|
||||
@@ -69,6 +69,33 @@ async function clearGuestRuleClaimCookie(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
/** True when this browser's claim cookie hashes to `claimTokenHash`. */
|
||||
export async function browserHoldsClaimForHash(
|
||||
claimTokenHash: string | null | undefined,
|
||||
): Promise<boolean> {
|
||||
if (typeof claimTokenHash !== "string" || claimTokenHash.length === 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const store = await cookies();
|
||||
const tokens = parseClaimTokens(
|
||||
store.get(GUEST_RULE_CLAIM_COOKIE_NAME)?.value,
|
||||
);
|
||||
if (tokens.length === 0) return false;
|
||||
let pepper: string;
|
||||
try {
|
||||
pepper = getSessionPepper();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return tokens.some(
|
||||
(token) => hashRuleClaimToken(token, pepper) === claimTokenHash,
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach ownerless published rules whose claim secrets are in this browser's
|
||||
* cookie to `userId`, then drop the cookie. Never throws to the caller.
|
||||
|
||||
+138
-32
@@ -1,14 +1,22 @@
|
||||
import type { User } from "@prisma/client";
|
||||
import {
|
||||
LISTED_PUBLISHED_RULE_WHERE,
|
||||
canReadPublishedRule,
|
||||
isListedPublishedRule,
|
||||
isPrivilegedAdminRead,
|
||||
type RuleVisibility,
|
||||
} from "../publishedRuleAccess";
|
||||
import { prisma } from "./db";
|
||||
import { isDatabaseConfigured } from "./env";
|
||||
import { browserHoldsClaimForHash } from "./guestRuleClaim";
|
||||
import { isRuleAdminEmail } from "./ruleAdmins";
|
||||
import { logAdminRuleRead } from "./adminRuleReadLog";
|
||||
|
||||
/**
|
||||
* Public fields safe to expose via the unauthenticated rule detail surfaces
|
||||
* (`GET /api/rules/[id]` and `/rules/[id]`). `userId` and `claimTokenHash`
|
||||
* stay server-side; callers get {@link PublicPublishedRule.isListed} instead.
|
||||
* Public fields safe to expose via readable rule detail surfaces
|
||||
* (`GET /api/rules/[id]` and `/rules/[id]` / `/r/[shareSlug]`).
|
||||
* `userId` and `claimTokenHash` stay server-side; callers get
|
||||
* {@link PublicPublishedRule.isListed} instead.
|
||||
*/
|
||||
const PUBLISHED_RULE_PUBLIC_SELECT = {
|
||||
id: true,
|
||||
@@ -26,38 +34,136 @@ export type PublicPublishedRule = {
|
||||
document: unknown;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
/** False for guest-claim rows; true for owned and orphaned-after-delete rows. */
|
||||
/** True only for public-and-featured Rules. */
|
||||
isListed: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch a single published rule by id for public read surfaces.
|
||||
*
|
||||
* Returns `null` when the database is not configured, the id does not match
|
||||
* any row, or the query throws — callers render a 404 in all missing cases
|
||||
* and are expected to surface the "DB not configured" state separately if
|
||||
* they care about distinguishing it (the API route does; the page does not).
|
||||
*/
|
||||
export async function getPublicPublishedRuleById(
|
||||
id: string,
|
||||
): Promise<PublicPublishedRule | null> {
|
||||
if (!isDatabaseConfigured()) return null;
|
||||
if (typeof id !== "string" || id.trim() === "") return null;
|
||||
try {
|
||||
const rule = await prisma.publishedRule.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
...PUBLISHED_RULE_PUBLIC_SELECT,
|
||||
userId: true,
|
||||
claimTokenHash: true,
|
||||
},
|
||||
export type ReadablePublishedRule = {
|
||||
rule: PublicPublishedRule;
|
||||
viewerIsOwner: boolean;
|
||||
visibility: RuleVisibility;
|
||||
shareSlug: string | null;
|
||||
};
|
||||
|
||||
const RULE_ACCESS_SELECT = {
|
||||
...PUBLISHED_RULE_PUBLIC_SELECT,
|
||||
userId: true,
|
||||
claimTokenHash: true,
|
||||
visibility: true,
|
||||
shareSlug: true,
|
||||
stakeholders: {
|
||||
select: { email: true, userId: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
function toPublicRule(row: {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
document: unknown;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
visibility: RuleVisibility;
|
||||
}): PublicPublishedRule {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
summary: row.summary,
|
||||
document: row.document,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
isListed: isListedPublishedRule({ visibility: row.visibility }),
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveAccessForRow(opts: {
|
||||
row: {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
document: unknown;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
userId: string | null;
|
||||
claimTokenHash: string | null;
|
||||
visibility: RuleVisibility;
|
||||
shareSlug: string | null;
|
||||
stakeholders: Array<{ email: string; userId: string | null }>;
|
||||
};
|
||||
viaShareSlug: boolean;
|
||||
user: User | null;
|
||||
requestPath: string;
|
||||
}): Promise<ReadablePublishedRule | null> {
|
||||
const { row, viaShareSlug, user, requestPath } = opts;
|
||||
const viewerEmail = user?.email.trim().toLowerCase() ?? null;
|
||||
const invitedEmails = row.stakeholders.map((s) => s.email.toLowerCase());
|
||||
const invitedUserIds = row.stakeholders
|
||||
.map((s) => s.userId)
|
||||
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
const isAdmin = isRuleAdminEmail(user?.email ?? null);
|
||||
const holdsGuestClaim = await browserHoldsClaimForHash(row.claimTokenHash);
|
||||
const access = {
|
||||
visibility: row.visibility,
|
||||
viaShareSlug,
|
||||
userId: user?.id ?? null,
|
||||
ownerUserId: row.userId,
|
||||
viewerEmail,
|
||||
invitedEmails,
|
||||
invitedUserIds,
|
||||
isAdmin,
|
||||
holdsGuestClaim,
|
||||
};
|
||||
if (!canReadPublishedRule(access)) return null;
|
||||
if (isPrivilegedAdminRead(access) && viewerEmail) {
|
||||
await logAdminRuleRead({
|
||||
ruleId: row.id,
|
||||
adminEmail: viewerEmail,
|
||||
adminUserId: user?.id ?? null,
|
||||
path: requestPath,
|
||||
});
|
||||
}
|
||||
return {
|
||||
rule: toPublicRule(row),
|
||||
viewerIsOwner: user != null && row.userId === user.id,
|
||||
visibility: row.visibility,
|
||||
shareSlug: row.shareSlug,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a published rule the viewer is allowed to read.
|
||||
*
|
||||
* Lookup is by internal id unless `viaShareSlug` is set. Shared-by-link
|
||||
* strangers must use the rotating slug so turning the link off invalidates it.
|
||||
* Returns `null` for missing rows, denied readers, and DB failures — callers
|
||||
* render the same 404 as a missing Rule.
|
||||
*/
|
||||
export async function getReadablePublishedRule(opts: {
|
||||
idOrSlug: string;
|
||||
user: User | null;
|
||||
viaShareSlug: boolean;
|
||||
requestPath: string;
|
||||
}): Promise<ReadablePublishedRule | null> {
|
||||
if (!isDatabaseConfigured()) return null;
|
||||
const idOrSlug = opts.idOrSlug.trim();
|
||||
if (idOrSlug.length === 0) return null;
|
||||
try {
|
||||
const row = opts.viaShareSlug
|
||||
? await prisma.publishedRule.findUnique({
|
||||
where: { shareSlug: idOrSlug },
|
||||
select: RULE_ACCESS_SELECT,
|
||||
})
|
||||
: await prisma.publishedRule.findUnique({
|
||||
where: { id: idOrSlug },
|
||||
select: RULE_ACCESS_SELECT,
|
||||
});
|
||||
if (!row) return null;
|
||||
return resolveAccessForRow({
|
||||
row,
|
||||
viaShareSlug: opts.viaShareSlug,
|
||||
user: opts.user,
|
||||
requestPath: opts.requestPath,
|
||||
});
|
||||
if (!rule) return null;
|
||||
const { userId, claimTokenHash, ...publicFields } = rule;
|
||||
return {
|
||||
...publicFields,
|
||||
isListed: isListedPublishedRule({ userId, claimTokenHash }),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -89,7 +195,7 @@ const LISTED_PUBLISHED_RULE_SITEMAP_CAP = 10_000;
|
||||
|
||||
/**
|
||||
* Public catalog of listed published rules (**most recently updated first**,
|
||||
* then stable `id` tie-break). Guest-claim rows are omitted.
|
||||
* then stable `id` tie-break). Only public-and-featured rows.
|
||||
* Returns `null` when the database is not configured or the query throws.
|
||||
*/
|
||||
export async function listListedPublishedRules(
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { getRuleAdminEmails } from "./env";
|
||||
|
||||
export function isRuleAdminEmail(email: string | null | undefined): boolean {
|
||||
if (typeof email !== "string") return false;
|
||||
const needle = email.trim().toLowerCase();
|
||||
if (needle.length === 0) return false;
|
||||
return getRuleAdminEmails().includes(needle);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { User } from "@prisma/client";
|
||||
import { RULE_VISIBILITY, type RuleVisibility } from "../ruleVisibility";
|
||||
import {
|
||||
emailInitials,
|
||||
type RuleShareSettings,
|
||||
type SharePerson,
|
||||
} from "../ruleShareTypes";
|
||||
import { formatShareUrlDisplay, shareCopyUrl } from "../sharePaths";
|
||||
import { prisma } from "./db";
|
||||
import { isRuleAdminEmail } from "./ruleAdmins";
|
||||
import { allocateShareSlug } from "./shareSlug";
|
||||
|
||||
function toShareSettings(opts: {
|
||||
visibility: RuleVisibility;
|
||||
shareSlug: string | null;
|
||||
title: string;
|
||||
origin: string;
|
||||
ruleId: string;
|
||||
ownerEmail: string;
|
||||
readers: SharePerson[];
|
||||
}): RuleShareSettings {
|
||||
const shareUrl = shareCopyUrl({
|
||||
origin: opts.origin,
|
||||
ruleId: opts.ruleId,
|
||||
shareSlug: opts.shareSlug,
|
||||
visibility: opts.visibility,
|
||||
});
|
||||
const shareUrlDisplay =
|
||||
opts.shareSlug &&
|
||||
(opts.visibility === RULE_VISIBILITY.shared_by_link ||
|
||||
opts.visibility === RULE_VISIBILITY.public_and_featured)
|
||||
? formatShareUrlDisplay(opts.origin, opts.shareSlug)
|
||||
: null;
|
||||
return {
|
||||
visibility: opts.visibility,
|
||||
shareSlug: opts.shareSlug,
|
||||
shareUrl,
|
||||
shareUrlDisplay,
|
||||
title: opts.title,
|
||||
ownerEmail: opts.ownerEmail,
|
||||
ownerInitials: emailInitials(opts.ownerEmail),
|
||||
readers: opts.readers,
|
||||
copyEnabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getOwnedRuleShareSettings(opts: {
|
||||
ruleId: string;
|
||||
user: User;
|
||||
origin: string;
|
||||
}): Promise<RuleShareSettings | "not_found" | "forbidden"> {
|
||||
const row = await prisma.publishedRule.findUnique({
|
||||
where: { id: opts.ruleId },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
userId: true,
|
||||
visibility: true,
|
||||
shareSlug: true,
|
||||
user: { select: { email: true } },
|
||||
stakeholders: {
|
||||
select: { email: true },
|
||||
orderBy: [{ invitedAt: "asc" }, { id: "asc" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!row) return "not_found";
|
||||
const isOwner = row.userId === opts.user.id;
|
||||
const isAdmin = isRuleAdminEmail(opts.user.email);
|
||||
if (!isOwner && !isAdmin) return "forbidden";
|
||||
const ownerEmail = (
|
||||
row.user?.email ?? opts.user.email
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const readers: SharePerson[] = row.stakeholders
|
||||
.map((s) => s.email.trim().toLowerCase())
|
||||
.filter((email) => email.length > 0 && email !== ownerEmail)
|
||||
.map((email) => ({
|
||||
email,
|
||||
initials: emailInitials(email),
|
||||
role: "reader" as const,
|
||||
}));
|
||||
return toShareSettings({
|
||||
visibility: row.visibility,
|
||||
shareSlug: row.shareSlug,
|
||||
title: row.title,
|
||||
origin: opts.origin,
|
||||
ruleId: row.id,
|
||||
ownerEmail,
|
||||
readers,
|
||||
});
|
||||
}
|
||||
|
||||
export async function patchOwnedRuleShare(opts: {
|
||||
ruleId: string;
|
||||
user: User;
|
||||
origin: string;
|
||||
visibility: RuleVisibility;
|
||||
communityAgreed?: boolean;
|
||||
}): Promise<
|
||||
| { ok: true; settings: RuleShareSettings }
|
||||
| { ok: false; reason: "not_found" | "forbidden" | "community_agreed" }
|
||||
> {
|
||||
const row = await prisma.publishedRule.findUnique({
|
||||
where: { id: opts.ruleId },
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
visibility: true,
|
||||
shareSlug: true,
|
||||
},
|
||||
});
|
||||
if (!row) return { ok: false, reason: "not_found" };
|
||||
|
||||
const isOwner = row.userId === opts.user.id;
|
||||
const isAdmin = isRuleAdminEmail(opts.user.email);
|
||||
if (!isOwner && !isAdmin) return { ok: false, reason: "forbidden" };
|
||||
|
||||
if (
|
||||
opts.visibility === RULE_VISIBILITY.public_and_featured &&
|
||||
!isAdmin
|
||||
) {
|
||||
return { ok: false, reason: "forbidden" };
|
||||
}
|
||||
|
||||
if (
|
||||
opts.visibility === RULE_VISIBILITY.shared_by_link &&
|
||||
row.visibility !== RULE_VISIBILITY.shared_by_link &&
|
||||
row.visibility !== RULE_VISIBILITY.public_and_featured &&
|
||||
opts.communityAgreed !== true
|
||||
) {
|
||||
return { ok: false, reason: "community_agreed" };
|
||||
}
|
||||
|
||||
if (!isOwner && opts.visibility !== RULE_VISIBILITY.public_and_featured) {
|
||||
return { ok: false, reason: "forbidden" };
|
||||
}
|
||||
|
||||
let shareSlug = row.shareSlug;
|
||||
if (opts.visibility === RULE_VISIBILITY.private) {
|
||||
shareSlug = null;
|
||||
} else if (
|
||||
opts.visibility === RULE_VISIBILITY.shared_by_link &&
|
||||
(row.visibility === RULE_VISIBILITY.private || shareSlug == null)
|
||||
) {
|
||||
shareSlug = await allocateShareSlug();
|
||||
}
|
||||
|
||||
await prisma.publishedRule.update({
|
||||
where: { id: row.id },
|
||||
data: {
|
||||
visibility: opts.visibility,
|
||||
shareSlug,
|
||||
},
|
||||
});
|
||||
|
||||
const settings = await getOwnedRuleShareSettings({
|
||||
ruleId: row.id,
|
||||
user: opts.user,
|
||||
origin: opts.origin,
|
||||
});
|
||||
if (settings === "not_found" || settings === "forbidden") {
|
||||
return { ok: false, reason: settings };
|
||||
}
|
||||
return { ok: true, settings };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { isShareSlug } from "../sharePaths";
|
||||
import { prisma } from "./db";
|
||||
|
||||
/** Unambiguous lowercase alphabet (no 0/o/1/i/l). */
|
||||
const SHARE_SLUG_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
|
||||
|
||||
function randomChunk(length: number): string {
|
||||
const bytes = randomBytes(length);
|
||||
let out = "";
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
out += SHARE_SLUG_ALPHABET[bytes[i]! % SHARE_SLUG_ALPHABET.length];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function generateShareSlug(): string {
|
||||
return `${randomChunk(4)}-${randomChunk(4)}`;
|
||||
}
|
||||
|
||||
export async function allocateShareSlug(): Promise<string> {
|
||||
for (let attempt = 0; attempt < 8; attempt += 1) {
|
||||
const shareSlug = generateShareSlug();
|
||||
if (!isShareSlug(shareSlug)) continue;
|
||||
const existing = await prisma.publishedRule.findUnique({
|
||||
where: { shareSlug },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) return shareSlug;
|
||||
}
|
||||
throw new Error("Could not allocate a unique share slug");
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { unlink } from "node:fs/promises";
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import { resolveUploadedFileById } from "./resolveUploadedFile";
|
||||
|
||||
async function unlinkResolved(id: string): Promise<void> {
|
||||
const resolved = await resolveUploadedFileById(id);
|
||||
if (!resolved) return;
|
||||
try {
|
||||
await unlink(resolved.absolutePath);
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to unlink file", id, err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteDiskFilesForUploadIds(
|
||||
ids: string[],
|
||||
): Promise<void> {
|
||||
const unique = [...new Set(ids)];
|
||||
for (const id of unique) {
|
||||
await unlinkResolved(id);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteUploadsForRule(ruleId: string): Promise<void> {
|
||||
const rows = await prisma.upload.findMany({
|
||||
where: { ruleId },
|
||||
select: { id: true },
|
||||
});
|
||||
await deleteDiskFilesForUploadIds(rows.map((r) => r.id));
|
||||
}
|
||||
|
||||
export async function deleteUploadsForDraft(draftId: string): Promise<void> {
|
||||
const rows = await prisma.upload.findMany({
|
||||
where: { draftId },
|
||||
select: { id: true },
|
||||
});
|
||||
await deleteDiskFilesForUploadIds(rows.map((r) => r.id));
|
||||
}
|
||||
|
||||
export async function deleteUploadsForUser(userId: string): Promise<void> {
|
||||
const [ownedRules, draft, ownedUploads] = await Promise.all([
|
||||
prisma.publishedRule.findMany({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.ruleDraft.findUnique({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.upload.findMany({
|
||||
where: { userId },
|
||||
select: { id: true },
|
||||
}),
|
||||
]);
|
||||
const ruleIds = ownedRules.map((r) => r.id);
|
||||
const [ruleUploads, draftUploads] = await Promise.all([
|
||||
ruleIds.length === 0
|
||||
? Promise.resolve([] as Array<{ id: string }>)
|
||||
: prisma.upload.findMany({
|
||||
where: { ruleId: { in: ruleIds } },
|
||||
select: { id: true },
|
||||
}),
|
||||
draft
|
||||
? prisma.upload.findMany({
|
||||
where: { draftId: draft.id },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve([] as Array<{ id: string }>),
|
||||
]);
|
||||
const ids = [
|
||||
...ownedUploads.map((r) => r.id),
|
||||
...ruleUploads.map((r) => r.id),
|
||||
...draftUploads.map((r) => r.id),
|
||||
];
|
||||
await deleteDiskFilesForUploadIds(ids);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isValidUploadFileId } from "./uploadConstants";
|
||||
|
||||
const UPLOAD_PATH_RE =
|
||||
/\/api\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/gi;
|
||||
|
||||
/** UUID stems referenced as `/api/uploads/{id}` inside JSON. */
|
||||
export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
||||
let text: string;
|
||||
try {
|
||||
text = JSON.stringify(value ?? null);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
||||
const id = match[1]?.toLowerCase();
|
||||
if (id && isValidUploadFileId(id)) ids.add(id);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import { extractUploadIdsFromUnknown } from "./extractUploadIds";
|
||||
|
||||
export async function linkUploadsToRule(opts: {
|
||||
ruleId: string;
|
||||
document: unknown;
|
||||
userId: string | null;
|
||||
}): Promise<void> {
|
||||
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: {
|
||||
ruleId: opts.ruleId,
|
||||
draftId: null,
|
||||
...(opts.userId ? { userId: opts.userId } : {}),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to link uploads to rule", opts.ruleId, err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function linkUploadsToDraft(opts: {
|
||||
draftId: string;
|
||||
payload: unknown;
|
||||
userId: string;
|
||||
}): Promise<void> {
|
||||
const ids = extractUploadIdsFromUnknown(opts.payload);
|
||||
if (ids.length === 0) return;
|
||||
try {
|
||||
await prisma.upload.updateMany({
|
||||
where: { id: { in: ids }, ruleId: null },
|
||||
data: {
|
||||
draftId: opts.draftId,
|
||||
userId: opts.userId,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to link uploads to draft", opts.draftId, err);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { logger } from "../../logger";
|
||||
import { prisma } from "../db";
|
||||
import type { CreateFlowUploadPurpose } from "./uploadConstants";
|
||||
import { extensionForMime } from "./uploadConstants";
|
||||
import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot";
|
||||
import { stripImageMetadata } from "./stripImageMetadata";
|
||||
import {
|
||||
validateCreateFlowUploadBytes,
|
||||
type CreateFlowUploadValidationReason,
|
||||
@@ -30,6 +33,7 @@ export type SaveCreateFlowUploadFailure = {
|
||||
export async function saveCreateFlowUpload(params: {
|
||||
purpose: CreateFlowUploadPurpose;
|
||||
buffer: Buffer;
|
||||
userId?: string | null;
|
||||
}): Promise<SaveCreateFlowUploadResult | SaveCreateFlowUploadFailure> {
|
||||
const root = getUploadRootFromEnv();
|
||||
if (!root) {
|
||||
@@ -42,18 +46,33 @@ export async function saveCreateFlowUpload(params: {
|
||||
return { error: "validation", reason: validated.reason };
|
||||
}
|
||||
|
||||
const stripped = stripImageMetadata(buffer, validated.mimeType);
|
||||
const id = randomUUID();
|
||||
const ext = extensionForMime(validated.mimeType);
|
||||
const fileName = `${id}${ext}`;
|
||||
const absolutePath = path.join(root, fileName);
|
||||
|
||||
await ensureUploadRootExists(root);
|
||||
await writeFile(absolutePath, buffer, { mode: 0o644 });
|
||||
await writeFile(absolutePath, stripped, { mode: 0o644 });
|
||||
|
||||
try {
|
||||
await prisma.upload.create({
|
||||
data: {
|
||||
id,
|
||||
mimeType: validated.mimeType,
|
||||
byteLength: stripped.length,
|
||||
purpose,
|
||||
userId: params.userId ?? null,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn("[uploads] failed to record upload row", id, err);
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
urlPath: `/api/uploads/${id}`,
|
||||
mimeType: validated.mimeType,
|
||||
byteLength: buffer.length,
|
||||
byteLength: stripped.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Strip GPS/author metadata from image bytes. JPEG APP1 (EXIF) and PNG
|
||||
* text / eXIf chunks are dropped. Other types are returned unchanged.
|
||||
*/
|
||||
export function stripImageMetadata(buffer: Buffer, mimeType: string): Buffer {
|
||||
const mime = mimeType.toLowerCase().split(";")[0]?.trim() ?? "";
|
||||
if (mime === "image/jpeg" || mime === "image/jpg") {
|
||||
return stripJpegExif(buffer);
|
||||
}
|
||||
if (mime === "image/png") {
|
||||
return stripPngMetadata(buffer);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function stripJpegExif(buffer: Buffer): Buffer {
|
||||
if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) {
|
||||
return buffer;
|
||||
}
|
||||
const out: Buffer[] = [buffer.subarray(0, 2)];
|
||||
let i = 2;
|
||||
while (i + 3 < buffer.length) {
|
||||
if (buffer[i] !== 0xff) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
const marker = buffer[i + 1]!;
|
||||
if (marker === 0xda) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
if (marker === 0xd9) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
break;
|
||||
}
|
||||
if (marker >= 0xd0 && marker <= 0xd7) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (marker === 0x01 || marker === 0xd8) {
|
||||
out.push(buffer.subarray(i, i + 2));
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (i + 3 >= buffer.length) break;
|
||||
const size = buffer.readUInt16BE(i + 2);
|
||||
const next = i + 2 + size;
|
||||
if (size < 2 || next > buffer.length) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
const isApp1 = marker === 0xe1;
|
||||
const isApp13 = marker === 0xed;
|
||||
if (!isApp1 && !isApp13) {
|
||||
out.push(buffer.subarray(i, next));
|
||||
}
|
||||
i = next;
|
||||
}
|
||||
return Buffer.concat(out);
|
||||
}
|
||||
|
||||
function stripPngMetadata(buffer: Buffer): Buffer {
|
||||
const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
if (buffer.length < 16 || !buffer.subarray(0, 8).equals(sig)) {
|
||||
return buffer;
|
||||
}
|
||||
const skip = new Set(["tEXt", "iTXt", "zTXt", "eXIf", "tIME"]);
|
||||
const out: Buffer[] = [buffer.subarray(0, 8)];
|
||||
let i = 8;
|
||||
while (i + 12 <= buffer.length) {
|
||||
const length = buffer.readUInt32BE(i);
|
||||
const type = buffer.subarray(i + 4, i + 8).toString("ascii");
|
||||
const chunkEnd = i + 12 + length;
|
||||
if (chunkEnd > buffer.length) {
|
||||
out.push(buffer.subarray(i));
|
||||
break;
|
||||
}
|
||||
if (!skip.has(type)) {
|
||||
out.push(buffer.subarray(i, chunkEnd));
|
||||
}
|
||||
i = chunkEnd;
|
||||
if (type === "IEND") break;
|
||||
}
|
||||
return Buffer.concat(out);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { isValidUploadFileId } from "./uploadConstants";
|
||||
|
||||
const UPLOAD_GRANT_COOKIE_NAME = "cr_upload_grant";
|
||||
const MAX_GRANT_IDS = 16;
|
||||
const COOKIE_MAX_AGE_SEC = 60 * 60 * 24 * 30;
|
||||
|
||||
function cookieOptions(): {
|
||||
httpOnly: true;
|
||||
secure: boolean;
|
||||
sameSite: "lax";
|
||||
path: "/";
|
||||
maxAge: number;
|
||||
} {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: COOKIE_MAX_AGE_SEC,
|
||||
};
|
||||
}
|
||||
|
||||
function parseGrantIds(raw: string | undefined): string[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
const ids: string[] = [];
|
||||
for (const item of parsed) {
|
||||
if (typeof item !== "string") continue;
|
||||
if (!isValidUploadFileId(item)) continue;
|
||||
ids.push(item.toLowerCase());
|
||||
}
|
||||
return ids.slice(-MAX_GRANT_IDS);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function issueGuestUploadGrantCookie(id: string): Promise<void> {
|
||||
if (!isValidUploadFileId(id)) return;
|
||||
const store = await cookies();
|
||||
const existing = parseGrantIds(store.get(UPLOAD_GRANT_COOKIE_NAME)?.value);
|
||||
const next = [
|
||||
...existing.filter((item) => item !== id),
|
||||
id.toLowerCase(),
|
||||
].slice(-MAX_GRANT_IDS);
|
||||
store.set(
|
||||
UPLOAD_GRANT_COOKIE_NAME,
|
||||
JSON.stringify(next),
|
||||
cookieOptions(),
|
||||
);
|
||||
}
|
||||
|
||||
export async function browserHoldsUploadGrant(id: string): Promise<boolean> {
|
||||
if (!isValidUploadFileId(id)) return false;
|
||||
try {
|
||||
const store = await cookies();
|
||||
const ids = parseGrantIds(store.get(UPLOAD_GRANT_COOKIE_NAME)?.value);
|
||||
return ids.includes(id.toLowerCase());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,13 @@ export const publishRuleBodySchema = z.object({
|
||||
|
||||
export type PublishRuleBody = z.infer<typeof publishRuleBodySchema>;
|
||||
|
||||
export const patchRuleShareBodySchema = z.object({
|
||||
visibility: z.enum(["private", "shared_by_link", "public_and_featured"]),
|
||||
communityAgreed: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type PatchRuleShareBody = z.infer<typeof patchRuleShareBodySchema>;
|
||||
|
||||
export const postRuleStakeholderBodySchema = z.object({
|
||||
email: stakeholderEmailSchema,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { RULE_VISIBILITY, type RuleVisibility } from "./ruleVisibility";
|
||||
|
||||
const SHARE_SLUG_RE = /^[a-z0-9]{4}-[a-z0-9]{4}$/;
|
||||
|
||||
export function isShareSlug(value: string): boolean {
|
||||
return SHARE_SLUG_RE.test(value);
|
||||
}
|
||||
|
||||
export function publishedRulePath(ruleId: string): string {
|
||||
return `/rules/${encodeURIComponent(ruleId)}`;
|
||||
}
|
||||
|
||||
export function shareRulePath(shareSlug: string): string {
|
||||
return `/r/${encodeURIComponent(shareSlug)}`;
|
||||
}
|
||||
|
||||
export function buildPublicRuleUrl(origin: string, ruleId: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}${publishedRulePath(ruleId)}`;
|
||||
}
|
||||
|
||||
export function buildShareRuleUrl(origin: string, shareSlug: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}${shareRulePath(shareSlug)}`;
|
||||
}
|
||||
|
||||
/** Host + path as drawn in the Share control, e.g. `communityrule.info/r/k7f2-9qxm`. */
|
||||
export function formatShareUrlDisplay(origin: string, shareSlug: string): string {
|
||||
try {
|
||||
return `${new URL(origin).host}/r/${shareSlug}`;
|
||||
} catch {
|
||||
const host = origin.replace(/^https?:\/\//, "").replace(/\/$/, "");
|
||||
return `${host}/r/${shareSlug}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* URL the Share control copies and shows.
|
||||
* Shared-by-link (and featured rows that still have a slug) use `/r/{slug}`.
|
||||
* Featured without a slug uses `/rules/{id}`. Private uses `/rules/{id}`.
|
||||
*/
|
||||
export function shareCopyUrl(opts: {
|
||||
origin: string;
|
||||
ruleId: string;
|
||||
shareSlug: string | null;
|
||||
visibility: RuleVisibility;
|
||||
}): string {
|
||||
if (
|
||||
opts.shareSlug &&
|
||||
(opts.visibility === RULE_VISIBILITY.shared_by_link ||
|
||||
opts.visibility === RULE_VISIBILITY.public_and_featured)
|
||||
) {
|
||||
return buildShareRuleUrl(opts.origin, opts.shareSlug);
|
||||
}
|
||||
return buildPublicRuleUrl(opts.origin, opts.ruleId);
|
||||
}
|
||||
+1
-1
@@ -25,7 +25,7 @@ const INDEXABLE_HOSTS = new Set([
|
||||
|
||||
export const NO_INDEX_ROBOTS = { index: false, follow: false } as const;
|
||||
|
||||
/** Unlisted (guest-claim) rule pages stay shareable but must not be indexed. */
|
||||
/** Shared-by-link and private rule pages stay shareable but must not be indexed. */
|
||||
export function robotsForPublishedRule(isListed: boolean):
|
||||
| {
|
||||
index: false;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RuleVisibility" AS ENUM ('private', 'shared_by_link', 'public_and_featured');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "PublishedRule" ADD COLUMN "visibility" "RuleVisibility" NOT NULL DEFAULT 'private';
|
||||
ALTER TABLE "PublishedRule" ADD COLUMN "shareSlug" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PublishedRule_shareSlug_key" ON "PublishedRule"("shareSlug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PublishedRule_visibility_updatedAt_idx" ON "PublishedRule"("visibility", "updatedAt");
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "PublishedRule" DROP CONSTRAINT "PublishedRule_userId_fkey";
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PublishedRule" ADD CONSTRAINT "PublishedRule_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- Pilot Rules with written consent are public and featured; every other Rule stays private.
|
||||
UPDATE "PublishedRule"
|
||||
SET visibility = 'public_and_featured'
|
||||
WHERE title IN (
|
||||
'Mutual Aid Colorado',
|
||||
'Food Not Bombs Boulder',
|
||||
'Boulder Street Medics'
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Upload" (
|
||||
"id" TEXT NOT NULL,
|
||||
"mimeType" TEXT NOT NULL,
|
||||
"byteLength" INTEGER NOT NULL,
|
||||
"purpose" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"draftId" TEXT,
|
||||
"ruleId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "Upload_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Upload_ruleId_idx" ON "Upload"("ruleId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Upload_draftId_idx" ON "Upload"("draftId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Upload_userId_idx" ON "Upload"("userId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Upload" ADD CONSTRAINT "Upload_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Upload" ADD CONSTRAINT "Upload_draftId_fkey" FOREIGN KEY ("draftId") REFERENCES "RuleDraft"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Upload" ADD CONSTRAINT "Upload_ruleId_fkey" FOREIGN KEY ("ruleId") REFERENCES "PublishedRule"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- Backfill upload rows from links already stored in published documents.
|
||||
INSERT INTO "Upload" ("id", "mimeType", "byteLength", "purpose", "ruleId", "createdAt")
|
||||
SELECT DISTINCT
|
||||
lower(m[1]),
|
||||
'application/octet-stream',
|
||||
0,
|
||||
'backfill',
|
||||
r.id,
|
||||
CURRENT_TIMESTAMP
|
||||
FROM "PublishedRule" r,
|
||||
LATERAL regexp_matches(
|
||||
r.document::text,
|
||||
'/api/uploads/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})',
|
||||
'g'
|
||||
) AS m
|
||||
ON CONFLICT ("id") DO UPDATE SET
|
||||
"ruleId" = EXCLUDED."ruleId";
|
||||
|
||||
-- Backfill upload rows from links already stored in drafts (skip ids already tied to a Rule).
|
||||
INSERT INTO "Upload" ("id", "mimeType", "byteLength", "purpose", "draftId", "createdAt")
|
||||
SELECT DISTINCT
|
||||
lower(m[1]),
|
||||
'application/octet-stream',
|
||||
0,
|
||||
'backfill',
|
||||
d.id,
|
||||
CURRENT_TIMESTAMP
|
||||
FROM "RuleDraft" d,
|
||||
LATERAL regexp_matches(
|
||||
d.payload::text,
|
||||
'/api/uploads/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})',
|
||||
'g'
|
||||
) AS m
|
||||
ON CONFLICT ("id") DO NOTHING;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AdminRuleReadLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"ruleId" TEXT NOT NULL,
|
||||
"adminEmail" TEXT NOT NULL,
|
||||
"adminUserId" TEXT,
|
||||
"path" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AdminRuleReadLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminRuleReadLog_ruleId_createdAt_idx" ON "AdminRuleReadLog"("ruleId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminRuleReadLog_adminEmail_createdAt_idx" ON "AdminRuleReadLog"("adminEmail", "createdAt");
|
||||
+47
-1
@@ -16,6 +16,7 @@ model User {
|
||||
sessions Session[]
|
||||
draft RuleDraft?
|
||||
rules PublishedRule[]
|
||||
uploads Upload[]
|
||||
/// At most one pending verified email change (CR-103).
|
||||
emailChangeToken EmailChangeToken?
|
||||
/// Rules this user was invited to as a stakeholder (after accepting invite).
|
||||
@@ -68,12 +69,19 @@ model RuleDraft {
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
payload Json
|
||||
updatedAt DateTime @updatedAt
|
||||
uploads Upload[]
|
||||
}
|
||||
|
||||
enum RuleVisibility {
|
||||
private
|
||||
shared_by_link
|
||||
public_and_featured
|
||||
}
|
||||
|
||||
model PublishedRule {
|
||||
id String @id @default(cuid())
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
title String
|
||||
summary String?
|
||||
document Json
|
||||
@@ -82,10 +90,48 @@ model PublishedRule {
|
||||
/// Hashed one-time secret so the publishing browser can claim this row on sign-in.
|
||||
/// Null for owned publishes and after a successful claim.
|
||||
claimTokenHash String? @unique
|
||||
/// Who can read this Rule. New rows start private.
|
||||
visibility RuleVisibility @default(private)
|
||||
/// Rotating public path `/r/{shareSlug}`. Null while private. Replaced when a link is turned back on.
|
||||
shareSlug String? @unique
|
||||
|
||||
stakeholders RuleStakeholder[]
|
||||
uploads Upload[]
|
||||
|
||||
@@index([userId])
|
||||
@@index([visibility, updatedAt])
|
||||
}
|
||||
|
||||
/// File written under UPLOAD_ROOT. Readers follow the linked Rule or draft.
|
||||
model Upload {
|
||||
id String @id
|
||||
mimeType String
|
||||
byteLength Int
|
||||
purpose String
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
draftId String?
|
||||
draft RuleDraft? @relation(fields: [draftId], references: [id], onDelete: Cascade)
|
||||
ruleId String?
|
||||
rule PublishedRule? @relation(fields: [ruleId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([ruleId])
|
||||
@@index([draftId])
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
/// Named-admin reads of Rules they do not already hold the pen for or belong to.
|
||||
model AdminRuleReadLog {
|
||||
id String @id @default(cuid())
|
||||
ruleId String
|
||||
adminEmail String
|
||||
adminUserId String?
|
||||
path String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([ruleId, createdAt])
|
||||
@@index([adminEmail, createdAt])
|
||||
}
|
||||
|
||||
/// Invite + access for a published rule: email invite at publish; userId set after magic-link-style accept.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractUploadIdsFromUnknown } from "../../lib/server/uploads/extractUploadIds";
|
||||
|
||||
const ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
|
||||
describe("extractUploadIdsFromUnknown", () => {
|
||||
it("collects unique upload ids from nested JSON", () => {
|
||||
expect(
|
||||
extractUploadIdsFromUnknown({
|
||||
logo: `/api/uploads/${ID}`,
|
||||
nested: { also: `/api/uploads/${ID}` },
|
||||
other: "/api/uploads/not-a-uuid",
|
||||
}),
|
||||
).toEqual([ID]);
|
||||
});
|
||||
|
||||
it("returns an empty list when nothing matches", () => {
|
||||
expect(extractUploadIdsFromUnknown({ text: "no files" })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,34 +3,26 @@ import {
|
||||
LISTED_PUBLISHED_RULE_WHERE,
|
||||
isListedPublishedRule,
|
||||
} from "../../lib/publishedRuleAccess";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
describe("isListedPublishedRule", () => {
|
||||
it("lists owned rules", () => {
|
||||
it("lists public and featured Rules only", () => {
|
||||
expect(
|
||||
isListedPublishedRule({ userId: "user-1", claimTokenHash: null }),
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("lists ownerless rows that are not waiting on a guest claim", () => {
|
||||
expect(isListedPublishedRule({ userId: null, claimTokenHash: null })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps guest-claim rows unlisted", () => {
|
||||
expect(
|
||||
isListedPublishedRule({
|
||||
userId: null,
|
||||
claimTokenHash: "claim-hash",
|
||||
}),
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.private }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("LISTED_PUBLISHED_RULE_WHERE", () => {
|
||||
it("matches owned rows or rows with no claim token", () => {
|
||||
it("matches public and featured rows", () => {
|
||||
expect(LISTED_PUBLISHED_RULE_WHERE).toEqual({
|
||||
OR: [{ userId: { not: null } }, { claimTokenHash: null }],
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const logAdminRuleReadMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
@@ -17,58 +20,178 @@ vi.mock("../../lib/server/db", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
browserHoldsClaimForHash: (...args: unknown[]) =>
|
||||
browserHoldsClaimForHashMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/adminRuleReadLog", () => ({
|
||||
logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
getPublicPublishedRuleById,
|
||||
getReadablePublishedRule,
|
||||
listListedPublishedRules,
|
||||
listListedPublishedRulesForSitemap,
|
||||
} from "../../lib/server/publishedRules";
|
||||
import { LISTED_PUBLISHED_RULE_WHERE } from "../../lib/publishedRuleAccess";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "owned-1",
|
||||
title: "Owned",
|
||||
summary: "Hi",
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
findUniqueMock.mockReset();
|
||||
findManyMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("getPublicPublishedRuleById", () => {
|
||||
it("returns isListed false for guest-claim rows without exposing claim tokens", async () => {
|
||||
describe("getReadablePublishedRule", () => {
|
||||
it("returns listed public-and-featured Rules to anonymous readers", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: "guest-1",
|
||||
title: "Guest rule",
|
||||
summary: null,
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: null,
|
||||
claimTokenHash: "secret-hash",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
);
|
||||
|
||||
const rule = await getPublicPublishedRuleById("guest-1");
|
||||
expect(rule).toMatchObject({
|
||||
id: "guest-1",
|
||||
title: "Guest rule",
|
||||
isListed: false,
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(rule).not.toHaveProperty("userId");
|
||||
expect(rule).not.toHaveProperty("claimTokenHash");
|
||||
});
|
||||
|
||||
it("returns isListed true for owned rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
expect(resolved?.rule).toMatchObject({
|
||||
id: "owned-1",
|
||||
title: "Owned",
|
||||
summary: "Hi",
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
isListed: true,
|
||||
});
|
||||
expect(resolved?.rule).not.toHaveProperty("userId");
|
||||
expect(resolved?.rule).not.toHaveProperty("claimTokenHash");
|
||||
});
|
||||
|
||||
const rule = await getPublicPublishedRuleById("owned-1");
|
||||
expect(rule?.isListed).toBe(true);
|
||||
it("hides private Rules from anonymous readers", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
expect(
|
||||
await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("lets the publishing browser read a private Rule with the guest claim", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ userId: null, claimTokenHash: "claim-hash" }),
|
||||
);
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(browserHoldsClaimForHashMock).toHaveBeenCalledWith("claim-hash");
|
||||
});
|
||||
|
||||
it("lets the owner read a private Rule by id", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: { id: "user-1", email: "owner@example.org" } as never,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(resolved?.viewerIsOwner).toBe(true);
|
||||
expect(resolved?.rule.isListed).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a shared-by-link Rule as public at /rules/{id}", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: null,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("lets anonymous readers use the rotating slug", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "k7f2-9qxm",
|
||||
user: null,
|
||||
viaShareSlug: true,
|
||||
requestPath: "/r/k7f2-9qxm",
|
||||
});
|
||||
expect(resolved?.rule.id).toBe("owned-1");
|
||||
expect(resolved?.rule.isListed).toBe(false);
|
||||
expect(findUniqueMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ where: { shareSlug: "k7f2-9qxm" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs named-admin reads of private Rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const resolved = await getReadablePublishedRule({
|
||||
idOrSlug: "owned-1",
|
||||
user: { id: "admin-1", email: "admin@example.org" } as never,
|
||||
viaShareSlug: false,
|
||||
requestPath: "/rules/owned-1",
|
||||
});
|
||||
expect(resolved?.viewerIsOwner).toBe(false);
|
||||
expect(logAdminRuleReadMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ruleId: "owned-1",
|
||||
adminEmail: "admin@example.org",
|
||||
path: "/rules/owned-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -100,4 +223,15 @@ describe("listListedPublishedRulesForSitemap", () => {
|
||||
expect(await listListedPublishedRulesForSitemap()).toEqual([]);
|
||||
expect(findManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("queries only public and featured Rules", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findManyMock.mockResolvedValueOnce([]);
|
||||
await listListedPublishedRulesForSitemap();
|
||||
expect(findManyMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: LISTED_PUBLISHED_RULE_WHERE,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,228 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
const findUniqueMock = vi.fn();
|
||||
const updateMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const allocateShareSlugMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||
update: (...args: unknown[]) => updateMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/shareSlug", () => ({
|
||||
allocateShareSlug: (...args: unknown[]) => allocateShareSlugMock(...args),
|
||||
}));
|
||||
|
||||
import { patchOwnedRuleShare } from "../../lib/server/ruleShare";
|
||||
|
||||
const owner = { id: "user-1", email: "owner@example.org" } as never;
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "rule-1",
|
||||
title: "Juniper Street Food Share",
|
||||
userId: "user-1",
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
findUniqueMock.mockReset();
|
||||
updateMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
allocateShareSlugMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
updateMock.mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe("patchOwnedRuleShare", () => {
|
||||
it("allocates a new slug when turning a private Rule on", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("k7f2-9qxm");
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(allocateShareSlugMock).toHaveBeenCalledTimes(1);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("requires community agreement the first time a link turns on", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
});
|
||||
expect(result).toEqual({ ok: false, reason: "community_agreed" });
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forbids the owner from setting public and featured", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
expect(result).toEqual({ ok: false, reason: "forbidden" });
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets a named admin set public and featured", async () => {
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
const admin = { id: "admin-1", email: "ops@example.org" } as never;
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
user: { email: "owner@example.org" },
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: admin,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
shareSlug: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("allocates a new slug after a link is turned off and on again", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "abcd-efgh",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("abcd-efgh");
|
||||
|
||||
const first = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
expect(first.ok).toBe(true);
|
||||
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "abcd-efgh",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(row());
|
||||
const off = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "private",
|
||||
});
|
||||
expect(off.ok).toBe(true);
|
||||
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row())
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "wxyz-1234",
|
||||
}),
|
||||
);
|
||||
allocateShareSlugMock.mockResolvedValueOnce("wxyz-1234");
|
||||
const second = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "shared_by_link",
|
||||
communityAgreed: true,
|
||||
});
|
||||
expect(second.ok).toBe(true);
|
||||
expect(allocateShareSlugMock).toHaveBeenCalledTimes(2);
|
||||
expect(updateMock).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "wxyz-1234",
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("clears the slug when the link is turned off", async () => {
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(row());
|
||||
|
||||
const result = await patchOwnedRuleShare({
|
||||
ruleId: "rule-1",
|
||||
user: owner,
|
||||
origin: "https://communityrule.info",
|
||||
visibility: "private",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(updateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
emailInitials,
|
||||
visibleShareReaders,
|
||||
type SharePerson,
|
||||
} from "../../lib/ruleShareTypes";
|
||||
|
||||
const readers: SharePerson[] = [
|
||||
{ email: "rosa@example.org", initials: "R", role: "reader" },
|
||||
{ email: "a@example.org", initials: "A", role: "reader" },
|
||||
{ email: "b@example.org", initials: "B", role: "reader" },
|
||||
];
|
||||
|
||||
describe("visibleShareReaders", () => {
|
||||
it("shows every reader when there is at most one", () => {
|
||||
expect(visibleShareReaders([])).toEqual({ shown: [], overflowCount: 0 });
|
||||
expect(visibleShareReaders(readers.slice(0, 1))).toEqual({
|
||||
shown: readers.slice(0, 1),
|
||||
overflowCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the first reader and counts the rest", () => {
|
||||
expect(visibleShareReaders(readers)).toEqual({
|
||||
shown: readers.slice(0, 1),
|
||||
overflowCount: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("emailInitials", () => {
|
||||
it("uses the first character of the local part", () => {
|
||||
expect(emailInitials("rosa@example.org")).toBe("R");
|
||||
expect(emailInitials("")).toBe("?");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
RULE_VISIBILITY,
|
||||
canReadPublishedRule,
|
||||
isListedPublishedRule,
|
||||
isPrivilegedAdminRead,
|
||||
type PublishedRuleReadAccess,
|
||||
} from "../../lib/ruleVisibility";
|
||||
|
||||
function access(
|
||||
overrides: Partial<PublishedRuleReadAccess> = {},
|
||||
): PublishedRuleReadAccess {
|
||||
return {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
viaShareSlug: false,
|
||||
userId: null,
|
||||
ownerUserId: "owner-1",
|
||||
viewerEmail: null,
|
||||
invitedEmails: [],
|
||||
invitedUserIds: [],
|
||||
isAdmin: false,
|
||||
holdsGuestClaim: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("isListedPublishedRule", () => {
|
||||
it("lists only public and featured Rules", () => {
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.private }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isListedPublishedRule({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canReadPublishedRule", () => {
|
||||
it("lets the owner, invited people, guest claim, and named admins read a private Rule", () => {
|
||||
expect(canReadPublishedRule(access())).toBe(false);
|
||||
expect(canReadPublishedRule(access({ userId: "owner-1" }))).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({ viewerEmail: "rosa@example.org", invitedEmails: ["rosa@example.org"] }),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(access({ userId: "u-2", invitedUserIds: ["u-2"] })),
|
||||
).toBe(true);
|
||||
expect(canReadPublishedRule(access({ holdsGuestClaim: true }))).toBe(true);
|
||||
expect(canReadPublishedRule(access({ isAdmin: true }))).toBe(true);
|
||||
});
|
||||
|
||||
it("lets anyone with the rotating slug read a shared-by-link Rule", () => {
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: true,
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: false,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("lets anyone read a public and featured Rule", () => {
|
||||
expect(
|
||||
canReadPublishedRule(
|
||||
access({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPrivilegedAdminRead", () => {
|
||||
it("is true only when a named admin would otherwise be denied", () => {
|
||||
expect(isPrivilegedAdminRead(access({ isAdmin: true }))).toBe(true);
|
||||
expect(
|
||||
isPrivilegedAdminRead(access({ isAdmin: true, userId: "owner-1" })),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPrivilegedAdminRead(
|
||||
access({
|
||||
isAdmin: true,
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPrivilegedAdminRead(
|
||||
access({
|
||||
isAdmin: true,
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
viaShareSlug: true,
|
||||
}),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
||||
deleteUploadsForRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { DELETE } from "../../app/api/rules/[id]/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
|
||||
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/linkUploads", () => ({
|
||||
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { PATCH } from "../../app/api/rules/[id]/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
|
||||
@@ -4,6 +4,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const logAdminRuleReadMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
@@ -21,17 +24,54 @@ vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
browserHoldsClaimForHash: (...args: unknown[]) =>
|
||||
browserHoldsClaimForHashMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/adminRuleReadLog", () => ({
|
||||
logAdminRuleRead: (...args: unknown[]) => logAdminRuleReadMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/rules/[id]/route";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
function makeContext(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
stakeholders: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
findUniqueMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("GET /api/rules/[id]", () => {
|
||||
@@ -86,80 +126,39 @@ describe("GET /api/rules/[id]", () => {
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 with { rule, viewerIsOwner: false } when a published rule exists and the viewer is anonymous", async () => {
|
||||
it("returns 404 for a private Rule when the viewer is anonymous", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: "user-1",
|
||||
claimTokenHash: null,
|
||||
};
|
||||
findUniqueMock.mockResolvedValueOnce(row);
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 for a public and featured Rule when the viewer is anonymous", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ visibility: RULE_VISIBILITY.public_and_featured }),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
rule: {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
isListed: boolean;
|
||||
};
|
||||
rule: { id: string; isListed: boolean };
|
||||
viewerIsOwner: boolean;
|
||||
};
|
||||
expect(body.rule.id).toBe("rule-1");
|
||||
expect(body.rule.title).toBe("Mutual Aid Mondays");
|
||||
expect(body.rule.summary).toBe("A grassroots community in Denver.");
|
||||
expect(body.rule.isListed).toBe(true);
|
||||
expect(body.viewerIsOwner).toBe(false);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("marks guest-claim rules as unlisted without exposing the claim token", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: "guest-1",
|
||||
title: "Unlisted",
|
||||
summary: null,
|
||||
document: {},
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
userId: null,
|
||||
claimTokenHash: "secret-hash",
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/guest-1"),
|
||||
makeContext("guest-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
rule: { isListed: boolean; claimTokenHash?: unknown; userId?: unknown };
|
||||
};
|
||||
expect(body.rule.isListed).toBe(false);
|
||||
expect(body.rule).not.toHaveProperty("claimTokenHash");
|
||||
expect(body.rule).not.toHaveProperty("userId");
|
||||
});
|
||||
|
||||
it("returns viewerIsOwner true when the signed-in user owns the rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
};
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row)
|
||||
.mockResolvedValueOnce({ userId: "user-1" });
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
@@ -167,23 +166,70 @@ describe("GET /api/rules/[id]", () => {
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { viewerIsOwner: boolean };
|
||||
expect(body.viewerIsOwner).toBe(true);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(2);
|
||||
expect(findUniqueMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns viewerIsOwner false when the signed-in user does not own the rule", async () => {
|
||||
it("returns 404 for a shared-by-link Rule at the internal id", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
const row = {
|
||||
id: "rule-1",
|
||||
title: "Mutual Aid Mondays",
|
||||
summary: "A grassroots community in Denver.",
|
||||
document: { sections: [] },
|
||||
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||
};
|
||||
findUniqueMock
|
||||
.mockResolvedValueOnce(row)
|
||||
.mockResolvedValueOnce({ userId: "other" });
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
shareSlug: "k7f2-9qxm",
|
||||
}),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 200 when the browser holds the guest claim", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({ userId: null, claimTokenHash: "claim-hash" }),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("logs named-admin reads of a private Rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
isRuleAdminEmailMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({
|
||||
id: "admin-1",
|
||||
email: "ops@example.org",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(row());
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(logAdminRuleReadMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ruleId: "rule-1",
|
||||
adminEmail: "ops@example.org",
|
||||
path: "/api/rules/rule-1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 200 for an invited reader of a private Rule", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({
|
||||
id: "reader-1",
|
||||
email: "rosa@example.org",
|
||||
});
|
||||
findUniqueMock.mockResolvedValueOnce(
|
||||
row({
|
||||
stakeholders: [{ email: "rosa@example.org", userId: "reader-1" }],
|
||||
}),
|
||||
);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1"),
|
||||
makeContext("rule-1"),
|
||||
|
||||
@@ -44,6 +44,10 @@ vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||
issueGuestRuleClaimCookieMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/linkUploads", () => ({
|
||||
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
$transaction: (fn: (tx: unknown) => Promise<unknown>) =>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const getOwnedRuleShareSettingsMock = vi.fn();
|
||||
const patchOwnedRuleShareMock = vi.fn();
|
||||
const getPublicOriginMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/publicOrigin", () => ({
|
||||
getPublicOrigin: (...args: unknown[]) => getPublicOriginMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleShare", () => ({
|
||||
getOwnedRuleShareSettings: (...args: unknown[]) =>
|
||||
getOwnedRuleShareSettingsMock(...args),
|
||||
patchOwnedRuleShare: (...args: unknown[]) => patchOwnedRuleShareMock(...args),
|
||||
}));
|
||||
|
||||
import { GET, PATCH } from "../../app/api/rules/[id]/share/route";
|
||||
|
||||
function makeContext(id: string) {
|
||||
return { params: Promise.resolve({ id }) };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
getOwnedRuleShareSettingsMock.mockReset();
|
||||
patchOwnedRuleShareMock.mockReset();
|
||||
getPublicOriginMock.mockReset();
|
||||
getPublicOriginMock.mockReturnValue("https://communityrule.info");
|
||||
});
|
||||
|
||||
describe("GET /api/rules/[id]/share", () => {
|
||||
it("returns 401 when not signed in", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns share settings for the owner", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
getOwnedRuleShareSettingsMock.mockResolvedValueOnce({
|
||||
visibility: "private",
|
||||
shareUrl: "https://communityrule.info/rules/rule-1",
|
||||
title: "Juniper",
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share"),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { share: { visibility: string } };
|
||||
expect(body.share.visibility).toBe("private");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH /api/rules/[id]/share", () => {
|
||||
it("returns 400 when community agreement is missing", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
|
||||
patchOwnedRuleShareMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
reason: "community_agreed",
|
||||
});
|
||||
const res = await PATCH(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/share", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ visibility: "shared_by_link" }),
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
makeContext("rule-1"),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,14 @@ vi.mock("../../lib/server/uploads/uploadRoot", async () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { saveCreateFlowUpload } from "../../lib/server/uploads/saveCreateFlowUpload";
|
||||
|
||||
const PNG_1X1 = Buffer.from(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
import {
|
||||
buildShareRuleUrl,
|
||||
formatShareUrlDisplay,
|
||||
isShareSlug,
|
||||
shareCopyUrl,
|
||||
shareRulePath,
|
||||
} from "../../lib/sharePaths";
|
||||
|
||||
describe("sharePaths", () => {
|
||||
it("accepts the rotating slug shape", () => {
|
||||
expect(isShareSlug("k7f2-9qxm")).toBe(true);
|
||||
expect(isShareSlug("K7F2-9QXM")).toBe(false);
|
||||
expect(isShareSlug("not-a-slug")).toBe(false);
|
||||
});
|
||||
|
||||
it("builds /r/{slug} URLs and the display host+path", () => {
|
||||
expect(shareRulePath("k7f2-9qxm")).toBe("/r/k7f2-9qxm");
|
||||
expect(buildShareRuleUrl("https://communityrule.info", "k7f2-9qxm")).toBe(
|
||||
"https://communityrule.info/r/k7f2-9qxm",
|
||||
);
|
||||
expect(
|
||||
formatShareUrlDisplay("https://communityrule.info", "k7f2-9qxm"),
|
||||
).toBe("communityrule.info/r/k7f2-9qxm");
|
||||
});
|
||||
|
||||
it("copies the slug URL once a link is on, otherwise the internal Rule URL", () => {
|
||||
expect(
|
||||
shareCopyUrl({
|
||||
origin: "https://communityrule.info",
|
||||
ruleId: "rule-1",
|
||||
shareSlug: "k7f2-9qxm",
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
}),
|
||||
).toBe("https://communityrule.info/r/k7f2-9qxm");
|
||||
expect(
|
||||
shareCopyUrl({
|
||||
origin: "https://communityrule.info",
|
||||
ruleId: "rule-1",
|
||||
shareSlug: null,
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
}),
|
||||
).toBe("https://communityrule.info/rules/rule-1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { isShareSlug } from "../../lib/sharePaths";
|
||||
import { generateShareSlug } from "../../lib/server/shareSlug";
|
||||
|
||||
describe("generateShareSlug", () => {
|
||||
it("returns the rotating slug shape", () => {
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
expect(isShareSlug(generateShareSlug())).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -227,7 +227,7 @@ describe("buildRobots", () => {
|
||||
});
|
||||
|
||||
describe("robotsForPublishedRule", () => {
|
||||
it("leaves listed rules indexable and noindexes unlisted guest-claim pages", () => {
|
||||
it("leaves public-and-featured Rules indexable and noindexes private and shared-by-link pages", () => {
|
||||
expect(robotsForPublishedRule(true)).toBeUndefined();
|
||||
expect(robotsForPublishedRule(false)).toEqual(NO_INDEX_ROBOTS);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { stripImageMetadata } from "../../lib/server/uploads/stripImageMetadata";
|
||||
|
||||
describe("stripImageMetadata", () => {
|
||||
it("drops JPEG APP1 EXIF", () => {
|
||||
const jpeg = Buffer.from([
|
||||
0xff, 0xd8, 0xff, 0xe1, 0x00, 0x06, 0x45, 0x78, 0x69, 0x66, 0xff, 0xda,
|
||||
0x00, 0x01,
|
||||
]);
|
||||
const out = stripImageMetadata(jpeg, "image/jpeg");
|
||||
expect(out[0]).toBe(0xff);
|
||||
expect(out[1]).toBe(0xd8);
|
||||
expect(out.includes(0x45)).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves non-image bytes unchanged", () => {
|
||||
const pdf = Buffer.from("%PDF-1.4");
|
||||
expect(stripImageMetadata(pdf, "application/pdf")).toBe(pdf);
|
||||
});
|
||||
});
|
||||
@@ -5,18 +5,61 @@ import { NextRequest } from "next/server";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const getUploadRootFromEnvMock = vi.fn();
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const getReadablePublishedRuleMock = vi.fn();
|
||||
const browserHoldsUploadGrantMock = vi.fn();
|
||||
let uploadRoot: string | null = null;
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadRoot", () => ({
|
||||
getUploadRootFromEnv: () => getUploadRootFromEnvMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
upload: {
|
||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/publishedRules", () => ({
|
||||
getReadablePublishedRule: (...args: unknown[]) =>
|
||||
getReadablePublishedRuleMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/uploadGrantCookie", () => ({
|
||||
browserHoldsUploadGrant: (...args: unknown[]) =>
|
||||
browserHoldsUploadGrantMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/uploads/[id]/route";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
|
||||
const FEATURED_ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||
const PRIVATE_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||
|
||||
beforeEach(async () => {
|
||||
uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-test-"));
|
||||
getUploadRootFromEnvMock.mockReset();
|
||||
getUploadRootFromEnvMock.mockImplementation(() => uploadRoot);
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
getReadablePublishedRuleMock.mockReset();
|
||||
browserHoldsUploadGrantMock.mockReset();
|
||||
browserHoldsUploadGrantMock.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -34,6 +77,7 @@ describe("GET /api/uploads/[id]", () => {
|
||||
});
|
||||
|
||||
it("returns 404 when the upload is not found", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce(null);
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
"https://x.test/api/uploads/550e8400-e29b-41d4-a716-446655440000",
|
||||
@@ -47,16 +91,93 @@ describe("GET /api/uploads/[id]", () => {
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns the file bytes with content type", async () => {
|
||||
const id = "550e8400-e29b-41d4-a716-446655440000";
|
||||
await writeFile(path.join(uploadRoot!, `${id}.png`), "png-bytes");
|
||||
it("returns featured file bytes with a short public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${FEATURED_ID}.png`), "png-bytes");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: FEATURED_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-1",
|
||||
rule: { visibility: RULE_VISIBILITY.public_and_featured },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.public_and_featured,
|
||||
rule: { isListed: true },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${id}`),
|
||||
{ params: Promise.resolve({ id }) },
|
||||
new NextRequest(`https://x.test/api/uploads/${FEATURED_ID}`),
|
||||
{ params: Promise.resolve({ id: FEATURED_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Content-Type")).toBe("image/png");
|
||||
expect(res.headers.get("Cache-Control")).toContain("immutable");
|
||||
expect(res.headers.get("Cache-Control")).toBe("public, max-age=3600");
|
||||
expect(await res.text()).toBe("png-bytes");
|
||||
});
|
||||
|
||||
it("returns 404 for a private file the viewer cannot read", async () => {
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-private",
|
||||
rule: { visibility: RULE_VISIBILITY.private },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce(null);
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.headers.get("Cache-Control")).toBeNull();
|
||||
});
|
||||
|
||||
it("serves a shared-by-link file to an anonymous viewer without a public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "shared");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: null,
|
||||
draftId: null,
|
||||
ruleId: "rule-shared",
|
||||
rule: { visibility: RULE_VISIBILITY.shared_by_link },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.shared_by_link,
|
||||
rule: { isListed: false },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(getReadablePublishedRuleMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ viaShareSlug: true }),
|
||||
);
|
||||
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
|
||||
});
|
||||
|
||||
it("serves a private file to a permitted reader without a public cache", async () => {
|
||||
await writeFile(path.join(uploadRoot!, `${PRIVATE_ID}.png`), "private");
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
id: PRIVATE_ID,
|
||||
userId: "user-1",
|
||||
draftId: null,
|
||||
ruleId: "rule-private",
|
||||
rule: { visibility: RULE_VISIBILITY.private },
|
||||
draft: null,
|
||||
});
|
||||
getReadablePublishedRuleMock.mockResolvedValueOnce({
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
rule: { isListed: false },
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(`https://x.test/api/uploads/${PRIVATE_ID}`),
|
||||
{ params: Promise.resolve({ id: PRIVATE_ID }) },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
|
||||
expect(await res.text()).toBe("private");
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,10 @@ vi.mock("../../lib/server/session", () => ({
|
||||
clearSessionCookie: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
||||
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { DELETE } from "../../app/api/user/me/route";
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
Reference in new issue
Block a user