Merge pull request 'Keep finished Rules private until a rotating share link is on, and delete files with the Rule' (#102) from adilallo/feature/CR-248-rule-visibility into main

Reviewed-on: #102
This commit was merged in pull request #102.
This commit is contained in:
an.di committed 2026-11-10 04:12:11 +00:00
commit 73d0856004
78 files changed
+4012 -580

No files matched your search

+3
View File
@@ -46,6 +46,9 @@ NEXT_PUBLIC_ENABLE_BACKEND_SYNC=
# SITE_INDEXING=true # SITE_INDEXING=true
# SITE_INDEXING=false # 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). # 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: # In production (e.g. Cloudron localstorage mount), set to the mounted path. Local dev example:
# UPLOAD_ROOT="/absolute/path/to/community-rule/var/uploads" # UPLOAD_ROOT="/absolute/path/to/community-rule/var/uploads"
+9 -13
View File
@@ -253,14 +253,8 @@ function CreateFlowLayoutContent({
resolve?.(choice); resolve?.(choice);
}, []); }, []);
const { const { onSelectExportFormat: onCompletedExportFormat } =
copyPublishedRuleLink, useCompletedRuleShareExport({
mailtoPublishedRule,
sharePublishedRuleViaSignal,
sharePublishedRuleViaSlack,
sharePublishedRuleViaDiscord,
onSelectExportFormat: onCompletedExportFormat,
} = useCompletedRuleShareExport({
setActionBanner: setCompletedFlowBanner, setActionBanner: setCompletedFlowBanner,
}); });
@@ -862,11 +856,13 @@ function CreateFlowLayoutContent({
<Share <Share
isOpen={shareModalOpen} isOpen={shareModalOpen}
onClose={() => setShareModalOpen(false)} onClose={() => setShareModalOpen(false)}
onCopyLink={() => void copyPublishedRuleLink()} ruleId={readLastPublishedRule()?.id ?? null}
onEmailShare={mailtoPublishedRule} onRequestLogin={() =>
onSignalShare={() => void sharePublishedRuleViaSignal()} openLogin({
onSlackShare={() => void sharePublishedRuleViaSlack()} nextPath: pathname,
onDiscordShare={() => void sharePublishedRuleViaDiscord()} backdropVariant: "blurredYellow",
})
}
/> />
<Create <Create
isOpen={leaveConfirmOpen} isOpen={leaveConfirmOpen}
+73 -1
View File
@@ -16,7 +16,18 @@ import {
logout, logout,
requestEmailChange, requestEmailChange,
type MyPublishedRule, type MyPublishedRule,
type PublishedRuleDetailForClient,
} from "../../../lib/create/api"; } from "../../../lib/create/api";
import {
downloadStoredRuleAsPdf,
downloadTextFile,
exportFilenameBase,
exportStoredRuleAsMarkdown,
} from "../../../lib/create/ruleExport";
import {
writeLastPublishedRule,
type StoredLastPublishedRule,
} from "../../../lib/create/lastPublishedRule";
import { import {
CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY, CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY,
CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE, CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE,
@@ -29,7 +40,6 @@ import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftS
import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage"; import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage";
import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry"; import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry";
import { createFlowStepPath } from "../create/utils/createFlowPaths"; import { createFlowStepPath } from "../create/utils/createFlowPaths";
import { writeLastPublishedRule } from "../../../lib/create/lastPublishedRule";
import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useMediaQuery } from "../../hooks/useMediaQuery";
import { import {
ProfilePageSignedOutView, ProfilePageSignedOutView,
@@ -315,6 +325,66 @@ export default function ProfilePageClient() {
void load(); void load();
}, [draftDeleteBusy, load]); }, [draftDeleteBusy, load]);
const toStoredRule = useCallback(
(rule: PublishedRuleDetailForClient): StoredLastPublishedRule | null => {
if (
rule.document === null ||
typeof rule.document !== "object" ||
Array.isArray(rule.document)
) {
return null;
}
return {
id: rule.id,
title: rule.title,
summary: rule.summary,
document: rule.document as Record<string, unknown>,
};
},
[],
);
const handleExportRulePdf = useCallback(
async (id: string) => {
setActionError(null);
const detail = await fetchPublishedRuleDetail(id);
const stored = detail ? toStoredRule(detail.rule) : null;
if (!stored) {
setActionError(t("actionError"));
return;
}
try {
downloadStoredRuleAsPdf(stored);
} catch {
setActionError(t("actionError"));
}
},
[t, toStoredRule],
);
const handleExportRuleMarkdown = useCallback(
async (id: string) => {
setActionError(null);
const detail = await fetchPublishedRuleDetail(id);
const stored = detail ? toStoredRule(detail.rule) : null;
if (!stored) {
setActionError(t("actionError"));
return;
}
try {
const markdown = exportStoredRuleAsMarkdown(stored);
downloadTextFile(
`${exportFilenameBase(stored)}-community-rule.md`,
markdown,
"text/markdown;charset=utf-8",
);
} catch {
setActionError(t("actionError"));
}
},
[t, toStoredRule],
);
const handleConfirmDeleteAccount = useCallback(async () => { const handleConfirmDeleteAccount = useCallback(async () => {
setActionError(null); setActionError(null);
setAccountDeleteBusy(true); setAccountDeleteBusy(true);
@@ -409,6 +479,8 @@ export default function ProfilePageClient() {
}} }}
onCloseDeleteAccount={() => setAccountDeleteOpen(false)} onCloseDeleteAccount={() => setAccountDeleteOpen(false)}
onConfirmDeleteAccount={handleConfirmDeleteAccount} onConfirmDeleteAccount={handleConfirmDeleteAccount}
onExportRulePdf={(id) => void handleExportRulePdf(id)}
onExportRuleMarkdown={(id) => void handleExportRuleMarkdown(id)}
onStartNewCustomRule={handleStartNewCustomRule} onStartNewCustomRule={handleStartNewCustomRule}
/> />
); );
@@ -9,6 +9,7 @@ import type { ListItem, ListSize } from "../../../components/layout/List";
import ListEntry from "../../../components/layout/ListEntry"; import ListEntry from "../../../components/layout/ListEntry";
import Icon from "../../../components/asset/icon"; import Icon from "../../../components/asset/icon";
import Dialog from "../../../components/modals/Dialog"; import Dialog from "../../../components/modals/Dialog";
import DeleteAccount from "../../../components/modals/DeleteAccount";
import Alert from "../../../components/modals/Alert"; import Alert from "../../../components/modals/Alert";
import HeaderLockup from "../../../components/type/HeaderLockup"; import HeaderLockup from "../../../components/type/HeaderLockup";
import { useTranslation } from "../../../contexts/MessagesContext"; import { useTranslation } from "../../../contexts/MessagesContext";
@@ -71,6 +72,8 @@ export type ProfilePageViewProps = {
onOpenDeleteAccount: () => void; onOpenDeleteAccount: () => void;
onCloseDeleteAccount: () => void; onCloseDeleteAccount: () => void;
onConfirmDeleteAccount: () => void; onConfirmDeleteAccount: () => void;
onExportRulePdf: (id: string) => void;
onExportRuleMarkdown: (id: string) => void;
onDismissProfileSuccess: () => void; onDismissProfileSuccess: () => void;
onDismissActionError: () => void; onDismissActionError: () => void;
onDismissRulesError: () => void; onDismissRulesError: () => void;
@@ -194,6 +197,8 @@ export function ProfilePageView({
onOpenDeleteAccount, onOpenDeleteAccount,
onCloseDeleteAccount, onCloseDeleteAccount,
onConfirmDeleteAccount, onConfirmDeleteAccount,
onExportRulePdf,
onExportRuleMarkdown,
onDismissProfileSuccess, onDismissProfileSuccess,
onDismissActionError, onDismissActionError,
onDismissRulesError, onDismissRulesError,
@@ -489,39 +494,18 @@ export function ProfilePageView({
} }
/> />
<Dialog <DeleteAccount
isOpen={accountDeleteOpen} isOpen={accountDeleteOpen}
onClose={() => { onClose={() => {
if (!accountDeleteBusy) onCloseDeleteAccount(); if (!accountDeleteBusy) onCloseDeleteAccount();
}} }}
backdropVariant="blurredYellow" onConfirm={onConfirmDeleteAccount}
title={t("deleteAccountModalTitle")} busy={accountDeleteBusy}
description={t("deleteAccountModalBody")} rules={rules
footer={ .filter((rule) => rule.role === "owner")
<> .map((rule) => ({ id: rule.id, title: rule.title }))}
<Button onExportPdf={onExportRulePdf}
type="button" onExportMarkdown={onExportRuleMarkdown}
size="medium"
buttonType="outline"
palette="default"
onClick={onCloseDeleteAccount}
disabled={accountDeleteBusy}
>
{t("deleteAccountCancel")}
</Button>
<Button
type="button"
size="medium"
buttonType="outline"
danger
palette="default"
onClick={onConfirmDeleteAccount}
disabled={accountDeleteBusy}
>
{t("deleteAccountConfirm")}
</Button>
</>
}
/> />
<Dialog <Dialog
+90
View File
@@ -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>
);
}
+18 -5
View File
@@ -1,7 +1,8 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import messages from "../../../../messages/en/index"; 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 { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../lib/create/publishedDocumentToDisplaySections";
import { import {
robotsForPublishedRule, robotsForPublishedRule,
@@ -14,17 +15,28 @@ interface PageProps {
params: Promise<{ id: string }>; 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({ export async function generateMetadata({
params, params,
}: PageProps): Promise<Metadata> { }: PageProps): Promise<Metadata> {
const { id } = await params; const { id } = await params;
const rule = await getPublicPublishedRuleById(id); const resolved = await loadReadableRule(id);
if (!rule) { if (!resolved) {
return { return {
title: messages.pages.ruleDetail.notFoundTitle, title: messages.pages.ruleDetail.notFoundTitle,
description: "The requested CommunityRule could not be found.", description: "The requested CommunityRule could not be found.",
}; };
} }
const { rule } = resolved;
const description = const description =
typeof rule.summary === "string" && rule.summary.trim().length > 0 typeof rule.summary === "string" && rule.summary.trim().length > 0
? rule.summary ? rule.summary
@@ -51,10 +63,11 @@ export async function generateMetadata({
export default async function PublicRuleDetailPage({ params }: PageProps) { export default async function PublicRuleDetailPage({ params }: PageProps) {
const { id } = await params; const { id } = await params;
const rule = await getPublicPublishedRuleById(id); const resolved = await loadReadableRule(id);
if (!rule) { if (!resolved) {
notFound(); notFound();
} }
const { rule } = resolved;
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document); const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
const description = const description =
@@ -20,12 +20,10 @@ function UseCaseCompletedRuleContainerComponent({
const router = useRouter(); const router = useRouter();
const mdUp = useCreateFlowMdUp(); const mdUp = useCreateFlowMdUp();
const tTopNav = useTranslation("pages.useCasesCompletedRule.topNav"); const tTopNav = useTranslation("pages.useCasesCompletedRule.topNav");
const [shareModalOpen, setShareModalOpen] = useState(false);
const [actionBanner, setActionBanner] = const [actionBanner, setActionBanner] =
useState<UseCaseCompletedRuleActionBanner | null>(null); useState<UseCaseCompletedRuleActionBanner | null>(null);
const { copyPageLink, mailtoPageLink, handleDuplicate } = const { copyPageLink, handleDuplicate } = useUseCaseCompletedRuleActions({
useUseCaseCompletedRuleActions({
slug, slug,
fixture, fixture,
setActionBanner, setActionBanner,
@@ -40,11 +38,7 @@ function UseCaseCompletedRuleContainerComponent({
duplicateLabel={tTopNav("duplicate")} duplicateLabel={tTopNav("duplicate")}
duplicateAriaLabel={tTopNav("duplicateAriaLabel")} duplicateAriaLabel={tTopNav("duplicateAriaLabel")}
exitLabel={tTopNav("return")} exitLabel={tTopNav("return")}
shareModalOpen={shareModalOpen} onShare={() => void copyPageLink()}
onShareOpen={() => setShareModalOpen(true)}
onShareClose={() => setShareModalOpen(false)}
onCopyLink={() => void copyPageLink()}
onEmailShare={mailtoPageLink}
onDuplicate={() => void handleDuplicate()} onDuplicate={() => void handleDuplicate()}
onExit={() => router.push(`/use-cases/${slug}`)} onExit={() => router.push(`/use-cases/${slug}`)}
actionBanner={actionBanner} actionBanner={actionBanner}
@@ -14,11 +14,7 @@ export type UseCaseCompletedRuleViewProps = UseCaseCompletedRuleProps & {
duplicateLabel: string; duplicateLabel: string;
duplicateAriaLabel: string; duplicateAriaLabel: string;
exitLabel: string; exitLabel: string;
shareModalOpen: boolean; onShare: () => void;
onShareOpen: () => void;
onShareClose: () => void;
onCopyLink: () => void;
onEmailShare: () => void;
onDuplicate: () => void; onDuplicate: () => void;
onExit: () => void; onExit: () => void;
actionBanner: UseCaseCompletedRuleActionBanner | null; actionBanner: UseCaseCompletedRuleActionBanner | null;
@@ -2,7 +2,6 @@
import CommunityRule from "../../../../../components/type/CommunityRule"; import CommunityRule from "../../../../../components/type/CommunityRule";
import CreateFlowTopNav from "../../../../../components/navigation/CreateFlowTopNav"; import CreateFlowTopNav from "../../../../../components/navigation/CreateFlowTopNav";
import Share from "../../../../../components/modals/Share";
import Alert from "../../../../../components/modals/Alert"; import Alert from "../../../../../components/modals/Alert";
import { CreateFlowHeaderLockup } from "../../../../../(app)/create/components/CreateFlowHeaderLockup"; import { CreateFlowHeaderLockup } from "../../../../../(app)/create/components/CreateFlowHeaderLockup";
import { import {
@@ -19,11 +18,7 @@ export function UseCaseCompletedRuleView({
duplicateLabel, duplicateLabel,
duplicateAriaLabel, duplicateAriaLabel,
exitLabel, exitLabel,
shareModalOpen, onShare,
onShareOpen,
onShareClose,
onCopyLink,
onEmailShare,
onDuplicate, onDuplicate,
onExit, onExit,
actionBanner, actionBanner,
@@ -59,15 +54,6 @@ export function UseCaseCompletedRuleView({
</div> </div>
</div> </div>
) : null} ) : null}
<Share
isOpen={shareModalOpen}
onClose={onShareClose}
onCopyLink={onCopyLink}
onEmailShare={onEmailShare}
onSignalShare={onCopyLink}
onSlackShare={onCopyLink}
onDiscordShare={onCopyLink}
/>
<CreateFlowTopNav <CreateFlowTopNav
hasShare hasShare
hasDuplicate hasDuplicate
@@ -76,7 +62,7 @@ export function UseCaseCompletedRuleView({
exitLabel={exitLabel} exitLabel={exitLabel}
buttonPalette="inverse" buttonPalette="inverse"
className="relative z-[21] shrink-0 !bg-transparent" className="relative z-[21] shrink-0 !bg-transparent"
onShare={onShareOpen} onShare={onShare}
onDuplicate={onDuplicate} onDuplicate={onDuplicate}
onExit={onExit} onExit={onExit}
/> />
+14
View File
@@ -11,6 +11,8 @@ import { apiRoute } from "../../../../lib/server/apiRoute";
import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas"; import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
import { readLimitedJson } from "../../../../lib/server/validation/requestBody"; import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp"; 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 () => { export const GET = apiRoute("drafts.me.get", async () => {
if (!isDatabaseConfigured()) { if (!isDatabaseConfigured()) {
@@ -67,6 +69,11 @@ export const PUT = apiRoute("drafts.me.put", async (request: NextRequest) => {
payload: jsonPayload, payload: jsonPayload,
}, },
}); });
await linkUploadsToDraft({
draftId: draft.id,
payload,
userId: user.id,
});
return NextResponse.json({ return NextResponse.json({
draft: { payload: draft.payload, updatedAt: draft.updatedAt }, 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 // Idempotent: missing draft is a no-op so callers can fire-and-forget after
// publish / exit without worrying about prior state. // 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 } }); await prisma.ruleDraft.deleteMany({ where: { userId: user.id } });
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
+21 -15
View File
@@ -8,9 +8,11 @@ import {
notFound, notFound,
unauthorized, unauthorized,
} from "../../../../lib/server/responses"; } from "../../../../lib/server/responses";
import { getPublicPublishedRuleById } from "../../../../lib/server/publishedRules"; import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
import { getSessionUser } from "../../../../lib/server/session"; import { getSessionUser } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute"; 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 { publishRuleBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
import { readLimitedJson } from "../../../../lib/server/validation/requestBody"; import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp"; import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
@@ -19,29 +21,27 @@ type RouteContext = { params: Promise<{ id: string }> };
export const GET = apiRoute<RouteContext>( export const GET = apiRoute<RouteContext>(
"rules.byId", "rules.byId",
async (_request, context) => { async (request, context) => {
if (!isDatabaseConfigured()) { if (!isDatabaseConfigured()) {
return dbUnavailable(); return dbUnavailable();
} }
const { id } = await context.params; const { id } = await context.params;
const user = await getSessionUser();
const rule = await getPublicPublishedRuleById(id); const resolved = await getReadablePublishedRule({
if (!rule) { idOrSlug: id,
user,
viaShareSlug: false,
requestPath: request.nextUrl.pathname,
});
if (!resolved) {
return notFound(); return notFound();
} }
const user = await getSessionUser(); return NextResponse.json({
let viewerIsOwner = false; rule: resolved.rule,
if (user) { viewerIsOwner: resolved.viewerIsOwner,
const ownerRow = await prisma.publishedRule.findUnique({
where: { id },
select: { userId: true },
}); });
viewerIsOwner = ownerRow?.userId === user.id;
}
return NextResponse.json({ rule, viewerIsOwner });
}, },
); );
@@ -90,6 +90,11 @@ export const PATCH = apiRoute<RouteContext>(
document: document as Prisma.InputJsonValue, document: document as Prisma.InputJsonValue,
}, },
}); });
await linkUploadsToRule({
ruleId: row.id,
document,
userId: user.id,
});
return NextResponse.json({ ok: true }); 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"); return forbidden("You do not have permission to delete this rule");
} }
await deleteUploadsForRule(row.id);
await prisma.publishedRule.delete({ where: { id: row.id } }); await prisma.publishedRule.delete({ where: { id: row.id } });
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
+86
View File
@@ -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 });
},
);
+18
View File
@@ -25,6 +25,7 @@ import { stakeholderInviteVerifyUrl } from "../../../lib/server/ruleStakeholderI
import { STAKEHOLDER_INVITE_TTL_MS } from "../../../lib/server/ruleStakeholders"; import { STAKEHOLDER_INVITE_TTL_MS } from "../../../lib/server/ruleStakeholders";
import { getSessionUser } from "../../../lib/server/session"; import { getSessionUser } from "../../../lib/server/session";
import { issueGuestRuleClaimCookie } from "../../../lib/server/guestRuleClaim"; import { issueGuestRuleClaimCookie } from "../../../lib/server/guestRuleClaim";
import { linkUploadsToRule } from "../../../lib/server/uploads/linkUploads";
import { apiRoute } from "../../../lib/server/apiRoute"; import { apiRoute } from "../../../lib/server/apiRoute";
import { getPublicOrigin } from "../../../lib/server/publicOrigin"; import { getPublicOrigin } from "../../../lib/server/publicOrigin";
import { import {
@@ -123,6 +124,12 @@ export const POST = apiRoute(
}); });
} }
await linkUploadsToRule({
ruleId: rule.id,
document,
userId: null,
});
return NextResponse.json({ return NextResponse.json({
rule: { rule: {
id: rule.id, id: rule.id,
@@ -155,6 +162,11 @@ export const POST = apiRoute(
document: document as Prisma.InputJsonValue, document: document as Prisma.InputJsonValue,
}, },
}); });
await linkUploadsToRule({
ruleId: rule.id,
document,
userId: user.id,
});
return NextResponse.json({ return NextResponse.json({
rule: { rule: {
@@ -241,6 +253,12 @@ export const POST = apiRoute(
); );
} }
await linkUploadsToRule({
ruleId: rule.id,
document,
userId: user.id,
});
return NextResponse.json({ return NextResponse.json({
rule: { rule: {
id: rule.id, id: rule.id,
+69 -7
View File
@@ -1,30 +1,92 @@
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { apiRoute } from "../../../../lib/server/apiRoute"; import { apiRoute } from "../../../../lib/server/apiRoute";
import { prisma } from "../../../../lib/server/db";
import { isDatabaseConfigured } from "../../../../lib/server/env";
import { import {
dbUnavailable,
notFound, notFound,
serverMisconfigured, serverMisconfigured,
} from "../../../../lib/server/responses"; } 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 { resolveUploadedFileById } from "../../../../lib/server/uploads/resolveUploadedFile";
import { getUploadRootFromEnv } from "../../../../lib/server/uploads/uploadRoot"; 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 }> }; type RouteContext = { params: Promise<{ id: string }> };
/** function cacheControlForVisibility(
* Public read for opaque upload ids (no auth). Unguessable UUID stem; visibility: "private" | "shared_by_link" | "public_and_featured" | null,
* do not use for sensitive documents without revisiting policy. ): string {
*/ if (visibility === RULE_VISIBILITY.public_and_featured) {
return "public, max-age=3600";
}
return "private, no-store";
}
export const GET = apiRoute<RouteContext>( export const GET = apiRoute<RouteContext>(
"uploads.byId", "uploads.byId",
async (_request, context) => { async (request, context) => {
if (!getUploadRootFromEnv()) { if (!getUploadRootFromEnv()) {
return serverMisconfigured( return serverMisconfigured(
"File uploads are not configured (UPLOAD_ROOT is unset).", "File uploads are not configured (UPLOAD_ROOT is unset).",
); );
} }
if (!isDatabaseConfigured()) {
return dbUnavailable();
}
const { id } = await context.params; 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,
lookup: "id",
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) { if (!resolved) {
return notFound("Upload not found"); return notFound("Upload not found");
} }
@@ -34,7 +96,7 @@ export const GET = apiRoute<RouteContext>(
status: 200, status: 200,
headers: { headers: {
"Content-Type": resolved.contentType, "Content-Type": resolved.contentType,
"Cache-Control": "public, max-age=31536000, immutable", "Cache-Control": cacheControlForVisibility(visibility),
"X-Content-Type-Options": "nosniff", "X-Content-Type-Options": "nosniff",
}, },
}); });
+10
View File
@@ -11,6 +11,7 @@ import { getSessionUser } from "../../../lib/server/session";
import { apiRoute } from "../../../lib/server/apiRoute"; import { apiRoute } from "../../../lib/server/apiRoute";
import { rateLimitKey } from "../../../lib/server/rateLimit"; import { rateLimitKey } from "../../../lib/server/rateLimit";
import { saveCreateFlowUpload } from "../../../lib/server/uploads/saveCreateFlowUpload"; import { saveCreateFlowUpload } from "../../../lib/server/uploads/saveCreateFlowUpload";
import { issueGuestUploadGrantCookie } from "../../../lib/server/uploads/uploadGrantCookie";
import { getUploadRootFromEnv } from "../../../lib/server/uploads/uploadRoot"; import { getUploadRootFromEnv } from "../../../lib/server/uploads/uploadRoot";
import { import {
CREATE_FLOW_UPLOAD_MAX_BYTES, CREATE_FLOW_UPLOAD_MAX_BYTES,
@@ -146,6 +147,7 @@ export const POST = apiRoute("uploads.post", async (request: NextRequest) => {
const saved = await saveCreateFlowUpload({ const saved = await saveCreateFlowUpload({
purpose: purposeRaw, purpose: purposeRaw,
buffer: buf, buffer: buf,
userId: user?.id ?? null,
}); });
if ("error" in saved) { 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({ return NextResponse.json({
url: saved.urlPath, url: saved.urlPath,
id: saved.id, id: saved.id,
+4 -5
View File
@@ -11,15 +11,13 @@ import {
getSessionUser, getSessionUser,
} from "../../../../lib/server/session"; } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute"; import { apiRoute } from "../../../../lib/server/apiRoute";
import { deleteUploadsForUser } from "../../../../lib/server/uploads/deleteUploadedFiles";
/** /**
* Delete the signed-in user and associated data. * Delete the signed-in user and associated data.
* *
* **Policy (CR-86 / Ticket 15):** Prisma `User` deletion cascades `Session` and * Prisma `User` deletion cascades `Session`, `RuleDraft`, and `PublishedRule`
* `RuleDraft`. `PublishedRule` uses `onDelete: SetNull` on `userId`, so published * (and uploads linked to those rows). Disk files are removed first.
* 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.
*/ */
export const DELETE = apiRoute("user.me.delete", async () => { export const DELETE = apiRoute("user.me.delete", async () => {
if (!isDatabaseConfigured()) { if (!isDatabaseConfigured()) {
@@ -32,6 +30,7 @@ export const DELETE = apiRoute("user.me.delete", async () => {
} }
try { try {
await deleteUploadsForUser(user.id);
await prisma.user.delete({ where: { id: user.id } }); await prisma.user.delete({ where: { id: user.id } });
} catch { } catch {
return internalError("Failed to delete account"); return internalError("Failed to delete account");
@@ -12,6 +12,8 @@ const backdropOverlayClasses: Record<CreateModalBackdropVariant, string> = {
"fixed inset-0 z-[9998] bg-[var(--color-surface-invert-brand-primary)]/85 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--color-surface-invert-brand-primary)]/75", "fixed inset-0 z-[9998] bg-[var(--color-surface-invert-brand-primary)]/85 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--color-surface-invert-brand-primary)]/75",
}; };
export type CreateModalPresentationValue = "dialog" | "sheet";
export type CreateModalFrameViewProps = { export type CreateModalFrameViewProps = {
isOpen: boolean; isOpen: boolean;
onOverlayClick: () => void; onOverlayClick: () => void;
@@ -24,6 +26,11 @@ export type CreateModalFrameViewProps = {
children: ReactNode; children: ReactNode;
/** Rendered below the dialog card on the backdrop (e.g. “Back to home”). */ /** Rendered below the dialog card on the backdrop (e.g. “Back to home”). */
belowCard?: ReactNode; belowCard?: ReactNode;
/**
* `sheet` is full-viewport below `md` (Figma 320–639) and a 546px dialog
* from `md`. `dialog` is the centered card used by Create and Dialog.
*/
presentation?: CreateModalPresentationValue;
}; };
/** /**
@@ -40,13 +47,22 @@ export function CreateModalFrameView({
dialogRef, dialogRef,
children, children,
belowCard, belowCard,
presentation = "dialog",
}: CreateModalFrameViewProps) { }: CreateModalFrameViewProps) {
if (!isOpen) return null; if (!isOpen) return null;
const isSheet = presentation === "sheet";
const overlayLayout = isSheet
? "flex flex-col items-stretch justify-end overflow-hidden p-0 md:items-center md:justify-center md:gap-6 md:overflow-y-auto md:px-4 md:py-8"
: "flex flex-col items-center justify-center gap-6 overflow-y-auto px-4 py-8";
const dialogShell = isSheet
? "flex h-dvh max-h-dvh min-h-0 w-full shrink-0 flex-col overflow-hidden rounded-none bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] md:h-auto md:max-h-[90vh] md:w-[546px] md:max-w-[546px] md:rounded-[var(--radius-500)]"
: "flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999]";
const content = ( const content = (
<div <div
ref={overlayRef} ref={overlayRef}
className={`${backdropOverlayClasses[backdropVariant]} flex flex-col items-center justify-center gap-6 overflow-y-auto px-4 py-8`} className={`${backdropOverlayClasses[backdropVariant]} ${overlayLayout}`}
onClick={onOverlayClick} onClick={onOverlayClick}
role="presentation" role="presentation"
> >
@@ -56,7 +72,7 @@ export function CreateModalFrameView({
aria-modal="true" aria-modal="true"
aria-label={ariaLabel} aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy} aria-labelledby={ariaLabelledBy}
className={`flex min-h-0 max-h-[90vh] w-full max-w-[560px] shrink-0 flex-col overflow-hidden rounded-[var(--radius-500)] bg-[var(--color-surface-default-primary)] shadow-[0px_0px_48px_0px_rgba(0,0,0,0.1)] z-[9999] ${className}`} className={`${dialogShell} ${className}`}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
{children} {children}
@@ -0,0 +1,60 @@
"use client";
/**
* Figma: Overlay / Modal / Delete Account (24985:1959)
* https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=24985-1959
*/
import { memo, useEffect, useId, useRef, useState } from "react";
import { useMessages } from "../../../contexts/MessagesContext";
import { useCreateModalA11y } from "../Create/useCreateModalA11y";
import { DeleteAccountView } from "./DeleteAccount.view";
import type { DeleteAccountProps } from "./DeleteAccount.types";
const DeleteAccountContainer = memo<DeleteAccountProps>((props) => {
const {
isOpen,
onClose,
onConfirm,
busy = false,
rules,
onExportPdf,
onExportMarkdown,
className = "",
backdropVariant = "blurredYellow",
} = props;
const dialogRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null);
const titleId = useId();
const copy = useMessages().modals.deleteAccount;
const [understood, setUnderstood] = useState(false);
useCreateModalA11y(isOpen, busy ? () => undefined : onClose, dialogRef);
useEffect(() => {
if (!isOpen) setUnderstood(false);
}, [isOpen]);
return (
<DeleteAccountView
isOpen={isOpen}
onClose={onClose}
onConfirm={onConfirm}
busy={busy}
rules={rules}
onExportPdf={onExportPdf}
onExportMarkdown={onExportMarkdown}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef}
overlayRef={overlayRef}
titleId={titleId}
copy={copy}
understood={understood}
onUnderstoodChange={setUnderstood}
/>
);
});
DeleteAccountContainer.displayName = "DeleteAccount";
export default DeleteAccountContainer;
@@ -0,0 +1,50 @@
import type { RefObject } from "react";
import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view";
export type DeleteAccountRule = {
id: string;
title: string;
};
export type DeleteAccountProps = {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
busy?: boolean;
rules: DeleteAccountRule[];
onExportPdf: (_id: string) => void;
onExportMarkdown: (_id: string) => void;
className?: string;
backdropVariant?: CreateModalBackdropVariant;
};
export type DeleteAccountCopy = {
title: string;
description: string;
yourRules: string;
exportPdf: string;
exportMarkdown: string;
confirmLabel: string;
confirmHint: string;
cancel: string;
confirm: string;
closeDialogAriaLabel: string;
};
export type DeleteAccountViewProps = {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
busy: boolean;
rules: DeleteAccountRule[];
onExportPdf: (_id: string) => void;
onExportMarkdown: (_id: string) => void;
className: string;
backdropVariant: CreateModalBackdropVariant;
dialogRef: RefObject<HTMLDivElement | null>;
overlayRef: RefObject<HTMLDivElement | null>;
titleId: string;
copy: DeleteAccountCopy;
understood: boolean;
onUnderstoodChange: (_checked: boolean) => void;
};
@@ -0,0 +1,139 @@
"use client";
import { memo } from "react";
import Avatar from "../../asset/Avatar";
import Icon from "../../asset/icon";
import Button from "../../buttons/Button";
import Checkbox from "../../controls/Checkbox";
import { CreateModalFrameView } from "../Create/CreateModalFrame.view";
import ModalHeader from "../ModalHeader";
import ContentLockup from "../../type/ContentLockup";
import { communityInviteInitials } from "../../../../lib/create/ruleInviteCardMeta";
import type { DeleteAccountViewProps } from "./DeleteAccount.types";
export const DeleteAccountView = memo(function DeleteAccountView({
isOpen,
onClose,
onConfirm,
busy,
rules,
onExportPdf,
onExportMarkdown,
className,
backdropVariant,
dialogRef,
overlayRef,
titleId,
copy,
understood,
onUnderstoodChange,
}: DeleteAccountViewProps) {
return (
<CreateModalFrameView
isOpen={isOpen}
onOverlayClick={busy ? () => undefined : onClose}
backdropVariant={backdropVariant}
presentation="sheet"
className={className}
ariaLabel={copy.title}
ariaLabelledBy={titleId}
overlayRef={overlayRef}
dialogRef={dialogRef}
>
<ModalHeader
onClose={busy ? undefined : onClose}
showMoreOptionsButton={false}
closeButtonAriaLabel={copy.closeDialogAriaLabel}
/>
<div className="shrink-0 bg-[var(--color-surface-default-primary)] px-6">
<ContentLockup
title={copy.title}
description={copy.description}
variant="modal"
alignment="left"
titleId={titleId}
/>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-x-clip overflow-y-auto px-6 pb-6 pt-6">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.yourRules}
</p>
{rules.map((rule) => (
<div
key={rule.id}
className="flex w-full items-center gap-3 overflow-hidden rounded-[12px] bg-[var(--color-surface-default-secondary)] p-3"
>
<Avatar
alt=""
initials={communityInviteInitials(rule.title)}
size="large"
shape="circle"
variant="filled"
/>
<p className="min-w-0 flex-1 truncate text-small-label text-[var(--color-content-default-primary)]">
{rule.title}
</p>
<div className="flex shrink-0 items-start gap-2">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={() => onExportPdf(rule.id)}
>
<Icon name="picture_as_pdf" size={14} />
{copy.exportPdf}
</Button>
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={() => onExportMarkdown(rule.id)}
>
<Icon name="markdown_copy" size={14} />
{copy.exportMarkdown}
</Button>
</div>
</div>
))}
<Checkbox
checked={understood}
disabled={busy}
label={copy.confirmLabel}
onChange={(data) => onUnderstoodChange(data.checked)}
/>
</div>
<div className="flex shrink-0 items-center justify-end gap-2 border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={busy}
onClick={onClose}
>
{copy.cancel}
</Button>
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
danger
disabled={busy || !understood}
onClick={onConfirm}
>
{copy.confirm}
</Button>
</div>
</CreateModalFrameView>
);
});
DeleteAccountView.displayName = "DeleteAccountView";
@@ -0,0 +1,5 @@
export { default } from "./DeleteAccount.container";
export type {
DeleteAccountProps,
DeleteAccountRule,
} from "./DeleteAccount.types";
+317 -30
View File
@@ -1,62 +1,349 @@
"use client"; "use client";
/** /**
* Figma: Community Rule System — "Modal / Share" * Figma: Overlay / Modal / Share (24972:2094)
* https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=22073-30884 * https://www.figma.com/design/agv0VBLiBlcnSAaiAORgPR/Community-Rule-System?node-id=24972-2094
* Copy-link hover / Copied! : 23769:27494 / 23769:27443
*/ */
import { memo, useCallback, useEffect, useId, useRef, useState } from "react"; import { memo, useCallback, useEffect, useId, useRef, useState } from "react";
import { useTranslation } from "../../../contexts/MessagesContext"; import { useMessages } from "../../../contexts/MessagesContext";
import {
addRuleStakeholder,
fetchRuleShare,
patchRuleShare,
} from "../../../../lib/create/api";
import { MAX_STAKEHOLDER_EMAILS } from "../../../../lib/create/stakeholderLimits";
import {
formatInviteCountWord,
parseInvitePaste,
} from "../../../../lib/create/parseInviteEmails";
import {
emailInitials,
visibleShareReaders,
type RuleShareSettings,
} from "../../../../lib/ruleShareTypes";
import { RULE_VISIBILITY } from "../../../../lib/ruleVisibility";
import { useCreateModalA11y } from "../Create/useCreateModalA11y"; import { useCreateModalA11y } from "../Create/useCreateModalA11y";
import { ShareView } from "./Share.view"; import { ShareView } from "./Share.view";
import type { ShareProps } from "./Share.types"; import type { SharePhase, ShareProps } from "./Share.types";
function selectValueFor(
visibility: RuleShareSettings["visibility"],
phase: SharePhase,
): "private" | "shared_by_link" {
if (phase === "confirm" || phase === "error") return "shared_by_link";
if (visibility === RULE_VISIBILITY.private) return "private";
return "shared_by_link";
}
function titleCountWord(n: number): string {
const word = formatInviteCountWord(n);
return word.charAt(0).toUpperCase() + word.slice(1);
}
const ShareContainer = memo<ShareProps>((props) => { const ShareContainer = memo<ShareProps>((props) => {
const {
isOpen,
onClose,
ruleId = null,
previewSettings,
onRequestLogin,
className = "",
backdropVariant = "blurredYellow",
} = props;
const dialogRef = useRef<HTMLDivElement>(null); const dialogRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLDivElement>(null); const overlayRef = useRef<HTMLDivElement>(null);
const titleId = useId(); const titleId = useId();
const t = useTranslation("modals.share"); const copy = useMessages().modals.share;
const [linkCopied, setLinkCopied] = useState(false);
useCreateModalA11y(props.isOpen, props.onClose, dialogRef); const [settings, setSettings] = useState<RuleShareSettings | null>(
previewSettings ?? null,
);
const [phase, setPhase] = useState<SharePhase>("idle");
const [communityAgreed, setCommunityAgreed] = useState(false);
const [inviteValue, setInviteValue] = useState("");
const [inviteBusy, setInviteBusy] = useState(false);
const [inviteError, setInviteError] = useState<string | null>(null);
const [turnOnBusy, setTurnOnBusy] = useState(false);
const [linkCopied, setLinkCopied] = useState(false);
const [saveFailed, setSaveFailed] = useState(false);
useCreateModalA11y(isOpen, onClose, dialogRef);
useEffect(() => { useEffect(() => {
if (!props.isOpen) { if (!isOpen) {
setPhase("idle");
setCommunityAgreed(false);
setInviteValue("");
setInviteError(null);
setLinkCopied(false); setLinkCopied(false);
setTurnOnBusy(false);
setSaveFailed(false);
if (!previewSettings) setSettings(null);
return;
} }
}, [props.isOpen]); if (previewSettings) {
setSettings(previewSettings);
return;
}
if (!ruleId) return;
let cancelled = false;
void (async () => {
const res = await fetchRuleShare(ruleId);
if (cancelled) return;
if (res.ok === false) {
if (res.status === 401) {
onRequestLogin?.();
onClose();
}
return;
}
setSettings(res.share);
})();
return () => {
cancelled = true;
};
}, [isOpen, onClose, onRequestLogin, previewSettings, ruleId]);
const onCopyLinkClick = useCallback(async () => { const applySettings = useCallback((next: RuleShareSettings) => {
try { setSettings(next);
const result = await props.onCopyLink(); setPhase("idle");
if (result !== false) { setCommunityAgreed(false);
setLinkCopied(true); setSaveFailed(false);
}, []);
const handleSelectValue = useCallback(
(value: string) => {
if (!settings) return;
if (value === "private") {
if (
settings.visibility === RULE_VISIBILITY.private &&
(phase === "confirm" || phase === "error")
) {
setPhase("idle");
setCommunityAgreed(false);
return;
} }
if (settings.visibility === RULE_VISIBILITY.private) return;
if (!ruleId) {
applySettings({
...settings,
visibility: RULE_VISIBILITY.private,
shareSlug: null,
shareUrlDisplay: null,
});
return;
}
void (async () => {
const res = await patchRuleShare(ruleId, "private");
if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
})();
return;
}
if (value === "shared_by_link") {
if (
settings.visibility === RULE_VISIBILITY.shared_by_link ||
settings.visibility === RULE_VISIBILITY.public_and_featured
) {
setPhase("idle");
return;
}
setPhase("confirm");
setCommunityAgreed(false);
setSaveFailed(false);
}
},
[applySettings, phase, ruleId, settings],
);
const handleTurnOnLink = useCallback(async () => {
if (!settings || !communityAgreed || turnOnBusy) return;
if (!ruleId) {
applySettings({
...settings,
visibility: RULE_VISIBILITY.shared_by_link,
shareSlug: settings.shareSlug ?? "k7f2-9qxm",
shareUrlDisplay:
settings.shareUrlDisplay ?? "communityrule.info/r/k7f2-9qxm",
});
return;
}
setTurnOnBusy(true);
const res = await patchRuleShare(ruleId, "shared_by_link", true);
setTurnOnBusy(false);
if (res.ok === false) {
setPhase("error");
return;
}
applySettings(res.share);
}, [applySettings, communityAgreed, ruleId, settings, turnOnBusy]);
const handleTurnOffLink = useCallback(async () => {
if (!settings) return;
if (!ruleId) {
applySettings({
...settings,
visibility: RULE_VISIBILITY.private,
shareSlug: null,
shareUrlDisplay: null,
});
return;
}
const res = await patchRuleShare(ruleId, "private");
if (res.ok) {
applySettings(res.share);
return;
}
setSaveFailed(true);
}, [applySettings, ruleId, settings]);
const handleInvite = useCallback(async () => {
if (!settings || inviteBusy) return;
const existing = [
settings.ownerEmail,
...settings.readers.map((r) => r.email),
];
const parsed = parseInvitePaste(
inviteValue,
existing,
MAX_STAKEHOLDER_EMAILS,
);
const email = parsed.added[0];
if (!email) {
setInviteError(copy.inviteInvalid);
return;
}
setInviteError(null);
if (!ruleId) {
setSettings({
...settings,
readers: [
...settings.readers,
{ email, initials: emailInitials(email), role: "reader" },
],
});
setInviteValue("");
return;
}
setInviteBusy(true);
const res = await addRuleStakeholder(ruleId, email);
if (res.ok === false) {
setInviteBusy(false);
setInviteError(res.error);
return;
}
const next = await fetchRuleShare(ruleId);
setInviteBusy(false);
if (next.ok) {
setSettings(next.share);
setInviteValue("");
}
}, [copy.inviteInvalid, inviteBusy, inviteValue, ruleId, settings]);
const handleCopyLink = useCallback(async () => {
if (!settings) return;
try {
await navigator.clipboard.writeText(settings.shareUrl);
setLinkCopied(true);
} catch { } catch {
setLinkCopied(false); setLinkCopied(false);
} }
}, [props.onCopyLink]); }, [settings]);
if (!settings) {
return ( return (
<ShareView <ShareView
{...props} isOpen={isOpen}
onClose={onClose}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef} dialogRef={dialogRef}
overlayRef={overlayRef} overlayRef={overlayRef}
titleId={titleId} titleId={titleId}
title={t("title")} copy={copy}
description={t("description")} communityName=""
copyLinkLabel={t("copyLink")} inviteValue=""
copiedLabel={t("copied")} onInviteValueChange={setInviteValue}
copiedLive={t("copiedLive")} onInvite={() => undefined}
inviteBusy={false}
inviteError={null}
ownerEmail=""
ownerInitials="?"
shownReaders={[]}
overflowLabel={null}
selectValue="private"
onSelectValue={() => undefined}
showLinkField={false}
shareUrlDisplay=""
onTurnOffLink={() => undefined}
showConfirm={false}
communityAgreed={false}
onCommunityAgreedChange={setCommunityAgreed}
onTurnOnLink={() => undefined}
turnOnDisabled
turnOnBusy={false}
showError={false}
showSaveError={false}
copyEnabled={false}
linkCopied={false}
onCopyLink={() => undefined}
/>
);
}
const selectValue = selectValueFor(settings.visibility, phase);
const { shown, overflowCount } = visibleShareReaders(settings.readers);
const overflowLabel =
overflowCount > 0
? copy.overflowReaders.replace("{{count}}", titleCountWord(overflowCount))
: null;
const showLinkField =
settings.visibility === RULE_VISIBILITY.shared_by_link && phase === "idle";
const showConfirm = phase === "confirm" || phase === "error";
const copyEnabled = phase !== "confirm" && phase !== "error";
return (
<ShareView
isOpen={isOpen}
onClose={onClose}
className={className}
backdropVariant={backdropVariant}
dialogRef={dialogRef}
overlayRef={overlayRef}
titleId={titleId}
copy={copy}
communityName={settings.title}
inviteValue={inviteValue}
onInviteValueChange={(value) => {
setInviteValue(value);
if (inviteError) setInviteError(null);
}}
onInvite={() => void handleInvite()}
inviteBusy={inviteBusy}
inviteError={inviteError}
ownerEmail={settings.ownerEmail}
ownerInitials={settings.ownerInitials}
shownReaders={shown}
overflowLabel={overflowLabel}
selectValue={selectValue}
onSelectValue={handleSelectValue}
showLinkField={showLinkField}
shareUrlDisplay={settings.shareUrlDisplay ?? ""}
onTurnOffLink={() => void handleTurnOffLink()}
showConfirm={showConfirm}
communityAgreed={communityAgreed}
onCommunityAgreedChange={setCommunityAgreed}
onTurnOnLink={() => void handleTurnOnLink()}
turnOnDisabled={!communityAgreed}
turnOnBusy={turnOnBusy}
showError={phase === "error"}
showSaveError={saveFailed}
copyEnabled={copyEnabled}
linkCopied={linkCopied} linkCopied={linkCopied}
onCopyLinkClick={onCopyLinkClick} onCopyLink={() => void handleCopyLink()}
signalLabel={t("signal")}
slackLabel={t("slack")}
discordLabel={t("discord")}
emailLabel={t("email")}
doneLabel={t("done")}
closeDialogAriaLabel={t("closeDialogAriaLabel")}
moreOptionsAriaLabel={t("moreOptionsAriaLabel")}
/> />
); );
}); });
+74 -29
View File
@@ -1,43 +1,88 @@
import type { ReactNode, RefObject } from "react"; import type { RefObject } from "react";
import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view"; import type { CreateModalBackdropVariant } from "../Create/CreateModalFrame.view";
import type {
RuleShareSettings,
SharePerson,
} from "../../../../lib/ruleShareTypes";
export type SharePhase = "idle" | "confirm" | "error";
export type ShareProps = { export type ShareProps = {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
/** Return `false` when the clipboard write did not succeed. */ ruleId?: string | null;
onCopyLink: () => void | boolean | Promise<void | boolean>; /** Story / test seed. Skips the share API when set. */
onEmailShare: () => void; previewSettings?: RuleShareSettings;
onSignalShare: () => void | Promise<void>; onRequestLogin?: () => void;
onSlackShare: () => void | Promise<void>;
onDiscordShare: () => void | Promise<void>;
className?: string; className?: string;
backdropVariant?: CreateModalBackdropVariant; backdropVariant?: CreateModalBackdropVariant;
}; };
export type ShareViewProps = ShareProps & { export type ShareCopy = {
title: string;
addPeoplePlaceholder: string;
invite: string;
inviteInvalid: string;
peopleWithAccess: string;
you: string;
holdsThePen: string;
canRead: string;
overflowReaders: string;
whoCanRead: string;
inviteOnly: string;
inviteOnlyHint: string;
anyoneWithLink: string;
anyoneWithLinkHint: string;
confirmBody: string;
communityAgreed: string;
turnOnLink: string;
turnOffLink: string;
linkHint: string;
copyLink: string;
copied: string;
copiedLive: string;
done: string;
errorTitle: string;
errorDescription: string;
saveErrorTitle: string;
saveErrorDescription: string;
closeDialogAriaLabel: string;
accessSelectAriaLabel: string;
};
export type ShareViewProps = {
isOpen: boolean;
onClose: () => void;
className: string;
backdropVariant: CreateModalBackdropVariant;
dialogRef: RefObject<HTMLDivElement | null>; dialogRef: RefObject<HTMLDivElement | null>;
overlayRef: RefObject<HTMLDivElement | null>; overlayRef: RefObject<HTMLDivElement | null>;
titleId: string; titleId: string;
title: string; copy: ShareCopy;
description: string; communityName: string;
copyLinkLabel: string; inviteValue: string;
copiedLabel: string; onInviteValueChange: (_value: string) => void;
copiedLive: string; onInvite: () => void;
inviteBusy: boolean;
inviteError: string | null;
ownerEmail: string;
ownerInitials: string;
shownReaders: SharePerson[];
overflowLabel: string | null;
selectValue: "private" | "shared_by_link";
onSelectValue: (_value: string) => void;
showLinkField: boolean;
shareUrlDisplay: string;
onTurnOffLink: () => void;
showConfirm: boolean;
communityAgreed: boolean;
onCommunityAgreedChange: (_checked: boolean) => void;
onTurnOnLink: () => void;
turnOnDisabled: boolean;
turnOnBusy: boolean;
showError: boolean;
showSaveError: boolean;
copyEnabled: boolean;
linkCopied: boolean; linkCopied: boolean;
onCopyLinkClick: () => void | Promise<void>; onCopyLink: () => void;
signalLabel: string;
slackLabel: string;
discordLabel: string;
emailLabel: string;
doneLabel: string;
closeDialogAriaLabel: string;
moreOptionsAriaLabel: string;
};
export type ShareChannelTileProps = {
label: string;
onClick: () => void | Promise<void>;
circleClassName: string;
icon: ReactNode;
copied?: boolean;
}; };
+278 -127
View File
@@ -7,26 +7,26 @@ import {
shareIconPath, shareIconPath,
type ShareIconName, type ShareIconName,
} from "../../../../lib/assetUtils"; } from "../../../../lib/assetUtils";
import ContentLockup from "../../type/ContentLockup"; import Avatar from "../../asset/Avatar";
import Button from "../../buttons/Button"; import Button from "../../buttons/Button";
import ModalHeader from "../ModalHeader"; import Checkbox from "../../controls/Checkbox";
import ModalFooter from "../ModalFooter"; import SelectInput from "../../controls/SelectInput";
import TextInput from "../../controls/TextInput";
import Alert from "../Alert";
import { CreateModalFrameView } from "../Create/CreateModalFrame.view"; import { CreateModalFrameView } from "../Create/CreateModalFrame.view";
import type { ShareChannelTileProps, ShareViewProps } from "./Share.types"; import ModalHeader from "../ModalHeader";
import ContentLockup from "../../type/ContentLockup";
import type { SharePerson } from "../../../../lib/ruleShareTypes";
import type { ShareViewProps } from "./Share.types";
/** Decorative glyphs in `public/assets/share/` — sizes match prior inline SVGs within the 60×60 circles. */ function ShareGlyph(props: { name: ShareIconName; size?: number }) {
function ShareAssetIcon(props: { const size = props.size ?? 24;
name: ShareIconName;
width: number;
height: number;
}) {
const { name, width, height } = props;
return ( return (
<Image <Image
src={getAssetPath(shareIconPath(name))} src={getAssetPath(shareIconPath(props.name))}
alt="" alt=""
width={width} width={size}
height={height} height={size}
className="shrink-0" className="shrink-0"
unoptimized unoptimized
aria-hidden aria-hidden
@@ -34,161 +34,312 @@ function ShareAssetIcon(props: {
); );
} }
function ShareChannelTile({ function PersonRow(props: {
label, initials: string;
onClick, title: string;
circleClassName, subtitle?: string;
icon, roleLabel: string;
copied = false, }) {
}: ShareChannelTileProps) {
return ( return (
<button <div className="flex w-full items-center gap-3 overflow-hidden">
type="button" <Avatar
onClick={() => void onClick()} alt=""
aria-pressed={copied || undefined} initials={props.initials}
className="group flex w-16 shrink-0 flex-col items-center gap-2 rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-border-invert-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-surface-default-primary)]" size="xlarge"
> shape="circle"
<div variant="filled"
className={`flex h-[60px] w-[60px] items-center justify-center rounded-full border border-solid transition-[transform,background-color,border-color,filter] duration-150 ease-out group-active:scale-90 ${circleClassName}`} />
> <div className="flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden">
{icon} <p className="truncate text-small-label text-[var(--color-content-default-primary)]">
{props.title}
</p>
{props.subtitle ? (
<p className="truncate text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
{props.subtitle}
</p>
) : null}
</div> </div>
<span <p className="shrink-0 text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
className={`max-w-[4.5rem] text-center text-x-small-label ${ {props.roleLabel}
copied </p>
? "text-[var(--color-border-default-positive-primary)]" </div>
: "text-[var(--color-content-default-tertiary)]" );
}`} }
>
{label} function ReaderRow({ reader, roleLabel }: { reader: SharePerson; roleLabel: string }) {
</span> return (
</button> <PersonRow
initials={reader.initials}
title={reader.email}
roleLabel={roleLabel}
/>
); );
} }
export const ShareView = memo(function ShareView({ export const ShareView = memo(function ShareView({
isOpen, isOpen,
onClose, onClose,
onEmailShare, className,
onSignalShare, backdropVariant,
onSlackShare,
onDiscordShare,
className = "",
backdropVariant = "blurredYellow",
dialogRef, dialogRef,
overlayRef, overlayRef,
titleId, titleId,
title, copy,
description, communityName,
copyLinkLabel, inviteValue,
copiedLabel, onInviteValueChange,
copiedLive, onInvite,
inviteBusy,
inviteError,
ownerEmail,
ownerInitials,
shownReaders,
overflowLabel,
selectValue,
onSelectValue,
showLinkField,
shareUrlDisplay,
onTurnOffLink,
showConfirm,
communityAgreed,
onCommunityAgreedChange,
onTurnOnLink,
turnOnDisabled,
turnOnBusy,
showError,
showSaveError,
copyEnabled,
linkCopied, linkCopied,
onCopyLinkClick, onCopyLink,
signalLabel,
slackLabel,
discordLabel,
emailLabel,
doneLabel,
closeDialogAriaLabel,
moreOptionsAriaLabel,
}: ShareViewProps) { }: ShareViewProps) {
const linkOn = selectValue === "shared_by_link";
return ( return (
<CreateModalFrameView <CreateModalFrameView
isOpen={isOpen} isOpen={isOpen}
onOverlayClick={onClose} onOverlayClick={onClose}
backdropVariant={backdropVariant} backdropVariant={backdropVariant}
className={`max-h-[90vh] w-[min(546px,calc(100vw-32px))] max-w-[546px] min-h-0 ${className}`} presentation="sheet"
ariaLabel={title} className={className}
ariaLabel={copy.title}
ariaLabelledBy={titleId} ariaLabelledBy={titleId}
overlayRef={overlayRef} overlayRef={overlayRef}
dialogRef={dialogRef} dialogRef={dialogRef}
> >
<ModalHeader <ModalHeader
onClose={onClose} onClose={onClose}
onMoreOptions={onClose} showMoreOptionsButton={false}
closeButtonAriaLabel={closeDialogAriaLabel} closeButtonAriaLabel={copy.closeDialogAriaLabel}
moreOptionsAriaLabel={moreOptionsAriaLabel}
/> />
<div className="shrink-0 bg-[var(--color-surface-default-primary)] px-[24px] py-[12px]"> <div className="shrink-0 bg-[var(--color-surface-default-primary)] px-6">
<ContentLockup <ContentLockup
title={title} title={copy.title}
description={description} description={communityName}
variant="modal" variant="modal"
alignment="left" alignment="left"
titleId={titleId} titleId={titleId}
/> />
</div> </div>
<div className="scrollbar-design flex min-h-0 flex-1 flex-col overflow-x-clip overflow-y-auto px-[24px] pb-6 pt-0"> <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-x-clip overflow-y-auto px-6 pb-6 pt-6">
{/* Channel circle hexes are third-party brand colors (copy/link, Signal, Slack, Discord), not DS tokens. */} <div className="flex w-full items-center gap-2">
<div className="flex flex-wrap gap-4"> <div className="min-w-0 flex-1">
<ShareChannelTile <TextInput
label={linkCopied ? copiedLabel : copyLinkLabel} type="email"
onClick={onCopyLinkClick} inputSize="medium"
copied={linkCopied} formHeader={false}
circleClassName={ showHelpIcon={false}
linkCopied label={copy.addPeoplePlaceholder}
? "border-2 border-[var(--color-gray-600)] bg-[var(--color-gray-700)]" placeholder={copy.addPeoplePlaceholder}
: "border-[var(--color-gray-600)] bg-[var(--color-gray-700)] group-hover:border-2 group-hover:border-[var(--color-border-default-positive-primary)] group-hover:bg-[var(--color-gray-600)]" value={inviteValue}
error={Boolean(inviteError)}
disabled={inviteBusy}
autoComplete="email"
onChange={(e) => onInviteValueChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
onInvite();
} }
icon={ }}
<ShareAssetIcon
name={linkCopied ? "check" : "link"}
width={24}
height={24}
/>
}
/>
<ShareChannelTile
label={signalLabel}
onClick={onSignalShare}
circleClassName="border-[#3a76f0] bg-[#3a76f0] group-hover:brightness-110"
icon={<ShareAssetIcon name="signal" width={26} height={26} />}
/>
<ShareChannelTile
label={slackLabel}
onClick={onSlackShare}
circleClassName="border-[#4a154b] bg-[#4a154b] group-hover:brightness-110"
icon={<ShareAssetIcon name="slack" width={26} height={26} />}
/>
<ShareChannelTile
label={discordLabel}
onClick={onDiscordShare}
circleClassName="border-[#5865f2] bg-[#5865f2] group-hover:brightness-110"
icon={<ShareAssetIcon name="discord" width={30} height={30} />}
/>
<ShareChannelTile
label={emailLabel}
onClick={onEmailShare}
circleClassName="border-[var(--color-surface-invert-brand-kiwi)] bg-[var(--color-surface-invert-brand-kiwi)] group-hover:brightness-110"
icon={<ShareAssetIcon name="mail" width={24} height={24} />}
/> />
</div> </div>
<p className="sr-only" aria-live="polite">
{linkCopied ? copiedLive : ""}
</p>
</div>
<ModalFooter
showBackButton={false}
showNextButton={false}
stepper={false}
footerContent={
<div className="absolute right-[16px] top-[12px] flex max-w-[calc(100%-32px)] flex-wrap items-center justify-end gap-3">
<Button <Button
buttonType="filled"
palette="default"
size="medium"
type="button" type="button"
onClick={onClose} buttonType="outline"
palette="default"
size="small"
disabled={inviteBusy || inviteValue.trim().length === 0}
onClick={onInvite}
> >
{doneLabel} {copy.invite}
</Button> </Button>
</div> </div>
} {inviteError ? (
<p className="-mt-3 text-x-small-paragraph text-[var(--color-content-default-negative-primary)]">
{inviteError}
</p>
) : null}
<div className="flex w-full flex-col items-start gap-3 overflow-hidden">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.peopleWithAccess}
</p>
<PersonRow
initials={ownerInitials}
title={copy.you}
subtitle={ownerEmail}
roleLabel={copy.holdsThePen}
/> />
{shownReaders.map((reader) => (
<ReaderRow
key={reader.email}
reader={reader}
roleLabel={copy.canRead}
/>
))}
{overflowLabel ? (
<p className="w-full text-x-small-paragraph text-[var(--color-content-default-tertiary)]">
{overflowLabel}
</p>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-2 overflow-hidden">
<p className="w-full text-small-label text-[var(--color-content-default-secondary)]">
{copy.whoCanRead}
</p>
<div className="flex w-full items-center gap-3">
<ShareGlyph name={linkOn ? "language" : "lock"} />
<div className="min-w-0 flex-1">
<SelectInput
showLabel={false}
iconHelp={false}
value={selectValue}
onChange={(data) => onSelectValue(data.target.value)}
options={[
{ value: "private", label: copy.inviteOnly },
{ value: "shared_by_link", label: copy.anyoneWithLink },
]}
/>
</div>
</div>
{!showConfirm && !showError ? (
<p className="w-full text-small-paragraph text-[var(--color-content-default-tertiary)]">
{linkOn ? copy.anyoneWithLinkHint : copy.inviteOnlyHint}
</p>
) : null}
{showSaveError ? (
<Alert
type="banner"
status="danger"
size="s"
title={copy.saveErrorTitle}
description={copy.saveErrorDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
className="w-full"
/>
) : null}
</div>
{showLinkField ? (
<div className="flex w-full flex-col items-start gap-3">
<TextInput
formHeader={false}
showHelpIcon={false}
label={copy.anyoneWithLink}
value={shareUrlDisplay}
disabled
textHint={copy.linkHint}
/>
<Button
type="button"
buttonType="ghost"
palette="default"
size="small"
onClick={onTurnOffLink}
>
{copy.turnOffLink}
</Button>
</div>
) : null}
{showConfirm || showError ? (
<div className="flex w-full flex-col items-start gap-4 overflow-hidden rounded-[8px] bg-[var(--color-surface-default-secondary)] p-4">
{showError ? (
<Alert
type="banner"
status="danger"
size="s"
title={copy.errorTitle}
description={copy.errorDescription}
hasLeadingIcon
hasBodyText
hasTrailingIcon={false}
className="w-full"
/>
) : null}
<p className="w-full text-small-paragraph text-[var(--color-content-default-primary)]">
{copy.confirmBody}
</p>
<Checkbox
checked={communityAgreed}
label={copy.communityAgreed}
onChange={(data) => onCommunityAgreedChange(data.checked)}
/>
<Button
type="button"
buttonType="filled"
palette="default"
size="small"
disabled={turnOnDisabled || turnOnBusy}
onClick={onTurnOnLink}
>
{copy.turnOnLink}
</Button>
</div>
) : null}
{linkCopied ? (
<Alert
type="toast"
status="positive"
size="s"
title={copy.copiedLive}
hasLeadingIcon
hasBodyText={false}
hasTrailingIcon={false}
className="w-full"
/>
) : null}
</div>
<div className="flex shrink-0 items-center justify-between border-t border-solid border-[var(--color-border-default-secondary)] bg-[var(--color-surface-default-primary)] px-6 py-4">
<Button
type="button"
buttonType="outline"
palette="default"
size="small"
disabled={!copyEnabled}
aria-pressed={linkCopied || undefined}
onClick={onCopyLink}
>
<ShareGlyph name={linkCopied ? "check" : "link"} size={14} />
{linkCopied ? copy.copied : copy.copyLink}
</Button>
<Button
type="button"
buttonType="filled"
palette="default"
size="small"
onClick={onClose}
>
{copy.done}
</Button>
</div>
</CreateModalFrameView> </CreateModalFrameView>
); );
}); });
+2
View File
@@ -89,7 +89,9 @@ export function partnerLogoPath(slug: string): string {
export type ShareIconName = export type ShareIconName =
| "check" | "check"
| "discord" | "discord"
| "language"
| "link" | "link"
| "lock"
| "mail" | "mail"
| "signal" | "signal"
| "slack"; | "slack";
+104
View File
@@ -1,4 +1,6 @@
import type { CreateFlowState } from "../../app/(app)/create/types"; import type { CreateFlowState } from "../../app/(app)/create/types";
import type { RuleShareSettings } from "../ruleShareTypes";
import { isRuleVisibility } from "../ruleVisibility";
import { migrateLegacyCreateFlowState } from "./migrateLegacyCreateFlowState"; import { migrateLegacyCreateFlowState } from "./migrateLegacyCreateFlowState";
const jsonHeaders = { "Content-Type": "application/json" }; const jsonHeaders = { "Content-Type": "application/json" };
@@ -750,6 +752,108 @@ export async function duplicateUseCaseTemplate(
} }
} }
export type FetchRuleShareResult =
| { ok: true; share: RuleShareSettings }
| { ok: false; status: number; error: string };
function isRuleShareSettings(value: unknown): value is RuleShareSettings {
if (!value || typeof value !== "object") return false;
const o = value as Record<string, unknown>;
return (
isRuleVisibility(o.visibility) &&
typeof o.shareUrl === "string" &&
typeof o.title === "string" &&
typeof o.ownerEmail === "string" &&
Array.isArray(o.readers)
);
}
export async function fetchRuleShare(
ruleId: string,
): Promise<FetchRuleShareResult> {
try {
const res = await fetch(
`/api/rules/${encodeURIComponent(ruleId)}/share`,
{ credentials: "include" },
);
if (!res.ok) {
const data = await safeParseJsonResponse(res);
return {
ok: false as const,
status: res.status,
error: readApiErrorMessage(data),
};
}
const data = await safeParseJsonResponse(res);
const share =
data && typeof data === "object" && "share" in data
? (data as { share: unknown }).share
: null;
if (!isRuleShareSettings(share)) {
return {
ok: false as const,
status: res.status,
error: DRAFT_SAVE_NETWORK_ERROR,
};
}
return { ok: true as const, share };
} catch {
return {
ok: false as const,
status: 0,
error: DRAFT_SAVE_NETWORK_ERROR,
};
}
}
export async function patchRuleShare(
ruleId: string,
visibility: "private" | "shared_by_link",
communityAgreed?: boolean,
): Promise<FetchRuleShareResult> {
try {
const res = await fetch(
`/api/rules/${encodeURIComponent(ruleId)}/share`,
{
method: "PATCH",
credentials: "include",
headers: jsonHeaders,
body: JSON.stringify({
visibility,
...(communityAgreed !== undefined ? { communityAgreed } : {}),
}),
},
);
if (!res.ok) {
const data = await safeParseJsonResponse(res);
return {
ok: false as const,
status: res.status,
error: readApiErrorMessage(data),
};
}
const data = await safeParseJsonResponse(res);
const share =
data && typeof data === "object" && "share" in data
? (data as { share: unknown }).share
: null;
if (!isRuleShareSettings(share)) {
return {
ok: false as const,
status: res.status,
error: DRAFT_SAVE_NETWORK_ERROR,
};
}
return { ok: true as const, share };
} catch {
return {
ok: false as const,
status: 0,
error: DRAFT_SAVE_NETWORK_ERROR,
};
}
}
export type DeleteAccountResult = { ok: true } | { ok: false; error: string }; export type DeleteAccountResult = { ok: true } | { ok: false; error: string };
/** /**
+6 -4
View File
@@ -8,10 +8,12 @@ import type {
import type { StoredLastPublishedRule } from "./lastPublishedRule"; import type { StoredLastPublishedRule } from "./lastPublishedRule";
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections"; import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
export function buildPublicRuleUrl(origin: string, ruleId: string): string { export {
const base = origin.replace(/\/$/, ""); buildPublicRuleUrl,
return `${base}/rules/${encodeURIComponent(ruleId)}`; buildShareRuleUrl,
} formatShareUrlDisplay,
shareCopyUrl,
} from "../sharePaths";
/** Safe filename fragment from rule title, with stable fallback. */ /** Safe filename fragment from rule title, with stable fallback. */
export function exportFilenameBase(rule: StoredLastPublishedRule): string { export function exportFilenameBase(rule: StoredLastPublishedRule): string {
+9 -18
View File
@@ -1,24 +1,15 @@
import type { Prisma } from "@prisma/client"; import type { Prisma } from "@prisma/client";
import { RULE_VISIBILITY } from "./ruleVisibility";
/** export {
* Access model for published CommunityRules: RULE_VISIBILITY,
* isListedPublishedRule,
* - **Readable without sign-in:** every published row is share-by-link at canReadPublishedRule,
* `/rules/[id]` and `GET /api/rules/[id]`. isPrivilegedAdminRead,
* - **Listed** (public catalog `GET /api/rules`, sitemap, indexable): owned } from "./ruleVisibility";
* rows, and ownerless rows that are *not* waiting on a guest claim export type { RuleVisibility, PublishedRuleReadAccess } from "./ruleVisibility";
* (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;
}
/** Prisma `where` for the public catalog and sitemap. */ /** Prisma `where` for the public catalog and sitemap. */
export const LISTED_PUBLISHED_RULE_WHERE: Prisma.PublishedRuleWhereInput = { export const LISTED_PUBLISHED_RULE_WHERE: Prisma.PublishedRuleWhereInput = {
OR: [{ userId: { not: null } }, { claimTokenHash: null }], visibility: RULE_VISIBILITY.public_and_featured,
}; };
+36
View File
@@ -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 };
}
+88
View File
@@ -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;
}
+23
View File
@@ -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);
}
}
+10
View File
@@ -29,3 +29,13 @@ export function getSmtpUrl(): string | undefined {
export function isDatabaseConfigured(): boolean { export function isDatabaseConfigured(): boolean {
return Boolean(getDatabaseUrl()); 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);
}
+27
View File
@@ -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 * Attach ownerless published rules whose claim secrets are in this browser's
* cookie to `userId`, then drop the cookie. Never throws to the caller. * cookie to `userId`, then drop the cookie. Never throws to the caller.
+138 -27
View File
@@ -1,14 +1,22 @@
import type { User } from "@prisma/client";
import { import {
LISTED_PUBLISHED_RULE_WHERE, LISTED_PUBLISHED_RULE_WHERE,
canReadPublishedRule,
isListedPublishedRule, isListedPublishedRule,
isPrivilegedAdminRead,
type RuleVisibility,
} from "../publishedRuleAccess"; } from "../publishedRuleAccess";
import { prisma } from "./db"; import { prisma } from "./db";
import { isDatabaseConfigured } from "./env"; 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 * Public fields safe to expose via readable rule detail surfaces
* (`GET /api/rules/[id]` and `/rules/[id]`). `userId` and `claimTokenHash` * (`GET /api/rules/[id]` and `/rules/[id]` / `/r/[shareSlug]`).
* stay server-side; callers get {@link PublicPublishedRule.isListed} instead. * `userId` and `claimTokenHash` stay server-side; callers get
* {@link PublicPublishedRule.isListed} instead.
*/ */
const PUBLISHED_RULE_PUBLIC_SELECT = { const PUBLISHED_RULE_PUBLIC_SELECT = {
id: true, id: true,
@@ -26,38 +34,141 @@ export type PublicPublishedRule = {
document: unknown; document: unknown;
createdAt: Date; createdAt: Date;
updatedAt: 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; isListed: boolean;
}; };
/** export type ReadablePublishedRule = {
* Fetch a single published rule by id for public read surfaces. rule: PublicPublishedRule;
* viewerIsOwner: boolean;
* Returns `null` when the database is not configured, the id does not match visibility: RuleVisibility;
* any row, or the query throws — callers render a 404 in all missing cases shareSlug: string | null;
* 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).
*/ const RULE_ACCESS_SELECT = {
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, ...PUBLISHED_RULE_PUBLIC_SELECT,
userId: true, userId: true,
claimTokenHash: true, claimTokenHash: true,
visibility: true,
shareSlug: true,
stakeholders: {
select: { email: true, userId: true },
}, },
}); } as const;
if (!rule) return null;
const { userId, claimTokenHash, ...publicFields } = rule; function toPublicRule(row: {
id: string;
title: string;
summary: string | null;
document: unknown;
createdAt: Date;
updatedAt: Date;
visibility: RuleVisibility;
}): PublicPublishedRule {
return { return {
...publicFields, id: row.id,
isListed: isListedPublishedRule({ userId, claimTokenHash }), 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. Pass `lookup: "id"`
* when the caller already has the Rule id but link visitors should still
* count as readers (file URLs on a shared Rule). Shared-by-link strangers
* opening the Rule itself 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;
lookup?: "id" | "shareSlug";
}): Promise<ReadablePublishedRule | null> {
if (!isDatabaseConfigured()) return null;
const idOrSlug = opts.idOrSlug.trim();
if (idOrSlug.length === 0) return null;
const lookup = opts.lookup ?? (opts.viaShareSlug ? "shareSlug" : "id");
try {
const row =
lookup === "shareSlug"
? 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,
});
} catch { } catch {
return null; return null;
} }
@@ -89,7 +200,7 @@ const LISTED_PUBLISHED_RULE_SITEMAP_CAP = 10_000;
/** /**
* Public catalog of listed published rules (**most recently updated first**, * 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. * Returns `null` when the database is not configured or the query throws.
*/ */
export async function listListedPublishedRules( export async function listListedPublishedRules(
+8
View File
@@ -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);
}
+167
View File
@@ -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 };
}
+32
View File
@@ -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");
}
+77
View File
@@ -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);
}
+20
View File
@@ -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];
}
+44
View File
@@ -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);
}
}
+21 -2
View File
@@ -1,9 +1,12 @@
import { writeFile } from "node:fs/promises"; import { writeFile } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { logger } from "../../logger";
import { prisma } from "../db";
import type { CreateFlowUploadPurpose } from "./uploadConstants"; import type { CreateFlowUploadPurpose } from "./uploadConstants";
import { extensionForMime } from "./uploadConstants"; import { extensionForMime } from "./uploadConstants";
import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot"; import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot";
import { stripImageMetadata } from "./stripImageMetadata";
import { import {
validateCreateFlowUploadBytes, validateCreateFlowUploadBytes,
type CreateFlowUploadValidationReason, type CreateFlowUploadValidationReason,
@@ -30,6 +33,7 @@ export type SaveCreateFlowUploadFailure = {
export async function saveCreateFlowUpload(params: { export async function saveCreateFlowUpload(params: {
purpose: CreateFlowUploadPurpose; purpose: CreateFlowUploadPurpose;
buffer: Buffer; buffer: Buffer;
userId?: string | null;
}): Promise<SaveCreateFlowUploadResult | SaveCreateFlowUploadFailure> { }): Promise<SaveCreateFlowUploadResult | SaveCreateFlowUploadFailure> {
const root = getUploadRootFromEnv(); const root = getUploadRootFromEnv();
if (!root) { if (!root) {
@@ -42,18 +46,33 @@ export async function saveCreateFlowUpload(params: {
return { error: "validation", reason: validated.reason }; return { error: "validation", reason: validated.reason };
} }
const stripped = stripImageMetadata(buffer, validated.mimeType);
const id = randomUUID(); const id = randomUUID();
const ext = extensionForMime(validated.mimeType); const ext = extensionForMime(validated.mimeType);
const fileName = `${id}${ext}`; const fileName = `${id}${ext}`;
const absolutePath = path.join(root, fileName); const absolutePath = path.join(root, fileName);
await ensureUploadRootExists(root); 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 { return {
id, id,
urlPath: `/api/uploads/${id}`, urlPath: `/api/uploads/${id}`,
mimeType: validated.mimeType, mimeType: validated.mimeType,
byteLength: buffer.length, byteLength: stripped.length,
}; };
} }
+86
View File
@@ -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);
}
+65
View File
@@ -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 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({ export const postRuleStakeholderBodySchema = z.object({
email: stakeholderEmailSchema, email: stakeholderEmailSchema,
}); });
+56
View File
@@ -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
View File
@@ -25,7 +25,7 @@ const INDEXABLE_HOSTS = new Set([
export const NO_INDEX_ROBOTS = { index: false, follow: false } as const; 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): export function robotsForPublishedRule(isListed: boolean):
| { | {
index: false; index: false;
+2
View File
@@ -38,6 +38,7 @@ import invite from "./pages/invite.json";
import navigation from "./navigation.json"; import navigation from "./navigation.json";
import metadata from "./metadata.json"; import metadata from "./metadata.json";
import modalsShare from "./modals/share.json"; import modalsShare from "./modals/share.json";
import modalsDeleteAccount from "./modals/deleteAccount.json";
import modalsPopoverExport from "./modals/popoverExport.json"; import modalsPopoverExport from "./modals/popoverExport.json";
import modalsAskOrganizerInquiry from "./modals/askOrganizerInquiry.json"; import modalsAskOrganizerInquiry from "./modals/askOrganizerInquiry.json";
@@ -159,6 +160,7 @@ export default {
metadata, metadata,
modals: { modals: {
share: modalsShare, share: modalsShare,
deleteAccount: modalsDeleteAccount,
popoverExport: modalsPopoverExport, popoverExport: modalsPopoverExport,
askOrganizerInquiry: modalsAskOrganizerInquiry, askOrganizerInquiry: modalsAskOrganizerInquiry,
}, },
+13
View File
@@ -0,0 +1,13 @@
{
"_comment": "Overlay / Modal / Delete Account 24985:1959",
"title": "Delete your account",
"description": "This deletes your account and every Rule you made. The people you invited lose access to them. Export any Rule you want to keep first.",
"yourRules": "Your Rules",
"exportPdf": "PDF",
"exportMarkdown": "RULE.md",
"confirmLabel": "I understand this can’t be undone",
"confirmHint": "Tick this to continue.",
"cancel": "Cancel",
"confirm": "Delete account",
"closeDialogAriaLabel": "Close"
}
+27 -9
View File
@@ -1,14 +1,32 @@
{ {
"title": "Share this CommunityRule", "_comment": "Overlay / Modal / Share 24972:2094",
"description": "Anyone with the link can view this rule.", "title": "Share this Rule",
"addPeoplePlaceholder": "Add people by email",
"invite": "Invite",
"inviteInvalid": "Enter an email address.",
"peopleWithAccess": "People with access",
"you": "You",
"holdsThePen": "Holds the pen",
"canRead": "Can read",
"overflowReaders": "{{count}} more people can read it",
"whoCanRead": "Who can read this Rule",
"inviteOnly": "Only people you invite",
"inviteOnlyHint": "Only people you invite can open it.",
"anyoneWithLink": "Anyone with the link",
"anyoneWithLinkHint": "Anyone with the link can read it without logging in. They can pass it on.",
"confirmBody": "Anyone with the link can read it without logging in and pass it on. Check with your community first.",
"communityAgreed": "Our community agreed to share this Rule",
"turnOnLink": "Turn on link",
"turnOffLink": "Turn off link",
"linkHint": "Turning the link off stops it working. Turning it on again makes a new one.",
"copyLink": "Copy link", "copyLink": "Copy link",
"copied": "Copied!", "copied": "Copied",
"copiedLive": "Link copied to clipboard", "copiedLive": "Link copied",
"signal": "Signal",
"slack": "Slack",
"discord": "Discord",
"email": "Email",
"done": "Done", "done": "Done",
"errorTitle": "The link didn’t turn on",
"errorDescription": "Check your connection and try again.",
"saveErrorTitle": "That change didn’t save",
"saveErrorDescription": "Check your connection and try again.",
"closeDialogAriaLabel": "Close", "closeDialogAriaLabel": "Close",
"moreOptionsAriaLabel": "More share options" "accessSelectAriaLabel": "Who can read this Rule"
} }
@@ -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
View File
@@ -16,6 +16,7 @@ model User {
sessions Session[] sessions Session[]
draft RuleDraft? draft RuleDraft?
rules PublishedRule[] rules PublishedRule[]
uploads Upload[]
/// At most one pending verified email change (CR-103). /// At most one pending verified email change (CR-103).
emailChangeToken EmailChangeToken? emailChangeToken EmailChangeToken?
/// Rules this user was invited to as a stakeholder (after accepting invite). /// 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) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
payload Json payload Json
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
uploads Upload[]
}
enum RuleVisibility {
private
shared_by_link
public_and_featured
} }
model PublishedRule { model PublishedRule {
id String @id @default(cuid()) id String @id @default(cuid())
userId String? userId String?
user User? @relation(fields: [userId], references: [id], onDelete: SetNull) user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
title String title String
summary String? summary String?
document Json document Json
@@ -82,10 +90,48 @@ model PublishedRule {
/// Hashed one-time secret so the publishing browser can claim this row on sign-in. /// Hashed one-time secret so the publishing browser can claim this row on sign-in.
/// Null for owned publishes and after a successful claim. /// Null for owned publishes and after a successful claim.
claimTokenHash String? @unique 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[] stakeholders RuleStakeholder[]
uploads Upload[]
@@index([userId]) @@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. /// Invite + access for a published rule: email invite at publish; userId set after magic-link-style accept.
+5
View File
@@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="9" stroke="white" stroke-width="2"/>
<path d="M3 12h18" stroke="white" stroke-width="2" stroke-linecap="round"/>
<path d="M12 3c2.5 3 3.5 6 3.5 9s-1 6-3.5 9c-2.5-3-3.5-6-3.5-9s1-6 3.5-9Z" stroke="white" stroke-width="2" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 382 B

+5
View File
@@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7 11V8a5 5 0 0 1 10 0v3" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="5" y="11" width="14" height="10" rx="2" stroke="white" stroke-width="2"/>
<path d="M12 15v2" stroke="white" stroke-width="2" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 384 B

+47
View File
@@ -0,0 +1,47 @@
import React, { useState } from "react";
import DeleteAccount from "../../app/components/modals/DeleteAccount";
/** Figma: Overlay / Modal / Delete Account — node 24985-1959. */
export default {
title: "Components/Modals/DeleteAccount",
component: DeleteAccount,
parameters: {
layout: "fullscreen",
docs: {
description: {
component:
"Account deletion lists each owned Rule with PDF and RULE.md export, then requires a confirmation checkbox.",
},
},
},
};
function DeleteAccountStoryHost() {
const [open, setOpen] = useState(true);
return (
<div className="min-h-[100dvh] bg-[var(--color-surface-invert-brand-primary)] p-6">
<button
type="button"
className="rounded-md bg-[var(--color-surface-default-primary)] px-4 py-2 text-small-paragraph text-[var(--color-content-default-primary)]"
onClick={() => setOpen(true)}
>
Open Delete Account
</button>
<DeleteAccount
isOpen={open}
onClose={() => setOpen(false)}
onConfirm={() => setOpen(false)}
rules={[
{ id: "rule-1", title: "Juniper Street Food Share" },
{ id: "rule-2", title: "Mutual Aid Colorado" },
]}
onExportPdf={() => undefined}
onExportMarkdown={() => undefined}
/>
</div>
);
}
export const Default = {
render: () => <DeleteAccountStoryHost />,
};
+38 -7
View File
@@ -1,7 +1,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import Share from "../../app/components/modals/Share"; import Share from "../../app/components/modals/Share";
/** Figma: Modal / Share — node 22073-30884 (Community Rule System). */ /** Figma: Overlay / Modal / Share — node 24972-2094. */
export default { export default {
title: "Components/Modals/Share", title: "Components/Modals/Share",
component: Share, component: Share,
@@ -10,12 +10,31 @@ export default {
docs: { docs: {
description: { description: {
component: component:
"Share modal for published rules (copy link and channel actions).", "Share settings for a finished Rule: invite people, confirm a link, or copy it.",
}, },
}, },
}, },
}; };
const previewSettings = {
visibility: "private",
shareSlug: null,
shareUrl: "https://communityrule.info/rules/rule-1",
shareUrlDisplay: null,
title: "Juniper Street Food Share",
ownerEmail: "name@example.org",
ownerInitials: "N",
readers: [
{ email: "rosa@example.org", initials: "R", role: "reader" },
{ email: "a@example.org", initials: "A", role: "reader" },
{ email: "b@example.org", initials: "B", role: "reader" },
{ email: "c@example.org", initials: "C", role: "reader" },
{ email: "d@example.org", initials: "D", role: "reader" },
{ email: "e@example.org", initials: "E", role: "reader" },
],
copyEnabled: true,
};
function ShareStoryHost() { function ShareStoryHost() {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
return ( return (
@@ -30,11 +49,7 @@ function ShareStoryHost() {
<Share <Share
isOpen={open} isOpen={open}
onClose={() => setOpen(false)} onClose={() => setOpen(false)}
onCopyLink={() => {}} previewSettings={previewSettings}
onEmailShare={() => {}}
onSignalShare={() => {}}
onSlackShare={() => {}}
onDiscordShare={() => {}}
/> />
</div> </div>
); );
@@ -43,3 +58,19 @@ function ShareStoryHost() {
export const Default = { export const Default = {
render: () => <ShareStoryHost />, render: () => <ShareStoryHost />,
}; };
export const AnyoneWithTheLink = {
render: () => (
<Share
isOpen
onClose={() => undefined}
previewSettings={{
...previewSettings,
visibility: "shared_by_link",
shareSlug: "k7f2-9qxm",
shareUrl: "https://communityrule.info/r/k7f2-9qxm",
shareUrlDisplay: "communityrule.info/r/k7f2-9qxm",
}}
/>
),
};
@@ -0,0 +1,53 @@
import { describe, it, expect, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import { renderWithProviders as render, screen } from "../../utils/test-utils";
import "@testing-library/jest-dom/vitest";
import DeleteAccount from "../../../app/components/modals/DeleteAccount";
describe("DeleteAccount modal", () => {
it("does not render dialog when closed", () => {
render(
<DeleteAccount
isOpen={false}
onClose={vi.fn()}
onConfirm={vi.fn()}
rules={[]}
onExportPdf={vi.fn()}
onExportMarkdown={vi.fn()}
/>,
);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("keeps Delete account disabled until the box is ticked", async () => {
const user = userEvent.setup();
const onConfirm = vi.fn();
const onExportPdf = vi.fn();
render(
<DeleteAccount
isOpen
onClose={vi.fn()}
onConfirm={onConfirm}
rules={[{ id: "rule-1", title: "Juniper Street Food Share" }]}
onExportPdf={onExportPdf}
onExportMarkdown={vi.fn()}
/>,
);
expect(
screen.getByRole("heading", { level: 1, name: "Delete your account" }),
).toBeInTheDocument();
expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument();
const confirm = screen.getByRole("button", { name: "Delete account" });
expect(confirm).toBeDisabled();
await user.click(screen.getByRole("button", { name: "PDF" }));
expect(onExportPdf).toHaveBeenCalledWith("rule-1");
await user.click(
screen.getByRole("checkbox", {
name: "I understand this can’t be undone",
}),
);
expect(confirm).toBeEnabled();
await user.click(confirm);
expect(onConfirm).toHaveBeenCalledTimes(1);
});
});
+184 -84
View File
@@ -1,117 +1,217 @@
import { describe, it, expect, vi } from "vitest"; import { describe, it, expect, vi, beforeEach } from "vitest";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { renderWithProviders as render, screen } from "../../utils/test-utils"; import { fireEvent } from "@testing-library/react";
import {
renderWithProviders as render,
screen,
waitFor,
} from "../../utils/test-utils";
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import Share from "../../../app/components/modals/Share"; import Share from "../../../app/components/modals/Share";
import { patchRuleShare } from "../../../lib/create/api";
import type { RuleShareSettings } from "../../../lib/ruleShareTypes";
const noopHandlers = { vi.mock("../../../lib/create/api", () => ({
onCopyLink: vi.fn(), patchRuleShare: vi.fn(),
onEmailShare: vi.fn(), fetchRuleShare: vi.fn(),
onSignalShare: vi.fn(), addRuleStakeholder: vi.fn(),
onSlackShare: vi.fn(), }));
onDiscordShare: vi.fn(),
const previewSettings: RuleShareSettings = {
visibility: "private",
shareSlug: null,
shareUrl: "https://communityrule.info/rules/rule-1",
shareUrlDisplay: null,
title: "Juniper Street Food Share",
ownerEmail: "name@example.org",
ownerInitials: "N",
readers: [
{ email: "rosa@example.org", initials: "R", role: "reader" },
{ email: "a@example.org", initials: "A", role: "reader" },
{ email: "b@example.org", initials: "B", role: "reader" },
{ email: "c@example.org", initials: "C", role: "reader" },
{ email: "d@example.org", initials: "D", role: "reader" },
{ email: "e@example.org", initials: "E", role: "reader" },
],
copyEnabled: true,
}; };
function openShare(overrides: Partial<RuleShareSettings> = {}) {
return render(
<Share
isOpen
onClose={vi.fn()}
previewSettings={{ ...previewSettings, ...overrides }}
/>,
);
}
const writeText = vi.fn().mockResolvedValue(undefined);
const sharedSettings: RuleShareSettings = {
...previewSettings,
visibility: "shared_by_link",
shareSlug: "k7f2-9qxm",
shareUrl: "https://communityrule.info/r/k7f2-9qxm",
shareUrlDisplay: "communityrule.info/r/k7f2-9qxm",
};
beforeEach(() => {
writeText.mockReset();
writeText.mockResolvedValue(undefined);
vi.mocked(patchRuleShare).mockReset();
Object.defineProperty(window.navigator, "clipboard", {
configurable: true,
value: { writeText },
});
});
describe("Share modal", () => { describe("Share modal", () => {
it("does not render dialog when closed", () => { it("does not render dialog when closed", () => {
render( render(
<Share isOpen={false} onClose={vi.fn()} {...noopHandlers} />, <Share
isOpen={false}
onClose={vi.fn()}
previewSettings={previewSettings}
/>,
); );
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
}); });
it("renders localized heading and copy link action when open", async () => { it("renders invite-only copy and people with access", () => {
const user = userEvent.setup(); openShare();
const onCopyLink = vi.fn();
render(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={onCopyLink}
/>,
);
expect(screen.getByRole("dialog")).toBeInTheDocument(); expect(screen.getByRole("dialog")).toBeInTheDocument();
expect( expect(
screen.getByRole("heading", { level: 1, name: /Share this CommunityRule/ }), screen.getByRole("heading", { level: 1, name: "Share this Rule" }),
).toBeInTheDocument(); ).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Copy link" })); expect(screen.getByText("Juniper Street Food Share")).toBeInTheDocument();
expect(onCopyLink).toHaveBeenCalledTimes(1); expect(screen.getByText("You")).toBeInTheDocument();
expect(screen.getByText("rosa@example.org")).toBeInTheDocument();
expect(screen.getByText("Five more people can read it")).toBeInTheDocument();
expect(screen.getByText("Only people you invite can open it.")).toBeInTheDocument();
}); });
it("invokes channel handlers for Signal, Slack, and Discord", async () => { it("copies the private Rule URL", async () => {
openShare();
fireEvent.click(screen.getByRole("button", { name: /Copy link/i }));
await waitFor(() => {
expect(screen.getByText("Link copied")).toBeInTheDocument();
});
expect(writeText).toHaveBeenCalledWith(
"https://communityrule.info/rules/rule-1",
);
expect(screen.getByRole("button", { name: /Copied/i })).toHaveAttribute(
"aria-pressed",
"true",
);
});
it("asks for community agreement before turning a link on", async () => {
const user = userEvent.setup();
openShare();
await user.click(screen.getByRole("button", { name: /Only people you invite/i }));
await user.click(
await screen.findByRole("option", { name: "Anyone with the link" }),
);
expect(
screen.getByText(
"Anyone with the link can read it without logging in and pass it on. Check with your community first.",
),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Turn on link" })).toBeDisabled();
expect(screen.getByRole("button", { name: /Copy link/i })).toBeDisabled();
await user.click(
screen.getByRole("checkbox", {
name: "Our community agreed to share this Rule",
}),
);
expect(screen.getByRole("button", { name: "Turn on link" })).toBeEnabled();
});
it("turns the preview link on after community agreement", async () => {
const user = userEvent.setup();
openShare();
await user.click(screen.getByRole("button", { name: /Only people you invite/i }));
await user.click(
await screen.findByRole("option", { name: "Anyone with the link" }),
);
await user.click(
screen.getByRole("checkbox", {
name: "Our community agreed to share this Rule",
}),
);
await user.click(screen.getByRole("button", { name: "Turn on link" }));
expect(
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"),
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Turn off link" }),
).toBeInTheDocument();
});
it("keeps the link on and says so when turning the Rule private does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup(); const user = userEvent.setup();
const onSignalShare = vi.fn();
const onSlackShare = vi.fn();
const onDiscordShare = vi.fn();
render( render(
<Share <Share
isOpen={true} isOpen
onClose={vi.fn()} onClose={vi.fn()}
{...noopHandlers} ruleId="rule-1"
onSignalShare={onSignalShare} previewSettings={sharedSettings}
onSlackShare={onSlackShare}
onDiscordShare={onDiscordShare}
/>, />,
); );
await user.click(screen.getByRole("button", { name: "Signal" })); await user.click(
await user.click(screen.getByRole("button", { name: "Slack" })); screen.getByRole("button", { name: /Anyone with the link/i }),
await user.click(screen.getByRole("button", { name: "Discord" })); );
expect(onSignalShare).toHaveBeenCalledTimes(1); await user.click(
expect(onSlackShare).toHaveBeenCalledTimes(1); await screen.findByRole("option", { name: "Only people you invite" }),
expect(onDiscordShare).toHaveBeenCalledTimes(1); );
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Turn off link" }),
).toBeInTheDocument();
expect(
screen.queryByText("Only people you invite can open it."),
).not.toBeInTheDocument();
});
it("keeps the link on and says so when turning the link off does not save", async () => {
vi.mocked(patchRuleShare).mockResolvedValueOnce({
ok: false,
status: 500,
error: "nope",
});
const user = userEvent.setup();
render(
<Share
isOpen
onClose={vi.fn()}
ruleId="rule-1"
previewSettings={sharedSettings}
/>,
);
await user.click(screen.getByRole("button", { name: "Turn off link" }));
expect(await screen.findByText("That change didn’t save")).toBeInTheDocument();
expect(
screen.getByDisplayValue("communityrule.info/r/k7f2-9qxm"),
).toBeInTheDocument();
}); });
it("calls onClose when Done is clicked", async () => { it("calls onClose when Done is clicked", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onClose = vi.fn(); const onClose = vi.fn();
render(<Share isOpen={true} onClose={onClose} {...noopHandlers} />); render(
<Share
isOpen
onClose={onClose}
previewSettings={previewSettings}
/>,
);
await user.click(screen.getByRole("button", { name: "Done" })); await user.click(screen.getByRole("button", { name: "Done" }));
expect(onClose).toHaveBeenCalledTimes(1); expect(onClose).toHaveBeenCalledTimes(1);
}); });
it("confirms Copy link with Copied! when the handler succeeds", async () => {
const user = userEvent.setup();
const onCopyLink = vi.fn().mockResolvedValue(true);
render(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={onCopyLink}
/>,
);
await user.click(screen.getByRole("button", { name: "Copy link" }));
expect(onCopyLink).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Copied!" })).toHaveAttribute(
"aria-pressed",
"true",
);
expect(screen.getByText("Link copied to clipboard")).toBeInTheDocument();
});
it("keeps Copy link when the handler reports failure", async () => {
const user = userEvent.setup();
render(
<Share
isOpen={true}
onClose={vi.fn()}
{...noopHandlers}
onCopyLink={vi.fn().mockResolvedValue(false)}
/>,
);
await user.click(screen.getByRole("button", { name: "Copy link" }));
expect(screen.getByRole("button", { name: "Copy link" })).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Copied!" }),
).not.toBeInTheDocument();
});
it("calls onClose when header overflow (more) is activated, matching modal chrome parity", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(<Share isOpen={true} onClose={onClose} {...noopHandlers} />);
await user.click(screen.getByRole("button", { name: "More share options" }));
expect(onClose).toHaveBeenCalledTimes(1);
});
}); });
+12 -3
View File
@@ -61,6 +61,8 @@ function viewProps(
onOpenDeleteAccount: vi.fn(), onOpenDeleteAccount: vi.fn(),
onCloseDeleteAccount: vi.fn(), onCloseDeleteAccount: vi.fn(),
onConfirmDeleteAccount: vi.fn(), onConfirmDeleteAccount: vi.fn(),
onExportRulePdf: vi.fn(),
onExportRuleMarkdown: vi.fn(),
onDismissProfileSuccess: vi.fn(), onDismissProfileSuccess: vi.fn(),
onDismissActionError: vi.fn(), onDismissActionError: vi.fn(),
onDismissRulesError: vi.fn(), onDismissRulesError: vi.fn(),
@@ -127,12 +129,13 @@ describe("ProfilePageView", () => {
); );
const dialog = screen.getByRole("dialog", { const dialog = screen.getByRole("dialog", {
name: copy.deleteAccountModalTitle, name: messages.modals.deleteAccount.title,
}); });
expect(dialog).toHaveTextContent(copy.deleteAccountModalBody); expect(dialog).toHaveTextContent(messages.modals.deleteAccount.description);
const confirm = within(dialog).getByRole("button", { const confirm = within(dialog).getByRole("button", {
name: copy.deleteAccountConfirm, name: messages.modals.deleteAccount.confirm,
}); });
expect(confirm).toBeDisabled();
expect(confirm.className).toContain( expect(confirm.className).toContain(
"border-[var(--color-border-default-negative-primary)]", "border-[var(--color-border-default-negative-primary)]",
); );
@@ -140,6 +143,12 @@ describe("ProfilePageView", () => {
"bg-[var(--color-surface-invert-primary)]", "bg-[var(--color-surface-invert-primary)]",
); );
await user.click(
within(dialog).getByRole("checkbox", {
name: messages.modals.deleteAccount.confirmLabel,
}),
);
expect(confirm).toBeEnabled();
await user.click(confirm); await user.click(confirm);
expect(onConfirmDeleteAccount).toHaveBeenCalledTimes(1); expect(onConfirmDeleteAccount).toHaveBeenCalledTimes(1);
}); });
@@ -118,6 +118,27 @@ describe("UseCaseCompletedRulePage", () => {
); );
}); });
test("Share copies the page link through a banner instead of a privacy modal", async () => {
const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(window.navigator, "clipboard", {
configurable: true,
value: { writeText },
});
render(
await UseCaseCompletedRulePage({
params: Promise.resolve({ slug: "food-not-bombs" }),
}),
);
await user.click(screen.getByRole("button", { name: "Share" }));
expect(writeText).toHaveBeenCalled();
expect(screen.getByText("Link copied")).toBeInTheDocument();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
test("Share button reads Share under the marketing case-study bundle", async () => { test("Share button reads Share under the marketing case-study bundle", async () => {
rtlRender( rtlRender(
<MessagesProvider messages={marketingMessages}> <MessagesProvider messages={marketingMessages}>
+1 -1
View File
@@ -31,7 +31,7 @@ describe("createFlowLayoutTokens", () => {
expect(CREATE_FLOW_PAGE_GUTTER_CLASS).toBe("px-5 md:px-12 lg:px-16"); expect(CREATE_FLOW_PAGE_GUTTER_CLASS).toBe("px-5 md:px-12 lg:px-16");
}); });
it("offsets fixed top banners below the create-flow header", () => { it("offsets fixed top banners below the create-flow header so Share stays clickable", () => {
expect(CREATE_FLOW_FIXED_TOP_BANNER_OFFSET_CLASS).toBe("top-14 md:top-16"); expect(CREATE_FLOW_FIXED_TOP_BANNER_OFFSET_CLASS).toBe("top-14 md:top-16");
}); });
+20
View File
@@ -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([]);
});
});
+9 -17
View File
@@ -3,34 +3,26 @@ import {
LISTED_PUBLISHED_RULE_WHERE, LISTED_PUBLISHED_RULE_WHERE,
isListedPublishedRule, isListedPublishedRule,
} from "../../lib/publishedRuleAccess"; } from "../../lib/publishedRuleAccess";
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
describe("isListedPublishedRule", () => { describe("isListedPublishedRule", () => {
it("lists owned rules", () => { it("lists public and featured Rules only", () => {
expect( expect(
isListedPublishedRule({ userId: "user-1", claimTokenHash: null }), isListedPublishedRule({ visibility: RULE_VISIBILITY.public_and_featured }),
).toBe(true); ).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( expect(
isListedPublishedRule({ isListedPublishedRule({ visibility: RULE_VISIBILITY.private }),
userId: null, ).toBe(false);
claimTokenHash: "claim-hash", expect(
}), isListedPublishedRule({ visibility: RULE_VISIBILITY.shared_by_link }),
).toBe(false); ).toBe(false);
}); });
}); });
describe("LISTED_PUBLISHED_RULE_WHERE", () => { 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({ expect(LISTED_PUBLISHED_RULE_WHERE).toEqual({
OR: [{ userId: { not: null } }, { claimTokenHash: null }], visibility: RULE_VISIBILITY.public_and_featured,
}); });
}); });
}); });
+191 -36
View File
@@ -3,6 +3,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const isDatabaseConfiguredMock = vi.fn(); const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn(); const findUniqueMock = vi.fn();
const findManyMock = vi.fn(); const findManyMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn();
const isRuleAdminEmailMock = vi.fn();
const logAdminRuleReadMock = vi.fn();
vi.mock("../../lib/server/env", () => ({ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(), isDatabaseConfigured: () => isDatabaseConfiguredMock(),
@@ -17,46 +20,29 @@ 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 { import {
getPublicPublishedRuleById, getReadablePublishedRule,
listListedPublishedRules, listListedPublishedRules,
listListedPublishedRulesForSitemap, listListedPublishedRulesForSitemap,
} from "../../lib/server/publishedRules"; } from "../../lib/server/publishedRules";
import { LISTED_PUBLISHED_RULE_WHERE } from "../../lib/publishedRuleAccess"; import { LISTED_PUBLISHED_RULE_WHERE } from "../../lib/publishedRuleAccess";
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
beforeEach(() => { function row(overrides: Record<string, unknown> = {}) {
isDatabaseConfiguredMock.mockReset(); return {
findUniqueMock.mockReset();
findManyMock.mockReset();
});
describe("getPublicPublishedRuleById", () => {
it("returns isListed false for guest-claim rows without exposing claim tokens", 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",
});
const rule = await getPublicPublishedRuleById("guest-1");
expect(rule).toMatchObject({
id: "guest-1",
title: "Guest rule",
isListed: false,
});
expect(rule).not.toHaveProperty("userId");
expect(rule).not.toHaveProperty("claimTokenHash");
});
it("returns isListed true for owned rules", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce({
id: "owned-1", id: "owned-1",
title: "Owned", title: "Owned",
summary: "Hi", summary: "Hi",
@@ -65,10 +51,168 @@ describe("getPublicPublishedRuleById", () => {
updatedAt: new Date("2026-01-02T00:00:00.000Z"), updatedAt: new Date("2026-01-02T00:00:00.000Z"),
userId: "user-1", userId: "user-1",
claimTokenHash: null, 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("getReadablePublishedRule", () => {
it("returns listed public-and-featured Rules to anonymous readers", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(
row({ visibility: RULE_VISIBILITY.public_and_featured }),
);
const resolved = await getReadablePublishedRule({
idOrSlug: "owned-1",
user: null,
viaShareSlug: false,
requestPath: "/rules/owned-1",
});
expect(resolved?.rule).toMatchObject({
id: "owned-1",
title: "Owned",
isListed: true,
});
expect(resolved?.rule).not.toHaveProperty("userId");
expect(resolved?.rule).not.toHaveProperty("claimTokenHash");
}); });
const rule = await getPublicPublishedRuleById("owned-1"); it("hides private Rules from anonymous readers", async () => {
expect(rule?.isListed).toBe(true); 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 of a shared Rule through when the caller already has the id", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(
row({
visibility: RULE_VISIBILITY.shared_by_link,
shareSlug: "k7f2-9qxm",
}),
);
const resolved = await getReadablePublishedRule({
idOrSlug: "owned-1",
user: null,
viaShareSlug: true,
lookup: "id",
requestPath: "/api/uploads/file-1",
});
expect(resolved?.rule.id).toBe("owned-1");
expect(findUniqueMock).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "owned-1" } }),
);
});
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 +244,15 @@ describe("listListedPublishedRulesForSitemap", () => {
expect(await listListedPublishedRulesForSitemap()).toEqual([]); expect(await listListedPublishedRulesForSitemap()).toEqual([]);
expect(findManyMock).not.toHaveBeenCalled(); 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,
}),
);
});
}); });
+228
View File
@@ -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,
},
}),
);
});
});
+36
View File
@@ -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("?");
});
});
+111
View File
@@ -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);
});
});
+4
View File
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(), getSessionUser: () => getSessionUserMock(),
})); }));
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
deleteUploadsForRule: vi.fn().mockResolvedValue(undefined),
}));
import { DELETE } from "../../app/api/rules/[id]/route"; import { DELETE } from "../../app/api/rules/[id]/route";
function makeContext(id: string) { function makeContext(id: string) {
+4
View File
@@ -23,6 +23,10 @@ vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(), getSessionUser: () => getSessionUserMock(),
})); }));
vi.mock("../../lib/server/uploads/linkUploads", () => ({
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
}));
import { PATCH } from "../../app/api/rules/[id]/route"; import { PATCH } from "../../app/api/rules/[id]/route";
function makeContext(id: string) { function makeContext(id: string) {
+117 -71
View File
@@ -4,6 +4,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const isDatabaseConfiguredMock = vi.fn(); const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn(); const findUniqueMock = vi.fn();
const getSessionUserMock = vi.fn(); const getSessionUserMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn();
const isRuleAdminEmailMock = vi.fn();
const logAdminRuleReadMock = vi.fn();
vi.mock("../../lib/server/env", () => ({ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(), isDatabaseConfigured: () => isDatabaseConfiguredMock(),
@@ -21,17 +24,54 @@ vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(), 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 { GET } from "../../app/api/rules/[id]/route";
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
function makeContext(id: string) { function makeContext(id: string) {
return { params: Promise.resolve({ id }) }; 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(() => { beforeEach(() => {
isDatabaseConfiguredMock.mockReset(); isDatabaseConfiguredMock.mockReset();
findUniqueMock.mockReset(); findUniqueMock.mockReset();
getSessionUserMock.mockReset(); getSessionUserMock.mockReset();
browserHoldsClaimForHashMock.mockReset();
isRuleAdminEmailMock.mockReset();
logAdminRuleReadMock.mockReset();
getSessionUserMock.mockResolvedValue(null); getSessionUserMock.mockResolvedValue(null);
browserHoldsClaimForHashMock.mockResolvedValue(false);
isRuleAdminEmailMock.mockReturnValue(false);
logAdminRuleReadMock.mockResolvedValue(undefined);
}); });
describe("GET /api/rules/[id]", () => { describe("GET /api/rules/[id]", () => {
@@ -86,80 +126,39 @@ describe("GET /api/rules/[id]", () => {
expect(res.status).toBe(404); 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); isDatabaseConfiguredMock.mockReturnValue(true);
const row = { findUniqueMock.mockResolvedValueOnce(row());
id: "rule-1", const res = await GET(
title: "Mutual Aid Mondays", new NextRequest("https://x.test/api/rules/rule-1"),
summary: "A grassroots community in Denver.", makeContext("rule-1"),
document: { sections: [] }, );
createdAt: new Date("2026-01-01T00:00:00Z"), expect(res.status).toBe(404);
updatedAt: new Date("2026-01-02T00:00:00Z"), });
userId: "user-1",
claimTokenHash: null, it("returns 200 for a public and featured Rule when the viewer is anonymous", async () => {
}; isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockResolvedValueOnce(row); findUniqueMock.mockResolvedValueOnce(
row({ visibility: RULE_VISIBILITY.public_and_featured }),
);
const res = await GET( const res = await GET(
new NextRequest("https://x.test/api/rules/rule-1"), new NextRequest("https://x.test/api/rules/rule-1"),
makeContext("rule-1"), makeContext("rule-1"),
); );
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as { const body = (await res.json()) as {
rule: { rule: { id: string; isListed: boolean };
id: string;
title: string;
summary: string | null;
isListed: boolean;
};
viewerIsOwner: boolean; viewerIsOwner: boolean;
}; };
expect(body.rule.id).toBe("rule-1"); 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.rule.isListed).toBe(true);
expect(body.viewerIsOwner).toBe(false); 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 () => { it("returns viewerIsOwner true when the signed-in user owns the rule", async () => {
isDatabaseConfiguredMock.mockReturnValue(true); isDatabaseConfiguredMock.mockReturnValue(true);
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
const row = { findUniqueMock.mockResolvedValueOnce(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" });
const res = await GET( const res = await GET(
new NextRequest("https://x.test/api/rules/rule-1"), new NextRequest("https://x.test/api/rules/rule-1"),
makeContext("rule-1"), makeContext("rule-1"),
@@ -167,23 +166,70 @@ describe("GET /api/rules/[id]", () => {
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as { viewerIsOwner: boolean }; const body = (await res.json()) as { viewerIsOwner: boolean };
expect(body.viewerIsOwner).toBe(true); 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); isDatabaseConfiguredMock.mockReturnValue(true);
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); findUniqueMock.mockResolvedValueOnce(
const row = { row({
id: "rule-1", visibility: RULE_VISIBILITY.shared_by_link,
title: "Mutual Aid Mondays", shareSlug: "k7f2-9qxm",
summary: "A grassroots community in Denver.", }),
document: { sections: [] }, );
createdAt: new Date("2026-01-01T00:00:00Z"), const res = await GET(
updatedAt: new Date("2026-01-02T00:00:00Z"), new NextRequest("https://x.test/api/rules/rule-1"),
}; makeContext("rule-1"),
findUniqueMock );
.mockResolvedValueOnce(row) expect(res.status).toBe(404);
.mockResolvedValueOnce({ userId: "other" }); });
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( const res = await GET(
new NextRequest("https://x.test/api/rules/rule-1"), new NextRequest("https://x.test/api/rules/rule-1"),
makeContext("rule-1"), makeContext("rule-1"),
+4
View File
@@ -44,6 +44,10 @@ vi.mock("../../lib/server/guestRuleClaim", () => ({
issueGuestRuleClaimCookieMock(...args), issueGuestRuleClaimCookieMock(...args),
})); }));
vi.mock("../../lib/server/uploads/linkUploads", () => ({
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("../../lib/server/db", () => ({ vi.mock("../../lib/server/db", () => ({
prisma: { prisma: {
$transaction: (fn: (tx: unknown) => Promise<unknown>) => $transaction: (fn: (tx: unknown) => Promise<unknown>) =>
+90
View File
@@ -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);
});
});
+8
View File
@@ -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"; import { saveCreateFlowUpload } from "../../lib/server/uploads/saveCreateFlowUpload";
const PNG_1X1 = Buffer.from( const PNG_1X1 = Buffer.from(
+46
View File
@@ -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");
});
});
+20
View File
@@ -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);
}
});
});
+1 -1
View File
@@ -227,7 +227,7 @@ describe("buildRobots", () => {
}); });
describe("robotsForPublishedRule", () => { 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(true)).toBeUndefined();
expect(robotsForPublishedRule(false)).toEqual(NO_INDEX_ROBOTS); expect(robotsForPublishedRule(false)).toEqual(NO_INDEX_ROBOTS);
}); });
+20
View File
@@ -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);
});
});
+131 -6
View File
@@ -5,18 +5,61 @@ import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const getUploadRootFromEnvMock = vi.fn(); 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; let uploadRoot: string | null = null;
vi.mock("../../lib/server/uploads/uploadRoot", () => ({ vi.mock("../../lib/server/uploads/uploadRoot", () => ({
getUploadRootFromEnv: () => getUploadRootFromEnvMock(), 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 { 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 () => { beforeEach(async () => {
uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-test-")); uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-test-"));
getUploadRootFromEnvMock.mockReset(); getUploadRootFromEnvMock.mockReset();
getUploadRootFromEnvMock.mockImplementation(() => uploadRoot); getUploadRootFromEnvMock.mockImplementation(() => uploadRoot);
isDatabaseConfiguredMock.mockReset();
isDatabaseConfiguredMock.mockReturnValue(true);
findUniqueMock.mockReset();
getSessionUserMock.mockReset();
getSessionUserMock.mockResolvedValue(null);
getReadablePublishedRuleMock.mockReset();
browserHoldsUploadGrantMock.mockReset();
browserHoldsUploadGrantMock.mockResolvedValue(false);
}); });
afterEach(() => { afterEach(() => {
@@ -34,6 +77,7 @@ describe("GET /api/uploads/[id]", () => {
}); });
it("returns 404 when the upload is not found", async () => { it("returns 404 when the upload is not found", async () => {
findUniqueMock.mockResolvedValueOnce(null);
const res = await GET( const res = await GET(
new NextRequest( new NextRequest(
"https://x.test/api/uploads/550e8400-e29b-41d4-a716-446655440000", "https://x.test/api/uploads/550e8400-e29b-41d4-a716-446655440000",
@@ -47,16 +91,97 @@ describe("GET /api/uploads/[id]", () => {
expect(res.status).toBe(404); expect(res.status).toBe(404);
}); });
it("returns the file bytes with content type", async () => { it("returns featured file bytes with a short public cache", async () => {
const id = "550e8400-e29b-41d4-a716-446655440000"; await writeFile(path.join(uploadRoot!, `${FEATURED_ID}.png`), "png-bytes");
await writeFile(path.join(uploadRoot!, `${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( const res = await GET(
new NextRequest(`https://x.test/api/uploads/${id}`), new NextRequest(`https://x.test/api/uploads/${FEATURED_ID}`),
{ params: Promise.resolve({ id }) }, { params: Promise.resolve({ id: FEATURED_ID }) },
); );
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toBe("image/png"); 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"); 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({
idOrSlug: "rule-shared",
viaShareSlug: true,
lookup: "id",
}),
);
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");
});
}); });
+4
View File
@@ -22,6 +22,10 @@ vi.mock("../../lib/server/session", () => ({
clearSessionCookie: vi.fn(), clearSessionCookie: vi.fn(),
})); }));
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
}));
import { DELETE } from "../../app/api/user/me/route"; import { DELETE } from "../../app/api/user/me/route";
beforeEach(() => { beforeEach(() => {